Question

I am making a word game as homework. But I'm stuck. I have a shuffled word but I need to reveal its first (then 2nd,3rd...) letter per turn. I tried to do something like this :

char[] arr = a.toCharArray();
   for ( int j = 0; j<arr.length; j++) {

          if (original[j] == shuffled[j] ) { //If the not shuffled word's first letter equals to shuffled word's first letter then move to the 2nd letter and reveal it. Maybe update the j to j+1?}

          else {
            char temp = shuffled[j];
            shuffled[j] = original[j];
            original[j] = temp;
            String h = new String(shuffled);
            System.out.println("test " + h) ; 

          }
        }

My output should be something like this :

Original word : Badger Shuffled word : drBage

1st turn : Brdage

2nd turn : Badrge

3rd turn : Badegr

4th turn : Badger

My Current output is :

Original word : Cat123

shuff 12Cta3

test C2Cta3

test CaCta3

test Catta3

test Cat1a3

test Cat123

test Cat123

Was it helpful?

Solution

The following pseudo code should help clarify your problem. I would invoke a function, for example reveal letter which I have defined below after each turn.

   public class Unscramble{

    public static void main(String[] args){

        char[] orig = args[0].toCharArray();
        char[] shuffled = args[1].toCharArray(); 
        int count = 0;

        while(count < orig.length){

            if(!(orig[count] == shuffled[count]))
                shuffled = revealLetter(shuffled,orig, count);

            count++;
            System.out.println(count + " " + new String(shuffled));
        }
    }


    /*
    * Reveal letter
    * @param shuffled the shuffled array
    * @param original original char array
    * @param index index of letter to reveal
    */
    public static char[] revealLetter(char[] shuffled, char[] original, int index){
      shuffled[index] = original[index];
      return shuffled;
    }
}

OTHER TIPS

Firstly, don't shuffle the word - you'll lose the right letter order.

Instead:

  • loop through the letters
  • print the first "n" letters from the original word
  • make a copy of the array from n+ to end
  • shuffle it then print it
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top