首页 > 解决方案 > 如何生成具有给定开始值和结束值的数字模式?

问题描述

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

一个。开始 = 1,结束 = 3
    123
    231
    312
湾。开始 = 2 ,结束 = 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

但是如何显示其余的数字?

标签: javascriptphpalgorithminteger

解决方案


你可以试试这个算法:

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))


推荐阅读