I am trying to sum an array where array length will be provided by user. I have done it but execution time is high then required. What is an efficient way to do it. my code
function summation(){
var p = prompt("Number Only","");
var arr = [] ;
var sum = 0 ;
for (var i = 0; i < p; i++) {
arr.push(parseInt(prompt("Number Only","")));
};
for (var i = 0; i <arr.length; i++) {
sum += arr[i];
};
document.write(sum);
}
(function(){
summation();
})();
Why to use an array when you don't need an array?
function summation(){
var p = prompt("Number Only","");
var sum=0;
for(var i=0;i<p;i++){
sum+=parseInt(prompt("Number Only", ""));
}
document.write(sum);
}
This solution features an infinite loop with break, a prompt with control, a continuing input and a type checking for numbers.
The first imput for the array size is not more necessary, because of the possibillity of immediately ending with cancel or empty input.
function summation() {
var arr = [],
sum = 0,
v;
while (true) {
v = prompt("Number Only (Press [Cancel] for end input)", "");
if (!v) {
break;
}
v = parseInt(v, 10);
if (isFinite(v)) {
arr.push(v);
sum += v;
}
}
document.write('Array: ' + arr + '<br>');
document.write('Sum: ' + sum + '<br>');
}
summation();
Related
I'm asking for help to find the sum of an array with elements that were pushed from a counter variable that had previously looped 10 times. I'm new to Javascript and was practicing for an assessment, and I've tried several different ways to do it and have only resulted with just a list of the elements within the numbers array.
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i ++) {
counter = [i + 73];
numbers.push(counter);
}
console.log(numbers);
function sum(arr) {
var s = 0;
for(var i = 0; i < arr.length; i++) {
s = s += arr[i];
}
return s;
}
console.log(sum([numbers]));
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var numbers = getArraySum([numbers]);
console.log(numbers);
you should push only the value of counter without the brackets and then make a reduce to have the sum of each number in the array
var counter = 10;
var numbers = [];
for (i = 1; i <= 10; i++) {
counter = i + 73;
numbers.push(counter);
}
console.log(numbers.reduce((a,b) => a+b));
You had a couple of typos in the code:
Typos
You were wrapping the sum in square brackets:
counter = [i + 73];
You should just remove the brackets like:
counter = i + 73;
2. You were wrapping a value that is already an array in square brackets while passing it as an argument to a function:
sum( [numbers] )
// ...
getArraySum( [numbers] );
You should remove the brackets, like this:
sum( numbers );
// ...
getArraySum( numbers );
Fix
I updated the code that you shared to fix the above-mentioned things:
var numbers = [];
// Loop 10 times and push each number to the numbers array
for (var i = 1; i <= 10; i ++) {
var sumNumbers = i + 73;
numbers.push(sumNumbers);
}
console.log(numbers);
function sum(arr) {
var total = 0;
for(var i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// Call the function by passing it the variable numbers, holding an array
var result1 = sum(numbers);
console.log( result1 );
function getArraySum(a) {
var total = 0;
for (var i in a) {
total += a[i];
}
return total;
}
var result2 = getArraySum(numbers);
console.log(result2);
I'm trying to add elements as asterisks inside array based on number of elements. Basically If numberOfRows is 3 then I want this output:
[
' * ',
' *** ',
'*****'
]
I'm struggling on setting asterisks using the index. Can anyone point me in the right direction? Thanks a lot!
Here's my code:
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var asterisk = "*"; // Need to update this based on number of rows
for (var i = 1; i <= numberOfRows; i++) {
value += asterisk;
arr.push(value);
}
return arr;
}
Got it working! Here's a perfect solution.
function myFunction(n) {
let arr = [];
for(let f = 1; f <= n; f++) {
arr.push(' '.repeat(n - f) + '*'.repeat(f + f - 1) + ' '.repeat(n - f));
}
return arr;
}
console.log(myFunction(3));
Try something like this;
function myFunction(numberOfRows) {
var arr = [];
var value = "";
var slots = numberOfRows * 2 - 1;
var spaceSlots, asteriskSlots, spaces;
for (var i = 0; i < numberOfRows; i++) {
asteriskSlots = i * 2 + 1;
spaceSlots = Math.floor((slots - asteriskSlots)/2);
spaces = new Array(spaceSlots).fill(' ').join('');
value = spaces + '*'.repeat(asteriskSlots) + spaces;
arr.push(value);
}
return arr;
}
console.log(myFunction(20));
I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
I am working through this Free Code Camp exercise.
Return the sum of all odd Fibonacci numbers up to and including the
passed number if it is a Fibonacci number. The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and
8, and each subsequent number is the sum of the previous two numbers.
And here is what I have so far...
Any suggestions?
function sumFibs(num) {
var arr, isFibVal, isEvenVal, sum, i = 0, fibonacci = function (num){
var a, b, result, fibArr = [1];
a=0;
b=1;
result=b;
for(var j = 0; j < num; j++){
result = a + b;
a = b;
b = result;
fibArr.push(result);
}
return fibArr;
},
isFib = function (val){
var prev = 0;
var curr = 1;
while(prev<=val){
if(prev == val){
return true;
} else {
return false;
}
curr = prev + curr;
prev = curr - prev;
}
},
isEven = function(someNumber){
return (someNumber % 2 === 0) ? true : false;
};
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
arr = fibonacci(num);
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
}
return sum;
}
All I get back is undefined which seems to be weird because i thought this part of my code was pretty cool—using the function values to check vs. in the if statement.
arr = fibonacci(num);
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
}
I won't give you the answer outright since you're going through FCC, but I'll provide you with some hints as to where to look:
See this segment:
for(var j = 0; j < num; j++){
result = a + b;
a = b;
b = result;
fibArr.push(result);
}
And this one:
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
Also, you probably don't need this segment at all:
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
Good luck. As someone who has finished a good chunk of the curriculum, I can say that Free Code Camp is the real deal.
You're pretty close and the other answer is good for pushing you in the right direction, I'll post a different way that does this using native JS functions:
Example of the code below in JSBin
function fibs(n) {
var f = [0, 1];
var extraNumber = 0;
for (var i = 0; i < n; i++) {
f.push(f[f.length - 1] + f[f.length - 2]);
}
// lets check if the passed in number is a fib:
if (f.indexOf(n) > -1) {
extraNumber = n;
}
console.log(f); // just to check we can cut all the logs later...
var filtered = f.filter(function(num) {
// filter out the even numbers
return num % 2 === 1;
});
console.log(filtered);
var sum = filtered.reduce(function(a, b) {
// add up whats left
return a + b;
});
console.log(sum);
return sum + extraNumber;
}
heres my solution, and i find it to be pretty readable:
function sumOddFibs(num) {
// initialize with 2 because
// fib sequence starts with 1 and 1
var sum = 2;
var prev = 1;
var curr = 1;
var next = 2;
while (next <= num) {
prev = curr;
curr = next;
next = prev + curr;
if (curr % 2 !== 0) {
sum += curr;
}
}
return sum;
}
You could start by defining variables for the previous number, current number, and total Fibonacci
To check for odd numbers, you could use an if statement and use %:
if (currNum % 2 !== 0){ }
If current number is odd, then you add it to the total
fibTotal += currNumber;
To determine the next Fibonacci number you, you will need to add the previous and current number:
var nextNumber = prevNumber + currNumber;
You will need to update the previous number to the current one
prevNumber = currNumber;
Set the current number to the next Fibonacci number in the sequence
currNumber = nextNumber;
Hope this helps.
Following were an output from an array returned by following function:
$scope.variantOptions = $scope.variantLists.join(", ");
medium,small,medium,small,small
How can I sort the result, so it represent the output as:
medium x 2,small x 3
EDIT
addCount function:
$scope.addCount = function($index){
$scope.counter = 1;
if($scope.activity['variant'][$index]['count'] != undefined ){
$scope.counter = parseInt($scope.activity['variant'][$index]["count"]) +1;
$scope.variantLists.push($scope.activity['variant'][$index]['variant_dtl_name']);
}
$scope.activity['variant'][$index]["count"] = $scope.counter;
console.log(arraySimplify($scope.variantLists));
};
Thanks!
pass your '$scope.variantLists' arry into this function it will give you the expected result.
function arraySimplify(arr){
arr.sort();
var rslt = [], element =arr[0] ,count = 0 ;
if(arr.length === 0) return; //exit for empty array
for(var i = 0; i < arr.length; i++){
//count the occurences
if(element !== arr[i]){
rslt.push(element + ' x ' + count);
count =1;
element = arr[i];
}
else{
count++;
}
}
rslt.push(element + ' x ' + count);
return rslt.join(', ');
}
Your code is working:
for (var i = 0;i < $scope.variantLists.length;i++) {
obj[arr[i]] = (obj[arr[i]] || 0) + 1;
}
Gives you an object:
obj = {medium: 2, small: 3}
To see it without having to go into the console, you can just alert the object after the 'for' loop:
alert(obj);
To get the EXACT string you want:
var string = "";
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var count = validation_messages[key];
string += key + " x " + count;
}
}
Although it may look like an entry in Code Golf but this is one of the rare times when Array.reduce makes sense.
var r = a.sort().reduce(
function(A,i){
A.set(i, (!A.get(i))?1:A.get(i)+1);
return A;
},new Map());
Which makes basically what Jon Stevens proposed but in a more modern and highly illegible way. I used a Map because the order in a normal Object dictionary is not guaranteed in a forEach loop. Here r.forEach(function(v,k,m){console.log(k + ":" + v);}) gets printed in the order of insertion.