Skip to content

Instantly share code, notes, and snippets.

@kylelong
Created February 24, 2019 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelong/3337a59041fea6dba2c566fbc211f2c8 to your computer and use it in GitHub Desktop.
Save kylelong/3337a59041fea6dba2c566fbc211f2c8 to your computer and use it in GitHub Desktop.
Week of 2/17/19 Cassido's interview question of the week
/**
* Created by Kyle Long on 2/24/19.
*/
public class removeOdd {
public static void main(String [] args){
System.out.println(removeForOdd(new int[]{2,4,6,7,8}));
System.out.println(removeForOdd(new int[]{4,4,4}));
System.out.println(removeForOdd(new int[]{1,2,3,4,5,6,7}));
}
/**
* Calculates array sum
* @param arr array to sum
* @return Array sum
*/
public static int sum(int [] arr){
int sum = 0;
for(int a: arr){
sum += a;
}
return sum;
}
/**
* Check for odd array sum ignoring an index
* @param index array index to ignore
* @param arr array to sum, ignoring index
* @return int of sum
*/
public static int sumIgnoreIndex(int index, int [] arr){
int sum = 0;
for(int i = 0; i < arr.length; i++){
if(i != index) sum += arr[i];
}
return sum;
}
/**
* Check for index to remove to sum array
* @param arr array to check
* @return index to remove to make array sum odd
*/
public static int removeForOdd(int [] arr){
if(sum(arr) % 2 != 0) return -1;
for(int i = 0; i < arr.length; i++){
if(sumIgnoreIndex(i, arr) % 2 != 0)return i;
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment