the blog

Generating Permutations and Combinations

by Carlyn Maw on August 22, 2009, no comments

One of the things I did when playing around with the HL1606 is write a routine that ran through ALL the colors. I mean all 64 possible permutations both my way and Synoptic Labs’ way to compare.  Did I write these out by hand? Um, no.

First of all, how do we know there are 64? If you look at the command byte for the HL1606 there are 6 bits involved in determining color, each of which can be one of two options (0 or 1). Doing the probability math: 2*2*2*2*2*2, 2 to the 6th… or 64.  The other way to think about it is that we have 4 options to chose from: 01, 11, 10, 00 or (right to left) ON, DOWN, UP, OFF.  We pick any one of these options 3 separate times (R, G and B).  4*4*4, 4 to the 3rd or again 64. Whether you think of it as 2 options 6 times or 4 options 3 times we can still simply count up in binary to generate the needed command bytes.

Since I needed to create a predefined array for my purposes I wrote a function that would spit out something serially I could copy and paste:

void loop() {  delay(2000); // time to switch over to serial mode  if (i < 1) { // do it only once  for (b=0; b<64; b ++) {    commandByte = b + B10000000;  // add the latch command    Serial.print("colorArray[");    Serial.print(b, DEC);    Serial.print("] = B");    Serial.print(commandByte, BIN);    Serial.println(";");  }  }  i++; }

Just a heads up, this works because I added the 1 onto the left edge of the command byte by adding the actual value of B10000000 to the variable NOT by trying to tack a “B10” on to it on with Serial.print before. Why not? 63 prints out as 111111, 6 characters, but 23 is 10111, 5 characters.  You can’t just paste numbers to left edge with text and expect the value to be correct when you copy the printout.

Writing your own program is way more time consuming for a non-numeric situation like writing out UP OFF DOWN and ON for the Synoptic Lab style code – In case you don’t remember those lines look like:

  docolor(DOWN, DOWN, UP,128/(2*SPULSE),1);  

I just borrowed Math is Fun‘s permutations and combinations calculator.  They generated the list and with a bit of find and replace magic in BBEdit I got the code I needed.

Oh, and for those of you who are curious and don’t care about having a pre-written array the following function does work.

void playAll() {  int b;    for (b=0; b<64; b ++) {    nextColor = colorArray[b];    nextCommand = nextColor + B10000000; // latch it    doColor2(nextCommand);  } }

Leave a Reply

carlynorama is Stephen Fry proof thanks to caching by WP Super Cache