JavaScript- get sum of values inside a for loop - javascript

I'm trying to sum all the variables,
as many times as they appear in the loop,
that is- for example if hitpoints appears
3 times(as in my code) sum -12 + -12 + -12;
And then at the end I need a final result - a
sum of all of the variable values as many
times as they appear.
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
console.log( i + "-" + hitpoints);
} else if ((i % 3 === 0) && (i% 5 ===0)) {
console.log( i + "-" + pointsx);
} else if (i %3 ===0) {
console.log ( i + "-" + points3);
} else if (i%5 ===0) {
console.log( i + "-" + points5);
} else {
console.log( i + "-" + points1);
}
}
}
calculate(30);

I assume you want the sum of the points.
Declare a variable sum and keep incrementing
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
var sum=0;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
sum += hitpoints;
} else if ((i % 3 === 0) && (i% 5 ===0)) {
sum += pointsx;
} else if (i %3 ===0) {
sum += points3;
} else if(i%5 ===0) {
sum += points5;
} else {
sum += points1;
}
}
console.log(sum)
}
calculate(30);

Related

Having problems with output

I build the code, which should return Knick if the number is odd, Knack if it's multiple of five and KnickKnack if it's either odd and multiple of five. The problem is that it returns line to line in console, I want it to concatenate in a string.
Here's the code:
function knickKnack(maxValue) {
const numbers = [];
for (var i = 1; i <=100; i++) {
if (i % 5 === 0 ) {
console.log ('KnickKnack, ');
} else if (i % 10 === 0) {
console.log ('Knack, ');
} else if (i % 2 === 1) {
console.log ('Knick, ');
} else {
console.log (i + ', ');
}
}
return numbers;
}
knickKnack();
function knickKnack(maxValue) {
var knickKnackString = '';
for (var i = 1; i <= maxValue; i++) {
if (i % 5 === 0 && i % 2 === 1)
knickKnackString += 'KnickKnack, ';
else if (i % 10 === 0)
knickKnackString += 'Knack, ';
else if (i % 2 === 1)
knickKnackString += 'Knick, ';
else
knickKnackString += i + ', ';
}
console.log(knickKnackString);
}
Try like this.

How to find the average in javascript?

So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();

Convert Double64 to Long64 and back on JavaScript

I need to convert Double64 to Long64 and back on JavaScript, like Double.doubleToLongBits() and Double.longBitsToDouble() on Java. And the results of methods must be the same as in Java. For example 1435.036452 -> 4654026172507377535 -> 1435.036452, or -1435.036452 -> -4569345864347398273 -> -1435.036452. As I unerstand, my code can convert Double64 to Long64 well, but I can't get back my value.
Double64 to Long64:
function toString64bitFloat(number) {
if(number === undefined || isNaN(number))
return 0;
let result = "";
const dv = new DataView(new ArrayBuffer(8));
dv.setFloat64(0, number, false);
for (let i = 0; i < 8; i++) {
let bits = dv.getUint8(i).toString(2);
if (bits.length < 8)
bits = new Array(8 - bits.length).fill('0').join("") + bits;
result += bits;
}
return result;
}
function stringToLong64(bitString) {
if(bitString === undefined || isNaN(bitString))
return 0;
let result = new BigInt64Array(1);
result[0] = BigInt(0);
if(bitString[0] === "1"){
for(let i = bitString.length; i > 0; i--)
if(bitString[i] === "0")
result[0] += BigInt(Math.pow(2, 63 - i));
result[0] = -result[0] - BigInt(1);
}else{
for(let i = bitString.length; i > 0; i--)
if(bitString[i] === "1")
result[0] += BigInt(Math.pow(2, 63 - i));
}
return result[0];
}
Long64 to Double64:
function toString64bitInt(number) {
let result = "";
let temp = number;
if(temp > 0){
result += "0";
for(let i = 1; i < 64; i++){
if(temp - BigInt(Math.pow(2, 63 - i)) >= 0){
result += "1";
temp -= BigInt(Math.pow(2, 63 - i));
} else {
result += "0"
}
}
} else {
result += "1";
temp = -temp + BigInt(0);
for(let i = 0; i < 63; i++){
if(temp - BigInt(Math.pow(2, 63 - i)) >= 0){
result += "0";
temp -= BigInt(Math.pow(2, 63 - i));
} else {
result += "1"
}
}
}
return result;
}
function stringTofloat64(bitString) {
let result = new Float64Array(1);
result[0] = 0.0;
if(bitString[0] === '1'){
for(let i = 1; i > 12; i++)
if(bitString[i] === '0')
result[0] += Math.pow(2, 11 - i);
for(let i = 12; i > 64; i++)
if(bitString[i] === '0')
result[0] += Math.pow(2, -(52 - i + 12));
result[0] = -result[0];
}else{
for(let i = 1; i > 12; i++){
if(bitString[i] === '1'){
result[0] += Math.pow(2, 11 - i);
}
}
for(let i = 12; i > 64; i++)
if(bitString[i] === '1'){
result[0] += Math.pow(2, -(52 - i + 12));
}
}
return result[0];
}

Nested while loops in javascript

I'm trying to make a grid of stars with a nested while loop.
It does work with a for loop:
for(m = 1; m <= 5; m++) {
for(n = 1;n <= 10; n++) {
document.write("*" + " ");
}
document.write("<br>");
}
but I can't figure out how I can solve it with a while loop:
while(m <= 5) {
while(n <= 10) {
document.write("*" + " ");
n++;
}
document.write("<br>");
m++;
}
Does anyone have any idea?
Thnx
You're missing the initializers. m needs to start and 1, and n needs to restart at 1 every time m is incremented.
var m, n;
m = 1;
while(m <= 5) {
n = 1;
while(n <= 10) {
document.write("*" + " ");
n++;
}
document.write("<br>");
m++;
}
The problem is that you do not reset the n variable, so everytime it is 10 and thus not entering the while loop. You need to do:
var m = 0,
n = 0,
div = document.getElementById('draw');
function writeToDiv(stringToWrite) {
div.innerHTML = div.innerHTML + stringToWrite;
}
while (m <= 5) {
while (n <= 10) {
writeToDiv("*" + " ");
n++;
}
n = 0;
writeToDiv("<br>");
m++;
}
<div id="draw">
</div>

Create range of letters and numbers

I'm creating a form where users can input a range. They are allowed to input letters and numbers. Some sample input:
From: AA01
To: AZ02
Which should result in:
AA01
AA02
AB01
AB02
And so on, till AZ02
And:
From: BC01
To: DE01
Should result in:
BC01
BD01
BE01
CC01
CD01
CE01
Etc
I managed to get it working for the input A01 to D10 (for example)
jsFiddle
However, i can't get it to work with multiple letters.
JS code:
var $from = $('input[name="from"]');
var $to = $('input[name="to"]');
var $quantity = $('input[name="quantity"]');
var $rangeList = $('.rangeList');
var $leadingzeros = $('input[name="leadingzeros"]');
$from.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$to.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$leadingzeros.on('click', function () {
updateQuantity();
});
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
if (xl != null && yl != null && xl[0].length > 0 && yl[0].length > 0) {
xl = xl[0].toUpperCase();
yl = yl[0].toUpperCase();
$rangeList.html('');
var a = yl.charCodeAt(0) - xl.charCodeAt(0);
for (var i = 0; i <= a; i++) {
if (!isNaN(x) && !isNaN(y)) {
if (x <= y) {
var z = (y - x) + 1;
$quantity.val(z * (a + 1));
$rangeList.html('');
for (var b = z; b > 0; b--) {
var c = ((y - b) + 1);
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(String.fromCharCode(65 + i) + c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
}
} else if (!isNaN(x) && !isNaN(y)) {
if (x < y) {
var z = (y - x) + 1;
$quantity.val(z);
$rangeList.html('');
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
$rangeList.html('');
for (var i = 0; i < result.length; i++) {
$rangeList.append(result[i] + '<br />');
}
}
function leadingZeroes(number, size) {
number = number.toString();
while (number.length < size) number = "0" + number;
return number;
}
This is perfect for a recursive algorithm:
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
return result;
}
Called as follows:
createRange('BC01', 'DE02'); // Generates an array containing all values expected
EDIT: Amended function below to match new test case (much more messy, however, involving lots of type coercion between strings and integers).
function prefixZeroes(value, digits) {
var result = '';
value = value.toString();
for (var i = 0; i < digits - value.length; i++) {
result += '0';
}
return result + value;
}
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
if (from.charCodeAt(0) < 65) {
fromInt = parseInt(from);
toInt = parseInt(to);
length = toInt.toString().length;
var innerRange = createRange(from.substring(length), to.substring(length));
for (var i = fromInt; i <= toInt; i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(prefixZeroes(i, length) + innerRange[j]);
}
}
} else {
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
}
return result;
}
Please note that because of your strict logic in how the value increments this method requires exactly 4 characters (2 letters followed by 2 numbers) to work. Also, this might not be as efficient/tidy as it can be but it took some tinkering to meet your logic requirements.
function generate(start, end) {
var results = [];
//break out the start/end letters/numbers so that we can increment them seperately
var startLetters = start[0] + start[1];
var endLetters = end[0] + end[1];
var startNumber = Number(start[2] + start[3]);
var endNumber = Number(end[2] + end[3]);
//store the start letter/number so we no which value to reset the counter to when a maximum boundry in reached
var resetLetter = startLetters[1];
var resetNumber = startNumber;
//add first result as we will always have at least one
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
//maximum while loops for saefty, increase if needed
var whileSafety = 10000;
while (true) {
//safety check to ensure while loop doesn't go infinite
whileSafety--;
if (whileSafety == 0) break;
//check if we have reached the maximum value, if so stop the loop (break)
if (startNumber == endNumber && startLetters == endLetters) break;
//check if we have reached the maximum number. If so, and the letters limit is not reached
//then reset the number and increment the letters by 1
if (startNumber == endNumber && startLetters != endLetters) {
//reset the number counter
startNumber = resetNumber;
//if the second letter is at the limit then reset it and increment the first letter,
//otherwise increment the second letter and continue
if (startLetters[1] == endLetters[1]) {
startLetters = '' + String.fromCharCode(startLetters.charCodeAt(0) + 1) + resetLetter;
} else {
startLetters = startLetters[0] + String.fromCharCode(startLetters.charCodeAt(1) + 1);
}
} else {
//number limit not reached so just increment the number counter
startNumber++;
}
//add the next sequential value to the array
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
}
return results;
}
var results = generate("BC01", "DE01");
console.log(results);
Here is a working example, which uses your second test case
Using #Phylogenesis' code, i managed to achieve my goal.
jsFiddle demo
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
var r = createRange(xl[0], yl[0]);
var z = (y - x) + 1;
if (x <= y) {
for (var j = 0; j < r.length; j++) {
var letters = r[j];
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
if (i == z) {
r[j] = letters + c + '<br />';
} else {
j++;
r.splice(j, 0, letters + c + '<br />');
}
}
}
} else {
for (var i = 0; i < r.length; i++) {
r[i] += '<br />';
}
}
$quantity.val(r.length);
$rangeList.html('');
for (var i = 0; i < r.length; i++) {
$rangeList.append(r[i]);
}
}
This works for unlimited letters and numbers, as long as the letters are first.
Thanks for your help!

Categories

Resources