How to convert a date into a random index in a list?

问题: I need something that generates a random item from a list, but that item is randomised every day and is consistent for all users. This is on a website, and thus using JavaS...

问题:

I need something that generates a random item from a list, but that item is randomised every day and is consistent for all users. This is on a website, and thus using JavaScript (although really I just need the algorithm you'd follow, not necessarily the code itself).

I've got day, month, and year stored in variables, but what could I do to convert this into an integer between 0 and list length?

Thanks!


回答1:

Simple algorithm:

Pair 3 integers to 1:

seed = pair(day, pair(month, year))

use this int to seed a random number generator, for desired randomness

seed -> [0, 1, 2, ..., array.length - 1]

index = Math.round(randomOf(seed) * (array.length - 1));
element = array[index]

Here's a basic javascript implementation of the aforementioned pairing function:

function pair(x, y) { return ((x + y) * (x + y + 1)) / 2 + y; }

implementing randomOf (check the link above for "random number generator"):

randomOf(seed){
   Math.seedrandom(seed);
   return Math.random();
}

回答2:

You can use this https://github.com/davidbau/seedrandom. So the idea is to change the seed for the random function to the date (maybe just the month, day, and year). For example:

Math.seedrandom('August 19, 1975');
console.log(Math.random());    // 0.8213442237794714
console.log(Math.random());    // 0.9082914871756658

and then to convert it to an integer you can use the function describe here:

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

edit:

Then for example to use it to get something in an array



   
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

let arr = ['firsEl', 'secondEl', 'thirdEl', 'fourthEl'];
let d = new Date(); //get todays date
let month = d.getMonth();
let day = d.getDate();
let year = d.getFullYear();
//make the random with seed
Math.seedrandom(`${month} ${day}, ${year}`);
//and finally using the function for int
let item = arr[getRandomInt(0, arr.length)]; 
console.log(item);
<script src="http://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.4/seedrandom.min.js"></script>
  • 发表于 2019-03-01 03:02
  • 阅读 ( 164 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除