Find maximum difference in array - javascript

I'm working on an algorithm to return the difference of any pair of numbers, such that the larger integer in the pair occurs at a higher index (in the array) than the smaller integer.
Examples...
Array: [2, 3, 10, 2, 4, 8, 1]
Solution: 10 - 2 = 8
Output: 8
Array: [7, 9, 5, 6, 3, 2]
Solution: 9 - 7 = 2
Output: 2
Here is what I have but it doesn't work for all tests...
var a = [22, 2, 4, 5, 6, 444, 1, 666];
// declare variables
var minNumber = a[0], // initilize to first element
maxNumber = a[0], // --- ^
minNumberIndex = 0, // min index
maxNumberIndex = a.length - 1; // max index
// loop through each element in array
for(i = 0; i < a.length; i++) {
// find min
if (a[i] < minNumber && i < maxNumberIndex) {
minNumber = a[i];
minNumberIndex = i;
}
// find max
if (a[i] >= maxNumber && i > minNumberIndex) {
maxNumber = a[i];
maxNumberIndex = i;
}
}
// return results
console.log("max: \t" + maxNumber);
console.log("min: \t" + minNumber + "index: " + minNumberIndex);
console.log(maxNumber - minNumber);
Please help!

O(n) solution:
function maxDifference(arr) {
let maxDiff = -1;
let min = arr[0];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > min && maxDiff < arr[i] - min) {
maxDiff = arr[i] - min;
}
if (arr[i] < min) {
min = arr[i];
}
}
return maxDiff;
}
console.log(maxDifference([1, 2, 3])); //2
console.log(maxDifference(3, 2, 1)); //-1
console.log(maxDifference([2, 3, 10, 2, 4, 8, 1])); //8
console.log(maxDifference([7, 9, 5, 6, 3, 2])); //2
console.log(maxDifference([22, 2, 4, 5, 6, 444, 1, 666])); //665
console.log(maxDifference([7, 9, 5, 6, 3, 2])); //2
console.log(maxDifference([666, 555, 444, 33, 22, 23])); //1
console.log(maxDifference([2, 3, 10, 2, 4, 8, 1])); //8

let MaxDifference = arr => {
let maxDiff = null;
for(let x = 0; x < arr.length; x++){
for(let y = x+1; y < arr.length; y++){
if(arr[x] < arr[y] && maxDiff < (arr[y] - arr[x])){
maxDiff = arr[y] - arr[x]
}
}
}
return maxDiff === null ? -1 : maxDiff;
}

You can have two arrays. Lets call them minlr and maxrl.
minlr - Where minlr[i] stores the minimum value till index i when going from left to right in the original array.
maxrl - Where maxrl[i] stores the maximum value till index i when going from right to left in the original array.
Once you have these 2 arrays, you iterate the arrays and find the max difference between maxrl[i] and minlr[i].
In your above examples:
minlr = {2,2,2,2,2,2,1};
maxrl = {10,10,10,8,8,8,1};
So the answer in this case would be 10 - 2 = 8.
minlr = {7,7,5,5,3,2};
maxrl = {9,9,6,6,3,2};
So the answer in this case would be 9 - 7 = 2

es6 version:
var a = [2, 3, 10, 2, 4, 8, 1];
var min = a[0];
var max = a[a.length-1];
var init = [[0,min], [a.length -1,max]];
var r = a.reduce((
res, e,i
)=>{
var [[mini, min ], [maxi ,max]] = res;
var t = res;
if(e<min && i<maxi){
t = [[i, e ], [maxi ,max]];
}
if(e>=max && i>mini){
t = [[mini, min ], [i ,e]];
}
return t;
}, init);
console.log(r[1][1]-r[0][1]);

Is this ok? for each item in the array, it looks at earlier items and adds the difference to the internal 'diffs' array (if the current item is greater). I then return the the largest value within the diffs array.
var findMaxDiff = function(arr){
var diffs = [];
for(var i = 1; i < arr.length; i++){
for(var j = 0; j < i; j++){
if(arr[i] > arr[j]){
diffs.push(arr[i]-arr[j]);
}
}
}
return Math.max.apply( Math, diffs );
}

Looping through the array and using recursion like so:
function maxDifference(a){
var maxDiff = a[1] - a[0];
for(var i = 2; i<a.length-1; i++){
var diff = a[i] - a[0];
maxDiff = diff>maxDiff ? diff : maxDiff;
}
if(a.length>1){
a.shift();
var diff = maxDifference(a);
maxDiff = diff>maxDiff ? diff : maxDiff;
}
return maxDiff;
}
var x = [2, 3, 10, 2, 4, 8, 1];
maxDifference(x); // returns 8
x = [7, 9, 5, 6, 3, 2];
maxDifference(x) // returns 2

In linear time and constant memory:
function maxDiff (nums) {
var diff = 0, left = 0, right = 0, cur_right = 0, cur_left = 0;
for (var i = 0; i < nums.length; i++) {
if (nums[i] < nums[cur_left]) {
cur_left = i;
if (cur_left > cur_right) {
cur_right = cur_left;
}
}
if (nums[i] >= nums[cur_right]) {
cur_right = i;
}
if (nums[cur_right] - nums[cur_left] > diff) {
diff = nums[cur_right] - nums[cur_left];
right = cur_right;
left = cur_left;
}
}
return [diff, left, right];
}
If you're only interested in what the difference is, and not where the numbers occur, you don't need left and right.

var maxDiff = function() {
var list = Array.prototype.slice.call(arguments, 0)[0];
var start = new Date().getTime();
if((list !== null) && (toString.call(list) !== "[object Array]")) {
console.warn("not an array");
return;
}
var maxDiff = list[1] - list[0];
var min_element = list[0];
var i, j;
for(i = 1; i < list.length; i++) {
if(list[i] - min_element > maxDiff) {
maxDiff = list[i] - min_element;
}
if(list[i] < min_element) {
min_element = list[i];
}
}
var end = new Date().getTime();
var duration = end - start;
console.log("time taken:: " + duration + "ms");
return maxDiff;
};

maxdiff = 0;
a = [2, 3, 10, 2, 4, 8, 1]
for (i=a.length-1; i >= 0; i--) {
for (j=i-1; j >= 0; j--) {
if (a[i] < a[j] ) continue;
if (a[i] -a[j] > maxdiff) maxdiff = a[i] -a[j]
}
}
console.log(maxdiff || 'No difference found')

we can use es6 + es2020 latest feature to fix this issue
function maxDiff(arr) {
var diff=0
if(arr?.length) diff=arr?.length?Math.max(...arr)-Math.min(...arr):0
return diff;
}
console.log(maxDiff([1, 2, 3])); //2
console.log(maxDiff([3, 2, 1])); //2
console.log(maxDiff([2, 3, 10, 2, 4, 8, 1])); //9
console.log(maxDiff([7, 9, 5, 6, 3, 2])); //7
console.log(maxDiff([22, 2, 4, 5, 6, 444, 1, 666])); //665
console.log(maxDiff([7, 9, 5, 6, 3, 2])); //7
console.log(maxDiff([666, 555, 444, 33, 22, 23])); //644
console.log(maxDiff([-0, 1, 2, -3, 4, 5, -6])); //11
console.log(maxDiff([2])); //0
console.log(maxDiff([])); //0

var a = [22, 2, 4, 5, 6, 444, 1, 666];
function solution(a) {
const max = Math.max.apply(null,a);
const min = Math.min.apply(null,a);
const diff = max-min;
return diff
}
console.log(solution(a))

you actually don't need any looping, just use Math.max(), Math.min(), and [].indexOf() to do the heavy-lifting for you:
function findDiff(a){
var max=Math.max.apply(0, a),
slot=a.lastIndexOf(max),
min=Math.min.apply(0, a.slice(0, slot));
if(a.length && !slot && !min-.153479 )return findDiff(a.slice(1));
return max-min;
}
//ex: findDiff([7, 9, 5, 6, 3, 2]) == 2
//ex: findDiff([666, 555, 444 , 33, 22, 23]) == 1
//ex: findDiff([2, 3, 10, 2, 4, 8, 1]) == 8

Related

Recursion problem on Codewars Kata - Snail Trail

Very new to coding so please bear with me. I am attempting to solve this Kata on Codewars: https://www.codewars.com/kata/snail/train/javascript
Basically given an array like
[
[1, 2, 3, 4],
[12,13,14,5],
[11,16,15,6],
[10,9, 8, 7]
];
It would return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16].
A snail trail spiraling around the outside of the matrix and inwards.
I am just solving for the case where the matrix is n x n where n is > 1 and an even number for now.
I got it working by declaring outputarray outside the function but I want that array to be declared within the function, hence the inclusion of this line: var outputarray = outputarray || [];
Not sure where I am going wrong.
snail = function(array) {
if (array.length == 0) {
return outputarray
}
var n = array[0].length - 1;
var outputarray = outputarray || [];
for (var i = 0; i <= n; i++) {
outputarray.push(array[0].splice(0, 1));
}
for (var i = 1; i <= n; i++) {
outputarray.push(array[i].splice(n, 1));
}
for (var i = n - 1; i >= 0; i--) {
outputarray.push(array[n].splice(i, 1));
}
for (var i = n - 1; i > 0; i--) {
outputarray.push(array[i].splice(0, 1));
}
array.pop();
array.shift();
snail(array);
}
Here's a non-recursive approach that doesn't mutate the input array. It works by keeping track of the top-left coordinate x, y and the size n of the spiral.
snail = function(array) {
const { length } = array;
const result = [];
let x = 0;
let y = 0;
let n = length;
while (n > 0) {
// travel right from top-left of spiral
for (let i = x; i < x + n; ++i) result.push(array[y][i]);
// shrink spiral and move top of spiral down
n--; y++;
// travel down from top-right of spiral
for (let i = y; i < y + n; ++i) result.push(array[i][x + n]);
// travel left from bottom-right of spiral
for (let i = x + n - 1; i >= x; --i) result.push(array[y + n - 1][i]);
// shrink spiral
n--;
// travel up from bottom-left of spiral
for (let i = y + n - 1; i >= y; --i) result.push(array[i][x]);
// move left of spiral right
x++;
}
return result;
}
console.log(snail([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]));
One option is to define another function inside snail, which calls itself recursively, while also defining the outputarray inside snail. That way, outputarray isn't exposed to the outer scope, but the recursive function can still see it.
Also note that splice returns an array, so right now, your outputarray gets composed of an array of arrays. Spread into push instead to fix it, so that the outputarray becomes an array of numbers:
const input = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
];
const snail = (array) => {
const outputarray = [];
const iter = () => {
if (array.length == 0) {
return
}
var n = array[0].length - 1;
for (var i = 0; i <= n; i++) {
outputarray.push(...array[0].splice(0, 1));
}
for (var i = 1; i <= n; i++) {
outputarray.push(...array[i].splice(n, 1));
}
for (var i = n - 1; i >= 0; i--) {
outputarray.push(...array[n].splice(i, 1));
}
for (var i = n - 1; i > 0; i--) {
outputarray.push(...array[i].splice(0, 1));
}
array.pop();
array.shift();
iter(array);
};
iter(array);
return outputarray;
}
console.log(snail(input));
You could take some borders for the left, right, upper and lower indices and loop until no more indices are available.
function snail(array) {
var upper = 0,
lower = array.length - 1,
left = 0,
right = array[0].length - 1,
i = upper,
j = left,
result = [];
while (true) {
if (upper++ > lower) break;
for (; j < right; j++) result.push(array[i][j]);
if (right-- < left) break;
for (; i < lower; i++) result.push(array[i][j]);
if (lower-- < upper) break;
for (; j > left; j--) result.push(array[i][j]);
if (left++ > right) break;
for (; i > upper; i--) result.push(array[i][j]);
}
result.push(array[i][j]);
return result;
}
console.log(...snail([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]));
This may not be according to the rules (or spirit?) of the kata, however, you can just glue it all together and sort.
function snail(trail) {
const numeric = (a, b) => a - b
const gather = (items, item) => items.push(parseInt(item, 10)) && items
const inline = (route, points) => points.reduce(gather, route) && route
const order = paths => paths.reduce(inline, []).sort(numeric)
return order(trail)
}
const trail = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
]
console.log(JSON.stringify(snail(trail)))
Try this:
const input = [
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
];
function snail(array) {
var res = [];
if (!array.length) return res;
var next = array.shift();
if (next) res = res.concat(next);
for (var i = 0; i < array.length; i++) {
res.push(array[i].pop());
}
next = array.pop()
if (next) res = res.concat(next.reverse());
for (var i = array.length - 1; i >= 0; i--) {
res.push(array[i].shift());
}
return res.concat(snail(array));
}
console.log(snail(input));
Here's my two cents, using the customary recursion:
function f(A){
return A.length > 1 ? A.splice(0,1)[0].concat(
f(A[0].map((c, i) => A.map(r => r[i])).reverse())) : A[0]
}
var A = [[ 1, 2, 3, 4], [12,13,14, 5], [11,16,15, 6], [10, 9, 8, 7]]
console.log(JSON.stringify(f(A)))

How to find the same values next to each other in multidimensional array?

I tried to write a function that would find in a multidimensional array (with values from 3 to 7) repeating values for at least 3 times next to each other (vertical and horizontal). And if it finds that, change it for a different value. Let's say 1.
I tried to do this by loops but it doesn't seem to be a good way to solve that or I messed it up. Because for some array it works, for some it does not.
Here's my code:
function searching(array) {
for (i = 0; i < array.length; i++) {
let horizontal = array[i][0];
let howMany = 1;
for (j = 1; j < array[i].length; j++) {
if (horizontal === array[i][j]) {
howMany += 1;
horizontal = array[i][j];
if (howMany >= 3) {
for (d = j; d > j - howMany; d--) {
array[i][d] = 0;
}
}
} else {
horizontal = array[i][j];
howMany = 1;
}
}
}
for (v = 0; v < array.length; v++) {
let vertical = array[0][v];
let howMany = 1;
for (x = 1; x < array.length; x++) {
if (vertical === array[x][v]) {
howMany++;
vertical = array[x][v];
if (howMany >= 3) {
for (d = x; d > x - howMany; d--) {
array[d][v] = 0;
}
}
} else {
vertical = array[x][v];
howMany = 1;
}
}
}
}
The idea is to for example give array:
let array = [
[3, 4, 5, 6, 7],
[3, 4, 5, 6, 7],
[3, 4, 5, 5, 5],
[3, 5, 6, 7, 4]
]
And the result should be:
let result = [
[1, 1, 1, 6, 7],
[1, 1, 1, 6, 7],
[1, 1, 1, 1, 1],
[1, 5, 6, 7, 4]
]
Thanks in advance for any ideas how to solve it :) Greetings!
The problems with your current code are
(1) You're only checking individual rows and columns, when you need to be checking them both (eg, with [[2, 2], [2, 5]], when at the starting position [0][0], you need to look at both [0][1] (and its neighbors, if matching) as well as [1][0] (and its neighbors, if matching).
(2) You're not actually checking for adjacency at the moment, you're just counting up the total number of matching elements in a particular row or column.
Iterate over all indicies of the array. If an index has already been checked, return early. Recursively search for neighbors to that index, and if at least 3 matching in total are found, set them all to 1. Put all matching neighbors in the checked set to avoid checking them again (even if there were less than 2 adjacent matches found total).
setAllAdjacentToOne([
[3, 4, 5, 6, 7],
[3, 4, 5, 6, 7],
[3, 4, 5, 5, 5],
[3, 5, 6, 7, 4]
]);
// all 9s stay, the rest get set to 1:
setAllAdjacentToOne([
[2, 2, 9, 7, 7],
[2, 9, 9, 9, 7],
[3, 4, 4, 5, 5],
[9, 4, 5, 5, 9]
]);
function setAllAdjacentToOne(input) {
const output = input.map(subarr => subarr.slice());
const checked = new Set();
const getKey = (x, y) => `${x}_${y}`;
const width = input[0].length;
const height = input.length;
const getAllAdjacent = (x, y, numToFind, matches = []) => {
if (x >= width || x < 0 || y >= height || y < 0) {
return matches;
}
const key = getKey(x, y);
if (!checked.has(key) && input[y][x] === numToFind) {
checked.add(key);
matches.push({ x, y });
getAllAdjacent(x + 1, y, numToFind, matches);
getAllAdjacent(x - 1, y, numToFind, matches);
getAllAdjacent(x, y + 1, numToFind, matches);
getAllAdjacent(x, y - 1, numToFind, matches);
}
return matches;
};
output.forEach((innerRowArr, y) => {
innerRowArr.forEach((num, x) => {
const allAdjacent = getAllAdjacent(x, y, num);
if (allAdjacent.length <= 2) {
return;
}
allAdjacent.forEach(({ x, y }) => {
output[y][x] = 1;
});
});
});
console.log(JSON.stringify(output));
}
I didn't understand the question at first...
So this is my code:
let array = [
[3, 4, 5, 6, 7],
[3, 4, 5, 6, 7],
[3, 4, 5, 5, 5],
[3, 5, 6, 7, 4]
];
function replace(arr, target = 1) {
let needToChange = []; // save the index to change
const numbers = [3, 4, 5, 6, 7];
const m = arr.length; // m rows
const n = arr[0].length; // n columns
let mi = 0;
let ni = 0;
// search in row
for (mi = 0; mi < m; mi++) {
for (let x = 0; x < numbers.length; x++) {
const num = numbers[x]; // number to search
let counter = 0; // counter for this number in row mi
let tempArr = [];
for (ni = 0; ni < n; ni++) {
const currentNum = arr[mi][ni];
if (currentNum === num) {
counter++;
tempArr.push([mi, ni]);
}
}
if (counter >= 3) {
needToChange = needToChange.concat(tempArr);
}
}
}
// search in column
for (ni = 0; ni < n; ni++) {
for (let x = 0; x < numbers.length; x++) {
const num = numbers[x]; // number to search
let counter = 0; // counter for this number in row mi
let tempArr = [];
for (mi = 0; mi < m; mi++) {
const currentNum = arr[mi][ni];
if (currentNum === num) {
counter++;
tempArr.push([mi, ni]);
}
}
if (counter >= 3) {
needToChange = needToChange.concat(tempArr);
}
}
}
// replace
needToChange.forEach(([i, j]) => {
array[i][j] = target;
});
}
replace(array);
array.forEach(row => {
console.log(row.join(', '));
})

find the first duplicate number from an array for which the second occurrence has the minimal index

i am trying to write a javascript code to find the first duplicate number from an arrayn for which the second occurrence has the minimal index.I have already written the function and it works fine for almost all given arrays except for the test case given below.
Input:
a: [1, 1, 2, 2, 1]
Output:
2
Expected Output:
1
The javascript code is given below
function firstDuplicate(a) {
var firstIndex = "";
var isMatch = false;
for (var i = 0; i <= a.length; i++) {
for (var j = i + 1; j <= a.length; j++) {
alert(a[i] + "," + a[j]);
if (a[i] === a[j]) {
firstIndex = j;
isMatch = true;
break;
}
}
}
if (isMatch)
return a[firstIndex];
else
return -1;
}
the program is bugged using alert statement inside the second for loop.I found that the value of a[i] and a[j] is same in the first execution of the loop itself yet the if condition right below fails. I wonder how this happens and can anyone plaese explain me why this happens?
You should only set firstIndex if it is lower than its current value.
Also, your loop bounds are incorrect. They should have < instead of <=.
console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1
function firstDuplicate(a) {
var firstIndex = Infinity;
var isMatch = false;
for (var i = 0; i < a.length; i++) {
for (var j = i + 1; j < a.length; j++) {
// ---------------vvvvvvvvvvvvvvvvv
if (a[i] === a[j] && j < firstIndex) {
firstIndex = j;
isMatch = true;
break;
}
}
}
if (isMatch)
return a[firstIndex];
else
return -1;
}
Here's another way to write it:
console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1
function firstDuplicate(a) {
let idx = Infinity;
for (const [i, n] of a.entries()) {
const dupIdx = a.indexOf(n, i+1);
if (dupIdx !== -1 && dupIdx < idx) {
idx = dupIdx;
}
}
return isFinite(idx) ? a[idx] : -1;
}
You could take a single loop approach with using a hash table for indicating visited items.
function firstDuplicate(array) {
var hash = Object.create(null),
i = 0,
l = array.length,
item;
while (i < l) {
item = array[i];
if (hash[item]) {
return item;
}
hash[item] = true;
i++;
}
return -1;
}
console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1
Solution in Javascript:
function solution(a) {
for (let i = 0; i < a.length; i++)
if (a.indexOf(a[i]) !== i) return a[i];
return -1;
}
console.log(solution([2, 1, 3, 5, 3, 2])); // 3
console.log(solution([2, 2])); // 2
console.log(solution([2, 4, 3, 5, 1])); // -1

Find triple duplicates in the array JS

Current code doesn't work. I want to alert all sequences of 3 equal numbers.
function myFunction() {
var fruits = [3, 3, 3, 5, 4, 6, 8, 9];
var a = fruits.sort();
document.getElementById("demo").innerHTML = a;
for(var i = 0, j = 1, k = 2; i < fruits.length, j < fruits.length, k < fruits.length; i++, j++, k++){
if(fruits[i].valueOf() == fruits[j].valueOf() == fruits[k].valueOf()){
alert(fruits[i].valueOf()+" "+fruits[j].valueOf() +" "+fruits[k].valueOf());
}
}
}
Hmm you can do like this but as of v0.0.1 works only for single digits.
var fruits = [3, 3, 3, 5, 4, 6, 8, 9, 6, 6, 6],
triple = fruits.join("").match(/(\d)\1\1/g).map(e=>e.split("").map(e=>e*1));
document.write(JSON.stringify(triple));
You can try this option:
for(var i = 0; i < fruits.length; i++){
if(fruits[i] === fruits[i+1] && fruits[i] === fruits[i+2]){
//msg
alert('found!');
}
}
try this:
var fruits = [3, 3, 3, 5, 4, 6, 8, 9];
var a = fruits.sort();
var cursor = 0;
var arraySize = fruits.length;
while(cursor < arraySize - 3){
//big step:
if(a[cursor] == a[cursor + 1] && a[cursor] == a[cursor + 2]){
console.log(a[cursor]);
cursor = cursor + 3;
continue;
}
//medium step:
if(a[cursor] == a[cursor + 1]){
cursor = cursor + 2;
continue;
}
cursor++;
}
it's output will be 3 (as there are 3 consecutive appearances of the element)
The solution using an unordered extended example array, Array.slice, Array.indexOf and Array.some functions:
function myFunction() {
var fruits = [3, 3, 5, 3, 4, 6, 8, 9, 9, 7, 9],
len = fruits.length, k = 0, notEqual = false, sequence;
fruits.sort();
while (k <= len) {
sequence = fruits.slice(k, k + 3);
if (sequence.length < 3) break;
notEqual = sequence.some((v, k, arr) => arr.indexOf(v) !== 0);
if (!notEqual) { // check if all numbers in the sequence are equal
console.log(sequence);
k += 2;
} else {
k += 1;
}
}
}
myFunction();
The output:
[3, 3, 3]
[9, 9, 9]
I can see two main problem in code
1) If condition in loop:
if(fruits[i].valueOf() == fruits[j].valueOf() == fruits[k].valueOf())
This condition will be always false because when it compare with two values result will be false or true then again that false and true will be compared with value which will be false every time i.e (true===3) result : false
2) I can see you are using in alerts valueOf method which you dont need you can use directly fruits[i] to get value.
function myFunction() {
var fruits = [3, 3, 3, 5, 4, 6, 8, 9];
var a = fruits.sort();
document.getElementById("demo").innerHTML = a;
for(var i = 0, i < fruits.length-3;i++){
if((fruits[i] == fruits[i+1]) &&(fruits[i]== fruits[i+2])){
alert(fruits[i]+" "+fruits[i+1] +" "+fruits[i+2]);
}
}}
try this one
for(var i = 0; i < fruits.length; i++) {
if(( fruits[i+1] !== null ) && (fruits[i] === fruits[i+1])) {
if(( fruits[i+2] !== null ) && (fruits[i] === fruits[i+2])) {
// your message
alert('');
}
}
}

Filtering an Array in Javascript to Find 3 Consecutive Numbers

Given an array of unsorted positive ints, write a function that finds runs of 3 consecutive numbers (ascending or descending) and returns the indices where such runs begin. If no such runs are found, return null.
function findConsecutiveRuns(input:Array):Array
Example: [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7] would return [0, 4, 6, 7]
My JS skills are a bit rusty, here is my attempt at this...
var numArray = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var newNumArray = [];
for(var i = 1; i < numArray.length; i++) {
if ((numArray[i] - numArray[i-1] != 1) || (numArray[i] + numArray[i+1] !=1) {
return 0;
}
else {
newNumArray.push(numArray[i]);
}
}
alert(newNumArray);
Here:
function f ( arr ) {
var diff1, diff2, result = [];
for ( var i = 0, len = arr.length; i < len - 2; i += 1 ) {
diff1 = arr[i] - arr[i+1];
diff2 = arr[i+1] - arr[i+2];
if ( Math.abs( diff1 ) === 1 && diff1 === diff2 ) {
result.push( i );
}
}
return result.length > 0 ? result : null;
}
Live demo: http://jsfiddle.net/Cc4DT/1/

Categories