for loops nested array output - javascript

Part of my homework I have to write a program that calculates all multiplication tables up to 10 and store the results in an array. The first entry formatting example is "1 x 1 = 1".
I think I have my code written right for the nested for loop but I'm not sure on how to output it properly.
var numOne = [1,2,3,4,5,6,7,8,9,10];
var numTwo = [1,2,3,4,5,6,7,8,9,10];
var multiple = [];
for (var i = 0; i < numOne.length; i++) {
for (var j = 0; j < numTwo.length; j++) {
multiple.push(numOne[i] * numTwo[j]);
console.log(numOne[i] * numTwo[j]);
}
}

You can use a template string, and you can just loop through the numbers in the arrays without using arrays (in the same way you were looping through the indices):
var multiple = [];
var m;
for (var i = 1; i <= 10; i++) {
for (var j = 1; j <= 10; j++) {
m = i * j;
multiple.push(m);
console.log(`${i} * ${j} = ${m}`);
}
}

var multiple = [];
var first = 1;
var last = 10;
for (var i = first; i <= last; i++) {
for (var j = first; j <= last; j++) {
multiple.push(i + " x " + j + " = " + (i*j));
console.log(multiple[multiple.length-1]);
}
}

Not sure if ES6 is part of your curriculum, so here is how to do it with and without template literals
// Create the arrays that you want to multiply
var numOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var numTwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Create a function that accepts both arrays as arguments
function multiply(arr1, arr2) {
var products = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
//Here we are using template literals to format the response, so that the program will show you the inputs and calculate the answer
products.push(`${arr1[i]} X ${arr1[j]} = ${arr1[i] * arr2[j]}`);
/* If ES6 is outside of the curriculum, the older method for formatting would be like this:
products.push(arr1[i] + " X " + arr2[j] + " = " + arr1[i]*arr2[j])
*/
}
}
console.log(products);
return products;
}
// Call the second function example
multiply(numOne, numTwo);

Related

Two Sum Leetcode in Javascript - code looks correct but Leetcode says it's wrong

I'm working on the 'Two Sum' problem in Leetcode.
I'm sure this code is correct, I've tested it in Repl and it looks correct there, but Leetcode is giving me an error.
Here's my code:
var arr = [];
var twoSum = function(nums, target) {
for(var i = 0; i < nums.length; i++){
for(var j = i+1; j < nums.length; j++){
console.log(nums[i] + ', ' + nums[j]);
var tot = nums[i] + nums[j];
if(tot === target){
arr.push(i,j);
console.log(arr);
return arr;
}
}
}
};
//var a = [2, 7, 11, 15];
//var b = 9;
var a = [2, 3, 4];
var b = 6;
twoSum(a, b);
The error I'm getting is as follows:
Input:
[3,2,4]
6
Output:
[0,1,1,2]
Expected:
[1,2]
Why is it expecting [1, 2]? Surely it should expect [0, 1] in this case, and then why is my code adding to the arr array twice? It looks like a bug to me...
Note: I see there's many posts about this problem on Leetcode, but none address the specific issue I have run into in Javascript.
Why is it expecting [1, 2]?
Because 2 + 4 = 6
Surely it should expect [0, 1] in this case
No, because 3 + 2 = 5
and then why is my code adding to the arr array twice?
Because you declared the array outside of the function. It is being re-used for every call to the function. Move the array declaration into your twoSum function or even better: Simply return [i, j] instead of pushing into the empty array.
Here is another solution you can try...
var twoSum = function(nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
let compliment = target - nums[i];
if (map[compliment]) {
return [(map[compliment] - 1), i];
} else {
map[nums[i]] = i + 1;
}
}
};
twoSum([2, 3, 4],6);
Click Here to RUN
Here is an optimum solution
/**
* #param {number[]} nums
* #param {number} target
* #return {number[]}
*/
function twoSum(nums, target) {
const numsObjs = {}; // create nums obj with value as key and index as value eg: [2,7,11,15] => {2: 0, 7: 1, 11: 2, 15: 3}
for (let i = 0; i < nums.length; i++) {
const currentValue = nums[i];
if (target - currentValue in numsObjs) {
return [i, numsObjs[target - currentValue]];
}
numsObjs[nums[i]] = i;
}
return [-1, -1];
}
console.log(twoSum([2, 7, 11, 15], 9))
This is my solution, which is a brute force method that uses javascript to search for all possible pairs of numbers.
var twoSum = function(nums, target) {
let numarray = new Array(2);
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
numarray[0] = i;
numarray[1] = j;
}
}
}
return numarray;
};

JavaScript - find the same first element using for loop

I've got to create var with few elements:
var arrNum = [4,7,5,3,4,5,6,7,8,10]
I need to find first number that is the same in array using for loop. So it will be "4" and "4"
I need to create var sameIndex and adjust the same number to sameIndex and print after for loop
So I did loop
for(var i = 0; i < arrNum.length; i++){
console.log("")
console.log("Loop number is " + i)
if(arrNum[i] === arrNum[i]{
break
sameIndex = going[i]
}
}
console.log(sameIndex)
It's not working.
One way would be to use Array#indexOf. It returns the first index of the given element in the array:
var arrNum = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10];
var i;
var sameIndex = -1;
for (i = 0; i < arrNum.length; i++) {
if (arrNum.indexOf(arrNum[i]) !== i) {
console.log('This is the second occurrence of', arrNum[i]);
sameIndex = arrNum.indexOf(arrNum[i]);
break;
}
}
console.log('The indices are', sameIndex, 'and', i);
If you're looking to get the first duplicate, then use :
var arrNum = [4,7,5,3,4,5,6,7,8,10];
function firstDuplicate(array){
var history = [];
for(var element of array){
if(history.indexOf(element)<0)
//not in the history yet
history.push(element);
else
return element;
}
return null; //or any distinctive value
}
var fDup = firstDuplicate(arrNum);
You could take a hash table and display the value.
var array = [4, 7, 5, 3, 4, 5, 6, 7, 8, 10],
hash = Object.create(null),
i;
for (i = 0; i < array.length; i++) {
if (hash[array[i]]) {
console.log('first dupe: ' + array[i]);
break;
}
hash[array[i]] = true;
}
A working script:
var arrNum = [4,7,5,3,4,5,6,7,8,10];
var sameIndex = -1, going = new Array();
for(var j = 0; j < arrNum.length; j++) {
for(var i = 1; i < arrNum.length; i++){
console.log("Loop number is " + j + ", " + i)
if(arrNum[i] === arrNum[j]){
sameIndex = i;
break;
}
}
if(sameIndex > 0) {
console.log(j, sameIndex)
break;
}
}
var arrNum = [4,7,5,3,4,5,6,7,8,10];
for(var i = 0; i < arrNum.length; i++){
for(var j = i+1; j < arrNum.length; j++) {
if(arrNum[i] === arrNum[j]) {
console.log('value: '+arrNum[i]+' index1: '+i+' index2: '+j);
}
}
}
Iterate over the original array and if the value is not in a comparison array - push it into a common numbers array. The first item in that common numbers array is the target.
var origArray = [4,7,5,3,4,5,6,7,8,10];
var newArray = [];
var commonNums = [];
origArray.forEach(function(item,i) {
newArray.indexOf(item) == -1
? newArray.push(item)
: commonNums.push({item: item, index:i});
})
if(commonNums.length > 0) {
var firstCommonNum = commonNums[0].item;
var firstCommonNumIndex = commonNums[0].index;
console.log("common number " + firstCommonNum);
console.log("Loop number is " + firstCommonNumIndex);
}

Output the sorted array to main element

I am new to javascript and working with DOM, so please bear with me.
I have an array called num that I want to sort and display. The sort is a selection sort that returns the number of moves it took.
I can display the unsorted array but can't figure out how to call my sort function and then display the sorted array to the screen. My code is below:
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
listlist
list[min] = temp;
count += 3;
}
return count;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
{
var html = "";
html += "Original:" + num + "<br>";
selection(num, fn);
html += "Sorted:" + num + "<br>";
}
demoP.innerHTML = html;
<div id="content"></div>
arr is undefined, you should use list instead. Returning count returns the number of operations (after it's been initialized), return list instead. And as list is local to the function, you need to set num to the return value of the function call.
<span id='content'/>
<script>
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count=0,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
list[min] = temp;
count += 3;
}
return list;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
var html = "";
html += "Original:" + num + "<br>";
num= selection(num, fn);
html += "Sorted:" + num + "<br>";
demoP.innerHTML = html;
</script>

Comparing two arrays isn`t working

I want to check for the same numbers in "checked" and "numbers". There are six numbers in each array and equal once shuld be outputed in the array "same".
There are 0 elements in "same" even if there are the same numbers in the array. The code to compare the two arrays is right ( I tested it before) but here it wont work.
Please help
Thanks
function getNumbers(){
var boxes = document.forms[0];
var checked = [];
var i;
for (i = 0; i < boxes.length; i++) {
if (boxes[i].checked) {
checked[checked.length] = boxes[i].value;
}
}
if(checked.length != 6){alert("Pick 6");}
else{
document.getElementById("Ausgabe2").innerHTML = "You picked: "+checked;
var numbers = [];
var randomnumber;
while(numbers.length < 6){
randomnumber = Math.ceil(Math.random()*49)
if(numbers.indexOf(randomnumber) > -1) continue;
numbers[numbers.length] = randomnumber;
}
numbers.sort(sortNumber);
document.getElementById("Ausgabe").innerHTML = numbers;
Here the comparing part begins. If I declare 'numbers' and 'checked' here again it works but I dont`t want to do this.
var same = [];
for (i = 0; i < 6; i++) {
if (numbers.indexOf(checked[i]) != -1) {
same.push(checked[i]);
}
}
document.getElementById("Ausgabe3").innerHTML = "You`ve got " + same.length + " right: " + same;
}
}
function sortNumber(a,b) {
return a - b;
}
Is it what you are looking for ?
"use strict"
var numbers = [1, 3, 5, 7, 9, 11];
var checked = [4, 5, 6, 7, 8, 9];
var same = [];
for (var i = 0; i < numbers.length; i++) {
for (var j = 0; j < checked.length; j++) {
if (numbers[i] === checked[j]) {
same.push(numbers[i]);
}
}
}
alert(same);
It's because each time you enter a value in array same you enter it at a fixed index which is undefined (or 0, depends on how you've initialized the array)
// These declarations are only for this demo
var numbers = [0, 1, 2, 3, 4, 5, 6];
var checked = [3, 4, 5, 6, 7, 8, 9];
var same = [];
// Start of the snippet
// Replace the below part in your code
var len = (numbers.length < checked.legth) ? numbers.length : checked.length;
for (i = 0; i < len; i++) {
if (numbers.includes(checked[i])) {
same.push(checked[i]); // This line is where your code had a error
}
}
// End of snippet
console.log('same array:');
console.log(same);
EDIT:
You are understood JS array wrong. Youv'e used the following loop multiple times in the updated snippet in your question
for (i = 0; i < boxes.length; i++) { // Iterate i from 0 till box.length
if (boxes[i].checked) {
checked[checked.length] = boxes[i].value; // For each value of i, the value of check.length is the same. So every time this condition is executed, you simply overwrite the value.
}
}
Try to update your function wit the one below, I've updated few logical error's...
function getNumbers() {
var boxes = document.forms[0];
var checked = [];
var i;
for (i = 0; i < boxes.length; i++) {
if (boxes[i].checked) {
checked.push(boxes[i].value); // Updated here
}
}
if (checked.length != 6) {
alert("Pick 6");
} else {
document.getElementById("Ausgabe2").innerHTML = "You picked: " + checked;
var numbers = [];
var randomnumber;
while (numbers.length < 6) {
randomnumber = Math.ceil(Math.random() * 49)
if (numbers.indexOf(randomnumber) > -1) continue;
numbers.push(randomnumber); // Updated here
}
numbers.sort(sortNumber);
document.getElementById("Ausgabe").innerHTML = numbers;
var same = [];
for (i = 0; i < 6; i++) {
if (numbers.indexOf(checked[i]) != -1) {
same.push(checked[i]);
}
}
document.getElementById("Ausgabe3").innerHTML = "You`
ve got " + same.length + "
right: " + same;
}
}

Javascript sum of arrays and average

I have an issue with getting the sum of two arrays and combining their averages while rounding off.
I don't want to hardcode but rather pass two random arrays. so here is the code but it keeps returning NaN
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
arr = [];
a = [];
b = [];
arr[0] = a;
arr[1] = b;
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
If you wanted to do it a bit more functionally, you could do something like this:
function sumAverage(arrays) {
const average = arrays.reduce((acc, arr) => {
const total = arr.reduce((total, num) => total += num, 0);
return acc += total / arr.length;
}, 0);
return Math.round(average);
}
console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));
Just try this method..this kind of issues sometimes occured for me.
For example
var total = 0;
total = total + sum / a.length;
And every concat use this method..
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle
function sumAverage(arr) {
var result = 0;
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for(var j = 0; j < a.length; j++ ){
sum += a[j] ;
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for(var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
As said in comments, you reset your arguments...
Use the variable "arguments" for dynamic function parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.
function sumAverage(array) {
var result = 0,
sum,
i, j;
for (i = 0; i < array.length; i++) {
sum = 0;
for (j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
result += Math.round(sum / array[i].length);
}
return result;
}
console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12
The problem is that you are emptying arr by saying arr = [].
Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.
Solution is to not empty passed arr and modify your code like below:
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total = sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math = add / b.length;
result = math + total;
result = Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
Basically I see a mistake here:
arr[0] = a; arr[1] = b;
That should be
a= arr[0]; b= arr[1];
and then remove:
arr = [];
I suggest you write your function like this:
function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}

Categories