gpt4 book ai didi

scala - 字典排列

转载 作者:行者123 更新时间:2023-12-01 07:14:17 27 4
gpt4 key购买 nike

我一直在研究 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com