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]);
}
}
}
Related
I have this function which returns an array of prime numbers:
function getPrimeFactors(n) {
var factors = [];
for (i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
var count = 0;
while (n % i === 0) {
n = n / i;
count++;
}
for (j = 1; j <= count; j++) {
factors.push(i);
}
}
}
if (n !== 1) {
factors.push(n);
}
return factors;
}
var numbers = [2, 3, 4, 5];
var array = [];
I want to get prime factors of all the numbers in the numbers array and push it into a new array (array)
for(i = 0; i < numbers.length; i++) {
array.push(getPrimeFactors(numbers[i]));
}
What am i doing wrong?
As mentioned by Damien Gold in the answer that was deleted, use var in your for-loops to make the variables local and to prevent your 2 functions from interfering with each other.
function getPrimeFactors(n) {
var factors = [];
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
var count = 0;
while (n % i === 0) {
n = n / i;
count++;
}
for (var j = 1; j <= count; j++) {
factors.push(i);
}
}
}
if (n !== 1) {
factors.push(n);
}
return factors;
}
And:
var numbers = [2, 3, 4, 5];
var array = [];
for(var i = 0; i < numbers.length; i++) {
array.push(getPrimeFactors(numbers[i]));
}
As a sidenote,
you are pushing arrays into your array instead of adding the values contained in your getPrimeFactors-array. If you instead want to push the resulting numbers into one array, try this:
for(var i=0; i<numbers.length; i++) {
array = array.concat(getPrimeFactors(numbers[i]));
}
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;
}
}
I come from a Ruby background, which features an enumerable class. In Ruby, I can easily find combinations of array elements.
array.combination(2).count
I know that JavaScript doesn't feature such built in functions, so I was wondering how I could implement this in JS. I was thinking something like
I have an array as follows
var numbers = [9,7,12]
var combos = []
for (var i = 0; i < numbers.length; i++) {
combos.push([numbers[i], numbers[i+1])
}
By the way, the possible combos are
[9,7], [9,12] and [7,12]
so by calling the length function on this array, 3 would be returned.
Any ideas?
How about:
for (var i = 0; i < numbers.length; i++)
for (var j = i + 1; j < numbers.length; j++)
combos.push([numbers[i], numbers[j]]);
Are you strictly talking about 2-combinations of the array or are you interested in a k-combinations solution?
Found this in this gist
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
if (k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i+1);
tailcombs = k_combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
Here's a recursive function, which should work for any number:
function combination(arr, num) {
var r= [];
for(var i = 0 ; i < arr.length ; i++) {
if(num===1) r.push([arr[i]]);
else {
combination(arr.slice(i+1), num-1).forEach(function(val) {
r.push([].concat(arr[i], val));
});
}
}
return r;
} //combination
Working Fiddle
I have an array and by looping I compare cell with a cell near it. I get the 'out of range' exception,
How can I fix it ?
for (var i = 0; i < array.length ; i++) {
if ((++array[i] == array[i+1])) {
alert("yes");
}
else {
alert("no");
}
}
Run your loop from for (var i=0; i<array.length -1; i++) instead (because you compare against array[i+1])
Just try with:
for (var i = 0; i < array.length - 1; i++) {}
Not sure what you had in mind but using ++ outside of a for loop is never a good idea as it can be confusing. Use another variable to point to another item in the array while looping together with a bounds checker is easier to debug and keeps loop simple.
//displays 01010
//1=2(0),2=2(1),2=4(0),4=4(1),4=5(0)
var ptr = 0;
var items = new Array (1, 2, 2, 4, 4, 5);
for (var i = 0; i < items.length; i++) {
ptr++
if(ptr >= items.length)break;
if (items[i] == items[ptr]) {
console.log(1);
}
else {
console.log(0);
}
}
//or
//displays 10001 as each value is increased then compared
//2=2(1),3=2(0),3=4(0),5=4(0),5=5(1)
ptr = 0;
for (var i = 0; i < items.length; i++) {
ptr++
if (ptr >= items.length) break;
if (++items[i] == items[ptr]) {
console.log(1);
}
else {
console.log(0);
}
}
I have an array of objects called seasons of length 300, and I trying to search through a certain property "Date" and add it to an array if it has not been found before. So far I have
var day=[];
for (var i=1; i<300; i++) {
var found=false;
for (var j=0; j<day.length; j++) {
if (day[j]==seasons[i]["Date"]) {
found=true;
break;
}
if (!found) {
day[day.length]=seasons[i]["Date"];
}
}
}
I'm not too sure where this is going wrong, and would appreciate some help. Thanks
You break out of the inner for-loop, so the if (!found) block is never executed.
Just put it after the inner loop:
for (var i = 1; i < 300; i++) {
var found = false;
for (var j = 0; j < day.length; j++) {
if (day[j] == seasons[i]["Date"]) {
found = true;
break;
}
}
if (!found) {
day[day.length] = seasons[i]["Date"];
}
}
Or do it in the if-block:
for (var i = 1; i < 300; i++) {
for (var j = 0; j < day.length; j++) {
if (day[j] == seasons[i]["Date"]) {
day[day.length] = seasons[i]["Date"];
break;
}
}
}
I guess the latter solution is easier to understand.