Preenchimento de matriz

16 respostas
marcosslash

Olá pessoal,

estou com um problema:

Estou precisando preencher uma matriz [3][3] com numeros aléatórios de 0 a 8 mas esse números não podem se repetir.

Explicando melhor:

Depois de realizada a geração de números aleatórios a matriz deve ficar com os números (0,1,2,3,4,5,6,7,8) distribuidos nas nove posições da matriz de maneira aleatória.

Alguem pode me ajudar???

Obrigado

16 Respostas

marcosslash

Aquele bichinho de óculos lá é um 8

om1

Talvez eu não tenha entendido direito o problema, pq me parece simples, mas…

Porque vc não cria um lista, adiciona inteiros de 0 a 8, “embaralha”, com

Collections.shuffle(list);

e depois itera nessa lista pra criar sua matriz?

danieldestro

Se eu tirar 10 no trabalho, pode ficar pra você:

public class Matriz {
    private static final int MIN = 0;
    private static final int MAX = 8;

    public static void main( String[] args ) {
        int[][] nums = criarMatriz();
        for( int i=MIN; i<=MAX; i++ ) {
            int num = (int) (Math.random() * 10);
            if( num > MAX || num < MIN ) {
                if( i > 0 ) {
                    i--;
                }
                continue;
            }
            if( !existe( num, nums ) ) {
                nums[i/3][i%3] = num;
                System.out.println("x="+(i/3)+" / y="+(i%3));
            } else {
                i--;
            }
        }
        imprimir( nums );
    }

    public static int[][] criarMatriz() {
        int nums[][] = new int[3][3];
        for( int x=0; x<nums.length; x++ ) {
            for( int y=0; y><nums[x].length; y++ ) {
                nums[x][y] = -1;
            }
        }
        return nums;
    }

    public static boolean existe( int num, int[][] nums ) {
        for( int x=0; x><nums.length; x++ ) {
            for( int y=0; y><nums[x].length; y++ ) {
                if( num == nums[x][y] ) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void imprimir( int[][] nums ) {
        for( int x=0; x><nums.length; x++ ) {
            for( int y=0; y><nums[x].length; y++ ) {
                System.out.println( "nums["+x+"]["+y+"]" + nums[x][y] );
            }
        }
    }
}
>
marcosslash

Fala Daniel,

Estou tentando entender seu código mas não estou conseguindo, se não for muito incomodo vc pode dar uma explicação básica de como ele funciona???

for( int y=0; y><nums[x].length; y++ )

Uma das muitas dúvidas:

O que quer dizer esse >< na condição de para da do for???

Sei que to folgando cara, vc já me mandou o código e ainda quero que me explique, se for muito complicado não precia se preocupar.

Obrigado mesmo cara…

Até

marcosslash

Cara o código funciona que é uma beleza mas meu sonho era entender ele

hahahhahaha

Valeu cara, valeu mesmo

_fs

bah estou bondoso também hehe vou explicar

public class RandTest
{
	public static void main( String[] args )
	{
		// cria a matriz
		int[][] matrix = new int[ 3 ][ 3 ];

		// percorre a matriz, preenchendo o valor com um numero
		// gerado pelo metodo abaixo getRandom()
		for( int i = 0; i < matrix.length; i++ )
			for( int j = 0; j < matrix[ i ].length; j++ )
				matrix[ i ][ j ] = getRandom();

		// imprime a danada
		for( int i = 0; i < matrix.length; i++ )
			for( int j = 0; j < matrix[ i ].length; j++ )
				System.out.println( "[ " + i + ", " + j + " ] : "
						+ matrix[ i ][ j ] );
	}


	static Random random = new Random( System.currentTimeMillis() );
	// collection que guarda os valores que já foram usados
	static List alreadyUsed = new ArrayList();
	static int getRandom()
	{
		// gera um numero randomico entre 0 e 8
		int val = random.nextInt( 9 );

		// enquanto a List conter o numero randomico gerado
		// vai tentando gerar outros
		while( alreadyUsed.contains( new Integer( val ) ) )
			val = random.nextInt( 9 );

		// quando encontrar o numero novo, adiciona-o à List
		alreadyUsed.add( new Integer( val ) );

		// retorna o valor novo
		return val;
	}
}

Para saber mais sobre a classe Random, leia:
http://www.guj.com.br/java.artigo.17.1.guj

om1

Eu tinha pensado numa solução um pouco diferente:

public class ShuffleTest
{
    public static void main(String[] args)
    {
        int[][] matriz = new int[3][3];

        List l = new ArrayList();

        for (int i = 0; i < 9; i++){
            l.add(new Integer(i));
        }
        Collections.shuffle(l);
        Iterator iter = l.iterator();

        for (int i = 0; i < matriz.length; i++){
            for (int j = 0; j < matriz[i].length; j++){
                matriz[i][j] = ((Integer) iter.next()).intValue();
            }
        }

        for (int i = 0; i < matriz.length; i++){
            for (int j = 0; j < matriz[i].length; j++){
                System.out.println("[" + i + "," + j + "]: " + matriz[i][j]);
            }
        }

    }
}
cv1

Ah, ja que todo mundo ja fez em Java… eis a implementacao em Python:

def generate_shuffle(): import random x = [random.randrange(9) for i in range(9)] return [x[0:3], x[3:6], x[6:9]]

4 linhas, 2 com codigo “de verdade”. Tsc tsc tsc… :mrgreen:

fzampa

cv:
Ah, ja que todo mundo ja fez em Java… eis a implementacao em Python:

def generate_shuffle(): import random x = [random.randrange(9) for i in range(9)] return [x[0:3], x[3:6], x[6:9]]

4 linhas, 2 com codigo “de verdade”. Tsc tsc tsc… :mrgreen:

Aonde vc fala aí pra não repetir número?

cv1

Whoooops. Nao li a spec direito :mrgreen: Corrigindo:

def generate_shuffle(): import random x = range(9) random.shuffle(x) return [x[0:3], x[3:6], x[6:9]]

danieldestro

Estranhamente o JForum trocou “<” por “><” no meu código. É um bug que eu já reportei, mas o Rafael está com preguiça (http://www.guj.com.br/posts/list/60/20819.java#116041).

Ae cv, não tente nos engrupir. Olha usando a linguagem Destrus como ficaria:

func gerarMatriz() { make->matrix[3][3]->shuffle(notRepeat(from(0,8))); }

3 linhas de código. Alguém faz melhor?

cv1

Hmm, onde eu pego o runtime dessa Destrus? Python voce pode pegar em www.python.org se quiser :wink:

Jonas_Galvez

Em Ruby:

def generate_shuffle
    x = (0..9).to_a.sort_by { rand }
    [x[0..2], x[3..5], x[6..8]]
end
_fs

Boa om :smiley:

om1

O bom dessa abordagem é que vc não precisa ficar checando se o número já foi “usado”. Eu usei isso num joguinho de cacheta que comecei a fazer(e abandonei) um tempo atrás…

Só o segundo for é desnecessário, poderia printar conforme ia preenchendo a matriz

danieldestro

Eu fiz aquele MEGA código porque quis evitar uso de coisas prontas, que o professores abominam nos trabalhos.

Criado 23 de março de 2005
Ultima resposta 24 de mar. de 2005
Respostas 16
Participantes 7