Created
August 2, 2012 04:58
-
-
Save bernieperez/3233805 to your computer and use it in GitHub Desktop.
An attempted at solving this: http://blog.jazzychad.net/2012/08/01/array-iteration-problem.html
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
/* | |
This is a attempted at coding this up: http://blog.jazzychad.net/2012/08/01/array-iteration-problem.html | |
Did it in about 15 mins... I might use this for a phone screen questions. | |
I did use Sublime Text... but that's fine I think. | |
*/ | |
public class Main { | |
public static void main(String[] args) { | |
// # add1 [1,4,1,5,1], 1, 0 -> [2,4,2,5,2] | |
// # add1 [1,4,1,5,1], 1, 2 -> [2,4,2,5,1] | |
// # add1 [1,4,1,5,1], 1, -2 -> [1,4,2,5,2] | |
Main.run(new int[] {1,4,1,5,1}, 1, 0); | |
Main.run(new int[] {1,4,1,5,1}, 1, 2); | |
Main.run(new int[] {1,4,1,5,1}, 1, -2); | |
} | |
public static int[] run(int[] arr, int val, int n) { | |
int count = (n == 0) ? Integer.MAX_VALUE : Math.abs(n); | |
int i = (n < 0) ? arr.length-1 : 0; | |
int inc = (i > 0) ? -1 : 1; | |
for(int x = 0; x < arr.length; x++) { | |
// If it matches | |
if (arr[i] == val) { | |
arr[i]++; | |
count--; | |
} | |
i = i + inc; | |
if (count <= 0) { | |
break; | |
} | |
} | |
return arr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment