一次性生成自定义图案编号序列 [英] Generate a custom pattern number sequence in one go
本文介绍了一次性生成自定义图案编号序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用功能初始化构造一次性生成以下数字序列:
I'd like to generate the following number sequence in one go using a functional initialization construct:
Array(0, 0, 0, 0, 3, 3, 6, 6, 9, 9, ..., n*3, n*3)
一种方法是做
Array.fill[Int](2)(0) ++ Array.tabulate(4)(_*3)
但是我需要将结构第二部分的每个值加倍,即先得到 0,0
然后是 3、3
等.如何复制第二个构造的值?
but I'd need to double each value of the second part of the construct i.e. to get 0, 0
then 3, 3
etc. How can I duplicate the values of the second construct?
我也无法弄清楚会产生这样的序列的数学函数.
I also couldn't figure out a mathematical function that would generate such sequence.
推荐答案
考虑单次通过的尾部递归解决方案
Consider tail-recursive solution for single pass
def pattern(n: Int): List[Int] = {
@tailrec def run(n: Int, acc: List[Int]): List[Int] = {
n match {
case 0 => 0 :: 0 :: 0 :: 0 :: acc
case i => run(i - 1, (i * 3) :: (i * 3) :: acc)
}
}
run(n-1, Nil)
}
这篇关于一次性生成自定义图案编号序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文