I have written this bit of code that sums the values of array. Can some one please explain why I'm getting undefined in the last console.log statement.
var array = [2,3,4,5,6,7];
var sum = 0;
for(var i = 0; i < array.length; i++) {
sum = array[i] + sum;
}
console.log(sum);
console.log(array[i]);
That's because the loop performed i++ and now i is equal to array.length.
JavaScript returns the primitive value undefined when you're trying to access object properties that were not previously defined.
The array however is only filled between places 0 and array.length - 1 since JavaScript arrays are 0 based.
Related
i am trying to figure out how this code works.
function Kth_greatest_in_array(arr, k) {
for (let i = 0; i < k; i++) {
let max_index = i;
const tmp = arr[i];
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[max_index]) {
max_index = j;
}
}
arr[i] = arr[max_index];
arr[max_index] = tmp;
}
return arr[k - 1];
}
console.log(Kth_greatest_in_array([1,2,6,4,5], 3))
As you can see the goal is to find third biggest value. But i don know how the second loop works. Could you explain it to me step by step. For example, what is the meaning of veriable j, especially why they typed let j = i +
This method basically performs an in-place sort of the arr array (but only "k" times - not a full sort), then returns the element (from the now partially sorted array) at index k-1.
The inner for loop looks through the remaining (unsorted) portion of the array to find the index of the item with the highest value:
if (arr[j] > arr[max_index]) {
max_index = j;
}
The specific statement you were asking about, let j = i + 1, means "declare a new variable, j, and set its initial value to one greater than the current iteration of the outer for loop". "j" is arbitrary and could be any valid identifier, it's just often used by convention when you have nested for loops since the outermost loop usually uses i (which is presumably short for "index").
At the end of each iteration of the outer for loop, these lines swap array elements so that this element is in the correct position:
arr[i] = arr[max_index];
arr[max_index] = tmp;
If you're curious to really understand the inner workings of a method like this, I'd highly encourage you to step through it with a debugger - it can be a great learning experience. Even just the tried-and-true method of sprinkling some temporary console.log statements can help illuminate what's going on (e.g., print the state of arr and max_index after every outer and inner loop iteration).
function insertionSort(arr) {
var length = arr.length,
val,
i,
j;
for(i = 0; i < length; i++) {
value = arr[i];
for(j = i - 1; j > -1 && arr[j] > value; j--) {
arr[j+1] = arr[j]
}
arr[j+1] = value;
}
return arr;
}
console.log(insertionSort([6,1,23,4,2,3]))
I am looking at an example of the insertion sort algorithm encoded in javascript, and having trouble understanding why it passes the conditional of the inner for loop. To be clear, this algorithm is correct -- I'm just having difficulty understanding why.
If j is initialized with i - 1, then the value of j is -1, since i is initialized at 0. In the first part of the conditional it states j > -1, which means it won't pass the this test, since j is not greater than -1.
Can someone tell me what I am missing?
You're right, the first iteration will not enter the second loop, but this is okay. Notice what that loop is doing. It's swapping array[j+1] with array[j]. When i == 0, then j == -1. You can't swap array[0] with array[-1], since it doesn't exist. This is a clever way of bypassing that issue.
However, this only happens on the first iteration. Subsequent iterations will enter the loop as expected.
Write a function that takes in a non-empty array of distinct integers and a target integer.
Your function should find all triplets in the array that sum up to the target sum and return a two-dimensional array of all these triplets.
Each inner array containing a single triplet should have all three of its elements ordered in ascending order
ATTEMPT
function threeNumberSum(arr, target) {
let results = [];
for (let i = 0; i < arr.length; i++) {
let finalT = target - arr[i];
let map = {};
for (let j = i+1; j < arr.length; j++) {
if (map[arr[j]]) {
results.push([arr[j], arr[i], map[arr[j]]]);
} else {
map[finalT-arr[j]] = arr[j];
}
}
}
return results;
}
My code is formatted all funny, but right now im not getting any output. Am I missing a console log somewhere or something?
Your problem is that you read input wrong.
Pay attention to the last part of question: How to Read Input that is Used to Test Your Implementation
You wrote a function that takes the array as first arg and the target integer as the second one. But the input is entered one by one, so your program should read one value at a time from the console input.
var myArray = []; //Create an empty array
//Fills empty array with values
for (i = 0; i < myArray.length - 1; i++) {
myArray[i] = i * i; //Each index is equal to the square of the index number 0=0, 1=1, 2=4, etc.
}
console.log(myArray.length);
console.log(myArray[0]);
console.log(myArray.length); returns 0 in console
console.log(myArray[0]); returns undefined in console
myArray.length returns the number of elements in the array myArray.
Your array when it reaches the loop has no elements in it ([]). So when you do myArray.length you will get the number 0 in return.
Thus your for loop will run zero times, as 0 < 0 is never true (and for it to run, your middle condition needs to evaluate to true), meaning when you reach your console.log nothing will be set in your array, and so myArray[0] will be undefined.
Thus, to generate values you need to use a number greater than zero in your for loop. In the example below, I created an array with 10 elements:
var myArray = []; //Create an empty array
//Fills empty array with values
for (i = 0; i < 10; i++) { // <--- Change to i < 10 here to run 10 times (for i ranging within [0, 10) (0 <= i < 10)
myArray[i] = i * i; //Each index is equal to the square of the index number 0=0, 1=1, 2=4, etc.
}
console.log(myArray.length); // 10
console.log(myArray[0]); // 0
console.log(myArray[1]); // 1
console.log(myArray[2]); // 4
myArray.length when you start the loop is zero. So, It doesn't even go into the loop, hence the array remains as you initialized it.
You can simply use the Array.from and generate the numbers with the mapFn as the second argument:
const generate = n => Array.from({length: n}, (x,i) => i*i)
console.log(generate(5))
console.log(generate(10))
I have the following code:
function bytesToMb(arr)
{
for(var i=0;i<arr.length;arr++)
{
var mbs= arr[i]/(1000*1000);
arr[i]=mbs;
}
return arr;
}
after the line arr[i]=mbs executes, the value of arr (the array object itself) becomes NAN.
why is that????
You are incrementing arr, arr + 1 = NaN because array is NaN; you ought to do i++ in your for loop instead...
You're using arr++ instead of i++ as the third clause in your for loop.
The type coercion from Array to Number leads to your NaN.
Change arr++ to i++
function bytesToMb(arr) {
for (var i = 0; i < arr.length; i++) {
var mbs = arr[i] / (1024 * 1024); // you should use 1024*1024 here to make it more precise if you need to.
arr[i] = mbs;
}
return arr;
}