Not yet rated

Problem

Calculate all possible repeating permutations of a set of numbers, for example a 4-digit passcode.

Solution

Use a small Java program to recursively iterate over the possible numbers in the set to generate all combinations.

Detailed explanation

package com.adampresley.NumDigits;
 
public class Main
{
   public static void main(String[] args)
   {
      // Possible digits here are 1,2,3, and 4
      go("1234", 4, new StringBuffer());
   }
 
   static void go(String input, int depth, StringBuffer output)
   {
      if (depth == 0)
      {
         System.out.println(output);
      }
      else
      {
         for (int i = 0; i < input.length(); i++)
         {
            output.append(input.charAt(i));
            go(input, depth - 1, output);
            output.deleteCharAt(output.length() - 1);
         }
      }
   }
}


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes