número binário aleatório

9 respostas
P

Olá! :smiley:

Alguém sabe gerar números binários aleatórios?

Abraços

9 Respostas

E

Um número binário é um número, portanto gere um número aleatório (use java.util.Random, por exemplo) e depois o converta para binário.

jcmird
public class Teste {
	
	public static void main(String []args){
		Integer numeroBin;
				
		numeroBin = new Integer( 1 + (int) (Math.random()*10));
		String printNumero = numeroBin.toBinaryString(numeroBin);
		
		System.out.println(numeroBin);
		System.out.println(printNumero);
		
		
	}

}
P

Obrigada, Edson e jcmird! :smiley:

Mas não há uma forma de gerar sem fazer a conversão de decimal para binário? Porque, na verdade, estou tentando fazer um algoritmo genético e no inicio tenho que gerar uma população com 4 individuos (cromossomo) e cada individuo tem q ser um número binário.

Abraços

ViniGodoy

Eu fiz uma classe para representar genomas binários em algoritmos genéticos, para o SofiaIA.
Posso posta-la para você aqui. É feita em Java. No blog tem a versão dela em C++.

A vantagem é que ela usa a representação binária mesmo, e tem método que facilitam a conversão de bits específicos em números inteiros.

Por exemplo, você pode querer o inteiro que é representado pelos bits 8 até 16, com ou sem sinal.

ViniGodoy

Como prometido:

import java.util.BitSet;
import java.util.Random;

/**
 * Represents a genome, with genes encoded as binary data. Provide useful
 * methods for setting and getting values into the binary string. Also, provide
 * a crossover and a mutation methods.
 */
public class BitGenome {

    private BitSet genes;

    /**
     * Creates a new genome with N bit size.
     */
    public BitGenome(int bits) {
        genes = new BitSet(bits);
    }
   
    /**
     * Creates a genome with random content.
     */
    public static BitGenome createRandom(int bits)
    {
        Random random = new Random();
        BitGenome genes = new BitGenome(bits);
        for (int i = 0; i < genes.size(); i++)
            genes.set(i, random.nextBoolean());
        return genes;
    }

    /**
     * Sets the given number in the specified position using cont bits.
     *
     * @param pos Position to set the number
     * @param number Number to set. The number range will vary from 0 to
     * (2^bits)-1
     * @param bits Number of bits that will be used to store this number.
     */
    public void setUnsigned(int pos, long number, int bits) {
        int max = ((2 << bits - 1) - 1);

        if (number > max) {
            throw new IllegalArgumentException("Invalid number " + number + "! Maximum value for " + bits + " bits is " + max + "!");
        }
        if (number < 0) {
            throw new IllegalArgumentException("Unsigned numbers cannot be smaller than 0!");
        }
        for (int i = pos + bits - 1; i >= pos; i--) {
            genes.set(i, (number & 1) == 1);
            number = number >> 1;
        }
    }

    /**
     * Sets the given signed number in the specified position using count bits.
     *
     * @param pos Position to set the number. The number range will vary from
     * -2^(bits-1)-1 to +2^(bits-1)-1
     * @param number Number to set.
     * @param bits Number of bits to use for storing.
     */
    public void setSigned(int pos, long number, int bits) {
        if (number < 0) {
            setUnsigned(pos + 1, -number, bits - 1);
            genes.set(pos);
            return;
        }

        setUnsigned(pos + 1, number, bits - 1);
        genes.clear(pos);
    }

    /**
     * Retrives the group of bits as a number, starting at the given position.
     * @param pos Position to start retrieving bits
     * @param bits Number of bits to retrieve.
     * @return An unsigned number, composed by all bits.
     */
    public long getUnsigned(int pos, int bits) {
        long num = 0;

        for (int i = pos; i < pos + bits; i++) {
            num = (num << 1) + (genes.get(i) ? 1 : 0);
        }
        return num;
    }

    /**
     * Retrives the group of bits as a number, starting at the given position.
     * @param pos Position to start retrieving bits
     * @param bits Number of bits to retrieve.
     * @return An unsigned number, composed by all bits. The first bit will be
     * used to define signal.
     */
    public long getSigned(int pos, int bits) {
        long num = getUnsigned(pos + 1, bits - 1);
        return genes.get(pos) ? -num : num;
    }

    /**
     * Sets the given bit to value.
     * @param bit Bit index to set.
     * @param value value to set.
     */
    public void set(int bit, boolean value) {
        genes.set(bit, value);
    }

    /**
     * Gets the given bit value.
     * @param bit Bit index to get.
     * @return The bit avlue.
     */
    public boolean get(int bit) {
        return genes.get(bit);
    }

    /** @return this genome size. */
    public int size() {
        return genes.length();
    }
}

Você também pode gerar um BitGenome aleatório fazendo:
BitGenome genome = BitGenome.createRandom(10);

Onde 10 é o número de bits no genoma.

P

Oi, ViniGodoy!

Gostaria muito q vc postasse por aq.

Desde já agradeço muito.

Abraços

P

ViniGodoy,

Muito Obrigada! :smiley:

Abraços

ViniGodoy

Acho que tenho uma versão mais atual dessa classe com números flutuantes também (float e double).
Se eu tiver, posto por aqui.

ViniGodoy

É, não tenho. Só o que tenho são diversos métodos de cruzamento, mutação, escala e seleção implementados. Como por exemplo, esse aqui:

package sofia.genetic.genome.bit.crossover;

import java.util.HashSet;
import java.util.Set;

import sofia.genetic.genome.bit.BitGenome;
import sofia.genetic.util.Two;

/**
 * Implement a n-point cut crossover. 
 * The genome 0000000 combined with 1111111 with cuts in 2 and 5 will generate two offspring:
 * <p>
 * parent1 - 00|000|00 <br>
 * parent2 - 11|111|11 <br>
 * <p>
 * offspring1 - 0011100
 * offspring2 - 1100011
 */
public class PointCrossover implements BitCrossoverMethod {
    private Set<Integer> cutSet;

    /**
     * Create a new a n-point cut crossover. 
     * The genome 0000000 combined with 1111111 with cuts in 2 and 5 will 
     * generate two offspring:
     * <p>
     * parent1 - 00|000|00 <br>
     * parent2 - 11|111|11 <br>
     * <p>
     * offspring1 - 0011100
     * offspring2 - 1100011
     * 
     * @param number of cuts. Duplicate cuts will be discarded, as well as 
     * indexes outside the genome boundaries.
     */
    public PointCrossover(int... cuts) {
        if (cuts.length == 0) {
            throw new IllegalArgumentException("Provide at least one cut!");
        }
        cutSet = new HashSet<Integer>(cuts.length);
        for (int cut : cuts) {
            cutSet.add(cut);
        }
    }

    public Two<BitGenome> crossover(BitGenome genome1, BitGenome genome2) {
        Two<BitGenome> mixins = new Two<BitGenome>(new BitGenome(genome1.size()),
                new BitGenome(genome2.size()));

        boolean flip = false;

        for (int i = 0; i < genome1.size(); i++) {
            if (cutSet.contains(i)) {
                flip = !flip;
            }

            mixins.getOne().set(i, flip ? genome1.get(i) : genome2.get(i));
            mixins.getTwo().set(i, flip ? genome2.get(i) : genome1.get(i));
        }

        return mixins;
    }
}
Criado 31 de agosto de 2009
Ultima resposta 1 de set. de 2009
Respostas 9
Participantes 4