how to store pairs of colours in an array?

edited August 2015 in How To...

I'm trying to create an array that can hold pairs of colour values for primary and secondary colours so the program can pick a pair of colours to use for display eg

pink & green, pink & blue, pink & yellow, green & pink, green & blue, blue & yellow etc

I've read up on 2d arrays but cannot figure out how to get this data into one - is this the right way to go about it, I'm a bit lost on this one....

Cheers Rich

Answers

  • edited August 2015

    Yes, 2D arrays would work.

    color[][] colours = new color[10][2]
    
    colours[0][0] = *first color of first pair*;
    colours[0][1] = *second color of first pair*;
    
    colours[1][0] = *first color of second pair*;
    colours[1][1] = *second color of second pair*;
    
    etc.
    
  • Or just 2 arrays (1D)

    not as elegant

    OR go oop / objects

  • edited August 2015

    My propose is to store the color pair as 1 long primitive datatype.
    Of course it's more complicated and needs helper functions in order to insert and extract
    primary & secondary color from the stored long.
    But at least it's 1D array and more cache memory friendly: :P

    // forum.processing.org/two/discussion/12296/
    // how-to-store-pairs-of-colours-in-an-array
    
    // GoToLoop (2015-Aug-30)
    
    static final color RED = #FF0000, GREEN = #008000, BLUE = #0000FF;
    
    static final int QTY = 4;
    final long[] cPairs = new long[QTY];
    long c;
    
    void setup() {
      cPairs[0] = createColorPair(RED, BLUE);
      cPairs[1] = createColorPair(BLUE, RED);
      cPairs[2] = createColorPair(BLUE, GREEN);
      cPairs[3] = createColorPair(GREEN, GREEN);
    
      println(cPairs);
      println();
    
      c = cPairs[0];
      assert getPrimary(c) == RED;
      assert getSecondary(c) == BLUE;
      cPairs[0] = c;
    
      c = cPairs[3];
      assert getPrimary(c) == GREEN;
      assert getSecondary(c) == GREEN;
    
      c = setPrimary(c, BLUE);
      assert getPrimary(c) == BLUE;
      assert getSecondary(c) == GREEN;
    
      c = setSecondary(c, RED);
      assert getPrimary(c) == BLUE;
      assert getSecondary(c) == RED;
      cPairs[3] = c;
    
      println(cPairs);
      exit();
    }
    
    static final long createColorPair(color p, color s) {
      return p & 0xffffffffL | (long) s << 040;
    }
    
    static final long setPrimary(long c, color p) {
      return c & ~0xffffffffL | p & 0xffffffffL;
    }
    
    static final long setSecondary(long c, color s) {
      return c & 0xffffffffL | (long) s << 040;
    }
    
    static final color getPrimary(long c) {
      return (color) c;
    }
    
    static final color getSecondary(long c) {
      return (color) (c >> 040);
    }
    
Sign In or Register to comment.