Ajuda em Java

2 respostas
amc97

Bom dia pessoal!
Queria a ajuda de vocês num projeto. Quero saber como faço para preencher uma matriz com uma sequencia de números, repetindo eles só uma vez. É para um jogo da memória, sem interface gráfica.
Agradeço se puderem ajudar!

2 Respostas

X

Aqui fiz um exemplo simples.

`public static void main(String[] args) {

//|***********************************************|
    //|                                               |
    //|ATENCAO ESSA CLASSE E PARA SER USADA COMO TESTE|
    //|                                               |
    //|***********************************************|
    

int[][] matriz = new int[4][4]; // == 16

int[] vetor = new int[matriz.length*matriz[0].length]; // 4 *4 == 16

int cont = 0;

    //Preenchendo o vetor
    for (int i = 0; i < vetor.length; i++) {
        if (i == vetor.length/2) {//Se cont == 8 ele vai zerar o cont
            //ou seja vai repetir vai ficar assim
            // 0 1 2 3 4 5 6 7 zero cont 0 1 2 3 4 5 6 7
            cont = 0;
        }
        vetor[i] = cont;
        cont++;
    }
//Metodo simples para sortear o vetor
vetor = sortearVetor(vetor);

int index = 0 ;

    //no caso a matriz tem tamanho 16 e o vetor tem tamanho 16
    // entao a matriz a cada for que era
    // 0 0 0 0 vai ser agora assim
    //vetor[index] index ++;
    for (int i = 0; i < matriz.length; i++) {
        for (int j = 0; j < matriz.length; j++) {
            matriz[i][j] = vetor[index];
            index++;
        }
    }

    //printando a matriz
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            System.out.print(matriz[i][j]+" ");
        }
        System.out.println("");
    }
}`

`public static int[] sortearVetor(int[] vetor){

Random random = new Random();
    
    for (int i = 0; i < vetor.length; i++) {
        
        int numeroRandom = random.nextInt(vetor.length);
        
        int aux1 = vetor[i];
        int aux2 = vetor[numeroRandom];
        
        vetor[i] = aux2;
        vetor[numeroRandom] = aux1;
    }
    
    return vetor;
}`
amc97

Valeu cara, foi boa :smile:

Criado 13 de abril de 2016
Ultima resposta 13 de abr. de 2016
Respostas 2
Participantes 2