checking for integer palindrome using javascript - javascript

I'm trying, and failing, to check for whether or not a 5-digit integer is a palindrome or not using javascript. I have gotten the code to correctly check for 5-digit strings (not integers yet). That part should be relatively easy to figure out.
My main question: Am I doing the structure for using functions in javascript? If so, how can I get the function call to work properly? It just quits the program upon receiving the desired input.
Code is as follows:
<script type="text/javascript">
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, '');
var len = userInput.length;
for (var i = 0; i < len/2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
while (counter < 10){
if (userInput.length == 5){
if (pandindrome(userInput) == true){
document.write("The input is a palindrome!");
}
else if (pandindrome(userInput) == false){
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
counter++;
}
else if (userInput.length != 5){
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
}
</script>

I have tested your code, everything works fine!
FIY, I set a variable isPalindrome to store the return value from the function palindrome. Then you can use it directly inside if statement, instead of compare to true.
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, "");
var len = userInput.length;
for (var i = 0; i < len / 2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
var isPalindrome = palindrome(userInput);
while (counter < 10) {
if (userInput.length == 5) {
if (isPalindrome) {
document.write("The input is a palindrome!");
} else {
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt(
"Please enter a 5-digit, numerical palindrome: "
);
isPalindrome = palindrome(userInput);
}
counter++;
} else if (userInput.length != 5) {
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
isPalindrome = palindrome(userInput);
}
}

Related

How to test if a number is prime and 9 digits long in JS

I have this code to detect a password with an algorithm that checks if the number is prime and 9 digits long
function passwordIsGiven() {
var password = document.getElementById("password").value;
var passwordLength = password.length;
for (let i = 0; i < password; i++) {
if (password % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && passwordLength == 9) {
window.alert("Correct");
window.location.replace("/html/index.html");
} else {
window.alert("Wrong code. Try again.");
}
}
<p>ENTER PASSCODE TO CONTINUE</p>
<input type="password" id="password">
<br><br>
<button type="submit" id="passwordButton" onClick="passwordIsGiven()">Submit</button>
Even with a correct 9 digit prime number it always says that its wrong.
You can do it like this:
And you must convert the value to a number using:
var password = Number(document.getElementById("password").value);
function passwordIsGiven() {
var password = document.getElementById("password").value;
var passwordLength = password.toString().length;
let isPrime = true;
for (let i = 2; i < password; i++) {
if (password % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && passwordLength === 9) {
window.alert("Correct");
window.location.replace("/html/index.html");
} else {
window.alert("Wrong code. Try again.");
}
}
And also add a check for num ===1...as it is is neither a prime nor a composite number.
I would go on a modular approce and split the test to two function. one which test the isPrime case and the other one which test the length.
const isPrime = num => {
for(let i = 2; i < num; i++){
if(num % i === 0){
return false;
}
}
return num > 1;
}
const is9digit = number => {
return number.toString().length;
}
const isPasswordValid = number => is9digit(number) && isPrime(number);
const testNumber = isPasswordValid(333);
if (testNumber) {
window.alert("Correct");
window.location.replace("/html/index.html");
}
else {
window.alert("Wrong code. Try again.");
}

Need help to track guesses higher or lower HTML

I was wondering if someone can help point me in the direction to use the .push() function to store a user's guesses in a higher or lower guessing game? And how would I be able to prevent duplicate guesses? I have the for loop commented because it would break my webpage. Thanks for any help!
let valid_input = false;
let number, input;
while(!valid_input){
input = window.prompt("Enter a positive number!");
number = Number(input);
if(number != NaN && number > 0){
valid_input = true;
}
}
let num = Math.floor(Math.random() * number) + 1;
console.log(num);
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
let totalGuess = [];
/*for(i = 0; guess != num; i++){
totalGuess.push(i);
}*/
if(guess == num) {
message.innerHTML = `You got it! Good Guess! </br> It took you ${totalGuess.indexOf(guess) + 2} to get it right and your guesses were ${totalGuess}`
console.log(`It took you ${totalGuess.indexOf(guess) + 1} guesses to get it right...`);
}
else if(guess <= 0){
message.innerHTML = "That number is out of range, try again."//Guess is negative
}
else if(guess > number){
message.innerHTML = "That number is out of range, try again."// Guess is higher than the range of number they inputed
}
else if (guess > num) {
message.innerHTML = "No, you guessed too high. Try a lower number!"// guessed too high
}
else if(guess < num){
message.innerHTML = "No, you guessed too low. Try a higher number!"// Guessed too low
}
else{
message.innerHTML = "Please enter a number!" //Guessed any non number
}
console.log(totalGuess);
}
You could use a Set data structure to store each guess. Set, unlike Array, ignores duplicate elements:
let totalGuess = new Set();
...
totalGuess.add(guess);
Always when there is a valid guess you just can push it to your array
totalGuess.push()
To check if the value is already in your array you can use Arrays includes method in combination with the Logical Not Operator !.
When the array is not including the number then push it.
if(!totalGuess.includes(SOMENUMBER)){
totalGuess.push()
}
The snippet shows how it works
let valid_input = false;
let number, input;
let totalGuess = [];
while (!valid_input) {
input = window.prompt("Enter a positive number!");
number = Number(input);
if (number != NaN && number > 0) {
valid_input = true;
}
}
document.getElementById('btn').addEventListener('click', do_guess)
const num = Math.floor(Math.random() * number) + 1;
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (guess == num) {
message.innerHTML = `You got it! Good Guess! </br> It took you ${totalGuess.length+1} to get it right and your guesses were ${totalGuess}`
console.log(`It took you ${totalGuess.length+ 1} guesses to get it right...`);
console.log(totalGuess);
totalGuess = [];
} else if (guess <= 0) {
message.innerHTML = "That number is out of range, try again." //Guess is negative
} else if (guess > number) {
message.innerHTML = "That number is out of range, try again." // Guess is higher than the range of number they inputed
} else if (guess > num) {
message.innerHTML = "No, you guessed too high. Try a lower number!" // guessed too high
if (!totalGuess.includes(guess)) {
totalGuess.push(guess);
}
} else if (guess < num) {
message.innerHTML = "No, you guessed too low. Try a higher number!" // Guessed too low
if (!totalGuess.includes(guess)) {
totalGuess.push(guess);
}
} else {
message.innerHTML = "Please enter a number!" //Guessed any non number
}
}
<input id="guess"></input>
<button id="btn">Click</button>
<div id="message"></div>

Testing for prime number. Values not pushing into array

I'm trying to push values into an array, then if the array holds just two values, declare it as a prime number. For some reason, the for loop doesn't seem to be sending any values into the array...
function primeOrNot() {
var input = parseInt(prompt('Please, give me a number'));
var list = [];
list.push(1);
list.push(input);
for (var i = 2; i < input / 2; i++) {
if (Math.floor(input / i) == input / i) {
list.push(i);
}
if (list.length == 2) {
alert('The number you chose is a prime number.');
} else 'The number you chose is not a prime number. You lose.';
}
console.log(list);
}
primeOrNot();
You are missing a closing } in the else. This works:
function primeOrNot() {
var input = parseInt(prompt("Please, give me a number"));
var list = [];
list.push(1);
list.push(input);
for(var i=2; i<input/2; i++){
if (Math.floor(input/i) == input/i) list.push(i);
}
if(list.length == 2){
alert("The number you chose is a prime number.");
} else alert("The number you chose is not a prime number. You lose.")
console.log(list);
}
primeOrNot();

Check for perfect number and print out divisors?

My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}

how to validate character and number in one textbox in javascript

The max size of textbox is given as 11. I want to print first 4 characters as alphabets and next 7 characters as numbers. Please give me a solution in javascript only.
function Myfunction2() {
var x2 = document.getElementById('text').value;
var re = /^[A-za-z]+$/;
for (i = 0; i < 4; i++) {
y = x2charAt(i);
if (re.test(x2.value)) {
alert("please enter char only");
}
}
}
function Myfunction() {
var x = document.getElementById("text").value;
for (i = 5; i < 11; i++) {
y = x.charAt(i);
if (y == " " || isNaN(y)) {
alert("not numeric");
}
}
}
Test it against an expected pattern:
/^[a-z]{4}[0-9]{7}$/i.test(value);
You could bind this to the actual input element as well to test it with each keystroke:
​var supercode = document.getElementById("supercode"),
rePattern = /^[a-z]{4}[0-9]{7}$/i;
supercode.addEventListener("keyup", function(e){
this.style.borderColor = rePattern.test(this.value) ? "green" : "red" ;
}, false);
Demo: http://jsfiddle.net/RfMK7/

Categories

Resources