Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a recursive method that generates a list of all possible character strings

ID: 3749602 • Letter: W

Question

Write a recursive method that generates a list of all possible character strings of a given length for a given numeric base. For example, generating all base 2 strings of length 3 should yield [000, 001, 010, 011, 100, 101, 110, 111]. Generating all base 4 strings of length 2 should yield [00, 01, 02, 03, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33]. Feel free to use a helper method if needed. Bases less than 2 should be rejected as should strings of length 0 or less.

public static List<String> generateAllStrings(int length, int base) {

   // insert your code here

}

Problem

Explanation / Answer

// this method creates a list which is updated by the recurcive method, we also take a buffer array dig

//to store the intermidiate digits found.

public static List<String> generateAllStrings(int length, int base)

{

List<String> numberList = new List<String>();   

int [ ] dig = new int[length];

   populateList(dig, length, base, 0, numberList );

    return numberList;

}

/*

* this recursive function 1st find all unit digit value i.e. for length 1, then it go on to find all ten's digit i.e * for length 2 and so on.

*/

void populateList(int[ ] dig, int length, int base, int index, List<string> numberList )

{

   int i;

   if (length == 0)

   {

     numberList.Add( Arrays.toString(dig));

);

   }

   if (length > 0)

   {

      for(i = 0; i <= base; ++i)

      {

        dig[index] = i;

        populateList(arr, length - 1, base, index+1, numberList);

      }

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote