Junk

Junk Commit Details

Date:2019-03-22 07:37:47 (4 months 1 day ago)
Author:Nicola Fontana
Branch:master
Commit:3d7a5af8ee06e80497aae1f916de9eaed8de1319
Parents: f7e26d7bc73a10d35d4b0d4ce98a359a46c0934c
Message:operators: first implementation

Changes:
Alua/operators.lua (full)

File differences

lua/operators.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
-- Implement the four basic operations *without* using + or -.
-- It works only with positive integers.
function inc_digit(d)
return ({ [0] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 })[tonumber(d)]
end
function dec_digit(d)
return ({ [0] = 9, 0, 1, 2, 3, 4, 5, 6, 7, 8 })[tonumber(d)]
end
function inc(n)
local s = tostring(n):reverse()
local t = {}
local r = true
for l in s:gmatch('.') do
if r then
l = inc_digit(tonumber(l))
r = l == 0
end
table.insert(t, l)
end
if r then
table.insert(t, 1)
end
return tonumber(table.concat(t):reverse())
end
function dec(n)
local s = tostring(n):reverse()
local t = {}
local r = true
for l in s:gmatch('.') do
if r then
l = dec_digit(tonumber(l))
r = l == 9
end
table.insert(t, l)
end
return tonumber(table.concat(t):reverse())
end
function add(a, b)
return b == 0 and a or add(inc(a), dec(b))
end
function sub(a, b)
return b == 0 and a or sub(dec(a), dec(b))
end
function mul(a, b)
return b == 0 and 0 or add(a, mul(a, dec(b)))
end
function div(a, b)
return b > a and 0 or inc(div(sub(a, b), b))
end
assert(add( 0, 0) == 0)
assert(add(10, 0) == 10)
assert(add( 0, 10) == 10)
assert(add(81, 19) == 100)
assert(add(82, 19) == 101)
assert(sub( 0, 0) == 0)
assert(sub( 10, 10) == 0)
assert(sub( 99, 99) == 0)
assert(sub( 10, 1) == 9)
assert(sub(101, 2) == 99)
assert(mul( 0, 0) == 0)
assert(mul(99, 0) == 0)
assert(mul(99, 1) == 99)
assert(mul( 7, 3) == 21)
assert(mul(11, 13) == 143)
assert(div( 0, 99) == 0)
assert(div( 11, 12) == 0)
assert(div( 99, 1) == 99)
assert(div(143, 13) == 11)
assert(div(143, 11) == 13)

Archive Download the corresponding diff file

Branches