Commit 5be5954

mo khan <mo@mokhan.ca>
2022-04-07 20:53:16
build a linked list calculator
1 parent f38c9a1
Changed files (1)
2022
04
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!"