Accumulating an array's values - Javascript - javascript

I'm trying to accumulate a series of numbers in an array e6
Here is the relevant code.
e3 = prompt(e1 + ", Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
e6 = e3.split(',');
for(var a=0;a <= e6.length ;a++) {
e9=e9 + +e6[a];
}
document.write(e9) ;
However, what get's printed is NaN instead of the default sum of 15. Any ideas how to fix? Thank you.
Edit: Forgot to mention that i already had declared all my variables earlier.
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11;
Edit2: Here is my entire work in action. https://jsfiddle.net/nhz0Lnx8/

You should be looking only as far as e6.length-1, but the best solution is to avoid the off by one errors.
var e3 = prompt("Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
var e6 = e3.split(',');
var e9 = 0;
e3.split(',').map((x)=>{e9 += +x})
document.write(e9)

The error is in the for loop declaration:
"a <= e6.length" should be "a < e6.length" ("less than equal or equal" should be changed to "less than")

var e3 = prompt("Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
var e6 = e3.split(',');
var e9 = 0;
for(var a=0;a < e6.length ;a++) {
e9 += parseInt( e6[a] );
}
document.write(e9) ;

Related

JS convert to ASCII numbers and reverse

I stuck on this can you help in JavaScript Alien message
Allowed languages
JavaScript
Your task is to translate a message in some alien language (let's call it Alienski).
The message could be created by following simple rules and from two known languages, English and Spanish.
Each word in Alienski is constructed by subtracting the letters from English and Spanish (absolute value) and that is the resulting letter.
There are two special cases. If in each of the words the symbol is '-' (hyphen) or ' ' (space) it is mandatory for it to be kept this way.
There won't be a case with a '-' (hyphen) and a ' ' (space) at the same time.
If one of the words is with more letters than the other just add the letters from the longer word to the result.
Example:
Copy
talk
hablar
Copy
a b c d....
0 1 2 3....
t - h = | 19 - 7 | = 12 = m
a - a = | 0 - 0 | = 0 = a
l - b = | 11 - 1 | = 10 = k
k - l = | 10 - 11 | = 1 = b
empty - a = a
empty - r = r
Result:
makbar
I stuck from 3 hours on this. Here is my code so far
let englishWord = 'talk'
let spanishWord = 'hablar'
let engToDigit = [];
let spnToDigit = [];
let alien = [];
for (var i = 0; i < englishWord.length; i++) {
engToDigit.push(englishWord.charCodeAt(i))
}
for (var y = 0; y < spanishWord.length; y++) {
spnToDigit.push(spanishWord.charCodeAt(y))
}
let result = engToDigit.map((a, i) => a - spnToDigit[i]);
for (let index = 0; index < result.length; index++) {
result[index] += 97;
console.log(result);
What it sounds like you need is to take this in small steps. First I would make a function that iterates through a string and converts each letter to its ASCII code. Try the following order:
Check if code is uppercase then get the numeric value.
Make sure charCode is greather than 96 and charCode is less than 123
Then turn all the codes to their numeric value by running and
collecting in an array: charCode - 97
Else check if the code is lower case then get the numeric value.
Make sure that charCode is greater than 64 and charCode is less than 91.
Then turn all the codes to their numeric value by running and collecting in an array: charCode - 65
Else just add the value to the array.
Outside the above loop return an array that is joined.
When the array is joined it will be a string like "19,0,11,10,-,7,0,1,11,0,17".
Check if there is a space or a hyphen.
Then you can split the array on the result of step 9.
Then split each array on ",".
Loop through each array and subtract the values.
Convert the values back by adding 65 - because there is no way at this point to know if a character was upper case.
Then use String.fromCharCode(##) to convert the code back to the non-readable alien word.

My solution to Project Euler #8 not working anymore

so , I solved a problem online where I found the Largest product of any 5 consecutive numbers In a 1000-digit number :
var bignumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
var bigarray = bignumber.split("");
var prod = [];
var buy = 1;
var z = 4;
for (var i = 0; i < bigarray.length; i+=z) {
mult = bigarray[i];
for (var x = 1; x <= z; x++) {
mult *= bigarray[i+x];
}
prod.push(mult);
}
prod.sort(function(a, b){return b-a});
document.write(prod[0]);
where z can be the number of the consecutive digits i want minus 1 ,, and the solution was 40824 wich is correct I think solution
Later I found that this problem belonged to Project Euler here , but instead It's 13 consecutive digits , so when I tried to change z = 12 , it gave me an Incorrect solution ,, why ?
Your mistake is in line for (var i = 0; i < bigarray.length; i+=z) {:
Change the loop condition to i < bigarray.length - z. Reason: Since the inner for loop advances up to z indices, the outer loop has to guarantee that there are at least z elements remining from index i.
Change the loop increment to i+=1. Reason: Consider finding the largest product of two consecutive digits in input "1221". 1*2 = 2 and 2*1 = 2 is what your algorithm computes. The solution however is 2*2 = 4 which can only be found when considering every input digit as a possible starting point.
Once you made these changes, you could start optimizing your algorithm. For example, you can kind of re-use the mult value from the previous iteration.
You may do as follows;
function getMaxProductConseq(s,n){
return Math.max(...s.split("")
.map((_,i,a) => a.slice(i,i+n))
.slice(0,s.length-n+1)
.map(sa => sa.reduce((p,c) => +p * +c)));
}
var bignumber = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
console.log(getMaxProductConseq(bignumber,13));

not getting desired output in javascript

i was trying to make a javascript program to convert a number between 20 and 100 to in words. so i wrote this-
var num = prompt("enter a number");
if (num>20 && num<100)
{
words(num);
}
else alert("Please enter a number between 20 and 100");
function words(num)
{
var ones = ["","one","two","three","four","five","six", "seven","eight", "nine"];
var tens = ["", "", "twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"];
var div= num/10;
var rem= num%10;
if (rem==0)
document.write(num+" = "+tens[div]);
else
document.write(num+" = "+tens[div]+" "+ones[rem]);
}
the problem is if i enter 30 ,40 like that numbers which are divisible by 10 i get correct output but if i enter 32 it will show "32 = undefined two".
what did i do wrong?
i am new to JS so dont know much.
32/10 is 3.2, not 3. You must round the result.
Change
var div= num/10;
to
var div= Math.floor(num/10);
You should be doing
var rem= num%10;
var div= (num - rem)/10;
Because 25/10 = 2.5 not 2
Working Fiddle

how to divide a number a in a series of all whole numbers?

Hi sorry for asking this if this is a stupid question.
I would like to ask how to securely divide a number in Javascript that it will always
output the result in a way that it will output pure whole numbers.
example:
10 / 2 ---> 5, 5 ( it would be 2 fives so it is whole number )
BUT
10 / 3 ---> 3, 3, 4 ( it would have two 3 and one 4 so that it would still result to 10 )
10/3 will give you 3.333333..., never four... if you want to check is a number will give you "whole numbers" as you say, use modulo (%).
Modulo finds the remainder of division of one number by another.
For example
10%5 = 0 because 10 divided by 5 is a "whole number"
10%3 = 1 because the closest 10/3 is 3... 3x3=9... 10-9=1
So in your code, if you want to know if a number divided by another number is whole, you need to do
if (number1%number2 == 0) { ... }
Read more about it here
EDIT :
I read your question again and I think this fiddle is what you want
var number1 = 10,
number2 = 3;
if (number1 / number2 == 0) {
alert('the numbers are whole');
} else {
var remainder = number1%number2;
var wholes = Math.floor(number1 / number2);
var output = '';
for (var i = 0; i < (wholes - 1); i++) {
output+= number2 + ', ';
}
output += (number2 + remainder);
alert(output);
}
Whatever your result is,just pass it through the parseInt function,For Eg:-
Suppose your answer is 4.3,
The whole number close to it will can be accounted using,
parseInt(4.3)
Which equals 4.
Another posibility: make the number a string and walk all the elements
var a = 11 / 4;
//turn it into a string and remove all non-numeric chars
a = a.toString().replace(/\D/g, '');
//split the string in seperate characters
a = a.split("");
var num = new Array();
//convert back to numbers
for (var i = 0; i < a.length; i++) {
num.push(parseFloat(a[i]));
}
alert(num);
On a sidenote, you'll have to do some kind of rounding, to prevent eternally repeating numbers, like 10/3.
Here is a fiddle
Look at this very simple example:
var x = 10;
var y = 3;
var result = x/y;
var rest = x%y;
for (var i=0; i<y; i++) {
var output;
if(i==y-1){
output = parseInt(result + rest);
}
else{
output = parseInt(result);
}
alert(output);
}
http://jsfiddle.net/guinatal/469Vv/4/

Why does NOT adding a '+ ""' after a mathematical operation in javascript make the counting of the new variables length undefined?

I'm counting the number of hours and then subtracting it by 12 if it goes above 12 (so that 1pm doesn't appear as 13pm). Below is part of my javascript code.
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12 + "";
}
Later in the code, when I'm trying count the length of the array variable 'hours[0]', it appears as unknown if I have this code instead:
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12;
}
and I don't understand why. Could someone help me out please?
The subtraction hours[0] - 12 returns a number, no matter if hours[0] contains a number or a string containing a number, e.g. "13". Adding the + "" converts the result of the subtraction to a string. A number has no length in javascript, and therefore invoking the length member of a number will return undefined.
If you add "" to an expression you're converting the resulto to a string and strings have a .length property. Numbers instead do not have a .length so what you're experiencing is normal...
var x = 42; // this is a number
var y = x + ""; // y is a string ("42")
var z1 = x.length; // this is undefined (numbers have no length)
var z2 = y.length; // this is the lenght of a string (2 in this case)

Categories