I am attempting one of reddits daily programmer challenges and for some reason my seemingly correct and simple code seems to be getting stuck.
Here is a link to the challenge I am doing
function play() {
var start = document.getElementById("userInput").value;
var number = parseInt(start);
if (Number.isInteger(number) === true) {
while (number != 1) {
if (number % 3 === 0) {
number / 3;
document.getElementById("answer").append(number + "/3");
} else if ((number - 1) % 3 === 0) {
number = number - 1;
document.getElementById("answer").append(number + "-1");
} else if ((number + 1) % 3 === 0) {
number = number + 1;
document.getElementById("answer").append(number + "+1");
} else {
document.getElementById("answer").append(number + "done");
}
}
} else {
document.getElementById("answer").innerHTML = "Please enter a WHOLE NUMBER";
}
}
Related
I need my code to only accept whole numbers, no decimals and should prompt an error when a decimal gets entered. I don't want a new function , I'm hoping I can just add lines to my function but I don't know what I need to add.
function number_function() {
number = parseInt(prompt('Enter a positive integer:'));
if (number < 0) {
alert('Error! Factorial for negative number does not exist. But I will show you the positive number');
number = number * -1;
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
} else if (number === 0) {
alert("Please enter a number greater than 0");
} else {
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
}
}
number_function();
You can do this to check if the number has decimals
const val = 10.7 % 1;
if (val !== 0) {
console.log('has decimals');
} else {
console.log('has no decimal');
}
JavaScript provides the built-in function Number.isInteger(n)
I tried one practice and check the requirement below.
You are on your way to find the gifts. All the gifts lie in your path in a straight line at prime
numbers and your house is at 0.
Given your current position find the closest gift to your position, and calculate the distance
between your current position and gift and tell the distance.
Ex:
For input 0, the output is 2
For number = 11, the output should be 0
For number = 2000000000, the output should be 11 For number = 1800000001, the output
should be 10
For the above logic I tried to use javascript and almost I have completed but i'm not getting the proper outpu as per the requirement,my output is returning any number.
Javascript
function isPrime(num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true
} else if (num % 2 === 0 || num % 3 === 0) {
return false
}
let i = 5
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
return false
}
i += 6
}
return true
}
HTML
<h1> Gift House</h1>
<label for="name">Enter a house Number</label>
<input type="text" id="inp" class="clr" />
<input type="button" id="checker" value="Calculate" onClick="findpos()">
<label for="name"> Distance of the gift house</label>
<input type="text" id="demo" value="" class="clr">
I understood your requirement,you have tried 2 steps properly but before those two steps you have to do one more logic to calculate prime number.Because you have called the function isPrime in your JS but where you defined the function?
Just include the below script in your JS code and check the output.
function findpos() {
var num = document.getElementById("inp").value;
var pos = 0;
while (true) {
if (isPrime(num)) {
break;
} else {
pos++;
num++;
}
}
document.getElementById("demo").value = pos;
}
Where is the isPrime function? how you called without defining the function.I think this is what the reason for your issue.
Check my below example,
function findpos() {
var num = document.getElementById("inp").value;
var pos = 0;
while (true) {
if (isPrime(num)) {
break;
} else {
pos++;
num++;
}
}
document.getElementById("demo").value = pos;
}
function isPrime(num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true
} else if (num % 2 === 0 || num % 3 === 0) {
return false
}
let i = 5
while (i * i <= num) {
if (num % i === 0 || num % (i + 2) === 0) {
return false
}
i += 6
}
return true
}
Hi This is my first time using this website, I did do some research about how to convert lowercase letter to uppercase letter but still filles. The requirement is to check if "even", covert the even digit letter to different type(lower to upper or upper to lower). below is my code:
function question4(str,pos)
{ var newLetter;
var kkk=str;
if (pos='even')
{
for (var i=0;i<str.length;i=i+2)
{
if (str[i].toString()==str[i].toString().toUpperCase())
{
newLetter=str[i].toString().toLowerCase();
kkk[i]=newLetter;
}else
{
newLetter=str[i].toUpperCase();
kkk[i]=newLetter;
}
}
}else if (pos='odd')
for ( i=0;i<str.length;i=i+2)
{
if (str[i]===str[i].toLowerCase())
{
alert('3');
}else if (str[i]===str[i].toUpperCase())
{
alert('4');
}
}
return kkk;
}
the requirement is: Write a function to change the case of all the characters in string based on their position which matches the value of the pos parameter function. function (str, pos [even|odd]). Example ( (‘abCd’, ‘odd’) return Abcd)
Update: now I have make "odd" condition working, but "even "still is not working, can any one take a look why?
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}else result=strr[i];
sum+=result;
}
return sum;
}
To achieve this, you can construct a string by concating char by char:
function question4(strInput, pos) {
let str = ""; // The string to construct
if (!pos || (pos !== "even" && pos !== "odd")) { // Validating pos
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++) // Looping on strInput
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
/* If we want switch odd and we are on even position or if we want switch even and we are on odd position, then we add the original char
*/
str += strInput[i];
}
else {
// In others case, we switch lower to upper and upper to lower
let char = strInput[i];
str += char == char.toUpperCase() ? char.toLowerCase() : char.toUpperCase();
}
}
return str;
}
console.log(question4('abCdef', "odd")); // Return "AbcdEf"
Associated bin
EDIT:
After seeing edit, i can see you want to do it without using toLower/UpperCase. As stated in comment i think it is a bad idea in js, but to experiment you can achieve this:
const reverser = {
"a": "a".charCodeAt(0),
"z": "z".charCodeAt(0),
"A": "A".charCodeAt(0),
"Z": "Z".charCodeAt(0),
};
const conversionValueToLower = reverser.a - reverser.A;
const conversionValueToUpper = reverser.A - reverser.a;
function reverseChar(char) {
var code = char.charCodeAt(0);
// If you want to go from upper to lower
if (code >= reverser.A && code <= reverser.Z) {
// Simply add the difference between lower and upper
return String.fromCharCode(code + conversionValueToLower);
} // Same logic here
else if (code >= reverser.a && code <= reverser.z) {
return String.fromCharCode(code + conversionValueToUpper);
}
/**
Or use if you want full digit
if (code <= 90 && code >= 65) {
return String.fromCharCode(code + 32);
}
else if (code >= 97 && code <= 122) {
return String.fromCharCode(code - 32);
}
**/
return char; // Other case return original char
}
function question4(strInput, pos) {
let str = "";
if (!pos || (pos !== "even" && pos !== "odd")) {
throw "invalid pos";
}
for (var i=0;i<strInput.length;i++)
{
let huPos = i + 1;
if ((pos === "even" && huPos%2 == 1) ||
(pos === "odd" && huPos%2 == 0)) {
str += strInput[i];
}
else {
str += reverseChar(strInput[i]);
}
}
return str;
}
console.log(question4('abCdef', "odd")); // return "AbcdEf"
Associated bin
Another way could be to code utils functions imitating toLower/UpperCase
I corrected your code in your answer aswell, without changing original logic
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
console.log(question4("abCd", "odd")) // return Abcd;
A simple solution for this question
// Function used to invert the letter case
const changeCase = c => {
if (c === c.toUpperCase()) return c.toLowerCase()
return c.toUpperCase()
}
const swapCaseConditional = (str, pos) => {
// Use split method to convert string into array and map the array
return str.split('').map((c, index) => {
if (pos === 'even') {
// if pos and index are even, change the letter case
if (index % 2) return changeCase(c)
return c
}
else {
// if pos and index are odd, change the letter case
if (!(index%2)) return changeCase(c)
return c
}
// Convert to string
}).join('')
}
console.log(swapCaseConditional('abCd', 'odd'))
I worked two nights and finally got it working. although not fully cover all the situations, but almost there.
function question4(strr,pos) {
var result ;
var sum="";
var aaa;
for (var i = 0; i <= strr.length - 1; i = i + 1)
{
if (pos == "odd"&&i%2==0)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result = String.fromCharCode(aaa + 32);
} else
result = String.fromCharCode(aaa - 32);
}
else if (pos == "even"&&i%2==1)
{ aaa=strr.charCodeAt(i);
if (aaa >= 65 && aaa <= 90 )
{
result= String.fromCharCode(aaa + 32);
} else if(aaa >=97&&aaa <=122)
{ result = String.fromCharCode(aaa - 32);}
else {result=strr[i];}
}else {result=strr[i];}
sum+=result;
}
return sum;
}
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)
}
}
I am trying to write javascript code that will emulate a program that prints ping for numbers divisible by three, pong for numbers divisible by five, and ping-pong for numbers divisible by both, otherwise just printing the number. I've got it to work but I know I should probably use jQuery to make this more efficient. I been following a tutorial on the prepend method and read up on it a bit but I can't figure out how to implement it into my code yet. Any pointers?
<ul>
<script>
ppCount = prompt("What number would you like me to ping-pong up to?");
// document.write(console.log(ppCount));
function pingPong (ppCount) {
for (var index = 1; index <= ppCount; index += 1) {
if (index % 3 === 0 && index % 5 === 0) {
document.write('<li>' + "ping-pong" + '</li>')
} else if (index % 3 === 0) {
document.write('<li>' + "ping" + '</li>')
} else if (index % 5 === 0) {
document.write('<li>' + "pong" + '</li>')
} else {
document.write('<li>' + index +'</li>')
}
document.write('<br>')
}
};
pingPong(ppCount);
</script>
</ul>
http://jsfiddle.net/5kj1m493/
<ul></ul>
and
$(function() {
$.each(new Array(prompt("What number would you like me to ping-pong up to?") * 1),
function(ind) {
var i = ind + 1;
var message = !(i % 5) && !(i % 3) ? 'ping-pong' :
(!(i % 5) ? 'pong' : (!(i % 3) ? 'ping' : i));
$('<li>').html(message).appendTo($('ul'));
});
});
Or with for loop ))
From the looks of it, You are writing the contents of document - on the fly - while the document is being loaded.
i.e, document.write() writes the content where it is encountered (In this case, inside the <ul>). I'm afraid it's possible to do the same with jQuery...
If you want to do this after the <ul> is created, You can do:
$(document).ready(function(){
var ppCount = new Array(prompt("What number would you like me to ping-pong up to?"));
function pingPong(ppCount) {
for (var index = 1; index <= ppCount; index++) {
if (index % 3 === 0 && index % 5 === 0) {
$("ul").append('<li>ping-pong</li>')
} else if (index % 3 === 0) {
$("ul").append('<li>ping</li>')
} else if (index % 5 === 0) {
$("ul").append('<li>pong</li>')
} else {
$("ul").append('<li>' + index + '</li>')
}
}
};
pingPong(ppCount);
})