Nothing happens after Prompt - javascript

Sorry, I wasn't clear enough. I need it to list all the numbers from 0 to the number inputted by the prompt into the HTML. I made some suggested changes but now I only get the result for the specific number inputted, not all the numbers up to that number. I am just starting out so please be gentle. Thanks!
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for(var i = 0; i <= number; i++) {
if ( i %15 == 0) {
result = "Ping-Pong";
}
else if (i %5 == 0) {
result = "Pong";
}
else if (i %3 == 0) {
result = "Ping";
}
else {
result = number;
}
document.getElementById("show").innerHTML = result;
};
});

You can do either:
for(var i = 0; i <= number; i++) {
var digit = number[i]; // or any other assigment to new digit var
if ( digit % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.
or
if ( number % 5 == 0) {
return "Ping-Pong";
}
.... rest of your code here.

Problem is you did nothing after the return keyword. Also you didn't declared variable as digit. I hope this is what you are looking for.
With loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
for (var i = 0; i <= number; i++) {
if (i % 15 == 0) { // replaced `digit` with `i`
result = "Ping-Pong";
} else if (i % 5 == 0) {
result = "Pong";
} else if (i % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without loop:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var result;
if (number % 15 == 0) { // replaced `digit` with `number`
result = "Ping-Pong";
} else if (number % 5 == 0) {
result = "Pong";
} else if (number % 3 == 0) {
result = "Ping";
} else {
result = number;
}
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Ok, I figured it out. For future reference, this is what I was trying to do:
$(function() {
var number = parseInt(prompt("Let me see a number:"));
var i
var text = "";
for(i = 1; i <= number; i++) {
if ( i %15 == 0) {
text += "<br>" + "Ping Pong" + "<br>";
}
else if (i %5 == 0) {
text += "<br>" + "Pong" + "<br>";
}
else if (i %3 == 0) {
text += "<br>" + "Ping" + "<br>";
}
else {
text += "<br>" + i + "<br>";
}
};
document.getElementById("show").innerHTML = text;
});

Related

Countdown from 100 to the number (N) and separate even and odd numbers. Show even numbers in the first line and odd numbers in the second line

<div id="counter">100</div>
<script>
function myFunction() {
var person = prompt("Please enter One number (N) where (N) is a positive integer.", "");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
function countdown() {
var i = document.getElementById('counter');
i.innerHTML = parseInt(i.innerHTML) - 1;
if (parseInt(i.innerHTML) == 95) {
clearInterval(timerId);
}
}
var timerId = setInterval(function () { countdown(); }, 1000);
</script>
<p id="demo"></p>
Example Test Cases:
Input: 10
Output:
100 98 96 94 92
99 97 95 93 91
Another one:
Input: 5
Output:
100 98 96
99 97
I have made my own script which counts down from 100-0, and places each number into an Array variable depending on whether it's Odd/Even.
Here it is:
var even = [];
var odd = [];
var number = 100;
changeNumber();
function changeNumber() {
document.getElementById("counter").innerText = number;
if (checkParity(number) == "even") {
console.log("even");
even.push(number);
} else {
console.log("odd");
odd.push(number);
}
if (number == 0) {
console.log("[Finished]");
console.log("Even numbers:");
console.log(even);
console.log("Odd numbers:");
console.log(odd);
} else {
setTimeout(function () {
number--;
changeNumber();
}, 100);
}
}
function checkParity(n) {
if (n % 2 == 0) {
return "even"
} else {
return "odd"
}
}
<div id="counter">100</div>
I hope that can help.
(function () {
const input = prompt("Please enter One number (N) where (N) is a positive integer.", "");
let count = 100;
if (isNaN(input) || input < 1) return;
const inerval = setInterval(() => {
count--;
if (count % 2 == 0) {
console.log('This is even Numbers ' + count);
} else {
console.log('This is odd Numbers ' + count);
}
if (input == count) return clearInterval(inerval);
}, 1000);
})();
I think this is a possible solution, without many changes to your original code:
<div id="counter">100</div>
<p id="results"></p>
<script>
var input = parseInt(prompt("Please enter One number (N) where (N) is a positive integer.", ""));
var half = parseInt(input / 2);
var i = document.getElementById('counter');
var res = document.getElementById('results');
res.innerHTML += "Even: ";
if (parseInt(i.innerHTML) % 2 == 0) {
res.innerHTML += i.innerHTML;
input--;
}
function countdown() {
if (input == 0) {
clearInterval(timerId);
return;
}
if (input == half) {
var newValue;
if (input % 2) {
newValue = parseInt(i.innerHTML) + input * 2 - 3;
}
else {
newValue = parseInt(i.innerHTML) + input * 2 - 1;
}
i.innerHTML = newValue;
res.innerHTML += "</br> Odd: ";
}
else {
i.innerHTML = parseInt(i.innerHTML) - 2;
}
res.innerHTML += " " + i.innerHTML;
input--;
}
var timerId = setInterval(function(){ countdown(); }, 1000);
</script>
<p id="demo"></p>
Basically you decrease it by 2 till you reach the half, then you go back to the start - 1, looping through the odd numbers (or even, if the counter value was odd at first).

No response from recursive function

I want to create a function that is able to determine if a number is same or palindrome. if a given number is palindrome or same then return 2 otherwise if it is not palindrome or same then i need check it twice by increment the given number by 1. after that if it palindrome or same then return 1. if no palindrome or same number found then return 0. i write the function which is giving me the exact result when i give the number as 11211 but the function don't show any response if i enter 1122 or other random value. please help me to find where the error of my function.
function sameOrPalindrome(num) {
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
here is my solution to this problem:
function reversedNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
function sameOrPalindrome(num) {
if (num === reversedNum(num)) {
return 2;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
Perhaps not using recurse - I think your function loops
const allEqual = arr => arr.every( v => v === arr[0] )
const sameOrPalin = num => {
const str = String(num);
let arr = str.split("")
if (allEqual(arr)) return 2
arr.reverse();
if (arr.join("") === str) return 1;
return 0
};
console.log("1111",sameOrPalin(1111));
console.log("2111",sameOrPalin(2111));
console.log("2112",sameOrPalin(2112));
console.log("1234",sameOrPalin(1234));
for (let i = 2111; i<=2113; i++) console.log(i,sameOrPalin(i));
Question: I assumed if palindrome test is true at first time then return 2. if not try incrementing by one and test the palindrome again . if true return 1 else try incrementing for last time and check the palindrome if true return 1 else 0.
Store string into array first and do arr.reverse().join("") to compare
let arr=num.toString().split("");
if(num.toString() == arr.reverse().join(""))
function sameOrPalindrome(num, times) {
let arr = num.toString().split("");
if (num.toString() == arr.reverse().join("")) {
if (times == 3) return 2
else return 1;
} else if (times > 0) {
num++; times--;
return sameOrPalindrome(num, times);
} else return 0
}
console.log(sameOrPalindrome(123321, 3));
console.log(sameOrPalindrome(223321, 3));
console.log(sameOrPalindrome(323321, 3));
Your function needs to know if it should not call itself any more, e.g. when it's doing the second and third checks:
function sameOrPalindrome(num,stop) { // <-- added "stop"
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else if(!stop) { // <-- check of "stop"
num++;
al = sameOrPalindrome(num,true); // <-- passing true here
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num,true); // <-- and also here
if (al == 2) {
return 1;
}
}
}
return 0;
}
for(let i=8225;i<8230;i++)
console.log(i,sameOrPalindrome(i));
function check_palindrom(num){
var c1 = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] == revArray[i]) {
c1++;
}
}
if(c1==0){
return 2;
}else{
return 1;
}
}//check_palindrom
function my_fun_check_palindrome(mynum){
//console.log(mynum);
var num = mynum;
var c2 = 0;
var al = 0;
var normalArray = mynum.toString().split("");
var revArray = mynum.toString().split("").reverse();
for (var j = 0; j < normalArray.length; j++) {
if (normalArray[j] == revArray[j]) {
c2++;
}
}
if(c2==0){
console.log('Number is palindrome. Return Value :'+ 2);
}
if(1){
console.log('checking again with incremeting value my one');
num = parseInt(num)+1;
al = check_palindrom(num);
if(al==2){
console.log('Number is palindrome. Return Value :'+ 1);
}else{
console.log('Number is not palindrome. Return Value :'+ 0);
}
}
}//my_fun_check_palindrome
console.log(my_fun_check_palindrome(1122));
console.log(my_fun_check_palindrome(11221));
We should always strive to make function more effiecient... you dont need to run full loop. plus actual checking of palindrome can me modularized
function isSameOrPalindrome(num) {
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse(),
i;
for (i = 0; i < normalArray.length / 2; i++) {
if (normalArray[i] !== revArray[i]) {
break;
}
}
if (i >= normalArray.length/2) {
return "Palindrome";
} else {
return "Not Palindrome";
}
}
function doCheck(num) {
var isPalindrome = isSameOrPalindrome(num);
console.log(isPalindrome);
if(isPalindrome === "Palindrome") {
return 2;
} else {
num++;
isPalindrome = isSameOrPalindrome(num);
if(isPalindrome === "Palindrome") {
return 1;
} else {
return 0
}
}
}
console.log("100",doCheck(100));

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

javascript function to add values outside of bracket into values inside the bracket

i am trying to create a function that automatically create questions to do.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var totalvar = getRandomInt(2,4);
var main = "";
for (var i = 1; i <= totalvar; i++) {
var test = getRandomInt(1,3);
// alert(test);
var myArray = ["A","B","C","A&apos;","B&apos;","C&apos;"];
var text ="";
for (var a = 1; a <= test; a++) {
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
var testing = random(myArray);
if (testing =="A") {
var testing2 ="A&apos;";
} else if (testing =="A&apos;") {
var testing2 ="A";
} else if (testing =="B") {
var testing2 ="B&apos;";
} else if (testing =="B&apos;") {
var testing2 ="B";
}else if (testing =="C") {
var testing2 ="C&apos;";
} else if (testing =="C&apos;") {
var testing2 ="C";
}
//alert(testing);
//alert(myArray);
text += testing
var index = myArray.indexOf(testing);
if (index > -1) {
myArray.splice(index, 1);
}
var index = myArray.indexOf(testing2);
if (index > -1) {
myArray.splice(index, 1);
}
}
var brackets = getRandomInt(1,3);
var chances = getRandomInt(1,3);
var lastLetter = main.charAt(main.length - 1);
if (brackets == 1) {
text = "(" + text + ")";
if (main == "") {
main = text;
} else if ( lastLetter == ')') {
if ( chances !== 1) {
main += text;
}else
main += "+" + text;
}else
main += "+" + text;
} else {
if (main == "") {
main = text;
} else if ( lastLetter == ')') {
if ( chances !== 1) {
main += text;
}else
main += "+" + text;
}else
main += "+" + text;
}
}
I have manage to get it to display questions that i want
B'C'+(A'C'B')+BCA
B+(C')(CAB)
A'BC+(C')A+AB'
B'C'+AB(A'C'B')+BCA
I am stucked as i couldnt get the function for the next step where it multiples the value outside the bracket
B'C'+A'C'B'+BCA
B+C'CAB
A'BC+C'A+AB'
B'C'+ABA'C'B'+BCA
The above is what i hope to achieve but im unable to create the function out
any tips guys?
use replace:
var str = "B'C'+(A'C'B')+BCA";
var response = str.replace(/([\(\)]+)/g, '');
console.log(response);
// output: "B'C'+A'C'B'+BCA"

JS Empty focused Input

If the user enters an invalid number, I want to empty the input. Negative numbers and numbers that are decimal are not allowed.
This is my Js Function:
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').html("");
}
$('#priceOutput').html(output);
}
But somehow the input is not empty if I enter a count that goes into the else section.
change the value of the input with val() instead of html():
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').val("");
}
$('#priceOutput').html(output);
}

Categories

Resources