clux / magic-forest

CPU bound benchmarking of languages using the magic forest problem

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

new language: crystal

davidhyman opened this issue · comments

Just an idea for a rainy day

https://crystal-lang.org

It's like ruby but compiled.

i was literally just trying that wtf

current sketch:

#!/usr/bin/env crystal

class Forest
  getter goats : Int32
  getter wolves : Int32
  getter lions : Int32
  def initialize(goats : Int32, wolves : Int32, lions : Int32)
    @goats = goats
    @wolves = wolves
    @lions = lions
  end

  def is_stable : Bool
    @goats == 0 && (@lions == 0 || @wolves == 0) || (@lions == 0 && @wolves == 0)
  end

  def is_valid : Bool
    @goats >= 0 && @lions >= 0 && @wolves >= 0
  end

  def ==(rhs : Forest) : Bool
    @goats == rhs.goats && @wolves == rhs.wolves && @lions == rhs.lions
  end
  def to_s
    "#{goats} #{wolves} #{lions}"
  end
  def <=>(rhs : Forest)
    if @goats != rhs.goats
      @goats - rhs.goats
    end
    if @wolves != rhs.wolves
      @wolves - rhs.wolves
    end
    if @lions != rhs.lions
      @lions - rhs.lions
    end
    0
  end
end

def mutate(forests : Array(Forest))
  forests.flat_map {|f|
    [
      Forest.new(f.goats - 1, f.wolves - 1, f.lions + 1),
      Forest.new(f.goats - 1, f.wolves + 1, f.lions - 1),
      Forest.new(f.goats + 1, f.wolves - 1, f.lions - 1)
    ]
  }.select(&.is_valid).sort {|x, y| x <=> y }.uniq
end

def solve(f : Forest)
  forests = [f]
  until forests.empty? || forests.any? &.is_stable
    forests = mutate(forests)
  end
  forests.select(&.is_stable)
end

initial = Forest.new(ARGV[0].to_i, ARGV[1].to_i, ARGV[2].to_i)
puts "Initial: #{initial.inspect}"
ss = solve(initial)
puts ss.size
#ss.each {|s| puts "Solution: #{s.inspect}" }