Compound assignment in Javascript resulting in NaN - javascript

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);

var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Related

Calculating sum of fractions in a loop

Implement a function fractionSum(n) that calculates and returns the sum of the following sequence:
1/n + 1/(n−1) + 1/(n−2) + ⋅⋅⋅ + 1/2 + 1
For example, fractionSum(5) calculates the following sum: 1/5+1/4+1/3+1/2+1
And then returns 2.283333333333333
I haven't even started writing function just yet since I'm still stuck at trying to figure out the right loop expression. This is what I've done so far:
var sum =0;
var fraction = 1;
var number = parseInt(prompt("Enter an integer: ", "5"));
for ( var counter = 0; counter <= number; counter++) {
fraction /= (number - counter); // do I need to declare parseFloat here for decimal# ?
sum += fraction;
}
document.write("The total value is " + sum);
The number doesn't match up at all from the example. I'm not sure what the problem is here.
I'm pretty confused right now. I know this is basic problem but I has tried multiple codes and it still didn't come out right.
Thank you so much
You're reusing the fraction from the previous iteration and dividing it by the next value. You need a new fraction instead:
fraction = 1 / (number - counter);
Also, you need the strict counter < number condition in the loop to avoid division by zero.
In the loop, counter must be less than number else at the end there will be divison by 0, the result will be infinity. Try this
let sum = 0;
let i = 0;
let num = parseInt(prompt("Enter an integer: ", "5"));
for(i; i < num; i++ ){
frac = 1 / ( num - i);
sum+= frac;
}
I figured it out. This is what I got:
<script>
function fractionSum(number) {
var sum =0;
for (var counter= 0 ; counter < number; counter++) {
sum += 1/(number - counter);
}
return sum;
}
var number = parseInt(prompt("Enter the value of n: ", "5"));
sum = fractionSum(number);
document.write("The fraction sum of order " + number + " is " + sum);
</script>
Thank you guys, it was very helpful

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

Ideas for how to catch the last index in a jscript for loop, where lengh of index is is unknown?

Consider the following for loop (and assuming we don't know 3 times table - i.e. how many results might occur).
<script summary>
function myFunction() {
var output_text = "";
var i;
for (i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if ("e.g. this is the last index?") {"e.g.then do this?"
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
}
</script>
Trying to 'output_text' as something like:
The number is 0
The number is 3
The number is 6
The number is 9
The number is 12
The number is 15
The number is the last 18
Any ideas for how to catch that last loop iteration.
This is just an example as actual application is a bit wordy - but the concept is the same.
I could run a count first to get index length, but wondered if there is an easier way.
Many thanks for anyone's time. Also first go at posting - any advice welcome.
Just add 3 to the current index and check if it exceeds 19.
function myFunction() {
var output_text = "";
var i;
const max = 19;
const factor = 3;
for (i = 0; i <= max; i++) {
if (i % factor === 0){
if (i + factor > max) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
return output_text;
}
document.write(myFunction());
If you have a number divisible by 3, perform a second check to see if 20 minus i < 3 and you'll know if it's the last number.
function myFunction() {
var output_text = "";
for (var i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if (20 - i < 3) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
document.getElementById("out").innerHTML = output_text;
}
myFunction();
<div id="out"></div>
The better approach is to show result of current iteration in the next iteration. In this case, last iteration will not be handled in the loop. So, you can handle it after easily.

How to declare a variable with no value?

The following code is what I am using to convert a hex to binary. To print binary out, I add individual strings to a previously declared blank variable. However, this prints out "undefined + binary". Is there a way to declare a variable with no value --even undefined. If not is there a better way to concatenate variables in a for loop without a previously declared variable?
All help will be appreciated!
var integer = prompt("Insert hex digit");
var userHexDigits = [];
var hexDigits = [0, 1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
var binaryDigits = ['0000', '0001','0010','0011', '0100','0101','0110','0111','1000','1001','1010','1011','1100','1101','1110','1111'];
var hexy = [];
var binary
for(i = 0; i < integer.length; i++) {
digit = i + 1;
document.write("Your digit #" + digit + " is: " + integer[i] + "<br/>");
userHexDigits.push(integer[i]);
}
for (var m = 0; m < userHexDigits.length; m++) {
hex = userHexDigits[m];
for(k =0; k < hexDigits.length; k++) {
if (hex == hexDigits[k]){
binary += binaryDigits[k] + " ";
}
}
}
document.write("<br/><br/>The number " + integer + " in binary is " + binary);
If you want a string variable with an empty value just:
var binary = "";

Javascript Showing even numbers only

I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>
To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );
Get a random integer over 1/2 the range and double it.

Categories

Resources