dinesman_problem_simple_2.sf 843 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
  4. #
  5. func solve(n, pred) {
  6. gather {
  7. n.permutations { |*candidate|
  8. if (pred.all { |p| p(candidate) }) {
  9. take(candidate)
  10. }
  11. }
  12. }
  13. }
  14. var predicates = [
  15. ->(s) { last(s) != "Baker" },
  16. ->(s) { first(s) != "Cooper" },
  17. ->(s) { (first(s) != "Fletcher") && (last(s) != "Fletcher") },
  18. ->(s) { index(s, "Miller") > index(s, "Cooper") },
  19. ->(s) { abs(index(s, "Smith") - index(s, "Fletcher")) != 1 },
  20. ->(s) { abs(index(s, "Cooper") - index(s, "Fletcher")) != 1 },
  21. ]
  22. var Names = ["Baker", "Cooper", "Fletcher", "Miller", "Smith"]
  23. var solutions = solve(Names, predicates)
  24. solutions.each { .join(', ').say }
  25. assert_eq(solutions, [["Smith", "Cooper", "Baker", "Fletcher", "Miller"]])