Need to remove += - javascript

The program usually displays something like 1+3+5+=9 but i want to get rid of the + after 5. Please help me with this issue that I have right now at the moment.
var userNum = prompt("Pick a number and every odd number between 1 and that
number will be added");
var increase = 0;
var totalSum = 0;
var expression = "+";
document.write("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will
increase by one
while(increase < userNum){
increase++
// if the increase is odd , it will be added to the totalSum
if(increase % 2 === 0){
} else {
document.write(increase+ expression)
totalSum = totalSum + increase
}
}
document.write( 0+ "=" + totalSum);

You could put the + sign in front, and on the first iteration, don't add it:
var userNum = prompt("Pick a number and every odd number between 1 and that number will be added");
var increase = 1,
totalSum = 0,
expression = "+",
str = "The sum of the odd numbers is: ";
while(increase < userNum) {
if(increase !== 1) { str += expression; }
str += increase;
totalSum += increase;
increase += 2;
}
document.write( str + "=" + totalSum );

Instead of creating the output while iterating, put your numbers into an array and simply .join("+") (MDN) the final array to create the string 1+3+5 for output at the end.
I leave the implementation for you as an exercise.

add values to array and join with + sign.
HTML:
<div class="sum">
</div>
JS:
var userNum=10;
var increase = 0;
var totalSum = 0;
var expression = "+";
$('.sum').text("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will
//increase by one
var txt=[];
while(increase < userNum){
increase++
// if the increase is odd , it will be added to the totalSum
if(increase % 2 === 0){}
else{
txt.push(increase);
totalSum = totalSum + increase
}
}
$(".sum").text(txt.join("+") + "=" + totalSum);
https://jsfiddle.net/u5o9qb0c/

Try checking for the last iteration of the while loop like- (you can replace your while loop with the below one)
while(increase < userNum){
increase++
if(increase % 2 !== 0){
if(increase === userNum){
document.write(increase)
}else{
document.write(increase+ expression)
totalSum = totalSum + increase
}
}
}
Hope this helps.

First and foremost, don't use document.write(). It has very limited use cases and more often than not will overwrite your existing document. Instead, set up an empty HTML element to use as an "output" area and then just write into that area.
Next, you get the extra + symbol because you are writing:
document.write(increase + expression);
and expression is hard-coded to the + symbol.
You'll need to only add that when another operand is added.
It should be like this:
/*
Place all of this code in "script" tags and place those tags
just before the closing body tag (</body>) so that this code won't run
until all of the HTML is parsed
*/
// Get a reference to the output element
var output = document.getElementById("output");
var endNum = prompt("Pick a number and every odd number between 1 and that number will be added");
// Since we know you want to start at 1, initialze the variable to 1
var increase = 1;
var totalSum = 0;
// This will hold the result that will be injected just once into the document
var result = "";
// while the increase is less than the userNum , the increase will increase by one
while(increase < endNum){
// Just check to see if we've already started writing the result
// and prepend the + sign if so.
if(result !== ""){
result += "+";
}
result += increase;
totalSum += increase;
// Just increment by 2 to stay with odd numbers
increase += 2;
}
output.innerHTML += result + "=" + totalSum;
<div id="output">
<h1>The sum of the odd numbers are:</h1>
</div>

What you're doing could be a lot more concise. See below.
Changed this increase variable to initialize to one, because that's always your first value according to the prompt.
Starting the expression as the leading text, because a) I want this printed before anything else, and b) I don't want the plus sign on the first iteration
Regarding the expression assignment in the loop, it's unnecessary to assign this every iteration as I have, it's more concise to just assign it than to check if I need to do it every time.
I move the increment of increase to later in the loop so that the value that gets printed is the what it is at the start of the loop. It's a matter of preference, but I would have had to initialize it to -1 if I wanted this to work with it incrementing before the document.write, which I don't like from the standpoint of conveying clear intent.
I also got rid of the semicolons for no reason at all other than that they weren't necessary. (Addendum: In the context of this discussion, I'm not prescribing making this change. It's my code style, but adding semicolons between the statements would have no relevant impact on the code snippet.)
var userNum = prompt("Pick a number and every odd number between 1 and that number will be added")
var increase = 1
var totalSum = 0
var expression = 'the sum of the odd numbers are:'
while (increase <= userNum) {
document.write(expression + increase)
totalSum += increase
increase += 2
expression = '+'
}
document.write("=" + totalSum)

Related

Luhn Check Javascript

I am attempting to have someone input there credit card number and validate if it is a valid number by doing the Luhn Check. I want to be able to check it if they input the whole card number as one big string or if they put spaces in it. In my function validate though I keep getting an error message that there is an illegal return statement for my total variable. Here is my current code.
<script type="text/javascript">
function validate(numbers) {
var sum;
var sum1;
var total;
for (i = 0; i < numbers.length; i++) {
if (numbers.length % 2 == 0) {
sum += numbers[i];
}
else
if ((numbers[i] * 2) >= 10) {
sum1 += numbers[i] - 9;
}
else
sum1 += numbers[i];
}
total = sum + sum1;
return total;
}
function cardnumber() {
var cardnumber = document.getElementById("input").value;
var numbers = cardnumber.split(" ");
var out = "";
for (i = 0; i < numbers.length; i++) {
out += validate(numbers[i]);
if (out % 10 == 0)
return true;
}
}
function getOutput() {
if (cardnumber()) {
alert("You card is valid.");
}
}
</script>
<body>
<h1>I will validate a credit card number</h1>
Card Type:
<input type="radio" id="c1" value="Visa">Visa</input>
Card number: <textarea id="input" style="vertical-align: middle;"></textarea></br>
<input type="button" value="Submit" onclick="getOutput()" /></br></br>
</body>
Your function validate is missing an opening curly brace after the for loop. This made your return statement outside of your function and since a return statement is invalid outside of a function it was an invalid return statement.
function validate(numbers){
var sum;
var sum1;
var total;
for (i=0; i<numbers.length; i++) { // this previous curly brace `{` was missing
if (numbers.length%2==0){
sum += numbers[i];
}
else
if ((numbers[i]*2)>=10){
sum1 += numbers[i] -9;
}
else
sum1 +=numbers[i];
}
total = sum + sum1;
return total;
}
EDIT WITH MORE CORRECTIONS:
There is quite a bit more wrong with the formatting of you functions you also need to include opening and closing curly braces around your other else statements. I would suggest getting a code editor like VS Code and downloading an extension similar to Bracket pair colorizer 2. It will highlight paired brackets together. This will help you with your formatting.
function validate(numbers){
var sum;
var sum1;
var total;
for (i=0; i<numbers.length; i++) {
if (numbers.length%2==0){
sum += numbers[i];
}
else {
if ((numbers[i] * 2) >= 10) {
sum1 += numbers[i] - 9;
}
else {
sum1 += numbers[i];
}
}
}
total = sum + sum1;
return total;
}
function cardnumber(){
var cardnumber= document.getElementById("input").value;
var numbers = cardnumber.split(" ");
var out ="";
for (i = 0; i < numbers.length; i++) {
out += validate(numbers[i]);
}
if (out %10==0)
return true;
}
function getOutput() {
if (cardnumber()) {
alert("You card is valid.");
}
}
These are all the changed lines (the left is new code and the right side is the old code):
Tips for completion
validate function
So, currently if you console.log your numbers are strings when they pass into the validate function. This is fine when they are sent into validate, but when you add the numbers at index i (i.e. numbers[i]) you should use parseInt(numbers[i], 10) to turn them into numbers, so for example sum += parseInt(numbers[i], 10); the same applies when adding to sum1. The other thing to note is that saying var sum will make sum equal the undefined value. When you add a number or string to an undefined value some unexpected things will probably happen, so since you need your sums and totals to be numbers you should instead initialize your sums and totals at 0. Like so:
var sum = 0;
var sum1 = 0;
var total = 0;
The only other thing wrong with your validate function is that your are checking if numbers.length%2==0 which instead you should be checking if i%2==0. You may have to think about why for a moment, but one thing you may notice is the length of numbers never changes during the iteration of the loop where as i does change at each step.
cardnumber function
Your out variable needs to be initialized to zero. Your cardnumber can instead be split by spaces and then joined by the empty string. This handles if the user accidentally types multiple spaces. Then since you join your split array you no longer would need a for loop.
var numbers = cardnumber.split(" ").join('');
var out =0;
out += validate(numbers);
Lines that need changing somehow
Here's a difference of the lines of the old code that where incorrect and need to be changed somehow. I'm not giving you the completed code, but hopefully this will be sufficient to help you figure out the rest on your own (I feel I shouldn't give you all of the solution due to some degree of academic integrity. I would feel I robbed you the opportunity to learn more if I don't at least let you think through and type it out on your own.). If you are wondering what needs to be changed on a specific line that is highlighted red all of it should be above, so best of luck.

JavaScript to check which one of the given numbers differs from other

I am stuck on a problem. I want to print the index of an array which differs from other elements of that array in evenness. To be more specific the input would be like 5 even numbers and 1 odd number. So print the position(index+1) of odd number.
My code
function Test(numbers){
var e = 0; //number of even numbers
var o = 0; //number of odd numbers
console.log(numbers.length);
for(var i = 0; i < numbers.length; i++){
if(numbers[i] % 2 == 0){
e++;
var pose = i; //index of even no
}
else{
o++
var poso = i; //index of odd number
}
}
if(e==1){ //only one even number
console.log(pose+1);
}
else if(o==1){ //only one odd number
console.log(poso+1);
}
else{
console.log("no number differs");
}
}
Test("2 4 7 8 6");
Expected output = '3';
The console prints :
"no number differs".
I have debugged and I found the problem. The console.log(numbers.length); is printing 9. That is it is including blank spaces as well. Same if we put comma ',' in between the numbers. Also if there is a two digit number it treats them as 2 separate elements.
Now I know that i can add code at the beginning to check if i=1,3,5... to break the loop but I would like to know if there is a better solution. Also if the solution is passing array in different format I would like to know how can we correct the code if we want to pass as above.
Pass an array as an argument like below.
function Test(numbers){
var e = 0; //number of even numbers
var o = 0; //number of odd numbers
console.log(numbers.length);
for(var i = 0; i < numbers.length; i++){
if(numbers[i] % 2 == 0){
e++;
var pose = i; //index of even no
}
else{
o++
var poso = i; //index of odd number
}
}
if(e==1){ //only one even number
console.log(pose+1);
}
else if(o==1){ //only one odd number
console.log(poso+1);
}
else{
console.log("no number differs");
}
}
var x = [2,4,7,8,6];
Test(x);
Your Program is absolutely fine.
I guess the problem is with how you are passing data to your function Test.
You are passing a string instead of array.
it should be like:
Test([2,4,7,8,6]);
Also If you want to pass it as string just make sure you split the String with ',' comma and make an array of the numbers and then feed it to your for loop.
In your code you are passing the argument as a string, but I guess you may need to pass an array.
If it is so then you can look into array#forEach method
Hope this snippet will be useful
function Test(numbers) {
// looping through the array
numbers.forEach(function(item, index) {
//checking if it is odd or even
if (item % 2 == 0) {
console.log("current number is Even & its index is " + index);
} else {
//updating index
var modIndex = index+1;
console.log("current number is Odd & its modified index is " + modIndex);
}
})
}
var num = ['2','4','7','8','6']
Test(num);
DEMO

Why is one of these Eloquent Javascript Chessboard solutions better than the other

I took on the Chessboard puzzle from the book Eloquent Javascript and devised the following solution without looking at hints
var newline = "\n";
var counter = .5;
var string1 = " # # # #";
var string2 = "# # # # ";
while (counter <= 3.5){
console.log(string1 + newline);
console.log(string2 + newline);
counter++
}
I originally had too many lines written out so simply changed my counter to 'half steps'.
Looking up how others accomplished this, I found this solution.
var size = 8;
for (var i = 0; i < size; i++) {
var line = "";
for (var j = 0; j < size; j++) {
var total = i + j;
if (total % 2 == 0) {
line += '#';
} else {
line += ' ';
}
}
console.log(line);
}
Can you explain why one version may be better than the other? Also, a plain-english explanation of the second would be helpful. I talked myself into a headache trying to comment it plainly.
Plain english explanation of second one - the var size = 8 will be the size of the board. The first for loop declares the var line and eventually logs it to console. It will log to console for every line, or row, if you prefer.
The second for loop will actually build the line, or row, adding to var line for each column in the row. Instead of having to declare two strings like you did in the first version, it knows how each row should end up looking based on some variables and a rule. The rule is if total is divisible by 2, then add a "#", and if not, then add a " ". total is calculated by adding i and j.
So in the first row i is always 0, and j will be 0, then 1, then 2, etc...so total be divisible by 2, then not divisible by 2, then divisible by 2, etc...then in the second row i will be equal to 1, and j again will be 0, then 1, then 2, etc..so now total will first not de divisible by 2, then divisible by 2, then not, etc...for the third row, i will be 2, which will basically act as i being 0 since both 0 and 2 leave no remainder when divided by 2. This is how the second for loop accomplishes the same thing as your string1 and string2. I'm sorry this is a bit wordy, hope it makes sense...I'll put some comments in the actual code below.
// sets size of board, since the first loop will run for this amount of
// times, and log a row to console each time, and the second loop will add
// this many characters to the string to be logged.
var size = 8;
// first loop, which will run a number of times equal to the size
// variable, and log a row to console each time
for (var i = 0; i < size; i++) {
// declares the string to be logged as the row
var line = "";
// this loop will run a number of times equal to the size
// variable, and add a character to the line variable each time,
// either a "#" or a " "
for (var j = 0; j < size; j++) {
// the total variable will be used to determine if the character added
// to the line is a "#" or a " "
// basically, any time i is 0 or divisible by 2, the row will
// begin with a "#" and alternate from there as j changes,
// if i is not divisible by 2, the row will begin with a " "
// and alternate from there
var total = i + j;
// this if else statement actually uses total to added either "#" or " "
if (total % 2 == 0) {
line += '#';
} else {
line += ' ';
}
}
// this is outside of the second loop, and now the line variable is done
// being added to, and the line is logged
console.log(line);
}

Comparing 2 arrays to output total integer

I have 2 arrays of numbers. I want to go through each array and find the number of times 1 number from each array adds up to the particular amount x.
If the particular amount x is reached as many times as another set number n then the function should print 'YES'. If x does not reach the set number of n then the function should print 'NO'.
The values of x , n and both arrays are in a string input. These values have been split into arrays as seen below in the code.
I have set up 2 for loops to run through each array and an if statement that checks for the condition of x meeting n.
The arrays I'm using in this code should print out the result of 'YES' however every time I run the code I'm getting 'NO' ? I've tried tinkering with the code but nothing has worked.
Any idea on where this code is broke and how to fix the problem?
Thanks :)
code:
var input = '2\n3 10\n2 1 3\n7 8 9';
function processData(input) {
var inputArray = input.split('\n');
var n = inputArray[1][0];
var x = inputArray[1].split(' ')[1];
var arrayA = inputArray[2].split(' ');
var arrayB = inputArray[3].split(' ');
var total = 0;
for(var i = 0; i < arrayA.length; i++) {
for(var j = 0; j < arrayB.length; j++) {
if(arrayA[i] + arrayB[j] == x) {
total = total + 1;
} if (total == n) {
return 'YES';
}
}
}
return 'NO';
}
console.log(processData(input));
arrayA[i] and arrayB[j] are strings, so arrayA[i] + arrayB[j] will be the concatenation of them (ex: '2' + '3' === '23').
If your logic is correct (i didn't quite understand what you are trying to do), it should be enough to convert them to numbers before adding them, using parseInt or some other method:
if(+arrayA[i] + (+arrayB[j]) == +x) { // used unary + to convert to number
total = total + 1;
} if (total == n) {
return 'YES';
}
PS: A cleaner version would be to convert each string in the array to number, but that involves more than adding 3 characters to your code.
PS2: You have a weird way of getting the input data. If you get it from another place in your JS code, you could simply pass it as an object with the relevant structure, otherwise you could pass it around in a more ... common format, like JSON.

JQuery/JavaScript increment number

I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery
I am struggling to do it.
Say I have a number like so:
1412015
the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2.
Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output:
1,412,016
1,412,017
1,412,018
Thanks
Eef
I'm not quite sure I understand your incrementation case and what you want to show.
However, I decided to chime in on a solution to format a number.
I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach.
I've tried to describe the lines with comments in case you're curious
Array parsing version:
function formatNum(num) {
//Convert a formatted number to a normal number and split off any
//decimal places if they exist
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//turn the string into a character array and reverse
var arr = parts[0].split('').reverse();
//initialize the return value
var str = '';
//As long as the array still has data to process (arr.length is
//anything but 0)
//Use a for loop so that it keeps count of the characters for me
for( var i = 0; arr.length; i++ ) {
//every 4th character that isn't a minus sign add a comma before
//we add the character
if( i && i%3 == 0 && arr[0] != '-' ) {
str = ',' + str ;
}
//add the character to the result
str = arr.shift() + str ;
}
//return the final result appending the previously split decimal place
//if necessary
return str + ( parts[1] ? '.'+parts[1] : '' );
}
Regular Expression version:
function formatNum(num) {
//Turn a formatted number into a normal number and separate the
//decimal places
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//reverse the string
var str = parts[0].split('').reverse().join('');
//initialize the return value
var retVal = '';
//This gets complicated. As long as the previous result of the regular
//expression replace is NOT the same as the current replacement,
//keep replacing and adding commas.
while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) {
retVal = str;
}
//If there were decimal points return them back with the reversed string
if( parts[1] ) {
return retVal.split('').reverse().join('') + '.' + parts[1];
}
//return the reversed string
return retVal.split('').reverse().join('');
}
Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting.
Super Short Firefox with Firebug only example:
var num = 1412015;
setInterval(function(){
//Your 0.54 value... why? I don't know... but I'll run with it.
num += 0.54;
console.log( formatNum( num ) );
},1000);
You can see it all in action here: http://jsbin.com/opoze
To increment a value on every second use this structure:
var number = 0; // put your initial value here
function incrementNumber () {
number += 1; // you can increment by anything you like here
}
// this will run incrementNumber() every second (interval is in ms)
setInterval(incrementNumber, 1000);
This will format numbers for you:
function formatNumber(num) {
num = String(num);
if (num.length <= 3) {
return num;
} else {
var last3nums = num.substring(num.length - 3, num.length);
var remindingPart = num.substring(0, num.length - 3);
return formatNumber(remindingPart) + ',' + last3nums;
}
}
function rounded_inc(x, n) {
return x + Math.ceil(n);
}
var x = 1412015;
x = rounded_inc(x, 0.54);

Categories

Resources