生成周围的数字,如果太大则自动换行

时间:2019-02-28 13:36:11

标签: javascript python arrays algorithm math

如何以这种方式生成数字?我想创建一个函数generate (current, limit, count)

  • 当前–数组中的中心数字
  • 限制–换行前的最高数量
  • 计数-例如,2表示当前数字之前和之后的两个数字。

此函数可能返回如下数组:

[ current - n, current - 1, current, current + 1, current + n ] (n <= count)

例如:

generate(5, 10, 2)

返回:

[3, 4, 5, 6, 7]

但是generate(1, 5, 2)必须返回[4, 5, 1, 2, 3 ]

当前前的数字来自最大数量计数的反向数组。

2 个答案:

答案 0 :(得分:0)

您可以对值进行一些调整以防止出现负数或零。

function generate(current, limit, count) {
    return Array.from(
        { length: count * 2 + 1 },
        (_, i) => (v => v <= 0 ? v + limit : v)
                  ((current + i - count + limit - 1) % limit + 1)
    );
}

console.log(generate(5, 10, 2).join(' '));  // 3 4 5 6 7
console.log(generate(1, 5, 2).join(' '));   // 4 5 1 2 3
console.log(generate(1, 2, 10).join(' '));  // 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1

答案 1 :(得分:-1)

我认为您可以使用列表或数组和for循环来实现此目的的一种非常简单的方法。

对于列表,如果您要使用前两个数字对其进行初始化,则需要使用current-n和current-1,只需使用循环将其他所有内容相加即可。

myList = [current-n,current-1]

对于i在范围(电流,限制,计数)中:      myList.append(i)