jeudi 24 novembre 2022

How to place 5 ships randomly in a list of 20 positions for battleship game?

I need to put 5 ships randomly (numbers 1 to 5 witout repetition) in a list of 20 positions. I need to place a 0 where no ships are placed. e.g Please, I'm stuck here!

for (int i = 0; i < barcosComputadora.length; i++) {
            if (i > 0) {
                barcosComputadora[i] = rnd.nextInt(6);

            }
        }
    

    static void imprimirArreglo(int[] pValores) {
        for (int i = 0; i < pValores.length; i++) {
            out.print(pValores[i] + "\t");
        }
    }

    public static void main(String[] args) throws Exception {
        int tam = 20;

        // tam = rnd.nextInt(20);
        int barcosComputadora[] = new int[tam];
        inicializarBarcosComputadora(barcosComputadora);
        out.println("\nValores del arreglo: ");
        imprimirArreglo(barcosComputadora);
    }


I got something like this:

0       0       5       2       2       0       2       2       5       2       1       0       0       4       5       3       0       0       3       4



Aucun commentaire:

Enregistrer un commentaire