i am working on a program where the user enters a number and the computer will generate N number of characters and print them in all combonations. For example:

enter number: 3

aaa aab aac aba abb abc aca acb acc
baa bab bac bba bbb bbc bca bcb bcc
caa cab cac cba cbb cbc cca ccb ccc

I have made the program build the array and randomize the characters however i dont know how to use recursion to print all the combos. Here is what i have so far:

import cs1.Keyboard;
import java.util.Random;

public class Letter
{

    public static void main(String[] args)
    {
        System.out.println("How many characters do you want");
        int number = Keyboard.readInt();

        char[] list = new char[number];

        Random generator = new Random();

        for(int index = 0; index < list.length; index++)
        {       
           int temp = generator.nextInt(26) + 65;
           list[index] = (char) temp; 
        }

        //check if all characters are different
        for(int index = 0; index < list.length-1; index++)
        {
            if(list[index] == (list[index+1]))
            {
              int temp = generator.nextInt(26) + 65;
              list[index+1] = (char) temp;
              index=0;
            }
        }

I believe recursion would be the best solution but i dont know how to use it to print the answer. Any help would be great. thanx

Recommended Answers

All 4 Replies

Member Avatar for iamthwee

This is the basic principle...

char stuff[]="abc";
     
     for(int i=0; i<3; i++)
     {
         for(int j=0; j<3; j++)
         {
             for(int k=0; k<3; k++)
             {
                 print stuff[i];
                 print stuff[j];
                 print stuff[k];
                 print newline
             }
             
         }
     }

From there you should be able to devise a general model and see where the recursion comes into play.

I understand that. I know thats how it works, but i dont know how to get the for loops to repeat N number of times. The program i am making has to work for any number N.
I'm new at the topic of recursion so im lost in trying to use it. But thanks for the help so for.

so parameterise the whole thing to take a number n instead of using a fixed number of iterations...

try the following:

public void printLoop(int index; char[] list; char[] string) {
  if (index == list.length) {
    System.out.print(new String(string) + " ");
    return;
  }

  for (int i = 0; i < list.length; i++) {
    string[index] = list[i];
    printLoop(index + 1, list, string);
  }
}

char[] string = new char[list.length];

for (int i = 0; i < list.length; i++) {
  string[0] = list[i];
  printLoop(1, list, string);
  System.out.println("");
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.