Array Helpers javascript exercise - javascript

I am trying to solve an exercise about array helpers in Javascript, this is my code.
var numbers = [1, 2, 3, 4, 5];
function square() {
var arraySquare = [];
for (i = 0; i < numbers.length; i++) {
arraySquare[i] = numbers[i] * numbers[i];
arraySquare.push(arraySquare[i]);
}
return arraySquare;
}
console.log(square());
function cube() {
var arrayCube = [];
for (i = 0; i < numbers.length; i++) {
arrayCube[i] = numbers[i] * numbers[i] * numbers[i];
arrayCube.push(arrayCube[i]);
}
return arrayCube;
}
console.log(cube());
function arrayAverage() {
var sum = 0;
var average = 0;
if (numbers === []) {
return NaN;
}
else {
for (i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
average = sum / i;
}
return average;
}
console.log(arrayAverage());
function arraySum() {
var sum = 0;
for (i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum;
}
console.log(arraySum());
function even() {
var arrayEven = [];
for (i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
arrayEven.push(numbers[i]);
}
}
return arrayEven;
}
console.log(even());
function odd() {
var arrayOdd = [];
for (i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) {
arrayOdd.push(numbers[i]);
}
}
return arrayOdd;
}
console.log(odd());
For some reason, the square() and cube() function, push the last element in the new arrays twice. Do you have any idea why this could happen?
Aside from this, the code seems to work just fine. If you notice any other problem in the code please mention it!
Any help will be really appreciated!

Because you are setting the ith element, and after that you are pushing a new value onto the array:
arrayCube[i] = numbers[i] * numbers[i] * numbers[i];
arrayCube.push(arrayCube[i]);
You should probably just do:
arrayCube.push(numbers[i] * numbers[i] * numbers[i]);

The problem lies here
arraySquare[i] = numbers[i] * numbers[i];
arraySquare.push(arraySquare[i]);
You are updating the array two times, your function doesn't just add an extra final number, but it adds two numbers, one at i and one at i+1 every time, the one at i+1 get overwritten the next iteration that's why only the final one stays.
you should just keep the first line

Checked for Square function. It worked for me.
var numbers = [1, 2, 3, 4, 5];
function square() {
var arraySquare = []; var a ;
for (i = 0; i < numbers.length; i++) {
a = numbers[i] * numbers[i];
arraySquare.push(a);
}
return arraySquare;
}
console.log(square());
Hope this works for both functions.
Regards,
Eby J

Related

Given a sequence of integers, return the sum of all the integers that have an even index, multiplied by the integer at the last index

This is my solution and it passes some of the tests, but not all of them. Can anyone help me and explain why? Thank you :)
function evenLast(numbers) {
let sum = 0;
let lastNum = numbers.pop();
let arr = numbers.filter(el => el % 2 === 0);
for(let i = 0; i < arr.length; i++) {
sum += (arr[i] * lastNum);
}
return sum;
}
You need to check the index, not the value
let arr = numbers.filter((_, i) => i % 2 === 0);
And you could multiply the sum at the last step.
for (let i = 0; i < arr.length; i++) {
sum += arr[i]);
}
return sum * lastNum;
A better approach takes only a single loop and sums the values by taking an increment of two.
function evenLast(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i += 2) sum += numbers[i];
return sum * numbers[numbers.length - 1];
}
function evenLast(arr) {
var lastarr = arr.slice(arr.length-1)
//return lastarr;
let newarr = [];
for(i=0; i<arr.length; i++){
if(arr[i] % 2 === 0) {
newarr.push(arr[i]);
}
}
//return newarr;
var sum1 =0;
for(i=0; i<newarr.length; i++) {
var sum = newarr[0] * lastarr[0];
var sum1 = newarr[1] * lastarr[0];
//return sum;
var sum2 = sum1 + sum;
//i++;
}
return sum2;
}
console.log(evenLast([2, 3, 4, 5]))

Faster Algorithm for JavaScript function call within a function

I have written a function and called another function inside but my tests show that it is not time optimized. How can I make the following code faster?
function maxSum(arr, range) {
function sumAll(array1, myrange) {
var total = 0;
if (Array.isArray(myrange)) {
for (var i = myrange[0]; i <= myrange[1]; i++) {
total += array1[i];
}
return total;
} else return array1[myrange];
}
var mylist = [];
var l = range.length;
for (var n = 0; n < l; n++) {
mylist.push(sumAll(arr, range[n]));
}
return Math.max.apply(null, mylist);
}
Algorithmic optimization: create new array with cumulative sums from index 0 to every index
cumsum[0] = 0;
for (var i = 1; i <= arr.Length; i++) {
cumsum[i] = cumsum[i-1] + arr[i-1]
Now you don't need to calculate sums for every range - just get difference
sum for range (i..j) = cumsum[j+1] - cumsum[i];
in your terms:
function sumAll(array1, myrange) {
return cumsum[myrange[1]+1] - cumsum[myrange[0]];
}
example:
arr = [1,2,3,4]
cumsum = [0,1,3,6,10]
sum for range 1..2 = 6 - 1 = 5
P.S. If your array might be updated, consider Fenwick tree data structure
1) You can define the function sumAll outside of the function maxSum because every time you call maxSum the javascript engine is recreating a fresh new function sumAll.
2) You can define myrange[1] as a variable in the initialiser part to avoid javascript to look for myrange[1] at each iteration.
for (var i = myrange[0]; i <= myrange[1]; i++) {
total += array1[i];
}
become this:
for (var i = myrange[0], len = myrange[1]; i <= len; i++) {
total += array1[i];
}
Full working code based on #MBo's excellent optimization. This passes all the tests at https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-challenge-version/train/javascript, which I gather is where this problem comes from.
function maxSum(arr, ranges) {
var max = null;
var sums = [];
var sofar = 0;
for (var i = 0; i <= arr.length; i++) {
sums[i] = sofar;
sofar += arr[i];
}
for (var i = 0; i < ranges.length; i++) {
var sum = sums[ranges[i][1]+1] - sums[ranges[i][0]];
if (max === null || sum > max) {
max = sum;
}
}
return max;
}

least common multiple: What is wrong with my code?

function lcm(arr) {
arr = arr.sort(function(a, b) {
return a - b;
});
var j = 1;
var num = arr[0];
for (i = 1; i < arr.length; i++) {
while (num % arr[i] !== 0) {
j = j + 1;
num = j * arr[0];
}
arr[0] = num;
}
return num;
}
console.log(lcm([3, 5, 6, 10]));
I am trying to find the least common multiple for a range of numbers in an array. The code works fine for array with two items, however the output for arrays with more than two items seems to exceed the value expected.
Can anyone help me find the bug in my code ?
Thank you
Set j back to 1 each time through the loop through the array elements. Otherwise, when you process the next number, you start with a high multiplier.
// function that find the least common multiple
function lcm(arr) {
arr = arr.sort(function(a, b) {
return a - b;
});
var num = arr[0];
for (i = 1; i < arr.length; i++) {
var j = 1;
while (num % arr[i] !== 0) {
j = j + 1;
num = j * arr[0];
}
arr[0] = num;
}
return num;
}
console.log(lcm([3, 5, 6, 10]));

How to generate 100 random numbers and checking each one for primality?

Write a Boolean function named isPrime which takes an integer as an argument and returns true if the argument is a prime number of false otherwise. Generate 100 random numbers and display the results of checking each one for primality.
This is supposed to output the random numbers that are prime (after the true or false check) but I am getting the results of 2 sets of numbers in order.
Here is my code:
var arr = []
while(arr.length < 100){
var randomnumber=Math.ceil(Math.random()*100)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
console.log(arr);
for(i = 0; i < 100; i++){
if(isPrime(i)) console.log(i);
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i==0)
return false;
}
return true;
}
You need to check for primality of arr[i] instead of i:
for(i = 0; i < 100; i++){
if(isPrime(arr[i])) console.log(arr[i]);
}
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
function myFunction() {
for(var i = 0; i < 100; i++) {
$('#demo').append('<div>'+i+'*****'+isPrime(i)+'</div>');
}
}
try it in an html page and dont forget to add jquery
The below code part, you are trying to check the numbers from 0 to 100
for(i = 0; i < 100; i++){
if(isPrime(i)) console.log(i);
}
But you should check the arr array one by one
for(i = 0; i < 100; i++){
if(isPrime(arr[i])) console.log(arr[i]);
}
Using an object to store the numbers let's you avoid the loop to check for duplicates and moving the check for isPrime () let's you skip the second loop. (Your issue was, as #Andrea pointed out, not passing arr [i] to isPrime)
var myRandObj = {};
var randomNumber = 0;
for (var i = 0; i < 100; i++) {
do {
randomNumber = Math.ceil(Math.random() * 100);
} while (typeof myRandObj[randomNumber] !== 'undefined');
myRandObj[randomNumber] = 0;
if (isPrime (randomNumber))
console.log (randomNumber);
}
console.log(arr) is printing the entire array to the console. Remove that line to debug further.
var arr = []
for(x = 0; x < 100; x++){
arr[x] = Math.ceil(Math.random()*100)
}
for(i = 0; i < 100; i++){
if(isPrime(arr[i])) console.log(arr[i]);
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i==0)
return false;
}
return true;
}

Split an array of numbers to arrays whose sum is less or equal than a given number

If array is: [1,2,3,4,5,6,7,8,9,10]
and max-sum is 25
The script should create three arrays
arr1:[1, 2, 3, 4, 5, 6] (sum=21)
arr2:[7,8,9] (sum=24)
arr3:[9,10] (sum=19)
I can create the first array but not the others, someone could kindly help me?
My jquery code is:
$(document).ready(function(){
numbers=[1,2,3,4,5,6,7,8,9,10]
total = 0;
newOne =[];
for(i = 0; i < numbers.length; i++) {
if(total<= (25-numbers[i])){
total += numbers[i];
newOne.push(numbers[i]);
};
};
numbers.splice(0,newOne.length);
console.log(newOne);
console.log(numbers);
});
Thanks to all
Perhaps a little simpler:
$(document).ready(function(){
var numbers=[1,2,3,4,5,6,7,8,9,10]
var total;
var newOne = [];
var index = -1;
while (numbers.length) {
total = 0;
index++;
newOne[index] = []
while (total + numbers[0] <= 25 ) {
total += numbers[0];
newOne[index].push(numbers.shift());
}
}
console.log(newOne);
console.log(numbers);
});
Something like
$(document).ready(function(){
numbers = [1,2,3,4,5,6,7,8,9,10];
total = 0;
coll = [];
newOne = null;
for (i = 0; i < numbers.length; i++) {
if (newOne !== null && total + numbers[i] <= 25) {
total += numbers[i];
newOne.push(numbers[i]);
} else {
// We enter in the else for i = 0 and when we have to
// create a new subarray
if (newOne !== null)
{
console.log(newOne);
}
total = numbers[i];
newOne = [ numbers[i] ];
coll.push(newOne);
}
}
// We have to print the last subarray (because normally
// a subarray is printed only when it's filled)
console.log(newOne);
}
I don't splice the original array. I even put in coll all the various sub-arrays.
If you only want to print the array at the end:
numbers = [1,2,3,4,5,6,7,8,9,10];
total = 0;
coll = [];
newOne = null;
for (i = 0; i < numbers.length; i++) {
if (newOne !== null && total + numbers[i] <= 25) {
total += numbers[i];
newOne.push(numbers[i]);
} else {
total = numbers[i];
newOne = [ numbers[i] ];
coll.push(newOne);
}
}
// Here we print the subarrays
for (i = 0; i < coll.length; i++)
{
console.log(coll[i]);
}

Categories

Resources