Home > Software design >  How to generate natural numbers not less than X and not more than Y, consisting of the same digits?
How to generate natural numbers not less than X and not more than Y, consisting of the same digits?

Time:12-21

Please help me understand the algorithm. It is necessary to generate natural numbers not less than X and not more than Y, consisting of the same digits. Memory limit 256 MB.

For example, the number 999999 meets this requirement, but the number 123123 does not.

I can't pass the test because I can't reduce my memory usage (565.56 Mb / 256 Mb)

Input data: (1 ≤ l,r ≤ 10**18) Output data format: The number of numbers in the given range. For example: r = 10, l = 100. Result 9 (11, 22, 33, 44, 55, 66, 77, 88, 99)

function numberOfTests(l, r) {
  let count = 0;

  for (let i = l; i <=  r; i  ) {
    let el = String(i).split("");
    el = [el.every((e, i, a) => e === a[0])];
    if (!el.includes(false)) {
      count  ;
    }
  }
  return count;
}

console.log(numberOfTests("10 100")); // 9
console.log(numberOfTests("4 7")); // 4

CodePudding user response:

You can try this:

const x= 200 // example
const y = 990 // example

const sameDigit = (num) => {
  let first = num % 10;
  while (num) {
    if (num % 10 !== first) return false;
num = Math.floor(num / 10);
  }
  return true
}

for (i=x 1;  i < y; i  ){
    if (sameDigit(i)) console.log(i)
}

You can have a function called sameDigits that checks each digit of a number to be the same. We call this function in our forloop each time we are checking a number and if the condition was true, we simply log that number.

CodePudding user response:

I'm unable to understand the code in the question or access the link. This answer answers the title of the post: get natural numbers between a low and high bound consisting only of repeating digits.

Thinking about it more of a lexical problem than a numeric one: We need to know the order of magnitude and first digit of the low bound, and the order of magnitude and the first digit of the high bound.

Then, it's just loops: from the low order of magnitude, to the high order, all the repeating digits number of that order (clipped to the low and high bounds).

function repeatDigitsFrom(lowBound, highBound) {
  const result = []
  const lowStr = lowBound.toString().trim()
  const highStr = highBound.toString().trim()
  for (let order=lowStr.length; order <=  highStr.length; order  ) {
    let startDigit = order === lowStr.length ? lowStr[0] : 1;
    let endDigit = order === highStr.length ? highStr[0] : 9;
    for (let d = startDigit; d <= endDigit; d  ) {
      let str = ''.padStart(order, d);
      let num = parseInt(str);
      // check to clean up the edges
      if (num >= lowBound && num <= highBound) result.push(num);
    }
  }
  return result
}

console.log(repeatDigitsFrom(291, 38222))

  • Related