I am working on online exam application,at the examine Login Question are displayed with 4 or 6 options. Let's take 4 options a b c d, if user select a then the value is 1 if b them value 2 if c then value 4 if d then value 8 if e value 16 if f then value 32:
a -> 1
b -> 2
c -> 4
d -> 8
e -> 16
f -> 32
User may choose multiple options, let suppose user choose a and b then answer is 1 + 2 == 3 three is right answer or user choose a d then 1 + 8 == 9 is the correct answer.
what is the logic to break down 9 into 1, 8 OR 11 into 1, 2, 8 or 35 into 1, 2, 32?
Bitwise operation seems like the way too go.
Since you tagged with Angular, I'll go with a Javascript solution :
function breakdown(input) {
var values = [1, 2, 4, 8, 16, 32];
var checked = [];
for (v of values) {
if (!!(input & v)) checked.push(v);
}
return checked;
}
Test cases:
breakdown(9)
> [1, 8]
breakdown(11)
> [1, 2, 8]
breakdown(35)
> [1, 2, 32]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With