I want to track a series of scored questions in a single number (the total score). Is that possible? and how?
For example, I have 30 questions with either 3 or 2 choices. For any given question, the user makes a selection and the score is incremented/decremented. Simple addition and subtraction is enough for that, but I want to also be able to go back and determine what they answered for any question.
My first thought is that this is some checksum operation or using some modula/shift operations (masking). So there could be a number of inputs such as the choice, question number, user number, etc.
Update: removed int preference as its unreasonable and lowered the number of questions.
4
An int
represents a fixed number of bits (usually 32 or 64). This is a measure of information content; it is fundamentally impossible to store more than this number of yes/no decisions in it. With three-way decisions the arithmetic becomes slightly more involved because they represent fractional numbers of bits (two three-way questions contain slightly more information than three two-way questions), but the principle remains.
Therefore using scalar values this way is a bad idea. It’s fragile (as soon as your questionnaire grows above the magic number of steps, it breaks), and even while it works, it’s expensive to encode and decode the information you actually want from the value it’s stored in. The question therefore becomes: Why do you want to use an int
? Are you sure structured data of some kind aren’t an easier and better choice?
1
You can store the value as a number if you have a datatype that can represent more than choices
count
possible values. In the case of 340, this is the number 12,157,665,459,056,928,801 which is just under 64 bits. So, you could hypothetically store this in a Unit64
(docs).
This isn’t a good idea.
-
As soon as you add another question, you will overflow this datatype. That will make life very difficult for refactoring.
-
You’ve got something that isn’t quite binary. This makes a mess of trying to decode it with binary operators. You can do it, but its very ugly.
-
If anything changes (you remove a question) it becomes very fragile. It is easy to break this.
These things combined should firmly point you in the direction of a list of three value enums which can then be serialized. Don’t worry about a specific number. Make it a nice structure that you can work from and then convert that into however you want to transmit it. When storing it in a database or the like, store it as a nice structure (not a big number).
Trying to pack things into bits doesn’t make sense anymore. Memory is cheap. Its easier to transmit a 40 character long string that contains [ynm]
that you an work with – clean code that you can reason about without getting a headache.
0