-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT-2.rb
More file actions
92 lines (77 loc) · 1.75 KB
/
T-2.rb
File metadata and controls
92 lines (77 loc) · 1.75 KB
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
82
83
84
85
86
87
88
89
90
91
92
# probably slow
def solution(a)
s = 0
a.each_with_index { |v, i|
s += v * (-2)**i
}
s = -s
x = 0xAAAAAAAA
r = (s + x) ^ x
r = ("%b" % r).reverse.split(//).map { |b| b.to_i }
r == [0] ? [] : r
end
# one more optimization, but still slow
def solution(a)
s = 0
e = 1
a.each { |v|
s += v * e
e *= -2
}
s = -s
x = 0xAAAAAAAA
r = (s + x) ^ x
r = ("%b" % r).reverse.split(//).map { |b| b.to_i }
r == [0] ? [] : r
end
# final solution
def solution(a)
# 0 - a
table = {
-2 => { bit: 0, carry: 1},
-1 => { bit: 1, carry: 1},
0 => { bit: 0, carry: 0},
1 => { bit: 1, carry: 0},
2 => { bit: 0, carry: -1},
3 => { bit: 1, carry: -1}
}
carry = 0
(0..a.count).each { |i|
number = 0 + (a[i] || 0) * (-1) + carry
a[i] = table[number][:bit]
carry = table[number][:carry]
}
# remove trailing zeros
last_one = a.rindex(1)
if last_one
a = a[0..last_one]
else
a = []
end
a
end
require "minitest/autorun"
require "byebug"
require "timeout"
# byebug
# solution([1])
# exit
class TestSolution < Minitest::Test
def test_default
assert_equal [1, 1, 0, 1], solution([1, 0, 0, 1, 1])
assert_equal [1, 1, 0, 1, 0, 1, 1], solution([1, 0, 0, 1, 1, 1] )
assert_equal [1, 0, 0, 1, 1], solution([1, 1, 0, 1])
assert_equal [1, 0, 0, 1, 1, 1], solution([1, 1, 0, 1, 0, 1, 1])
end
def test_simple
assert_equal [1, 1], solution([1])
end
def test_small
assert_equal [], solution([])
end
def test_large
Timeout::timeout(6) {
assert_equal [], solution([0] * 100_000 )
}
end
end