Theory: (mathematical)
Devide 3 by the upper most item value:
3 / 4 = 0.75
now floor that: 0 <- which means, you do not have a Key
you need to get the rest of the integral division though, in case you would've had the key:
3 % 4 = 3
now you repeat that down until you are left with either 1 or 0, determining, whether you've got a flashlight or not
Snippet: (mathematical)
function items(value)
local Key = math.floor(value/4)
local rest = value % 4
local Radio = math.floor(rest/2)
local Flashlight = rest % 2
return Key, Radio, Flashlight
end
items(0) --# returns 0,0,0
items(1) --# returns 0,0,1
items(2) --# returns 0,1,0
items(3) --# returns 0,1,1
items(4) --# returns 1,0,0
items(5) --# returns 1,0,1
items(6) --# returns 1,1,0
items(7) --# returns 1,1,1
Theory: (digital)
When you can use bitwise operations, you might as well determine the existance of a base2 digit by applying a so called 'mask'
Your number in bits: 0b011 being a decimal 3
0b111 would be 7
now with bitwise operations, you can do something like the following
0b001 -- mask for Flashlight
AND
0b011 -- number to check
=
0b001 -- and when this result is the same as the mask, then you have that item
0b010 -- shifting the 1 to mask for the Radio
AND
0b011 -- number to check
=
0b010 -- equals the mask, so you got a radio
0b100 -- mask for Key
AND
0b011
=
0b000 -- does not equal the mask, therefor no Key for you today
This bitwise approach is actually doing exactly the same as the mathematical approach, but when you are able to get the work out into a library(like a bit32 library), you can concentrate more on writing your actual thing, than worrying about the right exponent for each and everything. So the approach using a bit library is much more flexible and extendable
Further
Now the only thing remaining is, do you actually need to do this? Because you might as well just store them as number(allowing you to have multiples of each item) or as bool, to not interchange the formats all the time
Edited by InDieTasten, 16 November 2015 - 08:06 PM.