如何使下面的代码在保持Scala中的函数样式的同时,针对较大的'n'值运行? Seq.fill(n)(math.pow(Random.nextFloat,2)+math.pow(Random.nextFloat,2)).filter(p>如果使用迭代器,则无需在内存中创建中间集合 Seq.fill(n)(math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)).filter(_<1).size.toFloat/n*4 >迭代器。填充(n)(数学.pOW(No.NeXFLAST,2)+数学.PoW(随机.NExtFLASH,2)).FP>(p<P>,而不是在填充序列之后对小于1的值进行筛选,考虑将有效数字(即大于或等于1的数字)添加到列表中,从而节省集合上不必要的迭代。 Iterator.fill(n)(math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)).filter(_<1).size.toFloat/n*4
最终答案如何使下面的代码在保持Scala中的函数样式的同时,针对较大的'n'值运行? Seq.fill(n)(math.pow(Random.nextFloat,2)+math.pow(Random.nextFloat,2)).filter(p>如果使用迭代器,则无需在内存中创建中间集合 Seq.fill(n)(math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)).filter(_<1).size.toFloat/n*4 >迭代器。填充(n)(数学.pOW(No.NeXFLAST,2)+数学.PoW(随机.NExtFLASH,2)).FP>(p<P>,而不是在填充序列之后对小于1的值进行筛选,考虑将有效数字(即大于或等于1的数字)添加到列表中,从而节省集合上不必要的迭代。 Iterator.fill(n)(math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)).filter(_<1).size.toFloat/n*4,scala,functional-programming,Scala,Functional Programming,最终答案 def nums(n: Int): Iterator[Float] = { import scala.util.Random def helper(items: Iterator[Float], counter: Int): Iterator[Float] = { val num = math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2) if (counter > 0) { i
def nums(n: Int): Iterator[Float] = {
import scala.util.Random
def helper(items: Iterator[Float], counter: Int): Iterator[Float] = {
val num = math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)
if (counter > 0) {
if (num >= 1) helper( items ++ Iterator(num.toFloat), counter - 1) else helper(items, counter - 1)
} else items
}
helper(Iterator[Float](), n)
}
Scala REPL
nums(n).toFloat/(n * 4)
我得到这个错误
值填充不是对象java.util.Iterator的成员
您的代码中可能有import java.util.\u
。将其更改为仅导入您实际需要的内容。我谈论的Iterator
是scala.collection.Iterator
。别名为scal>a、 迭代器
。提示:将过滤器(条件)。大小
替换为计数(条件)
scala> def nums(n: Int): Iterator[Float] = {
| import scala.util.Random
| def helper(items: Iterator[Float], counter: Int): Iterator[Float] = {
| val num = math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)
| if (counter > 0) {
| if (num >= 1) helper( items ++ Iterator(num.toFloat), counter - 1) else helper(items, counter - 1)
| } else items
| }
| helper(Iterator[Float](), n)
| }
nums: (n: Int)Iterator[Float]
scala> nums(10000).size.toFloat/(10000 * 4)
res1: Float = 0.053925