Comparing array to var during iteration(cont.) - javascript

So here's my problem.. Might just be tired but, I want counter to ++ only if number has not occurred in array.
Meaning during the 4 iterations, counter should ++ only on iteration 1,3,4
var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
array.push(i);
number = temp[i];
}
document.write(counter);
But I'm drawing a blank here... Help?
(No this isn't homework)

if (array.indexOf(number) < 0)
counter++;

unfortunately JS doesn't have an "in_array", but it's pretty straight forward:
#MikeSamuel pointed out you can use indexOf (thanks Mike). So with that being said:
var array = [], number, temp = [4,2,5,9], counter = 0;
for(var i = 0; i <= 3; i += 1) {
array.push(i);
number = temp[i];
if (temp.indexOf(i)==-1) // much simpler, assuming you're checking if i is in temp.
counter++; // increase counter if it is not.
}
document.write(counter);
I'm not sure where you want the logic, so you'll have to figure that out or be more specific. Just know that you need to iterate through the array you're checking and check if the "needle" is in the "haystack" array.
EDIT Had the opposite, just added bool to check for existence.

Related

Sum of array elements in 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

Why won't my function work when I use splice?

I am trying to write a function which should calculate all prime numbers up to an input parameter and return it. I am doing this for practice.
I wrote this function in a few ways but I was trying to find new ways to do this for more practice and better performance. The last thing I tried was the code below:
function primes(num){
let s = []; // sieve
for(let i = 2; i <= num; i++){
s.push(i);
}
for(let i = 0; i < s.length; i++) {
for(let j = s[i]*s[i]; j <= num;) {
//console.log(j);
if(s.indexOf(j)!= -1){
s.splice(s.indexOf(j), 1, 0);
}
j+=s[i];
}
}
s = s.filter(a => a != 0);
return s;
}
console.log(primes(10));
The problem is that when I run this in a browser it keeps calculating and won't stop and I don't know why.
Note: when I comment out the splice and uncomment console.log(j); everything works as expected and logs are the things they should be but with splice, the browser keep calculating and won't stop.
I am using the latest version of Chrome but I don't think that can have anything to do with the problem.
Your problem lies in this line:
s.splice(s.indexOf(j), 1, 0);
Splice function third argument contains elements to be added in place of the removed elements. Which means that instead of removing elements, you are swapping their values with 0's, which then freezes your j-loop.
To fix it, simply omit third parameter.
function primes(num){
let s = []; // sieve
for(let i = 2; i <= num; i++){
s.push(i);
}
for(let i = 0; i < s.length; i++) {
for(let j = s[i]*s[i]; j <= num;) {
//console.log(j);
if(s.indexOf(j)!= -1){
s.splice(s.indexOf(j), 1);
}
j+=s[i];
}
}
return s;
}
console.log(primes(10));
Your problem is in this loop:
for(let j = s[i]*s[i]; j <= num;)
This for loop is looping forever because j is always less than or equal to num in whatever case you're testing. It is very difficult to determine exactly when this code will start looping infinitely because you are modifying the list as you loop.
In effect though, the splice command will be called setting some portion of the indexes in s to 0 which means that j+=s[i] will no longer get you out of the loop.

Understanding get second lowest and second highest value in array

Good day fellow Stack-ers,
I must ask your pardon if this question has been asked before or if it seems elementary (I am only a Javascript novice).
I have been doing w3c js challenges lately: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.
Here is my answer:
var array = [3,8,5,6,5,7,1,9];
var outputArray = [];
function arrayTrim() {
var sortedArray = array.sort();
outputArray.push(sortedArray[1],array[array.length-2]);
return outputArray;
}
arrayTrim();
and here is the answer that they have provided:
function Second_Greatest_Lowest(arr_num) {
arr_num.sort(function(x,y) {
return x-y;
});
var uniqa = [arr_num[0]];
var result = [];
for(var j=1; j < arr_num.length; j++) {
if(arr_num[j-1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
result.push(uniqa[1],uniqa[uniqa.length-2]);
return result.join(',');
}
alert(Second_Greatest_Lowest([1,2,3,4,5]));
I know that the for loop runs through until the length of the input, but I don't understand the if statement nested within the for loop. It seems like a long way around to the solution.
Thank you!
Your answer does not perform correct for input such as f.e. [3,8,5,6,5,7,1,1,9]. Your proposed solution returns 1 as the second lowest number here – whereas it should actually be 3.
The solution suggested by the site takes that into account – that is what the if inside the loop is for, it checks if the current number is the same as the previous one. If that’s the case, it gets ignored. That way, every number will occur once, and that in turn allows to blindly pick the second element out of that sorted array and actually have it be the second lowest number.
It seems like a long way around to the solution
You took a short cut, that does not handle all edge cases correctly ;-)
The loop in question:
for(var j=1; j < arr_num.length; j++) {
if(arr_num[j-1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
Provides some clue as to what it's doing by using a (reasonably) descriptive variable name: uniqa - or "unique array". The if statement is checking that the current element is not the same as the previous element - having sorted the array initially this works to give you a unique array - by only filling a new array if the element is indeed unique.
Thereafter the logic is the same as yours.
import java.util.Arrays;
public class BubbleWithMax_N_Min
{
public static void main(String[] agrs)
{
int temp;
int[] array = new int[5];
array[0] = 3;
array[1] = 99;
array[2] = 55;
array[3] = 2;
array[4] = 1;
System.out.println("the given array is:" + Arrays.toString(array));
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i] + "");
}
for (int i = 0; i < array.length; i++)
{
for (int j = 1; j < array.length - i; j++)
{
if (array[j - 1] > array[j])
{
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
System.out.println(" 2nd Min and 2nd Highest:");
for (int i = 0; i < 1; i++)
{
System.out.println(array[i+1]);
}
for (int i = 0; i < 1; i++)
{
int a= array.length-2;
System.out.println(array[a]);
}
}
}

Why does my code always end with undefined?

I wrote this JavaScript code, but it always ends **undefined**mycode? What have I done wrong/ how can I prevent this in the future. I am running my code through the chrome javascript console.
Here is my code
//Reverse a string
//-------------------------//
//Input a string
var string = prompt("Please enter string");
//console.log(string);
//Find length of string
var stringLength = string.length;
//console.log(stringLength);
//Creating an empty string for outputting answer
var reversedString = "";
//Start from length of the string and work backwards, inputting letter 1 at a time.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
//Outputting the reversed string;
alert(reversedString);
Thanks for any answers in advance
Change your loop from
for (var i = stringLength; i >= 0; i--){
to
for (var i = stringLength-1; i >= 0; i--){
The problem is, the array indices in javascript are 0 based.
Lets say the string entered in the prompt is "abc", the length of the string is 3. In the loop, you access it as string[3] which is undefined. Hence the error.
Here is the fiddle demonstrating the updated code:
http://jsfiddle.net/rf1vmyzg/
adding string[i] is the last thing this code does before alerting you, so therefore the last string[i], (first element in your array, I assume) has the value of undefined.
for (var i = stringLength; i >= 0; i--){
reversedString += string[i];
//console.log(string[i]);
}
I do not know on the top of my head why this is, but I know that it is always a good idea to stick to conventions, and the one for for loops is:
for(var i = 0; i < [length variable];i++) {
...
}
Right code
for (var i = stringLength-1; i >= 0; i--){
reversedString += string[i];
console.log(string[i]);
}
You should not do string[i] instead do string.charAt(i); Also change stringLength to stringLength - 1. That should fix your problem. If you want this to work across different browsers use charAt notation. Javascript arrays start at 0 not 1 that is why you do length - 1 to get the last element. For example:
for a 10 element array indexes are 0-9. 10 is outside the boundaries of the array.
for (var i = (stringLength - 1); i >= 0; i--){
reversedString += string.charAt(i);
This is the correct answer.

Javascript Euler Fibonacci for loop

I'm doing the Euler project problem 2 in which the objective is to sum the even numbers of the fibonacci sequence that have a value of less than 4 million. I've searched a bit and I've seen several solutions using a while loop but nothing simple using a for loop. I'm curious why I'm returning zero with the following code:
var array = [];
array[0] = 0;
array[1] = 1;
var total = 0;
for(var i=2;total<=4000000;i++) {
array[i] = array[i-1] + array[i-2];};
for(var x=0;x<array.length;x++){
if(array[x]%2 === 0){
total += array[x]};};
alert(total);
I'm guessing the problem is in my for loop using the total variable. I couldn't get it to work using array[i]<=4000000 either and I'm really curious behind the why here. Anyone know why this is? What can I change in the for loop condition (second statement) to get a correct total here?
First of all there is an infinite loop at first for. Your condition must be array[i-1] < 4000000. After that your second for loop will find the correct result.
Also for the problem, you don't need to store all fibonacci numbers then find sum of even numbers.
You can calculate sum when calculating fibonacci.
var first = 0;
var second = 1;
var sum = 0;
for(var current=first+second; current < 4000000; current = first+second){
if(current%2 === 0){
sum+=current;
}
first = second;
second = current;
}
I fixed it for you.
var i, data = [ 0, 1 ], total = 0;
for (i = 2; i <= 4000000; i++)
{
data[i] = data[i - 1] + data[i - 2];
if (data[i] % 2 === 0)
{
total += data[i];
}
}
alert(total);
I'm not sure what you termination condition should be like, you say have a value of less than 4 million, but this is ambiguous. Maybe it should be total <= 4000000 or data[i] <= 4000000. Your phrasing is not precise enough.
Sorry but for me your code going in a dead loop. first "for" use total as check but it's never incremented. If you want This is a solution for fibonacci sequence based on dinamic programming with memoization tecnic.
var f1 = 1;
var f2 = 1;
for(var i = 2; i < 40000; i++){
console.info(i, f1, f2);
var temp = f1 + f2;
f1 = f2;
f2 = temp;
}
alert(f2);

Categories