1.11M Members

Insert Commas Recursively

 
0
 

Hey I have an assignment to get a number from the user and print it as a string with commas in the correct space. For example if the number is 13904 it should read 13,904 or 1005 should read 1,005. I have to do this recursively. Working on my pseudo-code I had two ideas and I got stuck on both ideas. My first idea was to take the number as a variable and enter it into a character array then add a comma in the necessary spots, this seemed easier so it is what I went with. But I could not figure how to put each separate number from the variable in each of their own spots in the array. Any help would be greatly appreciated.

 
0
 

to do what you want to do, you would need a second array that is bigger so that you can transfer lets say 3 numbers from the original array and then manually add a comma, rince and repeat. but adding the comma where they belong in the original would cause the number in that spot to be lost.

if you HAVE to do this recursively, just printing not saving, i would simply have the method look if the string is less than 3 characters, if so print it, otherwise look for a period in case there are decimals, put in a temp string 3 chars left of the period, the period, and everything to its right(or if there is no period just the 3 last digits), then send the rest of the string to the recursive call, and after the recursive call print the bit of the string i saved in a temp string.

that would make the last recursive call (the "base" case) print first, then all the numbers from left to right would print out and the first call would finish with printing the final 3 digits + the period + the decimals.

let us know how it goes :)

 
0
 

O I see what you mean, I would need two arrays, that sounds like a pain. Your way sounds much easier, let me make sure I understand.
Ok so what I was thinking after reading what you said. Take a string, make an if else statement, if the string is greater than 3 digits then print the last three digits with a comma in front of them, and keep doing that?

 
1
 

no not really, my paragraph above is BASICLY youre whole pseudo code, but as i was testing it on my side theres a few things i noticed but anyways, the main issue you have to deal with , is that some numbers wont end with 3 numbers left of the first comma, like 1,234.56 or 12,345,678.99 , so you cant treat the string from left to right, you need to go from right to left.

start with the period and everything to its right if there is any , or if there is no period, the 3 last digits :

12234567.56 -> save 567.56 , call method with ("12234")

12234 -> save 234 , call method with ("12")

12 -> less than 3, return "12"

back in 12234 , return "12" + "," + "234"

back in 12234567.56 , return "12,234" + "," + "567.56"

and here you are back in your main with "12,234,567.56" and you can print it

 
0
 

In my opinion, you should find this code self-explanatory.

[EDIT: This is not a spoiler, just another way of doing it. Do it yourself once to get the hang of it.]

Oh, plus this code does not handle decimal points. If you want to tackle decimal points too, just split the string into two portions, one half being the left and one half being the right side. Then make the left half go through this procedure and print a dot and the right half as it is.

import java.io.BufferedReader;
import java.io.InputStreamReader;
//..............
try
{
   String rcb = new BufferedReader(new InputStreamReader(System.in)).readLine();
   if(rcb.length()>3)
   {
      char abc[] = rcb.toCharArray();
      for(int i=abc.length;i>2;i-=2)
      {
         System.out.print(abc[i] + ",");
      }
   }
}
catch(IOException e){e.printStackTrace();}
 
0
 

In my opinion, you should find this code self-explanatory.

[EDIT: This is not a spoiler, just another way of doing it. Do it yourself once to get the hang of it.]

Oh, plus this code does not handle decimal points. If you want to tackle decimal points too, just split the string into two portions, one half being the left and one half being the right side. Then make the left half go through this procedure and print a dot and the right half as it is.

import java.io.BufferedReader;
import java.io.InputStreamReader;
//..............
try
{
   String rcb = new BufferedReader(new InputStreamReader(System.in)).readLine();
   if(rcb.length()>3)
   {
      char abc[] = rcb.toCharArray();
      for(int i=abc.length;i>2;i-=2)
      {
         System.out.print(abc[i] + ",");
      }
   }
}
catch(IOException e){e.printStackTrace();}

i dont know what this is suposed to be, but its not working.

 
0
 

Haha. You don't expect it to work the first time. It has to have errors, or I'm not human. Let me correct it, wait. :)
Yup, got it. Forgot to include4 the odd-even number logic, AND there's an ArrayOutOfBoundsException. Just wait. :P

 
1
 

Haha. You don't expect it to work the first time. It has to have errors, or I'm not human. Let me correct it, wait. :)

it's not about errors , it compiled, i did have to add a -1 to your starting loop value since it was getting an index out of bound exception, but the logic is flawed here.

starting with the fact its not recursive.

for(int i = abc.length-1 ; i > 2 ; i-=2 ){
    System.out.print(abc[i] + ",");
}

2) i added -1 to the starting value of i cause it would cause an indexOutOfRangeException.
3) you print out the string from right to left, so 1234 would print 4321.
4) you decrease i by 2 every iteration which means your skipping 1 letter everytime.
5) you stop the loop at i <= 2 so you're missing the letters in the indexes 0 1 and 2.

this is the input im testing with : 12345678

and this is your methods output : 8,6,4,

 
0
 

i made my own recursive method for this thread yesterday to be able to better help MrHardRock, not gonna post the code cause I want him to work on his own, but here is the output with the recursivity trace :

for input : 1234567.89
output :

Call #1 is Formating : 1234567.89
Saving Decimals : .89
Saving : 567
Recursive Call #2 For : 1234

Call #2 is Formating : 1234
Saving : 234
Recursive Call #3 For : 1

Call #3 is Formating : 1

---Base Case Reached---
Recursive Call #3 Returned : 1
Recursive Call #2 Returned : 1,234
Recursive Call #1 Returned : 1,234,567.89

 
0
 

There you go... But what do you mean by recursive - like every 3 times? (CODE doesn't account for decimals or negative numbers)

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * @author dantinkakkar
 */
public class Main
{
    public static void main(String args[])
    {
      try
      {
        String rcb = new BufferedReader(new InputStreamReader(System.in)).readLine();
        if(rcb.length()>3&&rcb.length()%2!=0)
        {
         char abc[] = rcb.toCharArray();
         for(int i=0;i<abc.length-3;i++)
         {
             if((i+1)%2==0)
                System.out.print(abc[i] + ",");
             else
                 System.out.print(abc[i]);
         }
         for(int l=abc.length-3;l<abc.length;l++)
             System.out.print(abc[l]);
        }
        else if(rcb.length()>3&&rcb.length()%2==0)
        {
         char abc[] = rcb.toCharArray();
         for(int i=0;i<abc.length-3;i++)
         {
             if((i+1)%2!=0)
                System.out.print(abc[i] + ",");
             else if(i%2==0)
                 System.out.print(abc[i]);
         }
         for(int l=abc.length-3;l<abc.length;l++)
             System.out.print(abc[l]);
        }
        else
        {
            System.out.println(rcb);
        }
         }
      catch(java.io.IOException e){e.printStackTrace();}
    }

}
 
0
 

please stop posting code, MrHardRock isn't going to get better at problem solving and programming if we hand him his assignement on a silver plate.

also, i have not yet tested your new version but from the for loop i can tell it's wrong, for very similar reasons to those the first snippet was also.

Recursivity : http://en.wikipedia.org/wiki/Recursion

 
0
 

your second snippet :

input : 1234567
output : 12,34,567

close but no cigar! :P

 
0
 

Umm, Philip: I really don't understand what you're saying. The output it has produced (12,34,567) is perfectly correct! I guess you guys put commas after every 3 numbers, it's different here in India! :) We have lakhs and crores, not millions/trillions. We put a comma only before the last three, except for that, it's after every 2.

 
0
 

Im actually french canadian, so I personnaly use commas to seperate integers from decimals, and a optionaly a space to seperate sets of 3 integers...

but yes in the US sets of 3 integers are separated by a comma, while the integer and decimal parts a seperated by a period :

French canadian :

1 234 567,89$ or 1234567,89$

USA :

1,234,567.89$

 
0
 

the more interesting part was the recursivity not being correct.
to give a very simple (basic) explanation:

a recursive method is a method that calls itself.

for instance:

public int addTo100(int number){
  if ( number < 100 ){
    number += 1;
    number = addTo100(number);
  }
  return number;
}

the above is recursively adding to (at least) 100, since addTo100 calls itself.

sure it could be done with a for loop, but that would not be recursive.

 
0
 

@Philip. It's different for India, so not my fault there, I guess :P

And in my most recent snippet do delete and replace Line 35 with "else"

 
0
 

or factorials!!!

public int factorial(int n){
    if(n <= 1)return 1;
    return n * factorial(n-1);
}

i love that fucntion! :D

 
0
 

Ya, I got what you said, when you posted the Wikipedia link. Too lazy to disturb Google, I guess! :P :D

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: