爱因斯坦在Scala中的难题

时间:2012-12-31 06:07:04

标签: python scala

  

可能重复:
  Zebra puzzle in Scala

过去两天这个问题一直困扰着我。

解决此类谜题的Scala方法是什么?我试图在下面的Scala中实现python中显示的嵌套for循环,但它只是不起作用。循环已经在第二个约束上给出0结果。这可能是因为我是Scala的新手,并错过了一些细节。

如果有人有任何想法,请帮助我的可怜的灵魂,谢谢。

enter image description here

继承我的代码,

  val houses = List(1, 2, 3, 4, 5)
  val orderings = houses.permutations
  val List(first, _, middle, _, _) = houses

  def imright(h1: Int, h2: Int) = h1 - h2 == 1

  def nextto(h1: Int, h2: Int) = math.abs(h1 - h2) == 1

  for (List(red, green, ivory, yellow, blue) <- orderings if imright(green, ivory))
    for(List(englishman, spaniard, ukrainian, japanese, norwegian) <- orderings;
      if englishman == red; 
      if norwegian == first) println(orderings.length)

1 个答案:

答案 0 :(得分:0)

  val houses = List(1, 2, 3, 4, 5)
  val orderings = houses.permutations.toList
  val List(first, _, middle, _, _) = houses

  def imright(h1: Int, h2: Int) = h1 - h2 == 1

  def nextto(h1: Int, h2: Int) = math.abs(h1 - h2) == 1

  for (List(red, green, ivory, yellow, blue) <- orderings if imright(green, ivory))
    for(List(englishman, spaniard, ukranian, japanese, norwegian) <- orderings
      if (englishman == red)
    ) println(Map(
      "englishman" -> englishman
      ,"red" -> red
      ,"norwegian" -> norwegian
      ,"first" -> first
    ))