0

I have asked a similar question before: How to get this PRNG to generate numbers within the range?

How do I take that and make it work for a number which can be up to 5 bits (32 possible values)? I tried this but it is giving "invalid" values:

const fetch = (x, o) => {
  if (x >= o) {
    return x
  } else {
    const v = (x * x) % o
    return (x <= o / 2) ? v : o - v
  }
}

const fetch16 = (x) => fetch(x, 65519)
const fetch8 = (x) => fetch(x, 251)

// the last number can be anything.
// MODIFIED THIS
const build32 = (x, o) => fetch8((fetch8(x) + o) % 256 ^ 101) % 32

const j = 115; // If you don't want duplicates, either i or j should stay fixed
let i = 0
let invalid = [];
let valid = new Set;
while (i <= 32) { // <-- small fix here!
  let x = build32(i, j); // To test, you can swap i and j here, and run again.
  if (x > 31 || valid.has(x)) {
    invalid.push([i, j, x]);
  } else {
    valid.add(x);
  }
  i++;
}

console.log("invalid:", invalid);
console.log("valid:", [...valid]);
console.log("count of valid:", valid.size);

The system should iterate through the numbers 0-31 without repeating, in what seems like random order.

Lance
  • 75,200
  • 93
  • 289
  • 503
  • 1
    All of the _invalid_ values come from this statement: `if (x > 31 || valid.has(x))` - in each case, `x < 31` but `valid` has `x` - therefore it is placed into the invalid array. – Randy Casburn Jan 04 '22 at 16:57
  • 1
    I don't want it to be in the `valid` set, that's the problem. It should only be in there once for each. – Lance Jan 04 '22 at 17:06
  • 1
    based upon your comment to my deleted answer - I suggest you change the title of your question to read "**Why is my algorithm repeating values instead of producing 32 unique values?**" – Randy Casburn Jan 04 '22 at 17:50
  • 2
    This sounds needlessly complex. Why not just create an array of all the numbers from 0-31, shuffle it, then start popping values off the end until the array is empty? – kmoser Jan 04 '22 at 17:52
  • 1
    @kmoser - to be fair, the OP _did_ tag this with _algorithm_. – Randy Casburn Jan 04 '22 at 18:15
  • 1
    Shouldn't `build32` be called `build5`? It's the number of bits, no? – Bergi Jan 04 '22 at 19:58
  • 1
    "*The system should iterate through the numbers 0-31 without repeating, in what seems like random order.*" - I see no reason why it should do that. Can you explain your reasoning, please? – Bergi Jan 04 '22 at 19:58
  • @RandyCasburn I think it needs an [xyproblem](https://en.wikipedia.org/wiki/XY_problem) tag, too :) – kmoser Jan 05 '22 at 05:49

0 Answers0