scala - 字典排列

标签 scala functional-programming permutation

我一直在研究 Euler problem 24 项目,并在 Scala(无论如何我试图解决它的语言)中遇到了一个解决方案。我本来打算自己做,但现在我一头雾水地想知道这个解决方案是如何工作的。

问题:

The lexicographic permutations of 0, 1 and 2 are:

012, 021, 102, 120, 201, and 210.

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?



解决方案:
def permutations(s : String) : Seq[String] =
{
  if(s.size == 1)
    Seq(s);
  else
    s.flatMap(x => permutations(s.filterNot(_ == x)).map(x +));
}

val ans = permutations("0123456789")(1000000 - 1).toLong;

println(ans);

最佳答案

这在 Scala 中是微不足道的:

"0123456789".permutations.drop(999999).next

关于scala - 字典排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17991483/

相关文章:

scala - scala.Equals trait 中的 canEqual()

function - PL/SQL 将函数作为参数传递

haskell - 在 Haskell 中,为什么非穷举模式不是编译时错误?

scala - 如何在 Mockito 和 Scala 中使用隐式匹配器 stub 方法调用

scala - 如何以编程方式调用 Scala 编译器?

scala - Play Framework 2.5 中抽象类和对象的依赖注入(inject)

haskell - 究竟是什么使类型系统保持一致?

sql - 不同于排列的 PostgreSQL 组合

python - 生成列表中每个单词的所有组合和排列

algorithm - 用 [1..10] 中的数字填充 10 个位置的方法,使得第 i 个位置的数字的值比 1.. 到第 i 个位置的最大值大 1