gpt4 book ai didi

javascript - 回溯算法创建一个 "jumbled"但不是随机数组

转载 作者:行者123 更新时间:2023-11-30 21:15:13 25 4
gpt4 key购买 nike

<分区>

我编写了这个回溯算法,以从包含 10 个项目的输入数组中生成一个包含 70 个项目的看起来困惑的数组。它需要遵循的规则是:

  1. 每组5个无重复项
  2. 在 3 个连续的 5 组中的任何一个中,没有项目出现在相同位置
  3. 每个项目总共出现 7 次

这几乎可行,但前提是我使输入数组大于输出数组,这会违反规则 3。如果我使输入数组长度为 70,算法有时会起作用,但有时会溢出。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />

<title>Backtracking Pseudo Randomiser</title>
</head>

<body>
<button onclick=go();>Go</button>

<script>
function go() {

function pseudoRan(input,output) {
if (output.length==70) {
output=listToMatrix(output,5);
printIt(output);
return;
}
else {
var tmp=input.shift();
var mod=output.length % 5;
if (output.slice(-mod-1).indexOf(tmp)==-1 && output[output.length-5]!=tmp && output[output.length-10]!=tmp) {
output.push(tmp);
pseudoRan(input,output);
}
else {
input.push(tmp);
pseudoRan(input,output);
}

}


}

var input=["A","B","C","D","E","F","G","H","I","K"];
var output=[];
input=pool(input,70);
input=yatesShuffle(input);
pseudoRan(input, output);


//analyse it
var freqs=output.byCount();
var strFreqs="";
for(a=0;a<freqs.length;a++){
strFreqs+="Item: " + freqs[a].item + " ..." + freqs[a].frequency + "<br />";
document.getElementById("2").innerHTML=strFreqs;
}
}


function pool(array,total) {
var factor=total/array.length;
var newArray=[];
for (a=0;a<factor;a++) {
for (b=0;b<array.length;b++) {
newArray.push(array[b]);
}
}
//console.log(newArray);
return newArray;
}

function yatesShuffle (array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * i); // no +1 here!
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}


function listToMatrix(list, elementsPerSubArray) {
var matrix = [], i, k;

for (i = 0, k = -1; i < list.length; i++) {
if (i % elementsPerSubArray === 0) {
k++;
matrix[k] = [];
}

matrix[k].push(list[i]);
}

return matrix;
}

function printIt(array) {
for (i=0;i<array.length;i++) {
var str=" ";
for (j=0;j<array[i].length;j++) {
str+=array[i][j]+" ";
}
document.getElementById("1").insertAdjacentHTML('beforeend',str + "</br>");

//console.log(array[i]);
}
}
Array.prototype.byCount= function(){
var itm, a= [], L= this.length, o= {};
for(var i= 0; i<L; i++){
itm= this[i];
if(!itm) continue;
if(o[itm]== undefined) o[itm]= 1;
else ++o[itm];
}
for(var p in o) a[a.length]= {item: p, frequency: o[p]};
return a.sort(function(a, b){
return o[b.item]-o[a.item];
});
}

</script>
<div id="1" style="font-family:'Courier New';"></div>
<br />
<div id="2"></div>

</body>
</html>

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com