Do not repeat letters (char) in an ASCII matrix

Asked

Viewed 198 times

3

You had to create a 5x5 array by printing random characters from the ASCII table.

public class ExercicioClass01g {
    static Scanner ler = new Scanner(System.in);

    public static char mat[][] = new char[5][5];

    public static void gera(int lin, int col){
        Random gerador = new Random();
        int ctlin,ctcol;
        for(ctlin=0;ctlin<lin;ctlin++)
            for(ctcol=0;ctcol<col;ctcol++)
                mat[ctlin][ctcol]=(char)(gerador.nextInt(25)+65);

    }   

    public static void exibe(int lin, int col){
        int ctlin,ctcol;
        for(ctlin=0;ctlin<lin;ctlin++){
            for(ctcol=0;ctcol<col;ctcol++)
                System.out.print(mat[ctlin][ctcol]+" ");
            System.out.println();
        }       
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        gera(5, 5);
        exibe(5,5);
    }

I managed to print but I can’t do the lyrics (char) do not repeat in the matrix.

1 answer

3


Instead of using random generation use the algorithm Fisher-Yates. It would be nice to create a function that creates the list and then use as you wish:

public static List<Integer> randomNumbers(int start, int end, int count) {
    List<Integer> lista = new ArrayList<>(end - start + 1);
    for (int i = start; i <= end; i++) lista.add(i);
    Collections.shuffle(lista);
    lista = lista.subList(0, count);
    return lista;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, it worked :D

  • @Francinestivanin Take a look at the [tour] You can accept the answer and vote for it and any other posts on the site as well.

Browser other questions tagged

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