Created
April 9, 2022 12:21
-
-
Save jps/d75446d0b46f7e0e36d7329870b8321a to your computer and use it in GitHub Desktop.
soft zeros to left in an integer array
This file contains hidden or 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
| //Given an integer array | |
| //move all elements that are equal to 0 to the left while maintaining the order of other elements in the array. | |
| //[1,0,2,0,3] => [0,0,1,2,3]; | |
| /* | |
| [1,0,2,0,3] | |
| [0,1,2,0,3] | |
| [0,0,1,2,3] | |
| [1,2,3,4,5,6,7,8,0] | |
| [1,2,3,4,5,6,7,0,8] | |
| [1,2,3,4,5,6,0,7,8] | |
| [1,2,3,4,5,0,6,7,8] | |
| [1,2,3,4,0,5,6,7,8] | |
| [1,2,3,0,4,5,6,7,8] | |
| [1,2,0,3,4,5,6,7,8] | |
| [1,0,2,3,4,5,6,7,8] | |
| [0,1,2,3,4,5,6,7,8] | |
| */ | |
| var Mocha = require('mocha') | |
| var assert = require('assert') | |
| var mocha = new Mocha() | |
| const sortZeroToLeft = (array) => { | |
| for (let i = 0; i < array.length; ++i) { | |
| if (array[i] === 0) { | |
| array.splice(i,1); | |
| array.unshift(0); | |
| } | |
| } | |
| return array; | |
| } | |
| const sortZeroToLeft2 = (array) => { | |
| return array.sort((a,b) => { | |
| if(a === 0 && b === 0) | |
| { | |
| return 0; | |
| } | |
| if(a === 0) | |
| { | |
| return -1 | |
| } | |
| return 1; | |
| }); | |
| } | |
| // Bit of a hack, sorry! | |
| mocha.suite.emit('pre-require', this, 'solution', mocha) | |
| describe('sortZeroToLeft', () => { | |
| it('should work with standard test cases', function() { | |
| assert.deepEqual(sortZeroToLeft([1, 0]), [0, 1]); | |
| assert.deepEqual(sortZeroToLeft([1,0,2,0,3]), [0,0,1,2,3]); | |
| assert.deepEqual(sortZeroToLeft([1,2,3,4,5,6,7,8,0]), [0,1,2,3,4,5,6,7,8]); | |
| }); | |
| it('should handle empty array',() => { | |
| assert.deepEqual(sortZeroToLeft([]), []); | |
| }); | |
| }) | |
| describe('sortZeroToLeft 2', () => { | |
| it('should work with standard test cases', function() { | |
| assert.deepEqual(sortZeroToLeft2([1, 0]), [0, 1]); | |
| assert.deepEqual(sortZeroToLeft2([1,0,2,0,3]), [0,0,1,2,3]); | |
| assert.deepStrictEqual(sortZeroToLeft2([1,2,3,4,5,6,7,8,0]), [0,1,2,3,4,5,6,7,8]); | |
| assert.deepStrictEqual(sortZeroToLeft2([1,10,-1,11,5,0,-7,0,25,-35]), [0,0,1,10,-1,11,5,-7,25,-35]); | |
| }); | |
| it('should handle empty array',() => { | |
| assert.deepEqual(sortZeroToLeft2([]), []); | |
| }); | |
| }) | |
| mocha.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment