/**
         * Generate a random 2x2 position.
         * @param r         random int generator
         */
        public TwoByTwoState RandomState(Random r)
        {
            TwoByTwoState state = new TwoByTwoState();

            state.Permutation = r.Next(N_PERM);
            state.Orientation = r.Next(N_ORIENT);
            return(state);
        }
        private string Solve(TwoByTwoState state, int desiredLength, bool exactLength, bool inverse)
        {
            int[] solution      = new int[MAX_LENGTH];
            int[] best_solution = new int[MAX_LENGTH + 1];
            bool  foundSolution = false;
            int   length        = exactLength ? desiredLength : 0;

            while (length <= desiredLength)
            {
                best_solution[length] = 42424242;
                if (Search(state.Permutation, state.Orientation, 0, length, 42, solution, best_solution))
                {
                    foundSolution = true;
                    break;
                }
                length++;
            }

            if (!foundSolution)
            {
                return(null);
            }

            if (length == 0)
            {
                return("");
            }

            StringBuilder scramble = new StringBuilder(MAX_LENGTH * 3);

            if (inverse)
            {
                scramble.Append(inverseMoveToString[best_solution[length - 1]]);
                for (int l = length - 2; l >= 0; l--)
                {
                    scramble.Append(" ").Append(inverseMoveToString[best_solution[l]]);
                }
            }
            else
            {
                scramble.Append(moveToString[best_solution[0]]);
                for (int l = 1; l < length; l++)
                {
                    scramble.Append(" ").Append(moveToString[best_solution[l]]);
                }
            }

            return(scramble.ToString());
        }
 /**
  * Return a generator of a given position in exactly length number of turns or not at all.
  * Returns either the solution or the generator (inverse solution)
  * @param perm      permutation
  * @param orient    random int generator
  * @param length    length of the desired solution
  * @return          a string representing the solution or the scramble of a random position
  */
 public string GenerateExactly(TwoByTwoState state, int length)
 {
     return(Solve(state, length, true, true));
 }
 /**
  * Solve a given position in less than or equal to length number of turns.
  * Returns either the solution or the generator (inverse solution)
  * @param state     state
  * @param length    length of the desired solution
  * @return          a string representing the solution or the scramble of a random position
  */
 public string SolveIn(TwoByTwoState state, int length)
 {
     return(Solve(state, length, false, false));
 }