Skip to content

Instantly share code, notes, and snippets.

@Vaguery
Last active November 16, 2017 20:56
Show Gist options
  • Save Vaguery/7ad43893542dcf9b3bbae62e11903d6e to your computer and use it in GitHub Desktop.
Save Vaguery/7ad43893542dcf9b3bbae62e11903d6e to your computer and use it in GitHub Desktop.
Imperative code to investigate constraint satisfaction
@varnames = (0...9).collect {|i| "x#{i}".intern}
def manhattan_distance(p1,p2)
(p1[0]-p2[0]).abs + (p1[1]-p2[1]).abs
end
def assignment_from_permutation(permutation,pos)
h = Hash.new
permutation.each_with_index do |i,idx|
h[@varnames[i]] = pos[idx]
end
return h
end
def observed_distances(assignment)
h = Hash.new
assignment.keys.combination(2).each do |p1,p2|
h[[p1,p2].sort] = manhattan_distance(assignment[p1],assignment[p2])
end
return h
end
def assignment_errors(assignment,target)
observed = observed_distances(assignment)
diff = Hash.new
target.keys.each do |k|
diff[k] = (observed[k] - target[k]).abs
end
return diff
end
def satisfy_constraints?(assignment,target)
distances = observed_distances(assignment)
target.keys.each do |k|
return false if target[k] != distances[k]
end
return true
end
@positions = (0...3).to_a.repeated_permutation(2).to_a
@all_clues = observed_distances(
assignment_from_permutation((0...9).to_a,@positions))
File.open("./many_counts.csv", "w+") do |f|
f.sync = true
1000.times do |trial|
p trial
cluefulness = rand(35) + 1
some_clues = @all_clues.to_a.sample(cluefulness).to_h
answers = 0
(0...9).to_a.permutation(9).each_with_index do |perm,idx|
assignment = assignment_from_permutation(perm,@positions)
answers += 1 if satisfy_constraints?(assignment,some_clues)
end
f.write "#{cluefulness},#{answers},#{some_clues.inspect}\n"
f.flush
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment