开发者

Simple number pattern to store combinations as a unique sum

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开发者_StackOverflow社区 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?


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)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜