Write initial version of the library.

This commit is contained in:
2020-12-05 15:32:50 -08:00
commit a8363ae168
13 changed files with 325 additions and 0 deletions

1
spec/advent_spec.cr Normal file
View File

@@ -0,0 +1 @@
require "./spec_helper"

26
spec/graph_spec.cr Normal file
View File

@@ -0,0 +1,26 @@
require "./spec_helper"
describe Graph do
describe "#find_path" do
it "reports no paths in a graph with no edges" do
gr = Graph(String).new
elems = ["a", "b", "c", "d"]
elems.each &->gr.add_node(String)
elems.each do |elem|
elems.each do |other|
next if elem == other
gr.find_path(elem, other).should be_nil
end
end
end
it "computes the shortest path" do
gr = Graph(String).new
[{"a", "b", 1}, {"a", "c", 1}, {"c", "b", 1}, {"b", "d", 1}].each do |t|
from, to, cost = t
gr.add_edge(from, to, cost)
end
gr.find_path("a", "d").should eq({["a", "b", "d"], 2})
end
end
end

44
spec/heap_spec.cr Normal file
View File

@@ -0,0 +1,44 @@
require "./spec_helper"
describe Array do
describe "#heapify" do
it "preserves the elements in the array" do
a = Array(Int32).new(20) { rand(10) }
a.sort.should eq(a.clone.heapify!.sort)
end
it "creates an array with proper ordering" do
a = Array(Int32).new(20) { rand(10) }
a.heapify!
a.is_heap?.should be_true
end
it "maintains heap property while popping" do
a = Array(Int32).new(20) { rand(10) }
a.heapify!
20.times do |i|
a.heap_pop
a.is_heap?.should be_true
end
end
it "maintains heap property while pushing" do
a = [] of Int32
20.times do
a.heap_push(rand 10)
a.is_heap?.should be_true
end
end
it "pops numbers in descending order" do
a = Array(Int32).new(20) { rand(10) }
a.heapify!
last = Int32::MAX
20.times do
popped = a.heap_pop
popped.should be <= last
last = popped
end
end
end
end

18
spec/knapsack_spec.cr Normal file
View File

@@ -0,0 +1,18 @@
describe Array do
describe "#knapsack" do
it "works with costs of one" do
ans = [1,2,3,4,5,6].shuffle.knapsack(3) do |i|
{1, i}
end
ans[1].sort!
ans.should eq({15, [4,5,6]})
end
it "works in the non-greedy case" do
ans = [{2, 2}, {2, 2}, {3, 3}].shuffle.knapsack(4) do |i|
i
end
ans.should eq({4, [{2,2},{2,2}]})
end
end
end

2
spec/spec_helper.cr Normal file
View File

@@ -0,0 +1,2 @@
require "spec"
require "../src/advent"