Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Test.java
- public class Test {
- // the only purpose of this class is to have a main
- public static void main(String args[]) throws Exception {
- // execution starts here
- // create a target
- BitSequence target = new BitSequence(new int[]{1,1,1,1,1,1});
- System.out.println(target); //check
- BitSequence bs; // declare, do not assign, a BitSequence
- do { // repearedly..
- bs=new BitSequence(); // make a random BitSequence
- System.out.println(bs); // check
- } while (bs.match(target)!=6); // until a perfect match
- }
- }
- // BitSequence.java
- import java.util.BitSet;
- // This class models a sequence of bits as a 'chromosome'
- public class BitSequence {
- static final int bitLength=6; // how many bits - a constant
- static int lastID=1; // track ID of last one made
- BitSet bits=new BitSet(bitLength); // the class wraps a BitSet
- int id; // non-static field, for ID
- BitSequence()
- { // constructor - make a random sequence
- for(int i=0; i<bitLength; i++) // for each bit position
- if (Math.random()>0.5) // 50 50 chance
- bits.set(i); // make it a 1
- else bits.clear(i); // else 0
- id=lastID; // set id
- lastID++; // and move on
- }
- // overloaded constructor
- // make a BitSequence from an int array
- BitSequence (int[] values) // we do not check the length of values
- {
- for(int i=0; i<bitLength; i++) // go through array
- if (values[i]==1)
- bits.set(i); // and set
- else bits.clear(i); // or clear
- id=lastID;
- lastID++;
- }
- int match(BitSequence other) // count matches between this one and another
- {
- int matchCount=0;
- for (int p=bitLength-1; p>-1; p--) // for each bit position
- if (bits.get(p)==other.bits.get(p)) // teh .get returns a boolean
- matchCount++;
- return matchCount;
- }
- public String toString() // overload Object's toString
- { // so we can print a BitSequence
- StringBuffer sb = new StringBuffer(); // not a String, which is immutable
- sb.append("ID "+id+" : "); // start with the id
- for (int p=bitLength-1; p>-1; p--)
- {
- if (bits.get(p)) // true or false
- sb.append(" 1");
- else sb.append(" 0");
- }
- return sb.toString(); // convert to String
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment