Last active
January 4, 2016 22:29
-
-
Save mmloveaa/0c8475f73ae2866cb09d to your computer and use it in GitHub Desktop.
+1 Array
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
// Started on 12/27/2015, Got back to this question on 1/4/2016 | |
// +1 Array | |
// Given an array of integers of any length, return an array that has 1 added | |
// to the value represented by the array. | |
// For example an array [2, 3, 9] equals 239, add one would return an | |
// array [2, 4, 0]. | |
// [4, 3, 2, 5] would return [4, 3, 2, 6] | |
// The array can't be empty and only positive, single digit integers are allowed. | |
// The function should return null if the array is empty or any of the array | |
// values are negative or more than 10. | |
// [1, -9] would return null/nil/None (according to the language implemented). | |
// Test.assertSimilar(upArray([2,3,9]), [2,4,0]); | |
// Test.assertSimilar(upArray([4,3,2,5]), [4,3,2,6]); | |
// Test.assertSimilar(upArray([1,-9]), null); | |
function upArray(arr){ | |
// console.log("input array: ",arr) | |
// console.log(arr.length) | |
if(arr.length === 0){ | |
console.log('is this code running') | |
return null; | |
} | |
for(var i=0;i<arr.length;i++){ | |
if(arr[i]<0 || arr[i]>10){ | |
return null; | |
} | |
} | |
if(numberLook!==9){ | |
arr[arr.length-1]= arr[arr.length-1]+1 | |
} | |
var n=1 | |
var numberLook =arr[arr.length-n] | |
if (numberLook === 9) { | |
numberLook = 10 | |
} | |
while (numberLook === 10) { | |
if (arr.length - n === 0) { | |
if (numberLook === 10) { | |
arr[arr.length-n] = 0; | |
arr.unshift(1) | |
numberLook = 1; | |
} | |
} | |
else { | |
arr[arr.length-n] = 0; | |
arr[arr.length-n-1] += 1; | |
n++; | |
numberLook = arr[arr.length-n] | |
} | |
} | |
return arr; | |
} | |
// some edge case such as [9,8,9] , [9,9,9]. Now all cases will pass the test. | |
// Basic tests | |
// input array: [ 5, 7, 4 ] | |
// Test Passed: Value == [5,7,5] | |
// input array: [ 9, 9, 9 ] | |
// Test Passed: Value == [1,0,0,0] | |
// input array: [ 2, 1, 4, 7, 4, 8, 3, 6, 4, 7 ] | |
// Test Passed: Value == [2,1,4,7,4,8,3,6,4,8] | |
// Invalids array | |
// input array: [ 1, 2, 33 ] | |
// Test Passed: Value == null | |
// input array: [ 1, 2, -1 ] | |
// Test Passed: Value == null | |
// input array: [] | |
// is this code running | |
// Test Passed: Value == null | |
// 'Big' arrays | |
// input array: [ 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 7 ] | |
// Test Passed: Value == [9,2,2,3,3,7,2,0,3,6,8,5,4,7,7,5,8,0,8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment