Created
December 27, 2013 17:29
-
-
Save mefernandez/8149979 to your computer and use it in GitHub Desktop.
Now it's me.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('A function',function(){ | |
it('extracts the simmetric difference of two arrays of integers',function(){ | |
expect(diff([1,2,3], [4,5,6])).toEqual([1,2,3,4,5,6]); | |
expect(diff([1,2,3], [1,2,3])).toEqual([]); | |
expect(diff([1], [])).toEqual([1]); | |
expect(diff([1], [2])).toEqual([1,2]); | |
expect(diff([1,2,3], [1,2,3,4])).toEqual([4]); | |
}); | |
it('checks if integers in an array are ordered',function(){ | |
expect(isOrdered([1,2,3,4,5,6])).toBe(true); | |
expect(isOrdered([1])).toBe(true); | |
expect(isOrdered([1,2])).toBe(true); | |
expect(isOrdered([1,2,2])).toBe(true); | |
expect(isOrdered([1,2,2,3])).toBe(true); | |
expect(isOrdered([1,2,3,4,5,6].reverse())).toBe(true); | |
expect(isOrdered([1].reverse())).toBe(true); | |
expect(isOrdered([1,2].reverse())).toBe(true); | |
expect(isOrdered([1,2,2].reverse())).toBe(true); | |
expect(isOrdered([1,2,2,3].reverse())).toBe(true); | |
expect(isOrdered([1,2,1])).toBe(false); | |
expect(isOrdered([3,2,1,2])).toBe(false); | |
}); | |
}); | |
function diff(a, b) { | |
var c = a.concat(b).sort(); | |
var d = []; | |
if (c.length === 0) | |
return d; | |
if (c.length == 1) | |
return c; | |
// Check for the first element | |
if (c[0] < c[1]) | |
d.push(c[0]); | |
if (c.length > 2) { | |
// A number is unique if it's different from prev and next | |
for (var i=1; i<c.length-1; i++) { | |
if ((c[i-1] < c[i]) && (c[i] < c[i+1])) { | |
d.push(c[i]); | |
} | |
} | |
} | |
// Check the last element | |
if (c[c.length-2] < c[c.length-1]) | |
d.push(c[c.length-1]); | |
return d; | |
} | |
function isOrdered(a) { | |
if (a.length < 2) | |
return true; | |
var m = 0; | |
for (var i=0; i<a.length-1; i++) { | |
var x = (a[i] - a[i+1]); | |
// If they're equal, loop to next element | |
if (x === 0) | |
continue; | |
// m=0, we don't know if it's ordered up or down | |
if (m === 0) { | |
if (x < 0) | |
m = -1; | |
else if (x > 0) | |
m = 1; | |
} | |
// Ok, check if it's ordered | |
if ((x*m) < 0) | |
return false; | |
} | |
return true; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment