I don't really see how this could be wrong code.
In few examples, there is no output at all or it's only "10" in this one.
var num2 = 10;
while (num2 >= 10 && num2 <= 40 && num2%2===0){
console.log(num2);
num2++;
}
or like this:
var num2 = 10;
while (num2 >= 10 && num2 <= 40){
if (num2%2===0){
console.log(num2);
num2++;
}}
Your first loop stops after the first iteration because 11 is not an even number, so num2%2===0 is false.
Your second loop never stops because it only increments num2 if it's even (from 10 to 11), but 11 is not even and so num2 never changes.
Fix:
var num2 = 10;
while (num2 >= 10 && num2 <= 40) {
if (num2%2===0) {
console.log(num2);
}
num2++;
}
I.e. always increment num2, but only print the even numbers.
Alternatively:
var num2 = 10;
while (num2 >= 10 && num2 <= 40) {
console.log(num2);
num2 += 2;
}
I.e. start at an even number and always increment by 2.
Related
I am trying to learn python and I have tried to convert a code snippet in js to python. I have created a function in js to calculate GCD as follows:
// program to find the GCD of two integers
let gcd
function GCD() {
// take input
const number1 = prompt('Enter a first positive integer: ')
const number2 = prompt('Enter a second positive integer: ')
// looping from 1 to number1 and number2
for (let i = 1; i <= number1 && i <= number2; i++) {
if( number1 % i == 0 && number2 % i == 0) {
gcd = i
}
}
// display the gcd
document.write(`GCD of ${number1} and ${number2} is ${gcd}.`)
}
GCD()
If I supply the first integer as 9 and the second integer of 3, I get the GCD as 3.
I have tried to convert this to a python program as follows:
def gcd():
gcd = 0
num1 = int(input("Enter a first positive integer: "))
num2 = int(input("Enter a second positive integer: "))
for i in range(1, i<=num1 and i<=num2):
if num1 % i == 0 and num2 % i == 0:
gcd = i
print(f"GCD of: {num1} and: {num2} is {gcd}")
gcd()
But I don't know how to get the for loop in python quite right. If I change the for statement to:
def gcd():
gcd = 0
num1 = int(input("Enter a first positive integer: "))
num2 = int(input("Enter a second positive integer: "))
for i in range(1, num1 and num2):
if num1 % i == 0 and num2 % i == 0:
gcd = i
print(f"GCD of: {num1} and: {num2} is {gcd}")
gcd()
and I give the same input as before of 9 and 3, I get GCD of 1
You can't have an equivalent syntax as i <= number1 && i <= number2 as it is a boolean expression that works as stop condition which is checked at every iteration.
While a for loop in python code generates values with boudaries, to do the same, iterate until the lowest value:
for i in range(1, min(num1, num2) + 1):
if num1 % i == 0 and num2 % i == 0:
gcd = i
To use the condition of the JS code, you need a while loop:
i = 1
while i <= num1 and i <= num2:
if num1 % i == 0 and num2 % i == 0:
gcd = i
i += 1
this is a solution based on while loop
def gcd():
gcd=0
num1 = int(input("Enter a first positive integer: "))
num2 = int(input("Enter a second positive integer: "))
i = 1
while(i <= num1 and i <= num2):
if(num1 % i == 0 and num2 % i == 0):
gcd = i
i = i + 1
print("GCD : ", gcd)
gcd()
I'm a newbie writing a program that continues to ask the user for a number until the entered number is less than or equal to 100. I keep ending up in an infinite loop and I'm unsure of how to add the correct conditions to end the loop.
let num;
while (!(num === 100 && num < 99)) { // infinite loop
num = Number(prompt("Enter a number: "));
console.log(num);
}
I want to exit the loop when the user enters a number less than or equal to 100.
To resolve this issue use either
!(num === 100 || num < 100) or
!(num <= 100)
Issue: Num can never be both equal to 100 and less than 99 , so it will be false always and so while condition is true always
let num;
while (!(num <= 100)) { //or !(num === 100 || num < 100)
num = Number(prompt("Enter a number: "));
console.log(num);
}
let num;
while (true) {
num = Number(prompt("Enter a number: "));
if (num <= 100) {
break;
}
}
let num = 101;
while (num > 100) {
num = Number(prompt("Enter a number: "));
console.log(num);
}
Or with Do/While:
let num;
do {
num = Number(prompt("Enter a number: "));
console.log(num);
} while (num > 100);
I have 8 items in an array, I want to calculate the difference btw them. But my code has flaw, the output is wrong with different set of array.
What's wrong here?
const calculate_different_in_percentage = (num1, num2) => {
//zero handling
if (num2 === 0 && num1 > num2) {
return 100
}
if (num1 === 0 && num1 < num2) {
return 100
}
let result = 0
if (num1 > num2) {
result = ((num1 - num2) / num1) * 100
} else if (num2 > num1) {
result = ((num2 - num1) / num2) * 100
} else {
result = 0
}
if (!Number.isFinite(result)) result = 0
return result.toFixed(1)
}
https://jsfiddle.net/5ptfqgcw/2/
from 362 to 1916 the difference should be 529% but it didn't happens in my case, couldn't spot what's wrong.
from 362 to 1916 the difference should be 529% but it didn't happens
in my case, couldn't spot what's wrong.
You are calculating the percentage of difference between two elements in the order of appearance rather than just the percentage as you mentioned in your question.
To simply get the percentage use this simple code
const calculate_different_in_percentage = (num1, num2) => (num2 != 0 && num1 != 0) ? ((num2/num1)*100).toFixed(1) : 0;
Explanation
If num1 and num2 are not same and both numbers are not 0, then return ((num2/num1)*100).toFixed(1)
Else, return 0
Demo
let arr = [{ "total_count": 40}, { "total_count": 20},{"total_count": 0}, {"total_count": 100}, {"total_count": 362}, {"total_count": 1916}, {"total_count": 4046}, {"total_count": 2473}];
const calculate_different_in_percentage = (num1, num2) => (num2 != 0 && num1 != 0) ? ((num2 / num1) * 100).toFixed(1) : 0;
const result = [];
arr.forEach((obj, i) => {
if (!i) return
result.push({
count: obj.total_count,
difference: calculate_different_in_percentage(arr[i - 1].total_count, obj.total_count)
})
})
console.log(result);
I need to update a loop so that if 13 is a number between num1 and num2 (inclusive), then the loop skips it and continues to push the rest of the numbers to the array.
I am getting the error that I need to push 13 to the array. My updated code:
var addToArray = function(num1, num2) {
var array = [];
for (var i = num1; i <= num2; i++) {
if(num1 > 12 && num2 < 14 ){
continue;
}
array.push(i);
}
return array;
};
for(var i = 0; i < sum.length; i++){
if(sum[i] !== 13){
sumOfArray += sum[i];
}
I'm assuming num1 = 0 and num2 = sum.length. You should check to see if the item at sum[i] doesn't equal 13 and add the item if it doesn't. it will skip over the number 13 if you do.
var numsToAddExceptThriteen = function(num1, num2) {
var numsInArray = [];
var totalSum = 0;
//make sure we start with the smaller number;
if (num1 > num2) {
var tempNum = num2;
num2 = num1;
num1 = tempNum;
}
//cycle through values and skip 13
for ( var i = num1; i <= num2; i++ ) {
if ( i !== 13 ) {
numsInArray.push(i);
totalSum += i
}
}
//log both values
console.log(numsInArray);
console.log(totalSum);
};
numsToAddExceptThriteen(10, 80);
#Lkoprivica, I think what you will need is twofold. First you will need to define num1 and num2. I'm not sure how you are generating these numbers though, so cannot guess. As far as the loop, you could do something like so:
var num1, num2; //these should be populated with numbers from somewhere
for(var i = 0; i < sum.length; i++){
if( (sum[i] === 13 && sum[i] > num1 && sum[i] < num2 ) || (sum[i] === 13 && sum[i] < num1 && sum[i] > num2 ) ){
//we skip the else and move along if sum[i] is between num1 and num2 and if it equals 13
} else {
sumOfArray += sum[i];
}
}
I'm trying to create a game in which a user "bets" on if the next card will be in between the previous two shown. In order to calculate that, I created a random number through 52 and set it equal to an array variable value. I need a number 2-14 as opposed to 1-52 (to evaluate the # of the card in case 2 cards with same # and different suite show). To do that, I used slice to get the 1st letter of the array item and store it in a variable (num1, num2, numUser).
I then used if else statements to give the face cards (10, jack, queen, king, ace) # values. The issues is, I need to apply this to all 3 variables. Currently, the statement stops when it identifies a face card and sets the # value. If there are multiple face cards, the statement only applies to the first.
I tried wrapping this in a for loop and making it run 3 times- ex.(for (var i = 0; i > 3; i++), but that didn't work. Sorry if this is confusing, any help is greatly appreciated.
function outputCards(){
rand1 = Math.floor((Math.random() * 52));
rand2 = Math.floor((Math.random() * 52));
$('#cardUser').attr("src", "#");
if(rand1 == rand2){
rand2 = Math.floor((Math.random() * 52));
} else {
card1 = cards[rand1];
card2 = cards[rand2];
$('#cardOne').attr("src", "imgs/" + card1);
$('#cardTwo').attr("src", "imgs/" + card2);
}
}
function userCard(){
rand_user = Math.floor((Math.random() * 52));
if(rand_user == rand1 || rand_user == rand2){
rand_user = Math.floor((Math.random() * 52));
} else {
user_card = cards[rand_user];
$('#cardUser').attr("src", "imgs/" + user_card);
}
}
function outcome(){
userCard();
num1 = card1.slice(0,1);
num2 = card2.slice(0,1);
numUser = user_card.slice(0,1);
if(num1 == "j"){
num1 = 11;
} else if (num2 == "j") {
num2 = 11;
} else if (numUser === "j") {
numUser = 11;
} else if (num1 == "q") {
num1 = 12;
} else if (num2 == "q") {
num2 = 12;
} else if (numUser === "q") {
numUser = 12;
} else if (num1 == "k") {
num1 = 13;
} else if (num2 == "k") {
num2 = 13;
} else if (numUser === "k") {
numUser = 13;
} else if (num1 == "a") {
num1 = 14;
} else if (num2 == "a") {
num2 = 14;
} else if (numUser === "a") {
numUser = 14;
} else if(num1 == 1){
num1 = 10;
} else if(num2 == 1){
num2 = 10;
} else if(numUser == 1){
numUser = 10;
} else {
}
}
well theres more efficient ways to accomplish this, the most straightforward (and beginner friendly) one is to use 3 else if trees not a single one.
if(num1 == "j"){
num1 = 11;
} else if (num2 == "j") {
num2 = 11;
} else if (numUser === "j") {
numUser = 11;
...
you have these grouped together when they need to be separate
if(num1 == "j"){
num1 = 11;
} else if (num1 == "q") {
num1 = 12;
} else if (num1 === "k") {
num1 = 13;
...
if(num2 == "j"){
num2 = 11;
} else if (num2 == "q") {
num1 = 12;
} else if (num2 === "k") {
num2 = 13;
...
this can be accomplished by putting the if statements in a function
function outcome(number){
if(number == "j"){
return 11;
} else if (number == "q") {
return 12;
} else if (number === "k") {
...
} //etc
}
num1 = outcome(card1.slice(0,1))
num2 = outcome(card2.slice(0,1))
numUser = outcome(user_card.slice(0,1));
you can also create an object map to map the card letter with a number value
var cardMap = {
j: 11,
q: 12,
k: 13,
...
}
then you can do
num1 = cardMap[card1.slice(0,1)]
num2 = cardMap[card2.slice(0,1)]
numUser = cardMap[user_card.slice(0,1)]
An if-elseif block will stop execution whenever it finds a true conditional, regardless of how many you have.
So you want to evaluate the variable based on the first character, and you know that will always be the same, right? This is a great opportunity to use a simple function that does just that one job (as all functions should do).
function getCardValueFromFirstCharacter(character) {
// you may need to check for the number as well:
// if (character == "1") {
// return 1;
// } else if (character == "2") {
// return 2;
// }
// etc..
if (character == "j") {
return 11;
} else if (character == "q") {
return 12;
}
// etc..
}
Now, in your other function, your outcome function, you can call this one with each of your desired inputs:
function outcome() {
userCard();
num1 = getCardValueFromFirstCharacter(card1.slice(0,1));
num2 = getCardValueFromFirstCharacter(card2.slice(0,1));
numUser = getCardValueFromFirstCharacter(user_card.slice(0,1));
}
In this way, we have our single function that is solely responsible for identifying the value of a card based on the first character. This function can change its implementation to affect all of places we need to use it - so, let's say you decide Jokers should be evaluated as 20, you can add it to that one function, and all of your code will now work with that new value. Thus, breaking apart our code into tiny functions that do one thing and are referenced for that one thing all over our codebase is important.