The date "wrapper" in the deduction of months

What is the mathematical way to say 1 - 1 = 12 for monthly calculation? Adding is easy, 12 + 1% 12 = 1, but subtracting introduces 0, stuffing things.

My actual requirement is x = x + d, where x must always be from 1 to 12 before and after the summation, and d is any unsigned integer.

+3
source share
4 answers

I would work internally with a 0-month (0-11), adding up one for external consumption only (output, another calling method, expecting 1-12, etc.), so you can just as easily wrap backward as wrap forward .

>>> for i in range(15):
...  print '%d + 1 => %d' % (i, (i+1)%12)
...
0 + 1 => 1
1 + 1 => 2
2 + 1 => 3
3 + 1 => 4
4 + 1 => 5
5 + 1 => 6
6 + 1 => 7
7 + 1 => 8
8 + 1 => 9
9 + 1 => 10
10 + 1 => 11
11 + 1 => 0
12 + 1 => 1
13 + 1 => 2
14 + 1 => 3
>>> for i in range(15):
...  print '%d - 1 => %d' % (i, (i-1)%12)
...
0 - 1 => 11
1 - 1 => 0
2 - 1 => 1
3 - 1 => 2
4 - 1 => 3
5 - 1 => 4
6 - 1 => 5
7 - 1 => 6
8 - 1 => 7
9 - 1 => 8
10 - 1 => 9
11 - 1 => 10
12 - 1 => 11
13 - 1 => 0
14 - 1 => 1
+2
source

Assuming x and y are both in the range 1-12:

((x - y + 11) % 12) + 1

To abort this:

// Range = [0, 22]
x - y + 11

// Range = [0, 11]
(x - y + 11) % 12

// Range = [1, 12]
((x - y + 11) % 12) + 1
+3
source

, (11 + 1)% 12 = 0. :

x % 12 + 1

:

norm(x) = ((x - 1) % 12) + 1

,

norm(x + 1) = (((x + 1) - 1) % 12 + 1

norm(x + 1) = (x) % 12 + 1
0

% () 0.. (N-1) x% N. , 1..N( N = 12), y x :

(x + y - 1) % 12 + 1

y 1,

x % 12 + 1

. , , ( ) . , , , 1..N, , y N , (N - y) N. y ( ), :

(x + (12 - (y % 12) - 1) % 12 + 1

, .

0
source

Source: https://habr.com/ru/post/1699349/


All Articles