Sum of array elements in JavaScript - javascript

I'm trying to solve this problem where I initialize an array of 5 elements and print the sum of the elements. I can't wrap my head around the logic behind the solution. Please review my code.
Another problem with reading an array of 5 integers and printing the smallest element. I keep getting the wrong answer...
This's a script embedded inside an HTML file.
Problem 1
var num= [1,1,1,1];
var total=num[0];
for( var i=0 ; i < num.length ; i++)
{
total =+num[i];
}
window.alert("The total is "+ total);
I expected the answer to be 4, but all I get is 1.
Problem 2
var r = new Array(5);
var len = r.length;
for(var i=0 ; i <len ; i++)
{
r[i] = window.prompt("Enter the elements of the array");
}
var small= [0];
for(var j=0; j< len ; j++)
{
if(r[i] < small )
small = r[i];
}
window.alert("The smallest element is the array is "+small);
I get the last element in my array as the smallest element which's obviously isn't right.

In problem 1) you just need to change =+ to +=
In problem 2) you need to start in the first element of r and in the for loop you need index the r array by the variable j instead of i variable
var r = new Array(5);
var len = r.length;
for(var i=0 ; i <len ; i++)
{
r[i] = window.prompt("Enter the elements of the array");
}
var small = r[0];
for( var j=0; j< len ; j++)
{
if(r[j] < small )
small = r[j];
}
window.alert("The smallest element is the array is "+small);
But you could just do:
const min = Math.min(...r)
window.alert("The smallest element is the array is "+ min);

There are a couple things here.
For problem 1:
Since you initialize the total to the first item I think you end up counting it 2 times. Likely you'd want to initialize to 0. var total = 0.
You will also want to use += instead of =+ the latter sets the value instead of adding it.
For Problem 2:
new Array(5) creates a new sparse array. It's kinda weird. It's like it's full of undefined values. So when you assign small you'll want to access the first element of r, var small = r[0] but that will be undefined due to r being a sparse array. So you'll want var r = new Array(5).fill().map((x,i) => i) to set values in that array. You will also want to use j instead of i in the body of the second loop.
That should do it ;).

Hi The problem 1 could be tackled with reduce method check the Docs here:
The problem 2 could be solved with Math.min method:
var num= [1,1,1,1];
var numMin= [100,1121,1212,122, 12];
//Problem1
let totalSum = num.reduce( ( accumulator, currentItem ) => {
return accumulator = accumulator += currentItem;
} , 0 );
console.log(totalSum)
//Problem 2
console.log( 'Min',Math.min( ...numMin ) );
Here is a replit so you can play with the code

// Find array elements sum
let total = 0;
let arr = [1,2,3,4];
arr.map(el => total+=el);
console.log(total); // 10

// Find array smallest element
let arr = [1,-2,13,-4,7];
let smlEl = arr[0]
arr.map(el => {
if(el < smlEl) {
smlEl = el;
}
})
console.log(smlEl); // -4

Related

How to extract items from a subarray and push them to the main array

I'm doing a type speed test and, for this, I'll need to get a random item from an array, split every letter, push it to a new one and re-do this several times. But, every time I split the string from the first array, returns to my new array a subarray, instead of just letters. How can I extract everything from the subarrays and put into my main array?
var Pokemon = ["Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle","Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto","Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash","Nidoran","Nidorina","Nidoqueen","Nidoran","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff","Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth","Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam","Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash","Slowpoke","Slowbro","Magnemite","Magneton","Farfetch'd","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter","Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung","Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx","Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops","Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew"];
var wordsToWrite = []
var letterToWrite = []
function sortWords(){
var numberSorted = Math.floor(Math.random() * (151 - 1)) + 1;
wordsToWrite.push(Pokemon[numberSorted]);
}
var times = 150;
for(var i=0; i < times; i++){
sortWords()
}
console.log(wordsToWrite)
for(var k=0; k < wordsToWrite.length; k++){
var x = wordsToWrite[k];
var y = x.split('');
letterToWrite.push(y)
}
console.log(letterToWrite)
console.log(letterToWrite[14])
For example, when I try to console.log the 14th element from my array letterToWrite, it shows my entire word, and not the single letter that I want. What can I do to extract the letters from the subarray and displays it on the main array?
letterToWrite = [...letterToWrite, y]
instead of letterToWrite.push(y)
and ... is called spread operator. Check for more
After a long try, I could resolve it and I'll post to help if anyone had the same question.
var Pokemon = ["Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle","Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto","Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash","Nidoran","Nidorina","Nidoqueen","Nidoran","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff","Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth","Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam","Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash","Slowpoke","Slowbro","Magnemite","Magneton","Farfetch'd","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter","Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung","Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx","Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops","Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew"];
var characterToWrite = []
function sortWords(){
var numberSorted = Math.floor(Math.random() * (151 - 1)) + 1;
var x = Pokemon[numberSorted];
for(var k=0; k < x.length; k++){
charac = x[k];
characterToWrite.push(charac)
}
}
var times = 150;
for(var i=0; i < times; i++){
sortWords()
}
console.log(characterToWrite)

Javascript dynamic programming table, can't index 2D array like in Python in some cases?

Edit: Actually the logic is wrong here.
I solved it using Python3 with a dictionary that updates the last index at which a letter is seen. In dynamic programming lingo, it is similar to L.I.S (longest increasing subsequence).
If anyone knows how to solve this without using a dictionary, please comment because I learned DP in school and those lessons only used arrays so it should be possible with just arrays.
Original question:
I am trying Leetcode, 3. Longest Substring Without Repeating Characters.
I can solve this in Python making a 2D table for dynamic programming.
But in JavaScript which I am sort of new to, I am getting an error.
evalmachine.<anonymous>:41
var top = T[i-1][j]
^
TypeError: Cannot read property '1' of undefined
at lengthOfLongestSubstring (evalmachine.<anonymous>:4
My code:
/**
* #param {string} s
* #return {number}
*/
var lengthOfLongestSubstring = function(s) {
//empty string
if (s.length <= 0){
return 0
}
//initialize dict
var dict = {};
//initialize 2D table T
var T = new Array(s.length)
for (var i = 0; i<s.length; i++){
T[i] = new Array(s.length);
}
//base cases are diagonals
for (var i = 0; i < T.length; i++){
for (var j=0; j<T.length; j++){
if(i==j){
T[i][j] = 1;
}
else{
T[i][j] = 0;
}
}
}
//put base case in dict
//dict[s[0]]=1
for (var i=0; i < s.length; i++){
for (var j=i+1; j<s.length; j++){
var row_char = s.charAt(i);
var col_char = s.charAt(j);
if (row_char==col_char){
T[i][j] = 1;
}
else{
//console.log("j",j,T)
var left = T[i][j-1]
console.log(left)
var top = T[i-1][j]
console.log(top)
var bigger = Math.max(left,top);
T[i][j] = bigger + 1
}
}
}
//iterate each row to get max
var high = Number.MIN_SAFE_INTEGER;
for (var i = 0; i < s.length; i++){
if(T[i][s.length-1] > high){
high = T[i][s.length-1];
}
}
return high;
};
It is letting me fill the table with 0's and base case of 1 indexing like T[i][j] but then complaining about indexing like that to get the value which I don't understand.
I looked at this: How to get value at a specific index of array In JavaScript?
But it does not really say anything different.
On the first iteration of the loop following the //put base case in dict comment i is 0.
You're then attempting to access T[i-1][j], which is the equivalent of T[-1][j].
Because T doesn't have a -1 index, T[-1] resolves to undefined, upon which you attempt to access index [j] and you get the error you're seeing.

JavaScript neglecting the else statement

I created a function which takes in two values..
Both are numbers represented by n & p. What the function does is that it gets the number n and splits it up then squares it to the value of p and sums them in an increasing order like this: n^p + n^(p+1) + n^(p+2) + ...
Here is the function
function digPow(n, p) {
// ...
let num = n.toString();
let pow = p;
let arrn = [];
let arrp = [];
for (let i = 0; i < num.length; i++) {
arrn.push(JSON.parse(num[i]));
}
let index = arrn.join('');
let sindex = index.split('');
for (let j = 0; j < sindex.length; j++) {
let power = p + j;
let indexs = sindex[j];
let Mathpow = Math.pow(indexs, power);
arrp.push(Mathpow);
}
let total = 0;
for (let m in arrp) {
total += arrp[m]
}
let secondVal = total / n;
let totals = total / secondVal;
let mx = [-1]
if (totals.length == n.length) {
return secondVal
} else {
return -1
}
}
Now i created variables and arrays to store up the values and then the if part is my problem.. The if/else statement is meant to let the program check if a particular variable totals is equal to n which is the input.. if true it should return a variable secondVal and if not it should return -1..
So far its only returning secondVal and i'snt returning -1 in cases where it should like:
digPow(92, 1) instead it returns 0.14130434782608695
What do i do?
totals and n are both numbers. They don't have a .length property, so both totals.length and n.length evaluate to undefined. Thus, they are equal to each other.
There are plenty of other weird things going on in your code, too. I'd recommend finding a good JavaScript tutorial and working through it to get a better feel for how the language (and programming in general) works.
Let's start by stripping out the redundant variables and circular-logic code from your function:
function digPow(n, p) {
let num = n.toString();
// let pow = p; // this is never used again
// let arrn = []; // not needed, see below
// let arrp = []; // was only used to contain values that are later summed; can instead just sum them in the first place
// this does the same thing as num.split(''), and isn't needed anyway:
//for (let i = 0; i < num.length; i++) {
// arrn.push(JSON.parse(num[i]));
//}
// this is the same as the original 'num' variable
// let index = arrn.join('');
// This could have been num.split(), but isn't needed anyway
// let sindex = index.split('');
let total = 0; // moved this line here from after the loop below:
for (let j = 0; j < num.length; j++) { // use num.length instead of the redundant sindex
let power = p + j;
// The only reason for the sindex array was to get individual characters from the string, which we can do with .charAt().
//let indexs = sindex[j];
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
//arrp.push(Mathpow); // No need to collect these in an array
total += Mathpow; // do this instead
}
// No need for this loop, since we can sum the total during the previous loop
// let total = 0;
//for (let m in arrp) {
// total += arrp[m]
//}
let secondVal = total / n;
// let totals = total / secondVal;
// The above is the same thing as total / total / n, which is:
let totals = 1/n;
// This is never used
//let mx = [-1]
// This was totals.length and n.length, which for numbers would always be undefined, so would always return true
if (totals == n) {
return secondVal
} else {
return -1
}
}
So the above reduces to this functionally identical code:
function digPow(n, p) {
let num = n.toString();
let total = 0;
for (let j = 0; j < num.length; j++) {
let power = p + j;
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
total += Mathpow;
}
let secondVal = total / n;
let totals = 1 / n;
if (totals == n) {
return secondVal
} else {
return -1
}
}
Now let's talk about the logic. The actual output will always be -1, unless the input is 1, due to what's clearly a logic error in the totals variable: the only case where 1/n == n is true is when n==1.
Setting that aside, and looking only at the secondVal variable, some examples of what it's calculating for a given input would be
digPow(123,1) --> (1^1 + 2^2 + 3^3) / 123 --> 14/123
digPow(321,2) --> (3^2 + 2^3 + 1^4) / 321 --> 21/321
digPow(92, 1) --> (9^1 + 2^2) / 92 --> 13/92
I'm pretty sure from your description that that's not what you intended. I'm not at all sure from your description what you did intend, so can't be much help in correcting the function beyond what I've done here.
What I'd suggest is to sit down and think through your algorithm first; make sure you know what you're trying to build before you start building it. There were some syntax problems with your code, but the real issues are with the logic itself. Your original function shows clear signs of "just keep throwing more lines of code at it until something happens" rather than any planned thinking -- that's how you wind up with stuff like "split a string into an array, then join it back into a string, then split that string into another array". Write pseudocode first: break the problem down into steps, think through those steps for some example inputs and make sure it'll produce the output you're looking for. Only then should you bust out the IDE and start writing javascript.

I Want To Print 1 to 100 Numbers Using Arrays In Javascript Only

<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
var points = new Array(100);
var label = points.length;
for (var i = 0; i < label; i++) {
console.log(points[i]);
}
</script>
</body>
</html>
This is my First question in Stackoverflow. As i am an beginner, Please bare me and i need alot of support from you people. I m trying to print 1 to 100 numbers using arrays in javascript only. I'm Facing some errors in the above code. Please correct my mistakes to get the output..Thankyou in advance.
This will print 1-100 without any loops
Array.from({length: 100},(_,x) => console.log(x+1))
he said he wants to print 1-100 from an ARRAY...So the array needs to be populated, first. THEN, you can loop through the array.
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1; //This populates the array. +1 is necessary because arrays are 0 index based and you want to store 1-100 in it, NOT 0-99.
}
for (var i = 0; i < points.length; i++) {
console.log(points[i]); //This prints the values that you stored in the array
}
The array values are uninitialized. I'm assuming that you want to print the values 1 to 100 using arrays where the values 1 to 100 are inside the array.
First initialize the array.
var oneToHundredArray = [];
Now populate it with values 1 to 100.
for(var value = 1; value <= 100; value++) {
oneToHundredArray.push(value);
}
Now the contains the values you want. Just loop and print over it now.
for(var index = 0; index < oneToHundredArray.length; index++) {
console.log(oneToHundredArray[index]);
}
Done :)
Array.from(Array(100), (_,i) => console.log(i+1));
The second parameter acts as mapping callback, so you also do this...
const arr = Array.from(Array(100), (_,i) => i+1);
for(num of arr) {
console.log(num);
}
Reference: Array.from
You should start off with an empty array, then run a loop for 1-101, I logged the iterator so you can see the values populate, you then need a binding agent to hold the value of the iteration, then you would need to push those values to your empty array.
var numbersArray = [];
for( var i = 1; i <101; i++){
console.log(i);
var numbers = i;
numbersArray.push(numbers);
}
After that, you then need to run a loop for the length of the numbersArray to output the individual results.
for(var m=0; m<= numbersArray.length -1; m++){
console.log(numbersArray[m]);
}
output console.log logs numbers 1-100 respectively.
var label = new Array(100);
for (var i = 0; i < 100; i++) {
label[i] = i + 1;
}
for (var i = 0; i < label.length; i++) {
console.log(label[i]);
}
It's much more easier with "while"
var i = 1;
while (i < 100) {
document.write(i + "<br/>");
i++;
}
Using a for loop:
function get_array() {
var arr = [];
for(var i=1; i<=100; i++) {
arr.push(i);
}
console.log(arr);
}
get_array()

pushing arrays in multidimensional array

I want to push arrays containing random numbers (0 to 10) into a bigger array once the total of its contents is about to exceed 30. But the output is messed up.
var bigarray = new Array();
var smallarray = new Array();
var randNum = 0;
var total = 0;
for (var i = 0; i<10; i++){
randNum = (10*Math.random()).toFixed(0);
total = total + randNum;
if(total>30) {
bigarray.push(smallarray)
smallarray.length=0;
smallarray.push(randNum);
total = randNum;
} else {
smallarray.push(randNum);
}
}
alert(" BIG ARRAY IS "+bigarray);
two wrong things are visible on the first sight in the code
(1) instead of
randNum = (10*Math.random()).toFixed(0);
you probably want
randNum = Math.floor(11*Math.random());
Math.floor instead of toFixed() - see #kennebec comment
11 instead of 10 to return numbers 0 to 10, as 0 <= Math.random() < 1
(2) the following line pushes (many times) the reference to the same smallarray object.
bigarray.push(smallarray);
In the next step you clear the array with smallarray.length = 0. Because the array is not copied to the bigarray, but only referenced, the generated items are lost.
EDIT: I read your question wrong - the rest of the answer is fixed
You probably want to push the duplicate of the smallarray into bigarray, so replace the line above with the following:
bigarray.push(smallarray.slice(0));
You need another loop inside the main one to populate the smallarray, something like:
var bigarray = new Array();
for (var i = 0; i<10; i++){
// moving the variable declarations inside this loop means they are re-set for each small array
var smallarray = new Array();
// create the first entry for the small array
var randNum = Math.floor(11*Math.random());
var total = randNum;
// loop to populate the small array
while(total <= 30){
smallarray.push(randNum);
randNum = Math.floor(11*Math.random());
total += randNum;
}
bigarray.push(smallarray)
}
I made changes to you code and came up with this.
var bigarray = [];
var smallarray = [];
var randNum = 0;
var total = 0;
for (var i = 0; i < 10; i += 1) {
randNum = Math.floor(10 * Math.random()); // you will never have a value of 10?
total = total + randNum;
if (total > 30) {
bigarray.push(smallarray.slice())
smallarray.length = 0;
smallarray.push(randNum);
total = randNum;
} else {
smallarray.push(randNum);
}
}
alert(" BIG ARRAY IS " + bigarray);
On jsfiddle
Things I changed were:
Ran the code through a beautifier
Changed your use of new Array to []
{} and []
Use {} instead of new Object(). Use [] instead of new Array().
Because Object and Array can be overwritten by the user
Changed ++ to += 1
This pattern can be confusing.
Check out Code Conventions for the JavaScript Programming Language and jslint
Added array.slice when you push smallarray to bigarray, this makes a copy in this case. It is important to understand how javascript works, read Is JavaScript a pass-by-reference or pass-by-value language? Without using slice, which makes a copy as the array only contains primitives, when you set the length of the array to 0, then the data was lost.
Changed your use of number.toFixed to Math.floor so that randNum remains a number
Note: Math.random returns a floating-point, pseudo-random number in the range [0, 1] that is, from 0 (inclusive) up to but not including 1 (exclusive)
Whether your code now produces your expected out, I can not be sure from your description but this should be a good starting point.
var bigarray = new Array();
var smallarray = new Array();
var randNum = 0;
var total = 0;
for (var i = 0; i < 10; i++) {
for (var j = 0; j < smallarray.length; j++) {
total = total + smallarray[j];
}
if (total <= 30)
{
randNum = Math.floor((Math.random() * 10) + 1);
smallarray.push(randNum);
}
else {
bigarray.push(smallarray.slice(0));
smallarray.length = 0;
}
total = 0;
}
alert(" BIG ARRAY IS " + bigarray);

Categories