I need to create a sequence of numbers using while or for that consists of the sum of the symbols of the number.
For example, I have a sequence from 1 to 10. In console (if I've already written a code) will go just 1, 2,3,4,5,6,7,8,9,1. If I take it from 30 to 40 in the console would be 3,4,5,6,7,8,9,10,11,12,13.
I need to create a code that displays a sum that goes from 1 to 100. I don't know how to do it but in console I need to see:
1
2
3
4
5
5
6
7
8
9
1
2
3
4
etc.
I've got some code but I got only NaN. I don't know why. Could you explain this to me?
for (let i = '1'; i <= 99; i++) {
let a = Number(i[0]);
let b = Number(i[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log ('b false', a)
}
else {
console.log ('b true', a + b)
}
}
I hope you get what I was speaking about.
Although I like the accepted answer however from question I gather you were asking something else, that is;
30 become 3+0=3
31 become 3+1=4
37 becomes 3+7=10
Why are we checking for boolean is beyond the scope of the question
Here is simple snnipet does exactly what you ask for
for (let i = 30; i <= 40; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
what er are doing is exactly what Maskin stated begin with for loop then in each increment convert it to string so we can split it, this takes care of NAN issue.
you don't need to call to string just do it once as in let x then simply call the split as x[0] and so on.
within second number we have created a self computation (x[1])||0) that is if there is second value if not then zero. following would work like charm
for (let i = 1; i <= 10; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
Did you observe what happens to ten
here is my real question and solution what if you Don't know the length of the digits in number or for what ever reason you are to go about staring from 100 on wards. We need some form of AI into the code
for (let i = 110; i <= 120; i++) {
let x= Array.from(String(i), Number);
console.log(
x.reduce(function(a, b){ return a + b;})
);
};
You simply make an array with Array.from function then use simple Array.reduce function to run custom functions that adds up all the values as sum, finally run that in console.
Nice, simple and AI
You got NaN because of "i[0]". You need to add toString() call.
for (let i = '1'; i <= 99; i++) {
let a = Number(i.toString()[0]);
let b = Number(i.toString()[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log('b false', a)
} else {
console.log('b true', a + b)
}
}
So the way a for loop works is that you declare a variable to loop, then state the loop condition and then you ask what happens at the end of the loop, normally you increment (which means take the variable and add one to it).
When you say let i = '1', what you're actually doing, is creating a new string, which when you ask for i[0], it gives you the first character in the string.
You should look up the modulo operator. You want to add the number of units, which you can get by dividing by 10 and then casting to an int, to the number in the tens, which you get with the modulo.
As an aside, when you ask a question on StackOverflow, you should ask in a way that means people who have similar questions to you can find their answers.
Related
Beginning JavaScript learner here...
I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 6 in the elementary exercises.
Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.
// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");
if (userChoice == "+") {
for (var i = userNum; i > 0; i--) {
mySum += +i;
}
console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
for (var i = userNum; i > 0; i--) {
mySum *= +i;
// myArray.push(i); // for testing
}
console.log("Your answer is " + mySum);
// console.log(myArray); // for testing
}
When entering values for multiplication, the answer is always 0. Obviously, I thought 0 was being included in the iteration, so I setup an empty array myArray, and pushed all the numbers to the array using myArray.push(i);... 0 was never included as a value in the array.
Other than some obvious form-validation considerations, can anyone tell me what I'm missing? Why is my answer always 0?
Note: The sum section of the code seems to work brilliantly.
Please note I'm a beginniner to JavaScript, so if you'd like to comment, let me know WHY you changed the code the way you do, rather than simply spitting back code to me. That's a big help, thanks.
Well, you initialize mySum to 0 so in every iteration of the loop you'll multiplying i by zero and save the result (again, zero) back into mySum. For multiplication you'd have to start at one.
You didn't set mySum to 1 before multiplication. 0*i = 0.
Much apologies for the vague title, but I need to elaborate. Here is the code in question, which I read on http://ariya.ofilabs.com/2013/07/prime-numbers-factorial-and-fibonacci-series-with-javascript-array.html:
function isPrime(i) {
return (i > 1) && Array.apply(0, Array(1 + ~~Math.sqrt(i))).
every(function (x, y) {
console.log(x + ' ' + i % y);
return (y < 2) || (i % y !== 0)
});
}
isPrime(23);
isPrime(19);
isPrime(188);
Just for fun, I added those logs so we can see some output:
undefined NaN
undefined 0
undefined 1
undefined 2
undefined 3
undefined NaN
undefined 0
undefined 1
undefined 1
undefined 3
undefined NaN
undefined 0
undefined 0
This is the first time I have every seen apply and every, so bear with me, but my understanding is that apply basically calls the Array function, where the first argument is the substitution for its this and the second is the output...Never would think that would be useful, but this function seems to work, so...
Here, they seem to be creating an array of length equal to the square root of the number in question. I suppose that makes sense because the square root would be the largest possible factor of the number in question.
OK, so from here, if we were to log that array for, say, the first number, it would look like this:
> var i = 23;
undefined
> Array.apply(0, Array(1 + ~~Math.sqrt(i)));
[ undefined, undefined, undefined, undefined, undefined ]
Great, so it is an array of five undefined. Ok, fine, so from here, the every method is supposed to check whether every element in that array passes the callback function test (or whatever).
The Microsoft documentation specifies three possible arguments for the every method:
value
index
array
Therefore, in this example x is the value, i.e. undefined, and y is the index.
Our output agrees with that conclusion. However, I'm still fuzzy about nested return statements (if the lowest one returns, does its parent also return?), the || operator here (if the first test passes, does the every loop stop?), and just generally how this works.
EDIT
the log should be with an x, not a y. my mistake:
console.log(y + ' ' + i % y); -> console.log(x + ' ' + i % y);
EXPLANATION
So, how did I come across this code, you ask? Well, of course, the simplest way to check for a prime in Java would be like this:
public static boolean isPrime(double num) {
for (double i = 2.0; i < sqrt(num); i++) {
if (num % i == 0.0) {
return true;
}
}
return false;
}
or Python
def isPrime(num):
x = 2
isPrime = True
while x < math.sqrt(num):
if num % x == 0:
isPrime = False
break
x = x + 1
return isPrime
or js
function isPrime(n) {
for (var i = 2.0; i < Math.sqrt(n); i++) {
if (n % i === 0.0) {
return false;
}
}
return true;
}
But say I wanted to check for the largest prime factor of a number like 600851475143 These looping methods would take too long, right? I think this "hack", as we are describing it, may be even less efficient, because it is using arrays instead of integers or floats, but even still, I was just looking for a more efficient way to solve that problem.
The code in that post is basically crap. Teaching people to write code while simultaneously using hacks is garbage. Yes, hacks have their place (optimization), but educators should demonstrate solutions that don't depend on them.
Hack 1
// the 0 isn't even relevant here. it should be null
Array.apply(0, Array(1 + ...))
Hack 2
// This is just Math.floor(x), but trying to be clever
~~x
Hack 3
// this is an outright sin; totally unreadable code
// I bet most people don't know the binding precedence of % over +
y + ' ' + i % y
// this is evaluated as
y + ' ' + (i % y)
// example
2 + ' ' + (5 % 2) //=> "2 1"
I'm still fuzzy about nested return statements (if the lowest one returns, does its parent also return?),
No. A return only return the function the statement exists in
the || operator here (if the first test passes, does the every loop stop?)
No. Array.prototype.every will return false as soon as the callback returns a false. If a false is never returned from the callback, .every will return `true.
function isEven(x) { return x % 2 === 0; }
[2,4,5,6].every(isEven); //=> false, stops at the 5
[2,4,6].every(isEven); //=> true
Here's an example of .every short circuiting
[1,2,3,4,5,6].every(x=> {console.log(x, x<4); return x<4;});
// 1 true
// 2 true
// 3 true
// 4 false
//=> false
See how it stops once the callback returns false? Elements 5 and 6 aren't even evaluated.
... and just generally how this works.
&& kind of works like Array.prototype.every and || kind of works like Array.prototype.some.
&& will return false as soon as the first false is encountered; in other words, it expects every arguments to be true.
|| will return true as soon as the first true is encountered; in other words, it expects only some argument to be true.
Relevant: short circuit evaluation
I wrote this program out in plain code but I don't know Javascript well enough to get all the syntax right. I am a beginning programming please help me with corrections to my code. It is currently not running at all. We are still going over loops and it's really giving me trouble. This is for a college class. (I know this isn't formatted properly that's why i'm asking for help)
function main() {
alert("Welcome to the program");
var fatGrams = getFatGrams(fatGrams);
var calories = getCalories(fatGrams,calories);
var percentage = caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
Errors in your code :
The function keyword is not needed to call a function. Remove the keyword function before calling a function and simply call the function as getFatGrams(fatGrams);
You are not passing parameters to function caloriesPercentage. Change it to caloriesPercentage(fatGrams,calories);
The expression for a while loop should be enclosed in paranthesis as while(fatGrams < 0).
The OR should be written as ||.
Use + to concatenate 2 string (Or a string and a variable)
"The amount of calories that come from fat is, " + percentage
The expression for an while should also be enclosed in paranthesis as if(percentage < 0.3) and no then is needed. The curly brackets of if should be closed before else.
if(percentage < 0.3){
alert("The food is low in fat.");
}
else {
alert("The food is not too low in fat.");
}
assign value from prompt to variable as
fatGrams = prompt("Enter the new number of fat grams.");
Your final code should look like this :
function main() {
alert("Welcome to the program");
var fatGrams;
var calories;
var percentage;
getFatGrams(fatGrams);
getCalories(fatGrams,calories);
caloriesPercentage(fatGrams,calories);
displayPercentage(percentage);
}
function getFatGrams(fatGrams) {
fatGrams = prompt("Enter the number of fat grams in your food item");
while(fatGrams < 0){
alert("Error, the fat grams cannot be less than 0.");
fatGrams = prompt("Enter the new number of fat grams.");
}
return fatGrams;
}
function getCalories(fatGrams,calories) {
calories = prompt("Enter the number of calories in your food item.");
while (calories < 9 || calories > (fatGrams * 9)){
alert("Error, the calories cannot be less than 9 or exceed the fat grams * 9");
calories = prompt("Enter the new number of calories");
}
return calories;
}
function caloriesPercentage(fatGrams,calories){
percentage = (fatGrams * 9) / calories;
alert("The amount of calories that come from fat is, " + percentage);
return percentage;
}
function displayPercentage(percentage){
if(percentage < 0.3){
alert("The food is low in fat.");
}
else{
alert("The food is not too low in fat.");
}
}
main();
alert("End of program");
welcome to the wonderful world of programming!
It looks like you are getting the basics down, let me explain some of the issues you are having with JavaScript. I'm going to use some big words (as will many other experienced developers so get used to them!).
Function Declaration vs Function Invocation
The very first issue I see with your main() function is a confusion about when to use the function keyword in JavaScript. You only need to use function when you are declaring a function, or in other words when you want to "create a new function." When you declare something, you are creating it, and in JavaScript the function keyword is how you declare (aka create) a Function. Here is an example of creating a "named function" in javascript.
function addTwo( number ) {
return number + 2;
}
That right there is a "named function" declaration. On a side note, you can also create functions as "expressions" (which would be called a "function expression"). That would look like this
var addThree = function( number ) {
return number + 3;
};
Note that in both cases we are creating a function with the function keyword.
When you want to use a function, you "invoke" it. This is also referred to as "calling" a function. To call (aka invoke) a function you simply write the function name with parenthesis behind it, passing in any arguments. Function invocation works the same for both named functions and function expressions. So we could invoke the two functions above like so
var four = addTwo( 2 );
var five = addThree( 2 );
Simply put, only use the function keyword to make functions. To call or use a function just put ( argument, otherArg ) at the end of the function name.
Branching Statements
The next thing I see is that you're missing some parenthesis! JavaScript has a C style syntax so that means you need to put parenthesis around expressions for if, else if, and switch statements. Those keywords I listed are what we call Branching Statements. They allow you to conditionally execute code based on some true or false value, as opposed to Looping Statements that allow you to repeat code based on a true or false value. The structure for an if .. else branching statement in JavaScript is as follows.
if ( number % 2 === 0 ) {
number *= 2;
} else if ( number % 3 === 0 ) {
number *= 3;
} else {
number += 5;
}
For both if and else if you need to provide an "expression" to branch around. An else statement is always executed if none of the if or else if expressions evaluated to true. The else clause is not required so if you don't have any code in your else block you can just remove it! It is perfectly fine to have a single if statement like this in your code
if ( needsCleanup ) {
doCleanup();
}
Of course it would be ok to have an else if clause and no else clause, the else is always optional. But remember the else clause never has an expression so you should never write () after a simple else.
Looping Statements
Looping is a big concept that takes a while to master so don't get frustrated or discouraged! In JavaScript we have for, while and do while loops. Just like if statements looping statements need an expression, but in this case they need it to know when to stop looping. I'm not going to cover do while loops because they are rarely used and can be confusing when just starting out. Simply put, looping statements say: "keep executing this code block until the expression is false." I find it easiest to illustrate this with a for loop. For loops are a great way to run a code block a specific number of times. Let's look at an example that adds all the numbers from 1 to 10 with a for loop.
var sum = 0;
for ( var i = 1 ; i <= 10 ; i++ ) {
sum += i;
}
// sum will be 55
// i will be 11
A for loop has three expression separated by ;. The first is for initialization and is only executed before the loop starts (the var i = 1 part). The second is the condition that is checked before each iteration. The last is an increment operation that is executed at the end of every loop execution. If we were to re-write this for loop as a while look it would look like this...
var sum = 0;
var i = 1;
while ( i <= 10 ) {
sum += i;
i++;
}
So you can see the var i = 1 happens before the loop starts. The i <= 10 happens before each time the loop runs its body (the part in the {}). And the i++ happens at the end of the loop before it checks i <= 10 to see if it should keep looping.
String Concatenation
String concatenation is the process of putting two strings together. In JavaScript the + operator does double duty as addition 1 + 1 and string concatenation 'hello' + ' world'. So when you want to put two strings together you simply add them! If the strings are in variables then you can just "add" them together...
var salutation = 'Hello';
var name = 'Kylie';
var greeting = salutation + ', ' + name;
// greeting will be "Hello, Kylie"
I hope that clears some things up, if you have any questions please let me know!
Because this IS for a class I am NOT going to give you the answers but instead point out the issues.
Calling a function in Javascript and return a value:
var myvalue = myFunction();
You have function... in your main and need to fix that.
Some functions just return values and thus calling them needs no parameter (like above) others need parameters for the inputs which you have done.
Prompt returns a value and you need to capture that value:
var myinputvalue = prompt("enter value");
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Conditionls need to be wrapped in parenthesis when using while, if etc.
while (mything < 0){ Reference; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while
" OR " in a conditional is represented by || and an AND by &&
NOTE: You can use some on-line tools to work out some of the issues for example paste your code into http://jshint.com/ and it will tell you many of the syntax issues.
I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?
Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.
It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);
Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.
let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.
Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo
As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.
What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?
There is no specific function, but you can do it like this:
lowNumber < yourNumber && yourNumber < highNumber
Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:
Number.prototype.inRange = function( a,b ) {
var n = +this;
return ( n > a && n < b );
};
So you'd use it like this:
(5).inRange( 3, 7 ); // true
Example: http://jsfiddle.net/dTHQ3/
Um if it is greater than one and less than the other.
var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);
if ( yournumber < highNumber && yournumber > lowNumber ){
// do something
} else {
// do something else
}
The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?
With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.
Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.