This question already has answers here:
How to return values in javascript
(8 answers)
Closed 2 years ago.
I am trying to solve a challenge from jshero.net. The challenge is:
Write a function sum that calculates the sum of all elements of a
two-dimensional array. sum([[1, 2], [3]]) should return 6.
For this one I need to use a nested loop. The best solution I could come up with is:
function sum(num){
let mySum= [num.length]
var sum = 0;
for (var i = 0; i > mySum; i++) {
for (var j = 0; j > mySum; j++) {
sum =mySum[[i]+[j]];
}
}
}
But when I run the code I get the following error:
sum([[1]]) does not return 1, but undefined.
Test-Error! Correct the error and re-run the tests!
Do you guys have any ideea how to solve this?
I think the function should look something like this:
function sum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
return sum;
}
arr=[[1,2,3,4],5,6,[7,8],9]
var sum=0;
for(var d1 of arr)
if(d1.length) // undefined if not array||number
for(var d2 of d1)
sum+=d2;
else
sum+=d1;
// 45
Related
Good morning, am getting stuck with this kata, anyone can explain me ?
In this kata i have to return the sum of elements occupying prime-numbered indices.
I started my code like that, but didn't know what to do next. THANK YOU in advance.
function total(arr) {
for (let i = 2; i < arr.length; i++) {}
};
Please use ; after breaking condition which is i < arr.length here for (let i = 2; i < arr.length, i++) {}
You can loop over arr the way you are doing here and validate if index at which you are looping is prime itself.
If 2nd step is met you can add the value into summation var sum
return sum.
Please follow this thread to find know more about calculating if value is prime. Number prime test in JavaScript
function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
function total(arr) {
var sum = 0;
for (let i = 2; i < arr.length; i++) {
if(isPrime(i)) {
sum = sum + arr[i]
}
}
return sum;
}
I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.
<!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()
I am trying to do a simple factorial code challenge, but with Javascript, when I try to get the index position by looping of the indexes, I get NAN. I understand that NAN is of the typeOf number, just that Javascript doesn't know which number. I don't see why that is happening in this case. Also how can I use get the index of an array by looping over them in Javascript? Thanks!
// Input = 4 Output = 24
// Input = 8 Output = 40320
var total = 0;
var factor_Array = [];
function FirstFactorial(num) {
for (var i = 1; i <= num; i++){
factor_Array.unshift(i);
// console.log(factor_Array);
}
for (var j = 0; j < factor_Array.length; j++){
// Why does this work??? But not when I use 'j' to grab the index position? Seems like BOTH ways should work
total = factor_Array[0] * factor_Array[0+1];
total = factor_Array[j] * factor_Array[j+1];
}
console.log(total);
//return num;
}
FirstFactorial(4);
Because when j = (factor_Array.length-1) it tries to access the j+1 element, which doesn't exist.
The following would work as you expect
for (var j = 0; j < (factor_Array.length-1); j++){
total = factor_Array[j] * factor_Array[j+1];
}
When you loop
for (var j = 0; j < factor_Array.length; j++){
total = factor_Array[j] * factor_Array[j+1];
}
Then then on the last iteration you will be out of the array bounds since
j = factor_Array.length - 1
and you're accessing j + 1.
I am trying to write a program in javascript that gets an unspecified number of numbers out of a html textarea and tries all combinations (adding all numbers with eachother) to see if it mathches a number you specified.
Now I can make an array out of the string in the textarea and using for loops I add these up (see below code). The problem how can you do this for an unspecified number of numbers that are to be added up (e.g. adding up 7 different number if you enter 7 numbers in textarea)? I was thinking of using a second array and, which gets the numbers to add up out of the first loop. And then make te lenght of the loop variable by using a for loop with the lenght of the array containing all numbers (lines in my example) as endvalue.
How can I fill in the values of this 2nd array, making sure all combinations are used?
By the way, I wanted this code because I am a auditor. Sometimes a client reverses a couple of amounts in one booking, without any comment. This code will make it a lot easier to check what bookings have been reversed
edit: The awnser of cheeken seems to be working I only have one remark. What if multiple sub sets of your power set added up result in the number you are looking for? e.g.:findSum([1,2,3,4,5],6) can result [1,2,3] but also [2,4] or [1,5]. is it possible to let the function return multiple sub sets?
Found the answer my self :)
I replaced code
return numberSet;
By
document.getElementById("outp").value=document.getElementById("outp").value+ numberSet +"\n";
Thank you very much Cheeken
One more additional question. How do i format the input for parsing that function? The code below doesn't seem to work. inp is the ID of the textarea where the input is (the numbers are seperated with a semicolumn. The variable ge works so there is no problem there (tested it with [1,2,3,4] and it worked. What is wrong with this code?
re edit:
found the solution. The array needed to be parsed as a floating number added this code.`
for (var i=0; i < lines.length; i++) {
lines[i]= parseFloat(lines[i]);
}
findSum(document.getElementById("inp").value.split(";"), ge);
Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSum(numbers, targetSum) {
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
document.getElementById("outp").value=document.getElementById("outp").value+ numberSet +"\n";
}
}
function main()
{
ge= document.getElementById("getal").value;
findSum([1,1,0.5,0.1,0.2,0.2], ge);
}
</script>
</head>
<body>
<input type="button" onclick="main()" value="tel" /><input type="text" id="getal" /><br>
input<br><textarea id="inp" ></textarea><br>
output<br><textarea id="outp" ></textarea><br>
document.getElementById("inp").value.split(";")
</body>
</html>
More concretely, you're looking for a particular sum of each set in the power set of your collection of numbers.
You can accomplish this with the following bit of code.
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSum(numbers, targetSum) {
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
return numberSet;
}
}
Example invocation:
>> findSum([1,2,3,4,5],6)
[1, 2, 3]
>> findSum([1,2,3,4,5],0)
[]
>> findSum([1,2,3,4,5],11)
[1, 2, 3, 5]
If you'd like to collect all of the subsets whose sum is the value (rather than the first one, as implemented above) you can use the following method.
function findSums(numbers, targetSum) {
var sumSets = [];
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
sumSets.push(numberSet);
}
return sumSets;
}
Example invocation:
>> findSums([1,2,3,4,5],5);
[[2,3],[1,4],[5]]
>> findSums([1,2,3,4,5],0);
[[]]