如何生成具有给定起始值和结束值的数字模式?

How to generate a number pattern with given start and end value?

如何使用 php 生成这样的数字模式?

a. Start = 1, End = 3
    123
    231
    312
b. Start = 2 , End = 7
    234567
    345672
    456723
    567234
    672345
    723456

更新: 我试过这段代码:

function generate (int $start, int $end)
{
    $arr = [];
    for($start; $start <= $end; $start ++) {
        $arr[] = $start;
    }
    for($i = $arr[0]; $i <= count($arr); $i++) {
        for($l = $i - 1; $l < $end; $l ++) {
            echo $arr[$l];
        }
        echo " -> $i<br/>";
    }
}

并得到这个输出:

12345
2345
345
45
5

但是剩下的数字怎么显示呢?

怎么想的?

在编码之前,先了解要求的内容,并尝试用通俗易懂的语言表达,比如英语。您的模式只是说“向左旋转”或“取第一个数字。将其放在末尾。将其添加到输出中。继续这样做直到获得唯一数字”。既然我们明白了要做什么,你就得让计算机明白怎么做。

经过上面的解释,我觉得没必要加代码了。你可以自己尝试,因为我不想剥夺你自己做某事的乐趣。无论是哪种语言,创建一个包含从 startend 的所有数字的字符串 -> 在字符串开头擦除 -> 追加 -> 添加到输出。

棘手的情况(不是真的)是 startend 不是个位数。我把它留给你作为练习。 (提示:分隔符可以提供帮助。)

你可以试试这个算法:

const generate = (start, end) => {
    const length = end-start+1 
    let array = Array.from({length}, () => Array.from({length}, (x,i)=>i+start)) // creating 2D array and filling it with a loop from start value to end value
    for (let i = 0; i < array.length; i++) {
        poped = array[i].splice(i); // slice and put the element from index i to the last index 
        array[i].unshift(...poped) // adding poped value to the begining of the array
    }
    return array 
}

console.log(generate(1,3))
console.log(generate(2,7))