Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a number guessing version #14

Open
nbgraham opened this issue Feb 1, 2022 · 0 comments
Open

Add a number guessing version #14

nbgraham opened this issue Feb 1, 2022 · 0 comments
Labels
enhancement New feature or request

Comments

@nbgraham
Copy link
Owner

nbgraham commented Feb 1, 2022

Like https://nerdlegame.com/

Maybe use some code like this to generate the answer

const ops = '-+*/='
const nums = '0123456789'
const desiredLength = 8;

function getOne() {
  let one;
  while (!one) {
    one = tryOnce();
  }
  return one;
}

function tryOnce() {
  let current = '';

  while (current.length < desiredLength) {
    const prev = current[current.length - 1];
    const nextCanBeOp = nums.includes(prev);
    const nextCanBeNum = prev !== '0';

    let choices;
    if (nextCanBeOp && nextCanBeNum) {
      choices = Math.random() < 0.5 ? nums : ops; // 50/50 chance of choosing a number or operation next
    } else if (nextCanBeOp) {
      choices = ops;
    } else if (nextCanBeNum) {
      choices = nums;
    } else {
        return;
    }

    const index = Math.floor(Math.random() * choices.length);
    const char = choices[index];

    if (char === '=') {
      const result = eval(current);
      if (result >= 0) { // require the answer to be a single non-negative number
        const nerdle = current + '=' + Math.floor(result).toString();
        if (nerdle.length === desiredLength) {
          return nerdle;
        }
      }
      return undefined;
    } else {
      current += char;
    }
  }
}
@nbgraham nbgraham added the enhancement New feature or request label Feb 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant