相关疑难解决方法(0)

推广"下一个排列"功能

下面是一个函数的实现,它返回字典上的下一个排列.这在Euler问题中很有用.

它写的是在Strings上工作(我需要它).但是,它应该适用于任何可比较值的索引序列.我已经尝试通过将两次出现的String更改为IndexedSeq [Char]来推广它,但这会出错:

euler-lib.scala:26: error: type mismatch;
 found   : IndexedSeq[Char]
 required: String
      ((n.slice(pivot+1, successor):+ n(pivot)) + n.drop(successor+1)).reverse
                                                        ^
Run Code Online (Sandbox Code Playgroud)

为什么类型推断器在那里推断出String?我似乎没有做任何需要字符串的操作?

并且我可以通过使用IndexedSeq ["可比较的东西"]使其更加通用吗?我没能做到这一点.

  // return the lexographically next permutation to the one passed as a parameter
  // pseudo-code from an article on StackOverflow
  def nextPermutation(n:String):String = {
  // 1. scan the array from right-to-left
  //1.1. if the current element is less than its right-hand neighbor,
  //    call the current element the pivot,
  //    and stop scanning
  // (We scan left-to-right and return …
Run Code Online (Sandbox Code Playgroud)

generics types scala permutation

5
推荐指数
1
解决办法
1052
查看次数

生成1,000,000个随机排列的样本

我正在处理大量的整数排列.每个排列中的元素数量为K.元素大小为1个字节.我需要生成N个唯一的随机排列.
约束:K <= 144,N <= 1,000,000.

我想出了以下简单的算法:

  1. 生成N个随机排列的列表.将所有排列存储在RAM中.
  2. 对列表进行排序并删除所有重复项(如果有).重复数量相对较少.
  3. 如果有任何重复项,请将随机排列添加到列表中,直到有N个排列并返回到步骤2.

有一个更好的方法吗?特别是,有没有办法不将所有排列存储在RAM中(在生成时将它们写在磁盘上)?

编辑:最后,需要按顺序访问生成的排列(逐个访问,不需要随机访问).RAM是更关键的因素(我宁愿不在RAM中同时存储所有排列).

language-agnostic algorithm permutation combinatorics random-sample

3
推荐指数
2
解决办法
1400
查看次数