-5

可能重复:
Scala 中的斑马拼图

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

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

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

在此处输入图像描述

这是我的代码,

  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)
4

1 回答 1

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
    ))   
于 2012-12-31T10:08:22.273 回答