waltermilner

Untitled

Apr 9th, 2017
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1. //Test.java
  2. public class Test {
  3. // the only purpose of this class is to have a main
  4.   public static void main(String args[]) throws Exception {
  5.     // execution starts here
  6.     // create a target
  7.     BitSequence target = new BitSequence(new int[]{1,1,1,1,1,1});
  8.     System.out.println(target); //check
  9.     BitSequence bs; // declare, do not assign, a BitSequence
  10.     do { // repearedly..
  11.       bs=new BitSequence(); // make a random BitSequence
  12.       System.out.println(bs); // check
  13.     } while (bs.match(target)!=6); // until a perfect match
  14.   }
  15.  
  16. }
  17.  
  18. // BitSequence.java
  19. import java.util.BitSet;
  20.  
  21. // This class models a sequence of bits as a 'chromosome'
  22.  
  23. public class BitSequence {
  24. static final int bitLength=6; // how many bits - a constant
  25. static int lastID=1; // track ID of last one made
  26. BitSet bits=new BitSet(bitLength); // the class wraps a BitSet
  27. int id; // non-static field, for ID
  28.  
  29. BitSequence()
  30. { // constructor - make a random sequence
  31.   for(int i=0; i<bitLength; i++) // for each bit position
  32.     if (Math.random()>0.5) // 50 50 chance
  33.       bits.set(i); // make it a 1
  34.     else bits.clear(i); // else 0
  35.   id=lastID; // set id
  36.   lastID++; // and move on
  37. }
  38.  
  39. // overloaded constructor
  40. // make a BitSequence from an int array
  41. BitSequence (int[] values) // we do not check the length of values
  42. {
  43.   for(int i=0; i<bitLength; i++) // go through array
  44.     if (values[i]==1)
  45.       bits.set(i); // and set
  46.     else bits.clear(i); // or clear
  47.   id=lastID;
  48.   lastID++;
  49. }
  50.  
  51. int match(BitSequence other) // count matches between this one and another
  52. {
  53.   int matchCount=0;
  54.   for (int p=bitLength-1; p>-1; p--) // for each bit position
  55.     if (bits.get(p)==other.bits.get(p)) // teh .get returns a boolean
  56.       matchCount++;
  57.   return matchCount;
  58. }
  59.  
  60. public String toString() // overload Object's toString
  61. {   // so we can print a BitSequence
  62.   StringBuffer sb = new StringBuffer(); // not a String, which is immutable
  63.   sb.append("ID "+id+" : "); // start with the id
  64.   for (int p=bitLength-1; p>-1; p--)
  65.   {
  66.     if (bits.get(p)) // true or false
  67.     sb.append(" 1");
  68.     else sb.append(" 0");
  69.   }
  70.   return sb.toString(); // convert to String
  71.  
  72. }
  73.  
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment