views:

195

answers:

3

This is a math problem, but I'm sure this must come up in some programming scenarios, at least I hope so, and I was wondering if there was a name for this type of situation:

Suppose I have 7 items in a series. For the sake of this example, let's use days of the week. I would like a user to submit which days of the week they plan to come in the following week. They are presented with a standard series of checkboxes, one for each day of the week.

I would like to store which days they choose in one database field as a single integer.

Obviously, I could assign each day a number, 1 - 7 (leaving 0 out in case the user leaves all choices unchecked). But then I run into problems if one user chooses Monday and Tuesday ( 1 + 2) and another chooses Wednesday (3).

I could also give each day of the week some bizarre unique such that it was impossible for any combination of digits to be identical to any other combination.

My hope is that rather than make up such a series for the second scenario, some numerical property already exists (perhaps the square of each number in the series, etc) that is already well-used and respected. Ideally, this would be so familiar to programming, that deriving the individual digits would take very little overhead of a common programming language (in my case PHP).

Did I just dream this up, or does something like this exist?

+4  A: 

You could use

Monday = 1
Tuesday = 2
Wednesday = 4
Thursday = 8
Friday = 16
Saturday = 32
Sunday = 64

The combinations will be unique.

Then Monday and Tuesday = 3, and Wednesday = 4.

This gives a good explanation of the idee in C#

Enum Flags Attribute

astander
+5  A: 

Use a bitmask - powers of 2.

Monday = 2 ^ 0 = 1
Tuesday = 2 ^ 1 = 2

and so on. Then Monday and Tuesday becomes:

Monday | Tuesday = 3 (or 00000011 in binary)
David M
Oh I see! Not only does this avoid overlap (which makes sense from astander's answer) but expressing the integer in binary actually gives a on/off for each day of the week possible. Wow, maybe I should take a class or something. Thanks!
Anthony
I do believe that I learned this technique in class when I studied computer science way back when. One for those of us who believe education is important and useful.
High Performance Mark
A: 

Back in the days when memory was precious, programmers often went to a lot of trouble to encode settings, parameters, game layouts, and so on as bit sets. Some languages even had bit sets built into them.

I remember once reading a tutorial on bit sets that used them to store board layouts for solving the Eight Queens problem.

Most C programmers had their own little library of bit manipulation macros for just these kinds of problems. See Bit Sets for example. They are still used a lot in code that does direct hardware manipulation -- turning bits on and off in digital I/O for example.

clartaq