基于标识符生成阵列的一个特定排列

时间:2016-11-23 03:52:20

标签: javascript

我希望生成一个项目数组的特定排列,给定项目,以及生成哪种排列的标识符。这应该是确定性的(不是随机的)。

例如,对于三个项目,有6个安排。每次用户访问我们的网站时,我们都希望他们看到一个特定的安排,根据他们上次看到的内容进行选择。 ("我上次看到订单#1 ['a', 'b', 'c'],所以这一次,向我展示订单#2,即['a', 'c', 'b']")

const items = ['a', 'b', 'c'];

const possibleArrangements = [
  ['a', 'b', 'c'],
  ['a', 'c', 'b'],
  ['b', 'a', 'c'],
  ['b', 'c', 'a'],
  ['c', 'a', 'b'],
  ['c', 'b', 'a'],
];

有许多方法可以通过暴力生成整个可能性列表,但是生成每个可能的排列对于这个用例来说似乎有点过分,当我们真正需要的是获得一个基于的所需安排时标识符。鉴于相同的项目和相同的标识符,我正在寻找一种方法来每次生成相同的排列,并且只有那种安排。

magicFunction(['a', 'b', 'c'], 2)

>> ['b', 'a', 'c']

欢迎提出建议;谢谢!

1 个答案:

答案 0 :(得分:1)

使用递归功能。
如果您想要所有可能的安排,我回答了类似的问题herehere

function magicFunction(arr,index){
    // Finds the number of arrangement possibility starts with a character
    // For example there are 2 arrangement possibility that starts with 'a'
    var partsNum = factorial(arr.length - 1);

    // If the index is invalid return undefined
    if (partsNum * arr.length < index + 1 || index < 0){ return; } //Invalid index

    // Find the starting character index of the arrangement 
    var startIndex = 0;
    while (index + 1 > partsNum){
        startIndex++;
        index -= partsNum;
    }

    // Keeps a reference of the starting character
    var startWith = arr[startIndex];

    arr.splice(startIndex,1); //Removes the character from array
    return startWith  + (arr.length > 0 ? magicFunction(arr,index) : "");
}

function factorial(num){
    var ans = 1;
    while (num > 1){
       ans *= num;
       num--;
    }
    return ans;
}

console.log(magicFunction(['a', 'b', 'c'], 0));
console.log(magicFunction(['a', 'b', 'c'], 1));
console.log(magicFunction(['a', 'b', 'c'], 2));
console.log(magicFunction(['a', 'b', 'c'], 3));
console.log(magicFunction(['a', 'b', 'c'], 4));
console.log(magicFunction(['a', 'b', 'c'], 5));