// 数组乱序(最多有N个位置不动)
function sortItem(list, count = 1) {
let result = [];
let hold = 0;
let needchange = false;
for (let i = 0; i < list.length; i++) {
let select = [];
select = this.reduceArray(list, result);
if (hold >= count && select.length > 1) {
select = this.reduceArray(select, [list[i]]);
}
if (i == list.length - 1 && select[0] == list[i]) {
needchange = true;
}
let randomIndex = this.math.between(0, select.length - 1);
if (randomIndex == i) {
hold++;
}
result.push(select[randomIndex]);
}
// 交换最后一个的位置
if (needchange) {
let last = result[result.length - 1];
for (let i = 0; i < result.length - 1; i++) {
if (list[i] != result[i] && result[i] != last) {
let tmp = result[i];
result[i] = result[result.length - 1];
result[result.length - 1] = tmp;
break;
}
}
}
return result;
}
// 数据相减(不动原数组)
function reduceArray(a, b) {
let result = [];
for (let i = 0; i < a.length; i++) {
let pass = false;
for (let j = 0; j < b.length; j++) {
if (a[i] == b[j]) {
pass = true;
break;
}
}
if (!pass) {
result.push(a[i]);
}
}
return result;
}
// 从数据中获取不重复随机(前N个重复)
function getRandomItem(list, undiffCount = 3) {
if (list == null || list.length <= 0) {
return;
}
// filter play list
let playList = [];
if (list.length > undiffCount) {
if (list.hasplayed == null) {
list.hasplayed = [];
}
for (let i = 0; i < list.length; i++) {
let isplayed = false;
for (let j = 0; j < list.hasplayed.length; j++) {
if (list[i] == list.hasplayed[j]) {
isplayed = true;
break;
}
}
if (!isplayed) {
playList.push(list[i]);
}
}
} else {
playList = list;
}
let randomIndex = this.math.between(0, playList.length - 1);
let randomItem = playList[randomIndex];
// update catched list
if (list.length > undiffCount) {
if (list.hasplayed == null) {
list.hasplayed = [];
}
for (let i = undiffCount - 1; i >= 0; i--) {
if (i > 0) {
list.hasplayed[i] = list.hasplayed[i - 1];
} else {
list.hasplayed[i] = randomItem;
}
}
}
return randomItem;
}
JS数组操作
最新推荐文章于 2022-09-26 23:42:28 发布