fork(28) download
  1. import java.util.ArrayList;
  2.  
  3. class CombinationOf3And4 {
  4.  
  5. /*
  6.  * http://w...content-available-to-author-only...s.org/zoho-interview-set-2-campus/
  7.  * Form a number system with only 3 and 4. Find the nth number of the number system.
  8.  * e.g. The numbers are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444 ….
  9.  */
  10. public static void main(String[] args) {
  11. printCombinations(20);
  12. }
  13. public static void printCombinations(int n){
  14. ArrayList<String> numbers = new ArrayList<String> ();
  15. numbers.add("3");
  16. numbers.add("4");
  17. int currentNumber = 0;
  18. while(numbers.size()<n){
  19. ArrayList<String> threePrefixed = new ArrayList<String>();
  20. ArrayList<String> fourPrefixed = new ArrayList<String>();
  21.  
  22. for(int i=currentNumber;i<numbers.size();i++){
  23. // Retrieve all numbers.
  24. // For every number create new number with prefix "3" & with prefix "4".
  25. // then push all 3-prefixed-number into array and then 4-prefixed-number
  26. threePrefixed.add("3"+numbers.get(i));
  27. fourPrefixed.add("4"+numbers.get(i));
  28. currentNumber++;
  29. }
  30.  
  31. for(String s:threePrefixed){
  32. numbers.add(s);
  33. }
  34. for(String s:fourPrefixed){
  35. numbers.add(s);
  36. }
  37. }
  38. System.out.println("Printing result");
  39. for(String s:numbers){
  40. System.out.print(" "+s);
  41. }
  42.  
  43. }
  44. }
  45.  
  46.  
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
Printing result
 3 4 33 34 43 44 333 334 343 344 433 434 443 444 3333 3334 3343 3344 3433 3434 3443 3444 4333 4334 4343 4344 4433 4434 4443 4444