Home > Software design >  how to generate random random from x to y and check if it's palindrom or not
how to generate random random from x to y and check if it's palindrom or not

Time:07-31

so i already make a code to check if the string palindrom or not

let randomNumber = '13431'
let b = ''
 


//to check palindrom or not
for (i = randomNumber.length-1 ; i >= 0 ; i--) {
    b = b   randomNumber[i]
}
    if (randomNumber === b) {
        console.log('palindrom')
} else {
        console.log('not')
}

but i want to make the randomNumber is really random using loops (from x to y), like this

for (let i = 12 ; i < 30 ; i  ) {
    console.log(i)
    
}

so i'll generate random number from 12 -> 30 but ends in '22' using break; bcs it's palindrom

CodePudding user response:

It will generate random number and check if the number is palindrome:

function isPalindrome (str) {
    return str.split('').reverse().join('') == str;
}

start = Math.floor(Math.random() * 100); // your case 12
end = Math.floor(Math.random() * 100);  // your case 30
for (i = start; i <= end; i  ) {
    if (isPalindrome(i.toString())) {
        console.log(`Number ${i} is palindrome`);
        break;
    }
}

CodePudding user response:

you can do something like this

//generate an array from start to stop
const generateRangeNumbers = (start, stop) => Array.from({length: stop - start   1}).map((_, i) => start   i)
//this checks if the number is palindrome
const isPalindrome = n => n.toString().split('').reverse().join('') === n.toString()

//this returns an array of palindrome in the range
const result = generateRangeNumbers(12, 30).filter(isPalindrome)

//if you need just the first match you can use find instead of filter
const result2 = generateRangeNumbers(12, 30).find(isPalindrome)
console.log(result, result2)

you can do it with loops in this way

let result
for (let i = 12; i <= 30; i  ) {
  if (i.toString() === i.toString().split('').reverse().join('')) {
    result = i
    break;
  }
}

console.log(result)

  • Related