2016-11-23 119 views
0

我正在寻找生成一个项目数组的特定排列,给定项目和一些标识符的排列生成。这应该是确定性的(不是随机的)。基于标识符生成一个特定的排列排列

例如,对于三个项目,有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']

建议将受到欢迎;谢谢!

+0

你就不能缓存排列集合时被更新? 'magicFunction()'然后会拉取请求的索引。我没有看到你将如何获得'magicFunction(['a','b','c'],5)'而不会立即产生所有排列来获得最后一个排列。 –

+0

我们可以硬编码所有排列的列表,但是对于6个项目列表,这是720个硬编码项目。 (它变得很快)没有缓存,因为可能的排列列表是在前端生成的,并且最多的DB将存储一个特定用户上次看到的排列。 – abought

+1

这里有:http://stackoverflow.com/questions/7918806/finding-n-th-permutation-without-computing-others它仍然涉及迭代*东西*以获得所需的排列。也许它会为你工作。 –

回答

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

+0

如果我正确地阅读这篇文章,一个缺点是需要强力计算至少每个排列,直到包括所需的排列。这可能是可行的,但随着人们在网站上进一步深入,他们会为每个访问过的新页面做越来越多的计算。理想情况下,我希望找到一种方法,可以避开不必要的中间工作,直接进入所需的状态。 – abought