diff options
| author | mo khan <mo@mokhan.ca> | 2022-04-07 14:53:16 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2022-04-07 14:53:16 -0600 |
| commit | 5be5954f25c723801188b40aca1e62e4b9433378 (patch) | |
| tree | 9dfbbdd66c6af12702e77224cf8b696e7cad8f41 | |
| parent | f38c9a12b571fb5f84019eada3dac8292e003ed5 (diff) | |
build a linked list calculator
| -rw-r--r-- | 2022/04/07/main.rb | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/2022/04/07/main.rb b/2022/04/07/main.rb new file mode 100644 index 0000000..466ac0a --- /dev/null +++ b/2022/04/07/main.rb @@ -0,0 +1,80 @@ +#!/usr/bin/env ruby + +=begin +You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. + +Example: + + Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) + Output: (7 -> 0 -> 8) + + Explanation: 342 + 465 = 807. + +=end + +def assert(x) + assert_equal(true, x) +end + +def assert_equal(x, y) + raise [x, y].inspect unless x == y +end + +class Node + attr_accessor :next + attr_reader :value + + def initialize(value) + @value = value + end + + def equal?(other) + self == other + end + + def eql?(other) + self == other + end + + def ==(other) + self.value == other&.value && self&.next == other&.next + end + + def inspect + "#{value}->#{self.next.inspect}" + end +end + +class Solution + def self.add(left, right) + return left if right.nil? + return right if left.nil? + + total = left.value + right.value + result = Node.new(total % 10) + if total >= 10 + total = total / 10 + result.next = add(add(Node.new(total), left.next), right.next) + else + result.next = add(left.next, right.next) + end + result + end +end + +assert Node.new(2).eql?(Node.new(2)) + +left = Node.new(2) +left.next = Node.new(4) +left.next.next = Node.new(3) + +right = Node.new(5) +right.next = Node.new(6) +right.next.next = Node.new(4) + +expected = Node.new(7) +expected.next = Node.new(0) +expected.next.next = Node.new(8) + +assert_equal(expected, Solution.add(left, right)) +puts "yay!" |
