Answer the question
In order to leave comments, you need to log in
How to make an algorithm for the selection of options?
Essence of the question:
An array of data flies from the server, it can contain n elements.
1) You need to get a pair of array indices m times, that is - [ [x,y], .... , [z, c] ], and the pairs in the array should not be repeated, that is, x != y && z ! = c && [x, y] != [z, c]
2) Then get a random sample from, the second element of the pair [x, y] + 5 of any elements that are not equal to x or y
The option below is invalid
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
return [i, j]
}
}
Answer the question
In order to leave comments, you need to log in
I sketched something, understand if you want:
const array = ['a', 'b', 'c', 'd', 'e', '1', '2', 'a', 'b', 'c', 'd', 'f', 'g', 'h', 'j'];
const getRandowPairs = arr => {
const sorted = [...new Set(arr)].sort((a, b) => Math.round(Math.random()) || -1);
let res = [];
for (let i = 0; i + 1 < sorted.length; i += 2){
res.push([sorted[i], sorted[i + 1]]);
}
return res;
};
const getRandomArr = arr => {
const index = Math.floor(Math.random() * arr.length);
const item = arr[index];
arr.splice(index, 1);
arr = arr.flatMap(e => e);
const set = new Set();
while (set.size < 5){
let i = Math.floor(Math.random() * arr.length);
if (!item.includes(arr[i])){
set.add(arr[i]);
}
}
return [item[1], ...set];
};
console.log(getRandomArr(getRandowPairs(array))); // [ "c", "e", "h", "a", "1", "2" ]
console.log(getRandomArr(getRandowPairs(array))); // [ "1", "a", "d", "f", "h", "c" ]
console.log(getRandomArr(getRandowPairs(array))); // [ "f", "b", "j", "g", "a", "2" ]
const array = ['a', 'b', 'c', 'd', 'e', '1', '2', 'a', 'b', 'c', 'd', 'f', 'g', 'h', 'j'];
const getRandowPair = arr => {
const sorted = [...new Set(arr)].sort((a, b) => Math.round(Math.random()) || -1);
let res = [];
for (let i = 0; i + 1 < sorted.length; i += 2){
res.push([sorted[i], sorted[i + 1]]);
}
return res[Math.floor(Math.random() * res.length)];
};
const item = getRandowPair(array);
const set = new Set();
while (set.size < 5){
let i = Math.floor(Math.random() * array.length);
if (!item.includes(array[i])){
set.add(array[i]);
}
}
const result = [item[1], ...set];
console.log(result); // [ "e", "h", "c", "2", "j", "b" ]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question