Javascript Array compareLexicographically(arr)
//### Problem 2. Lexicographically comparison //* Write a script that compares two char arrays lexicographically (letter by letter). Array.prototype.compareLexicographically = function (arr){ for(var ind = 0; ind < Math.min(this.length, arr.length); ind++){ if(arr[ind] !== this[ind]){ return this[ind] < arr[ind] ? -1 : 1; }// w w w . j a v a 2 s . c o m } if(this.length != arr.length){ this.length < arr.length ? -1 : 1; } return 0; } var a = 'abc'.split(''), b = 'acb'.split(''); console.log(a.compareLexicographically(b));
Array.prototype.compareLexicographically = function (arr) { for (var ind = 0; ind < Math.min(this.length, arr.length) ; ind++) { if (arr[ind] !== this[ind]) { return this[ind] < arr[ind] ? -1 : 1; }/*w w w.j a v a2 s . c om*/ } if (this.length != arr.length) { this.length < arr.length ? -1 : 1; } return 0; } document.writeln(['a', 'b', 'c'].compareLexicographically(['a', 'b', 'c'])); document.writeln(['a', 'b', 'c'].compareLexicographically(['a', 'c', 'b'])); document.writeln(['a', 'c', 'b'].compareLexicographically(['a', 'b', 'c']));
// Write a script that compares two char arrays // lexicographically (letter by letter). Array.prototype.compareLexicographically = function (arr){ for (var ind = 0; ind < Math.min(this.length, arr.length); ind++) { if (arr[ind] !== this[ind]) { return this[ind] < arr[ind] ? -1 : 1; }//from w w w.j a v a 2 s .c om } if (this.length != arr.length) { this.length < arr.length ? -1 : 1; } return 0; } console.log(['a', 'b', 'c'].compareLexicographically(['a', 'b', 'c'])); console.log(['a', 'b', 'c'].compareLexicographically(['a', 'c', 'b'])); console.log(['a', 'c', 'b'].compareLexicographically(['a', 'b', 'c']));