Related
I have a requirement where I have to reverse an array without changing the index of '#' presents in an array, like below example:
Array [18,-4,'#',0,8,'#',5] should return [5, 8, "#", 0, -4, "#", 18], here numbers should be reversed, excluding '#' while keeping the same index.
I have tried to get the correct output, but it doesn't seem to be correct in all scenarios:
var arr = [18,-4,'#',0,8,'#',5]; // giving result is correct
var arr1 = [18,-4,0,'#',8,'#',5]; // result is not correct
var reverse = function(numbers, start, end){
var temp = numbers[start];
numbers[start] = numbers[end];
numbers[end] = temp;
}
var flip = function(numbers) {
var start = 0;
var end = numbers.length-1;
for(var i=0;i<parseInt(numbers.length/2);i++) {
if(numbers[i] === '#') {
start = i+1;
end = numbers.length - i - i;
reverse(numbers, start, end);
} else if (numbers[numbers.length - i - 1] === '#') {
start = i;
end = numbers.length - i - 2;
reverse(numbers, start, end);
} else {
reverse(numbers, start, end);
}
}
return numbers;
}
var arr = [18,-4,'#',0,8,'#',5];
var arr1 = [18,-4,0,'#',8,'#',5];
console.log(flip(arr));
console.log(flip(arr1));
You could simplify the function and use only two indices, the start and end and check if the value at the indices should stay, then choose another index for swapping.
const
swap = (array, a, b) => [array[a], array[b]] = [array[b], array[a]],
flip = numbers => {
var start = 0,
end = numbers.length - 1;
while (start < end) {
if (numbers[start] === '#') {
start++;
continue;
}
if (numbers[end] === '#') {
end--;
continue;
}
swap(numbers, start++, end--);
}
return numbers;
},
array1 = [18, -4, '#', 0, 8, '#', 5],
array2 = [18, -4, 0, '#', 8, '#', 5];
console.log(...flip(array1));
console.log(...flip(array2));
The trivial approach would be to remove all '#''s, reverse the array using the built in [].reverse method, and then re-insert the '#''s:
let flip = numbers => {
let removed = numbers.reduce((r, v, i) =>
v === '#' ? r.concat(i) : r
, []);
let reversed = numbers.filter(v => v !== '#').reverse();
removed.forEach(i => reversed.splice(i, 0, '#'));
return reversed;
};
let arr = [18, -4, '#', 0, 8, '#', 5];
let arr1 = [18, -4, 0, '#', 8, '#', 5];
console.log(flip(arr));
console.log(flip(arr1));
You can try this:
var numbers = arr.filter(a => a !== '#')
var revArr = [];
arr.forEach((currentValue) => {
if(currentValue !== "#") {
revArr.push(numbers.pop());
} else {
revArr.push("#");
}
});
You can base your algorithm on two basic array (array of reversed numbers and and an array with "#" saved positions)
const array = [5, 8, "#", 0, -4, "#", 18];
function flip(array) {
const arrayNumbers = array.filter((el, index) => el !== "#").reverse();
var counter = 0;
return array.map(el => el === "#").map(el => {
if (!el) {
let num = arrayNumbers[counter];
counter = counter + 1;
return num;
} else {
return "#"
}
})
}
console.log(flip(array));
var arr = [18,-4,'#',0,8,'#',5]
var stack = []
for (i=0 ; i<arr.length; i++) {
if (arr[i] == '#') continue;
stack.push(arr[i]);
}
for (i=0 ; i<arr.length; i++) {
if (arr[i] != '#') {
arr[i] = stack.pop();
}
}
console.log(arr)
The above code should solve your problem.
The implementation uses stack where we keep inserting elements into stack untill we see a '#' and skip it.
While creating the output array we refer the original array for '#' index and stack for reverse index.
You can do it like this.
int end = v.length - 1;
int start = 0;
for (int i = 0; i < v.length >> 1; i++) {
if (v[start].equals("#")) {
start++;
continue;
}
if (v[end].equals("#")) {
end--;
continue;
}
Object temp = v[end];
v[end] = v[start];
v[start] = temp;
end--;
start++;
}
System.out.println(Arrays.toString(v));
I'm trying to solve this exercise of finding the number that appears an odd number of times in an array. I have this so far but the output ends up being an integer that appears an even number of times. For example, the number 2 appears 3 times and the number 4 appears 6 times, but the output is 4 because it counts it as appearing 5 times. How can it be that it returns the first set that it finds as odd? Any help is appreciated!
function oddInt(array) {
var count = 0;
var element = 0;
for(var i = 0; i < array.length; i++) {
var tempInt = array[i];
var tempCount = 0;
for(var j = 0; j <array.length; j++) {
if(array[j]===tempInt) {
tempCount++;
if(tempCount % 2 !== 0 && tempCount > count) {
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
function findOdd(numbers) {
var count = 0;
for(var i = 0; i<numbers.length; i++){
for(var j = 0; j<numbers.length; j++){
if(numbers[i] == numbers[j]){
count++;
}
}
if(count % 2 != 0 ){
return numbers[i];
}
}
};
console.log(findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])); //5
console.log(findOdd([1,1,1,1,1,1,10,1,1,1,1])); //10
First find the frequencies, then find which ones are odd:
const data = [1,2,2,2,4,4,4,4,4,4,5,5]
const freq = data.reduce(
(o, k) => ({ ...o, [k]: (o[k] || 0) + 1 }),
{})
const oddFreq = Object.keys(freq).filter(k => freq[k] % 2)
// => ["1", "2"]
If we are sure only one number will appear odd number of times, We can XOR the numbers and find number occurring odd number of times in n Comparisons.XOR of two bits is 1 if they are different else it will be 0. Truth table is below.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
So when we do XOR of all the numbers, final number will be the number appearing odd number of times.
Let's take a number and XOR it with the same number(Appearing two times). Result will be 0 as all the bits will be same. Now let's do XOR of result with same number. Now result will be that number because all the bits of previous result are 0 and only the set bits of same number will be set in the result. Now expanding it to an array of n numbers, numbers appearing even number of times will give result 0. The odd appearance of the number result in that number in the final result.
func oddInt(numbers: [Int]) -> Int {
var result = 0
for aNumber in numbers {
result = result ^ aNumber
}
return result
}
Here is a solution with O(N) or O(N*log(N))
function findOdd(A) {
var count = {};
for (var i = 0; i < A.length; i++) {
var num = A[i];
if (count[num]) {
count[num] = count[num] + 1;
} else {
count[num] = 1;
}
}
var r = 0;
for (var prop in count) {
if (count[prop] % 2 != 0) {
r = prop;
}
}
return parseInt(r); // since object properies are strings
}
#using python
a=array('i',[1,1,2,3,3])
ans=0
for i in a:
ans^=i
print('The element that occurs odd number of times:',ans)
List item
output:
The element that occurs odd number of times: 2
Xor(^)operator when odd number of 1's are there,we can get a 1 in the output
Refer Xor Truth table:
https://www.electronicshub.org/wp-content/uploads/2015/07/TRUTH-TABLE-1.jpg
function oddInt(array) {
// first: let's count occurences of all the elements in the array
var hash = {}; // object to serve as counter for all the items in the array (the items will be the keys, the counts will be the values)
array.forEach(function(e) { // for each item e in the array
if(hash[e]) hash[e]++; // if we already encountered this item, then increments the counter
else hash[e] = 1; // otherwise start a new counter (initialized with 1)
});
// second: we select only the numbers that occured an odd number of times
var result = []; // the result array
for(var e in hash) { // for each key e in the hash (the key are the items of the array)
if(hash[e] % 2) // if the count of that item is an odd number
result.push(+e); // then push the item into the result array (since they are keys are strings we have to cast them into numbers using unary +)
}
return result;
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));
Return only the first:
function oddInt(array) {
var hash = {};
array.forEach(function(e) {
if(hash[e]) hash[e]++;
else hash[e] = 1;
});
for(var e in hash) { // for each item e in the hash
if(hash[e] % 2) // if this number occured an odd number of times
return +e; // return it and stop looking for others
}
// default return value here
}
console.log(oddInt([1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5]));
That happens because you are setting the element variable each time it finds an odd number, so you are setting it when it find one, three and five 4.
Let's check the code step by step:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j <array.length; j++) {
// If the current number is the same as the one that we are looking for, sum it up
console.log("Current number at position", j, "is", array[j]);
if(array[j]===tempInt) {
tempCount++;
console.log("Number found. Current count is", tempCount);
// Then, if currently there are an odd number of elements, save the number
// Note that you are calling this altough you don't have looped throgh all the array, so the console will log 3 and 5 for the number '4'
if(tempCount % 2 !== 0 && tempCount > count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
What we want to do is to check for the count AFTER looping all the array, this way:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j <array.length; j++) {
// If the current number is the same as the one that we are looking for, sum it up
console.log("Current number at position", j, "is", array[j]);
if(array[j]===tempInt) {
tempCount++;
console.log("Number found. Current count is", tempCount);
}
}
// After getting all the numbers, then we check the count
if(tempCount % 2 !== 0 && tempCount > count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = tempInt;
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);
By the way, this is only for you to understand where was the problem and learn from it, although this is not the most optimized way of doing this, as you may notice that you are looking for, let's say, number 2 three times, when you already got the output that you want the first time. If performance is part of the homework, then you should think another way :P
This is because your condition if(tempCount % 2 !== 0 && tempCount > count) is true when the 5th 4 is checked. This updates the count and element variables.
When the 6th 4 is checked, the condition is false.
To fix, move the condition outside the innermost loop so that it's checked only after all the numbers in the array are counted.
function oddInt(array, minCount, returnOne) {
minCount = minCount || 1;
var itemCount = array.reduce(function(a, b) {
a[b] = (a[b] || 0) + 1;
return a;
}, {});
/*
itemCount: {
"1": 1,
"2": 3,
"4": 6,
"5": 2,
"7": 3
}
*/
var values = Object.keys(itemCount).filter(function(k) {
return itemCount[k] % 2 !== 0 && itemCount[k]>=minCount;
});
return returnOne?values[0]:values;
}
var input = [1, 2, 2, 2, 4, 4, 4, 4, 4, 4, 5, 5, 7, 7, 7];
console.log(oddInt(input, 3, true));
console.log(oddInt(input, 1, true));
console.log(oddInt(input, 2, false));
"A" is the array to be checked.
function findOdd(A) {
var num;
var count =0;
for(i=0;i<A.length;i++){
num = A[i]
for(a=0;a,a<A.length;a++){
if(A[a]==num){
count++;
}
} if(count%2!=0){
return num;
}
}
}
function oddOne (sorted) {
let temp = sorted[0];
let count = 0;
for (var i = 0; i < sorted.length; i++) {
if (temp === sorted[i]) {
count++;
if (i === sorted.length - 1) {
return sorted[i];
}
} else {
if (count % 2 !== 0) {
return temp;
}
count = 1;
temp = sorted[i];
}
}
}
function oddInt(array) {
let result = 0;
for (let element of array) {
result ^= element
}
return result
}
var oddNumberTimes = (arr) => {
let hashMap = {};
for (let i = 0; i < arr.length; i++) {
hashMap[arr[i]] = hashMap[arr[i]] + 1 || 1;
}
for (let el in hashMap) {
if (hashMap[el] % 2 !== 0) {
return el;
}
}
return -1;
};
You can use bitwise XOR:
function oddInt(array) {
return array.reduce(function(c, v) {
return c ^ v;
}, 0);
}
console.log(oddInt([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]) == 5);
console.log(oddInt([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]) == 10);
Had to implement a solution for a similar problem and here it is:
function findtheOddInt(A) {
let uniqueValues = [...new Set(A)]; // Get the unique values from array A
const odds = [];
uniqueValues.forEach(element => {
const count = A.reduce((acc, cur) => cur === element ? acc + 1: acc, 0) // count the occurrences of the element in the array A
if (count % 2 === 1) {
odds.push(element);
}
});
return odds[0]; // Only the first odd occurring element
}
var arr=[1,2,2,2,2,3,4,3,3,3,4,5,5,9,9,10];
var arr1=[];
for(let i=0;i
{
var count=0;
for(let j=0;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
if(count%2 != 0 )
{
arr1.push(arr[i]);
}
}
console.log(arr1);
I have a question . How do you retrieve elements that has no double value in an array?? For example: [1,1,2,2,3,4,4,5] then you retrieve [3,5] only.
Thanks in advance
for (var j = 0; j < newArr.length; j++) {
if ((arr1.indexOf(newArr[j]) === 0) && (arr2.indexOf(newArr[j]) === 0)) {
index = newArr.indexOf(j); newArr.splice(index, 1);
}
}
If the item in the array is unique then the index found from the beginning should equal the index found from the end, in other words:
var xs = [1, 1, 2, 2, 3, 4, 4, 5];
var result = xs.filter(function(x) {
return xs.indexOf(x) === xs.lastIndexOf(x);
});
console.log(result); //=> [3, 5]
sorry for the presentation its my first post !
You have to compare each element of your array to the others in order to get the number of occurence of each element
var tab = [1,1,2,2,3,4,4,5] //The array to analyze
tab = tab.sort(); // we sort the array
show(tab); // we display the array to the console (F12 to open it)
var uniqueElementTab = []; // this array will contain all single occurence
var sameElementCounter = 0;
for(x=0;x<tab.length;x++){ // for all element in the array
sameElementCounter = 0;
for(y=0;y<tab.length;y++){ // we compare it to the others
if((tab[x]==tab[y])){
sameElementCounter+=1; // +1 each time we meet the element elsewhere
}
}
if(sameElementCounter<=1){
uniqueElementTab.push(tab[x]); //if the element is unique we add it to a new array
}
}
show(uniqueElementTab); // display result
function show(tab) { // Simple function to display the content of an array
var st="";
for(i=0;i<tab.length;i++){
st += tab[i]+" ";
}
console.log(st+"\n");
}
Hope it helps.
Here is a simple "tricky" solution using Array.sort, Array.join, Array.map, String.replace and String.split functions:
var arr = [1, 1, 2, 2, 3, 4, 4, 5];
arr.sort();
var unique = arr.join("").replace(/(\d)\1+/g, "").split("").map(Number);
console.log(unique); // [3, 5]
create new array tmp,and check already value exist by indexOf .If existed delete by splice function..
var arr = [1,1,2,2,3,4,4,5];
var tmp = [];
var dup = [];
for(var i = 0; i < arr.length; i++){
var ind = tmp.indexOf(arr[i]);
if(ind == -1){
if(dup.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
else{
tmp.splice(ind,1);
dup.push(arr[i]);
}
}
console.log(tmp);
This would be my way of doing this job.
var arr = [1,1,2,2,3,4,4,5],
uniques = Object.keys(arr.reduce((p,c) => (c in p ? Object.defineProperty(p, c, {enumerable : false,
writable : true,
configurable : true})
: p[c] = c,
p), {}));
console.log(uniques);
A solution for unsorted arrays with a hash table for the items. Complexity O(2n)
var array = [1, 1, 2, 2, 3, 4, 4, 5, 1],
hash = Object.create(null),
single;
array.forEach(function (a, i) {
hash[a] = a in hash ? -1 : i;
});
single = array.filter(function (a, i) {
return hash[a] === i;
});
console.log(single);
If the array is sorted, you can solve this in O(n) (see "pushUniqueSinglePass" below):
function pushUniqueSinglePass(array, unique) {
var prev; // last element seen
var run = 0; // number of times it has been seen
for (var i = 0; i < array.length; i++) {
if (array[i] != prev) {
if (run == 1) {
unique.push(prev); // "prev" appears only once
}
prev = array[i];
run = 1;
} else {
run++;
}
}
}
function pushUniqueWithSet(array, unique) {
var set = new Set();
for (var i = 0; i < array.length; i++) {
set.add(array[i]);
}
for (let e of set) {
unique.push(set);
}
}
// Utility and test functions
function randomSortedArray(n, max) {
var array = [];
for (var i = 0; i < n; i++) {
array.push(Math.floor(max * Math.random()));
}
return array.sort();
}
function runtest(i) {
var array = randomSortedArray(i, i / 2);
var r1 = [],
r2 = [];
console.log("Size: " + i);
console.log("Single-pass: " + time(
pushUniqueSinglePass, array, r1));
console.log("With set: " + time(
pushUniqueWithSet, array, r2));
// missing - assert r1 == r2
}
[10, 100, 1000, 10000,
100000, 1000000
].forEach(runtest);
function time(fun, array, unique) {
var start = new Date().getTime();
fun(array, unique);
return new Date().getTime() - start;
}
This is much more efficient than using maps or sorting (time it!). In my machine, a 1M sorted array can have its unique elements found in 18 ms; while the version that uses a set requires 10x more.
I've been looking around the website and all I find are questions regarding finding the index of a value in an array, but that value is the only occurrence of that value in the array. I was wondering is there was a way to find the index of a repeated value every time that it occurs.
Say there's and array like so:
var arr = [45,56,76,4,53,43,6,273,884,69,47,58,225,222,23,13,89,900,7,66,78,74,69];
Is it possible to loop through this and find the indexes of the value 69?
Here's a way to do it in modern browsers:
function findIndexes(arr, val){
return arr.map(function(v,i){ return v==val && i }).filter(Number);
}
console.log(findIndexes(arr, 69)); //=> [9,22]
Of course it's possible. Computers are amazing.
var positions = [];
for (var i = 0; i < arr.length; ++i)
if (arr[i] === 69)
positions.push(i);
At the end of that loop, the array "positions" will contain all the indexes of the array where 69 was found.
You could generalize this:
function indexes(arr, value) {
var rv = [];
for (var i = 0; i < arr.length; ++i)
if (arr[i] === value)
rv.push(i);
return rv;
}
and then:
var i69 = indexes(arr, 69);
Since we're all posting various ways to perform simple tasks...
var arr = [45,56,76,4,53,43,6,273,884,69,47,58,225,222,23,13,89,900,7,66,78,74,69];
arr.reduce(function(res, n, i) {
return n === 69 ? res.concat(i) : res;
}, []);
Loop while the next indexOf is not -1..
function allIndicesOf(arr, val) {
var found = [], i = -1;
while (-1 !== (i = arr.indexOf(val, i + 1))) found.push(i);
return found;
}
var arr = [0, 1, 2, 3, 2, 1, 8, 5, 2, 0, 4, 3, 3, 1];
allIndicesOf(arr, 3); // [3, 11, 12]
My idea
function indexs(arr,val){
var start = arr.indexOf(val),result = [];
while(start >= 0){
result.push(start);
start = arr.indexOf(val,start+1);
}
return result;
}
Have fun :)
var arr = [45,56,76,4,53,43,6,273,884,69,47,58,225,222,23,13,89,900,7,66,78,74,69],
i = arr.length,
o = {};
while( i-- ) {
if( !o[ arr[i] ] ) {
`o[ arr[i] ] = [];`
}
o[ arr[i] ].push( i );
}
alert( o[69] );
I'm looking for something similar to Groovy's every() method, which tests every element of a list if it meets some criteria. If they all meet the criteria, the function returns true. Otherwise, false. I've tried something like this:
var arr = [1, 0, 1, 0, 1, 1];
var allOnes = $.grep(arr, function(ind) {
return this == 1;
}).length == arr.length;
..but its not very clean. I haven't had any luck while searching through the API. Is using grep() the only way to do it?
if it is a plain js array, you have $.grep()
.filter() is for use with jQuery or DOM Elements
Here is a plugin I made that might make it easier:
(function($) {
$.fn.allOnes = function() {
var allVal = true;
this.each(function(ind, item) {
if (item != 1) {
allVal = false;
return allVal;
}
});
return allVal;
};
})(jQuery);
var arr = [1, 1, 0, 1, 1, 1];
console.log($(arr).allOnes());
Fiddle: http://jsfiddle.net/maniator/NctND/
The following plugin is an expansion of the above and lets you search for a specific number: http://jsfiddle.net/maniator/bFNnn/
(function($) {
$.fn.allValue = function(pred) {
var allOnes = true;
this.each(function(ind, item) {
if (item != pred) {
allOnes = false;
return allOnes;
}
});
return allOnes;
};
})(jQuery);
var arr = [1, 1, 1, 1, 1, 1];
console.log($(arr).allValue(1));
here is example of function you can use.
var arr = [1, 0, 1, 0, 1, 1];
var allOnes = arr.check(1);
//this function compares all elements in array and if all meet the criteria it returns true
Array.prototype.chack = function(cond)
{
var ln = 0;
for(i=0; i<this.length; i++)
{
if(bond === this[i])
{
ln++
}
}
if(ln == this.length)
return true;
else
return false;
}
How about just turning your working code into a method on array, to ease its reuse:
Array.prototype.every = function(predicate){
return $.grep(this,predicate).length == this.length;
}
usage:
alert([1,0,1,0].every(function(i) { return i == 1; }));
Working example: http://jsfiddle.net/59J5A/
Edit: changed to grep
You could always implement an allOnes method:
function allOnes(array) {
var result = [];
for(var i = 0; i < array.length; i += 1) {
if (array[i] === 1) { result.push(true); }
}
return array.length == result.length;
}
or you could be a bit more abstract and test for true/false:
function all(array) {
var result = [];
for(var i = 0; i < array.length; i += 1) {
if (array[i]) { result.push(true); }
}
return array.length == result.length;
}
var arr = [1, 0, 1, 0, 1, 1];
var allOnes = all(arr);
or even better, maybe have a changeable predicate:
function all(array, predicate) {
var result = [],
predicate = predicate || function(x) { if (x) { return true; } };
for(var i = 0; i < array.length; i += 1) {
if (predicate(array[i])) { result.push(true); }
}
return array.length == result.length;
}
var allOnes = all(arr, function(x) { return x === 1; })