Logic question

Started by
1 comment, last by Bacterius 9 years, 4 months ago

I am coding the game and I am a bit stuck on how to handle collisions. Here is how it works:

You have three buttons for example A, B, C. A = 1, B = 2, C = 3. If I press ABC, the sum would be 1 + 2 + 3 = 6. After the total calculation I will use total value as a key and fetch the data from the map. Here is were I am a bit stuck. When I do BBB = 6 and ABC = 6 I get a conflict or AAC = 5 and BBA = 5. How do I avoid these collisions. I dont mind rewriting the entire thing but I am pretty sure there are some kind of techniques on handling these kind of problems.

Thanks.

Advertisement

You could maybe do something with bits, Im not sure what it is youre doing, or how the data is being fetched, the resulting values would vary a bit, but they would be unique.

unsigned int but1 = ..., but2= ..., but3= ...;

// shift button into place and OR them together

unsigned int key = (but1 << 16) | (but2 << 8) | but3; // 00000000 00000000 00000000 00000000 = 00000000 button1 button2 button3

A B C = 66051 = 00000000 00000001 00000010 00000011

B B B = 131586 = 00000000 00000010 00000010 00000010

B B A = 131585 = 00000000 00000010 00000010 00000001

A A C = 65795 = 00000000 00000001 00000001 00000011

It seems like bitfields are what you want, but it only seems so, because you need to distinguish order as well, so just recording that a button was clicked is not enough. One easy way to do this is to set A = 0, B = 1, C = 2, keep a "total" variable initialized to zero, and each time you click a button, you multiply the total by 3 before adding the corresponding value to the total. After all buttons are clicked, you add to the total (3^N - 3) / 2 where N is the number of buttons clicked. You can verify collisions are now impossible, and you get the following mapping:

A = 0

B = 1

C = 2

AA = 3

AB = 4

AC = 5

BA = 6

BB = 7

BC = 8

CA = 9

CB = 10

CC = 11

AAA = 12

AAB = 13

AAC = 14

ABA = 15

and so on...

in particular, BBB = 25 and ABC = 17, AAC = 14 and BBA = 24.

This mapping also works for any number of button clicks, i.e. two-button or four-button click combinations will also all have their own unique keys. If you know you will only ever need three-button click combinations, you can just drop the final addition involving N if you want to. This construction also happens to be optimal, producing the smallest possible keys, and also letting you convert the key back to the respective button clicks efficiently, should that be of use to you. Note the keys start from zero, just increment them if you need them to start at one.

(perhaps a "purer" mapping would be to add (3^N - 1) / 2 instead, and let 0 be the key corresponding to "no clicks at all" i.e. N = 0, but that's up to you)

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

This topic is closed to new replies.

Advertisement