Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สุ่มดัชนีของค่าเป้าหมายในอาร์เรย์ (Random Pick Index) ใน JavaScript

ปัญหา

รับอาร์เรย์ arr (อาจซ้ำ) และค่า num ที่มีอยู่ในอาร์เรย์ คืนดัชนีของ num แบบสุ่ม (ถ้ามีหลายดัชนี)

ตัวอย่าง

const arr = [5, 3, 6, 7, 3, 4, 2, 3]; const num = 3;

3 อยู่ดัชนี 1, 4, 7 → คืนหนึ่งในนั้นแบบสุ่ม (เช่น 4)

โค้ดตัวอย่าง (Recursive Search + Random)

const arr = [5, 3, 6, 7, 3, 4, 2, 3]; const num = 3; 
Array.prototype.pick = function(target) { 
  const targets = []; 
  this.findTarget(0, this.length, target, targets); 
  return targets[Math.floor(Math.random() * targets.length)]; 
}; 
Array.prototype.findTarget = function(start, end, target, targets) { 
  if(start + 1 === end || start === end) { if(this[start] === target) targets.push(start); return; } 
  let j = start + Math.floor((end - start)/2); 
  this.findTarget(start, j, target, targets); 
  this.findTarget(j, end, target, targets); 
}; 
console.log(arr.pick(num));

ผลลัพธ์

4