Skip to content

Instantly share code, notes, and snippets.

@bernieperez
Created August 2, 2012 04:58
Show Gist options
  • Save bernieperez/3233805 to your computer and use it in GitHub Desktop.
Save bernieperez/3233805 to your computer and use it in GitHub Desktop.
/*
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