2

I have 8 check-boxes, that have values of 1,2,4,16,256,512,1024,4096.

Depending on what is selected depends on what number I am given, ie: 5 = 1 & 4 are selected, 20 = 16 & 4, 528 = 512 & 16

Now I understand how find out what check box's are selected by doing a manual calculation, or creating a map. ie

[
  { number: 1, boxes: [1] }, 
  { number: 2, boxes: [2] },
  { number: 3, boxes: [1,2] },
  { number: 4, boxes: [4] },
  { number: 5, boxes: [4,1] },
  { number: 6, boxes: [4,2] },
  { number: 7, boxes: [4,2,1] }
 ] 

But this isn't what I am looking for.

  • What subject / phrase would you search for to understand this better?
  • In code, how could you receive a list of checkboxes based on the number presented?

ie:

def test() {

   def checkBoxList = getCheckBoxList(1536)
   assert checkBoxList == [1024,512]

  checkBoxList = getCheckBoxList(7)
  assert checkBoxList == [4,2,1]

  //etc
}


def getCheckBoxList(int number) {

    //Magic code -- Returns [] of boxes based on number

}

1 Answers1

0

Started in the next value multiple of 2 which is greater than the parameter and then subtracting other multiples. Works for your case?

def getCheckBoxList(int number) {
  def list = []
  Integer filter = 1

  while(filter < number) { filter *= 2 }

  filter /= 2

  while (filter != 0) {
    if (filter <= number) {
      list << filter
      number -= filter
    }

    filter /= 2
  }

  list
}

assert getCheckBoxList(1536) == [1024,512]
assert getCheckBoxList(7) == [4,2,1]
assert getCheckBoxList(17) == [16, 1]
assert getCheckBoxList(15) == [8, 4, 2, 1]
assert getCheckBoxList(29) == [16, 8, 4, 1]
assert getCheckBoxList(528) == [512, 16]
Will
  • 14,348
  • 1
  • 42
  • 44
  • Many thanks, just what I was looking for, also please see [stackoverflow.com/questions/8447](http://stackoverflow.com/questions/8447/enum-flags-attribute), ultimately this is what I was trying to achieve using enum and bitwise operators. – Antony Jukes Dec 18 '12 at 09:16