From cfd4d1447ac86f0358ba4a859894abec349f0244 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Sun, 6 Dec 2020 20:51:20 -0800 Subject: [PATCH] Add a zip_with function. --- spec/util_spec.cr | 29 +++++++++++++++++++++++++++++ src/advent/util.cr | 8 ++++++++ 2 files changed, 37 insertions(+) create mode 100644 spec/util_spec.cr diff --git a/spec/util_spec.cr b/spec/util_spec.cr new file mode 100644 index 0000000..2097efa --- /dev/null +++ b/spec/util_spec.cr @@ -0,0 +1,29 @@ +require "./spec_helper" + +describe Array do + describe "#union" do + it "works with no elements" do + ([] of Set(Int32)).union.should eq(Set(Int32).new) + end + + it "correctly performs a union" do + [Set { 1 }, Set { 2 }, Set {1, 2, 3}].union.should eq(Set { 1,2,3}) + end + end + + describe "#intersect" do + expect_raises(Enumerable::EmptyError) do + ([] of Set(Int32)).intersect + end + + it "correctly performs an intersection" do + [Set {1}, Set {1,2}, Set {1,2,3}].intersect.should eq(Set{1}) + end + end + + describe "#zip_with" do + it "performs as expected" do + [1,2,3].zip_with([2,3,4]) { |l,r| l*r }.should eq([2,6,12]) + end + end +end diff --git a/src/advent/util.cr b/src/advent/util.cr index 3953353..e49183a 100644 --- a/src/advent/util.cr +++ b/src/advent/util.cr @@ -1,4 +1,12 @@ class Array(T) + def zip_with(other : Array(R), &block : T, R -> U) forall R, U + dest = [] of U + zip(other) do |l, r| + dest << yield l, r + end + dest + end + def union reduce(T.new) do |l, r| l | r