JAVA - Generate a random & scrambled word

Asked

Viewed 1,320 times

1

I intend to generate a randomized, scrambled word from a vector. It’s already generating a random word, but it’s not scrambled. I created a method called Scramble where the words will be shuffled but I don’t know I can call on Main.

Current code:

import java.util.Random;
import java.util.Scanner;


public class findthewordgame {
    public static void arrayword () {

        String[] wordgame = new String[5];

        wordgame[0] = "TEA";
        wordgame[1]= "COFFE";
        wordgame[2]= "BOAT";
        wordgame[3]="SEA";
        wordgame[4]="SUN";


       int idx = new Random().nextInt(wordgame.length);
       String random = (wordgame[idx]);

       System.out.println(wordgame[idx]);

    }

    public static String scramble(Random random, String inputString )
    {
    // Convert your string into a simple char array:
    char a[] = inputString.toCharArray();

    // Scramble the letters using the standard Fisher-Yates shuffle, 
    for( int i=0 ; i<a.length ; i++ )
    {
        int j = random.nextInt(a.length);
        // Swap letters
        char temp = a[i]; a[i] = a[j];  a[j] = temp;
    }       

    return new String( a );
}

    public static void main (String[] args){
         arrayword();


    }
}

1 answer

2


To make it work just call the method scramble, that is not to be called. I could do it with:

public static void arrayword () {

   ...
   System.out.println(scramble(new Random(), random));
}

And although it already works, it’s not very good because another object is being created Random when a previous one had already been created.

We can review this and other code details and turn it into:

//objeto que gera os aleatorios agora é sempre o mesmo e apenas criado uma vez
static Random aleatorio = new Random();

public static void arrayWord () { //agora o nome em camel case

    String[] wordgame = { //inicialização do array mais simples assim
        "TEA",
        "COFFEE",
        "BOAT",
        "SEA",
        "SUN"
    };

    int idx = aleatorio.nextInt(wordgame.length);
    String palavraEscolhida = (wordgame[idx]);

    System.out.println(palavraEscolhida); //escrever a variavel anterior, a escolhida
    System.out.println(scramble(palavraEscolhida));
}

//agora não recebe o aleatorio, usa o mesmo da classe
public static String scramble(String inputString ) 
{
    // Convert your string into a simple char array:
    char[] a = inputString.toCharArray();

    // Scramble the letters using the standard Fisher-Yates shuffle, 
    for( int i=0 ; i<a.length ; i++ )
    {
        int j = aleatorio.nextInt(a.length);

        //Mais legível assim linha a linha
        char temp = a[i]; 
        a[i] = a[j];  
        a[j] = temp;
    }       

    return new String(a);
}

Example working on Ideone

  • String[] wordgame = {"TEA", "COFFE", "BOAT", "SEA", "SUN"}; - Simpler yet.

  • And would already take advantage and tidy up code style details, such as more or less spaces, variable names and use char[] a instead of char a[].

  • @Victorstafusa Yes I agree and I appreciate the comments. This last one from char a[] I didn’t even notice!

  • I did as suggested is working and is not. appears the word twice once correctly written and in the same line again but scrambled. i intend that the word generates only once and only shuffled. it has to help sff?

  • Just comment System.out.println(palavraEscolhida); and already giving.

  • @Dianamadeira take into account that the algorithm you are using to shuffle (which I did not change on purpose) does not guarantee 100% that the word battled will be different from the original, although it is very likely. If you imagine a word with 3 letters that changes: 1-3, 2-2 and 3-1, it is the same as the original. For that not to happen would have to use another algorithm, or using the same continue to shuffle the same word until different.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.