Last active
June 17, 2018 21:40
-
-
Save JokingChicken/b1eeeebc706c5413d5e89034e9c06fe0 to your computer and use it in GitHub Desktop.
check diffrence between two arrays
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
/* | |
* creator: Danj (https://github.com/DanBrothers) | |
* description: check diffrence between two arrays | |
* license: MIT, please link to this if you copy (thanks) | |
* | |
* usage: | |
//returns array of diffrences | |
diff(arrayone, arraytwo); | |
//can also be used to check two files, by creating two arrays of the two files | |
//check for every line | |
diff(file1text.split("/n"), file2text.split("/n")); | |
*/ | |
//this function is to sort the two arrays for easy use | |
function diff(a1, a2){ | |
var matrix = new Array(a1.length+1); | |
for(var y=0; y<matrix.length; y++){ | |
matrix[y] = new Array(a2.length+1); | |
for(var x=0; x<matrix[y].length; x++){ | |
matrix[y][x] = 0; | |
} | |
} | |
for(var y=1; y<matrix.length; y++){ | |
for(var x=1; x<matrix[y].length; x++){ | |
if(a1[y-1]===a2[x-1]){ | |
matrix[y][x] = 1 + matrix[y-1][x-1]; | |
} else { | |
matrix[y][x] = Math.max(matrix[y-1][x], matrix[y][x-1]); | |
} | |
} | |
} | |
try { | |
//loop thru array and return new matrix | |
return getDiff(matrix, a1, a2, x-1, y-1, new Array()); | |
} catch(e){ | |
alert(e); | |
} | |
} | |
//this function is to get the diffrence between two | |
function getDiff(matrix, a1, a2, x, y, newmatrix){ | |
//check if there is a difference | |
if(x>0 && y>0 && a1[y-1]===a2[x-1]){ | |
// the two values are the same | |
// continue in the array | |
getDiff(matrix, a1, a2, x-1, y-1, (newmatrix[x-1] = a1[x-1])); | |
} else { | |
if(x>0 && (y===0 || matrix[y][x-1] >= matrix[y-1][x])){ | |
// a2 contains one more item then a1 | |
// continue in the array | |
getDiff(matrix, a1, a2, x-1, y, (newmatrix[x-1] = a2[x-1])); | |
} else if(y>0 && (x===0 || matrix[y][x-1] < matrix[y-1][x])){ | |
// a1 contains one more item then a2 | |
// continue in the array | |
getDiff(matrix, a1, a2, x, y-1, (newmatrix[y-1] = a1[y-1])); | |
} else { | |
//there are no new items, so return the new matrix | |
return newmatrix; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment