I used random function
, to generate a 4 digit number.
The generated 4 digit random number
should not be in the sequence of 1111, 2222, 3333, .... The generated random number could be of any number except 1111, 2222, 3333, 4444,..
I used the below approach,
But, i could get the repeating of digits using the below code. Could somebody please help.
function repeatingDigit(n) {
let num = n.toString();
for (var i = 0; i <= num.length; i ) {
if (num.substr(i) == num.substr( i)) {
alert('This pattern can not be used');
}
else {
return parseInt(n);
}
}
}
repeatingDigit(Math.floor(1000 Math.random() * 9000));
Thank you.
CodePudding user response:
You could just check if it's divisible by 1111
:
function repeatingDigit(n) {
if (n % 1111 === 0) {
alert('This pattern can not be used');
}
return n;
}
repeatingDigit(Math.floor(1000 Math.random() * 9000));
CodePudding user response:
You can use a regular expression to test for that:
function repeatingDigit(n) {
let num = n.toString();
if (/(\d)\1{3}/.test(num)) {
alert('This pattern can not be used');
} else {
return parseInt(n);
}
}
repeatingDigit(Math.floor(1000 Math.random() * 9000));
The regular expression /(\d)\1{3}/
tests for digits \d
and checks if the following three characters are the same as the first found digit.
CodePudding user response:
You can also use every() function which is inbuilt function provided by javascript to check wheather number is repeated or not after splitting number to array.
function repeatingDigit(num) {
var arr = String(num).split('');
if(arr.every(function (digit) { return digit === arr[0]}))
return 'Repeated Number!!';
else
return num;
}
console.log(repeatingDigit(Math.floor(1000 Math.random() * 9000)))
Hope This Answer Will Help You! Happy Coding :)