Skip to content

Commit f6463ad

Browse files
committed
dgr and dgs
1 parent ef1c44a commit f6463ad

File tree

4 files changed

+83
-5
lines changed

4 files changed

+83
-5
lines changed

loda/lang/operation.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,13 @@ class Type(Enum):
6767
BAN = 21 # bitwise and
6868
BOR = 22 # bitwise or
6969
BXO = 23 # bitwise xor
70-
LPB = 24 # loop begin
71-
LPE = 25 # loop end
72-
CLR = 26 # clear
73-
SEQ = 27 # sequence
74-
DBG = 28 # debug
70+
DGS = 24 # digit sum
71+
DGR = 25 # digital root
72+
LPB = 26 # loop begin
73+
LPE = 27 # loop end
74+
CLR = 28 # clear
75+
SEQ = 29 # sequence
76+
DBG = 30 # debug
7577

7678
type: Type
7779
"""Type of this operation."""

loda/runtime/operations.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,30 @@ def bxo(a, b):
212212
return a ^ b
213213

214214

215+
def dgs(a, b):
216+
"""Digit sum in base b."""
217+
if a is None or b is None or b < 2:
218+
return None
219+
sign = -1 if a < 0 else 1
220+
aa = abs(a)
221+
r = 0
222+
while aa > 0:
223+
r += aa % b
224+
aa //= b
225+
return sign * r
226+
227+
228+
def dgr(a, b):
229+
"""Digital root in base b."""
230+
if a is None or b is None or b < 2:
231+
return None
232+
if a == 0:
233+
return 0
234+
sign = -1 if a < 0 else 1
235+
aa = abs(a)
236+
return sign * (1 + ((aa - 1) % (b - 1)))
237+
238+
215239
def exec_arithmetic(t: Operation.Type, a, b):
216240
"""Execute an arithmetic operation."""
217241
if t == Operation.Type.MOV:
@@ -258,5 +282,9 @@ def exec_arithmetic(t: Operation.Type, a, b):
258282
return bor(a, b)
259283
elif t == Operation.Type.BXO:
260284
return bxo(a, b)
285+
elif t == Operation.Type.DGS:
286+
return dgs(a, b)
287+
elif t == Operation.Type.DGR:
288+
return dgr(a, b)
261289
else:
262290
raise ValueError("operation type not arithmetic: {}".format(t))

tests/operations/dgr.csv

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Op1,Op2,Result
2+
5,10,5
3+
15,10,6
4+
125,10,8
5+
1235,10,2
6+
12345,10,6
7+
-5,10,-5
8+
-15,10,-6
9+
-125,10,-8
10+
-1235,10,-2
11+
-12345,10,-6
12+
1,2,1
13+
3,2,1
14+
7,2,1
15+
15,2,1
16+
31,2,1
17+
-1,2,-1
18+
-3,2,-1
19+
-7,2,-1
20+
-15,2,-1
21+
-31,2,-1
22+
19,3,1
23+
18446744073709551615,2,1
24+
18446744073709551615,4,3

tests/operations/dgs.csv

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Op1,Op2,Result
2+
5,10,5
3+
15,10,6
4+
125,10,8
5+
1235,10,11
6+
12345,10,15
7+
-5,10,-5
8+
-15,10,-6
9+
-125,10,-8
10+
-1235,10,-11
11+
-12345,10,-15
12+
1,2,1
13+
3,2,2
14+
7,2,3
15+
15,2,4
16+
31,2,5
17+
-1,2,-1
18+
-3,2,-2
19+
-7,2,-3
20+
-15,2,-4
21+
-31,2,-5
22+
19,3,3
23+
18446744073709551615,2,64
24+
18446744073709551615,4,96

0 commit comments

Comments
 (0)