Comparing two arrays isn`t working - javascript

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;
}
}

Related

for loops nested array output

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);

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);
}

Array Processing logic correction

I have an array [1,2,4,5,1,7,8,9,2,3]
and i would like it to generate all subset which sum of values are less than 10
current result [[1,2,4],[5,1],[7],[8],[9],[2,3]]
expected result [[4,5,1],[9,1],[8,2],[3,7],[1,2]]
that is what i did
var a = [1,2,4,5,1,7,8,9,2,3], tempArr = []; tempSum = 0, result = [];
for (var i = 0;i< a.length; i += 1 ) {
tempSum+=a[i];
tempArr.push(a[i]);
if((tempSum+a[i+1])>10) {
result.push(tempArr);
tempSum = 0;
tempArr = [];
} else if (i == a.length-1 && tempArr.length > 0) { // if array is [1,2,3]
result.push(tempArr);
}
}
but it gives me [[1,2,4],[5,1],[7],[8],[9],[2,3]] and it has 6 subset, but i expect to get [[4,5,1],[9,1],[8,2],[3,7],[1,2]] which has 5 subset.
Below logic is in JavaScript :-
var limit = 10;
var arr = [1,2,4,5,1,7,8,9,2,3];
arr.sort();
var ans = new Array ( );
while(arr.length >0){
var ts = arr[arr.length-1];
arr.splice(arr.length-1 , 1);
var ta= new Array ( );
ta.push(ts);
var x = arr.length-1;
while(x>=0){
if(ts + arr[x] <= limit){
ts = ts + arr[x];
ta.push(arr[x]);
arr.splice(x , 1);
}
x= x-1;
}
ans.push(JSON.stringify(ta));
}
alert(ans);
It is Giving Output as required .
[9,1],[8,2],[7,3],[5,4,1],[2]
I have removed duplicates then added maxSum parameter to combine function to generate all subset which have those conditions and then sorted subsets by sum of the values and sliced them.
You could change parameters to fit it for your problem.
var arr = [1,2,4,5,1,7,8,9,2,3]
MAX_SUM = 10,
MIN_SUBSET_LEN = 2,
RESULT_LEN = 5;
//remove duplicates
var uniqeSet = arr.filter(function(value, index){
return this.indexOf(value) == index
},arr);
// a function to get all subset which
// their length are greater than minLength and
// sum of values are little than maxSum
var combine = function(sourceArr, minLength, maxSum) {
var fn = function(n, src, got, all, sum) {
if(sum <= maxSum){
if (n == 0) {
if (got.length > 0) {
all.push({arr:got,sum:sum});
}
return;
}
for (var j = 0; j < src.length; j++) {
var tempSum = sum
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all, sum + src[j]);
}
}
return;
}
var all = [];
for (var i = minLength; i < sourceArr.length; i++) {
fn(i, sourceArr, [], all, 0);
}
return all;
}
var result = combine(uniqeSet, MIN_SUBSET_LEN, MAX_SUM);
var sortedSliced = result.sort(function(a1, a2){
return a2.sum - a1.sum;
}).slice(0, RESULT_LEN).map(function(m){return m.arr;});
console.log(JSON.stringify(sortedSliced));

unexpected result in function separating unique and non unique items

The aim of the bellow function is to output only the non-unique items from an array that is passed as an argument:
"use strict";
function nonUnique(data){
var tab = [];
for(var d = 0; d < data.length; d++) {
if(typeof(data[d]) == "string"){
tab[d] = data[d].toUpperCase();
}
else{
tab[d] = data[d];
}
}
var count = 0;
var tab_non_unique = [];
var tab_unique = [];
for(var i = 0; i < tab.length; i++){
for(var j = 0; j < tab.length; j++){
if(tab[i] == tab[j]){
count ++;
}
if(count > 1){
tab_non_unique.push(tab[i]);
count = 0;
break;
}
if (count == 1) {
tab_unique.push(tab[i]);
}
}
}
return tab_non_unique;
}
I have tested the function by calling it on different arrays but somehow on
nonUnique([1, 2, 3, 4, 5]);
it fails by returning:
=> [ 2, 4 ]
I don't understand what in my code causes 2 and 4 to raise the counter higher than 1 and thus end up in the tab_non_unique array. Any help would be greatly appreciated, thanks.
The problem is that you reset count only if a non-unique is found. But it should be reset always when starting with a new number.
So put the count=0 at the top of the loop.
for (var i = 0; i < tab.length; i++) {
count = 0;
for (var j = 0; j < tab.length; j++) {
if (tab[i] == tab[j]) {
count++;
}
if (count > 1) {
tab_non_unique.push(tab[i]);
break;
}
if (count == 1) {
tab_unique.push(tab[i]);
}
}
}

Trying to convert nested loop to recursive function

I'm trying to create a recursive version of the following nested loops and to get the same results as the reference code. The example is below.
This is a version on Codepen http://codepen.io/anon/pen/XbQMLv
(The intent of the code is to output only unique combinations of integers from the indexes.)
Original code and output:
var len = 4;
for (var a = 0; a < len; a++) {
for (var b = a + 1; b < len; b++) {
for (var c = b + 1; c < len; c++) {
console.log(a, b, c);
}
}
}
// Outputs:
// 0 1 2
// 0 1 3
// 0 2 3
// 1 2 3
Recursive code and output:
var len = 4;
var end = 3;
var data = [];
var loop = function (index) {
if (index === end) {
console.log(data);
return;
}
for (var i = index; i < len; i++) {
data[index] = i;
loop(i + 1);
}
}
loop(0);
// Outputs:
// [ 0, 1, 2 ]
// [ 0, 2, 3 ]
// [ 1, 3, 2 ]
// [ 2, 3, 3 ]
Not sure what I'm missing here.
You have a single little error in your code:
You call a recursive function from your i + 1, but not your index + 1.
It causes index to be equal not current array index but it's value.
For example, when you passed [0, 1, 2], your data now is [0, 1] and you are about to insert 3, you call loop(3 + 1), index 4 goes out of an array range. if (index === end) condition fails and it doesn't output. for (var i = index; i < len; i++) loop fails as well, and everything is going wrong.
It should be:
var len = 4;
var end = 3;
var data = [];
var loop = function (index) {
if (index === end) {
console.log(data);
return;
}
for (var i = index; i < len; i++) {
data[index] = i;
loop(index + 1); // <--- HERE
}
}
loop(0);
Here is the working JSFiddle demo.
Update:
Oh, now I see. You need a[i] > a[i-1] condition to be true for all combinations. Just add a start variable which will save the last inserted value in order to comply with this rule.
var len = 4;
var end = 3;
var data = [];
var loop = function (start, index) {
if (index === end) {
document.body.innerHTML += "<br/>" + data;
return;
}
for (var i = start; i < len; i++) { // We start from 'start' (the last value + 1)
data[index] = i;
loop(i + 1, index + 1); // Here, we pass the last inserted value + 1
}
}
loop(0, 0); // At beginning, we start from 0
Updated JSFiddle demo with passing argument.
You can check the previous value instead of passing a value as an argument if it looks wrong for you. Condition will be like "if it is a first number, start from 0; else - start from the next number after the previous one".
var start = (index === 0 ? 0 : data[index-1] + 1);
Updated JSFiddle demo with calculating start.
There are a couple of errors; you are recursing starting from i+1 instead of index+1 and you are counting from index instead of counting from data[index-1]+1.
The corrected version is:
var len = 4;
var end = 3;
var data = [];
var loop = function (index) {
if (index === end) {
console.log(data);
return;
}
for (var i = (index==0 ? 0 : data[index-1]+1); i < len; i++) {
data[index] = i;
loop(index + 1);
}
}
As you are having three for loops one inside another, you have to pass 2 arguments for recursion function.
var len = 4;
var end = 3;
var data = [];
var loop = function(start, index) {
if (index === end) {
console.log(data);
return;
}
for (var i = start; i < len; i++) {
data[index] = i;
loop(i + 1, index + 1); //Pass as like a+1 & b+1
}
}
loop(0, 0);
Output the exact expected result.
var len = 4;
var end = 3;
var data = [];
var loop = function(i) {
if(data.length === end) {
// console.log(data); -> Wont work in snippet
// Snippet workaround
document.getElementsByTagName('body')[0].innerHTML += data.join(',') + '<br/>';
return;
}
if(i >= len)
return;
data.push(i);
loop(i + 1);
data.pop();
loop(i + 1);
};
loop(0);

Categories