JSFiddle - React, Tailwind, and code Playground

by evgkch

JavaScript

const iterator = (mod, i = 0) => ({
	next: () => (i = ++i % mod),
 	prev: () => --i < 0 ? (i = mod - 1) : (i = i % mod),
  getValue: () => i,
});

const res = [];

function test(n){
	let k = 0;
  const itr = iterator(n);
  while (itr.getValue() != n / 2)
  { 
  	Math.random() > 0.5
    	? itr.next()
      : itr.prev();
    k++;
  }
  res.push(k);
};

for(let i = 0; i < 10000; i++)
{
	test(6)
}

console.log(res);
console.log(res.reduce((a, b) => a + b) / res.length);