Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
89
Task/Balanced-ternary/11l/balanced-ternary.11l
Normal file
89
Task/Balanced-ternary/11l/balanced-ternary.11l
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
T BalancedTernary
|
||||
. -:str2dig = [‘+’ = 1, ‘-’ = -1, ‘0’ = 0]
|
||||
. -:dig2str = [1 = ‘+’, -1 = ‘-’, 0 = ‘0’]
|
||||
. -:table = [(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)]
|
||||
|
||||
[Int] digits
|
||||
|
||||
F (inp)
|
||||
I all(inp.map(d -> d C (0, 1, -1)))
|
||||
.digits = copy(inp)
|
||||
E
|
||||
X ValueError(‘BalancedTernary: Wrong input digits.’)
|
||||
|
||||
F :from_str(inp)
|
||||
R BalancedTernary(reversed(inp).map(c -> .:str2dig[c]))
|
||||
|
||||
. F :int2ternary(n)
|
||||
I n == 0
|
||||
R [Int]()
|
||||
V n3 = ((n % 3) + 3) % 3
|
||||
I n3 == 0 {R [0] [+] .:int2ternary(n -I/ 3)}
|
||||
I n3 == 1 {R [1] [+] .:int2ternary(n -I/ 3)}
|
||||
I n3 == 2 {R [-1] [+] .:int2ternary((n + 1) -I/ 3)}
|
||||
X RuntimeError(‘’)
|
||||
|
||||
F :from_int(inp)
|
||||
R BalancedTernary(.:int2ternary(inp))
|
||||
|
||||
F to_int()
|
||||
R reversed(.digits).reduce(0, (y, x) -> x + 3 * y)
|
||||
|
||||
F String()
|
||||
I .digits.empty
|
||||
R ‘0’
|
||||
R reversed(.digits).map(d -> .:dig2str[d]).join(‘’)
|
||||
|
||||
. F :neg(digs)
|
||||
R digs.map(d -> -d)
|
||||
|
||||
F -()
|
||||
R BalancedTernary(.:neg(.digits))
|
||||
|
||||
. F :add(a, b, =c = 0)
|
||||
I !(!a.empty & !b.empty)
|
||||
I c == 0
|
||||
R I !a.empty {a} E b
|
||||
E
|
||||
R .:add([c], I !a.empty {a} E b)
|
||||
E
|
||||
(V d, c) = .:table[3 + (I !a.empty {a[0]} E 0) + (I !b.empty {b[0]} E 0) + c]
|
||||
V res = .:add(a[1..], b[1..], c)
|
||||
I !res.empty | d != 0
|
||||
R [d] [+] res
|
||||
E
|
||||
R res
|
||||
|
||||
F +(b)
|
||||
R BalancedTernary(.:add(.digits, b.digits))
|
||||
|
||||
F -(b)
|
||||
R (.) + (-b)
|
||||
|
||||
F *(b)
|
||||
F _mul([Int] a, b) -> [Int]
|
||||
I !(!a.empty & !b.empty)
|
||||
R [Int]()
|
||||
E
|
||||
[Int] x
|
||||
I a[0] == -1 {x = .:neg(b)}
|
||||
E I a[0] == 0 {}
|
||||
E I a[0] == 1 {x = b}
|
||||
E
|
||||
assert(0B)
|
||||
V y = [0] [+] @_mul(a[1..], b)
|
||||
R .:add(x, y)
|
||||
|
||||
R BalancedTernary(_mul(.digits, b.digits))
|
||||
|
||||
V a = BalancedTernary.from_str(‘+-0++0+’)
|
||||
print(‘a: ’a.to_int()‘ ’a)
|
||||
|
||||
V b = BalancedTernary.from_int(-436)
|
||||
print(‘b: ’b.to_int()‘ ’b)
|
||||
|
||||
V c = BalancedTernary.from_str(‘+-++-’)
|
||||
print(‘c: ’c.to_int()‘ ’c)
|
||||
|
||||
V r = a * (b - c)
|
||||
print(‘a * (b - c): ’r.to_int()‘ ’r)
|
||||
Loading…
Add table
Add a link
Reference in a new issue