Skip to content

Commit f63f0df

Browse files
committed
task3 solution (without priority queue)
1 parent b5d84aa commit f63f0df

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

week4/priority-queues/task3/solution.rb

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,3 @@
1-
### Taxicab numbers
2-
3-
# A `taxicab` number is an integer that can be expressed as the sum of two cubes of positive integers in two different ways: `a^3 + b^3 = c^3 + d^3`.
4-
# For example, `1729` is the smallest taxicab number: `9^3 + 10^3 = 1^3 + 12^3`.
5-
# Design an algorithm to find all taxicab numbers with `a`, `b`, `c`, and `d` less than `n`.
6-
7-
# - Version 1: Use time proportional to `(n^2)*log(n)` and space proportional to `n^2`.
8-
# - Version 2: Use time proportional to `(n^2)*log(n)` and space proportional to `n`.
9-
101
def baseline(n)
112
arr = []
123

@@ -26,4 +17,24 @@ def baseline(n)
2617
arr.sort.uniq
2718
end
2819

20+
def solution(n)
21+
# n
22+
numbers = (1...n).map { |i| i**3 }
23+
24+
# n^2
25+
h = {}
26+
numbers.each_with_index do |a, i|
27+
((i + 1)...(n - 1)).each do |j|
28+
b = numbers[j]
29+
s = a + b
30+
h[s] ||= []
31+
h[s] << [a, b]
32+
end
33+
end
34+
35+
h = h.select { |k, v| v.size > 1 }
36+
h.keys
37+
end
38+
2939
p baseline(30)
40+
p solution(30)

0 commit comments

Comments
 (0)