In: Computer Science
Write a static method remove(int v, int[] in) that will return a new array of the integers in the given array, but with the value v removed. For example, if v is 3 and in contains 0, 1, 3, 2, 3, 0, 3, and 1, the method will return an array containing 0, 1, 2, 0, and 1. Hint: You can follow two steps to solve this problem: Create an array in the method, let say you called it result. Before you create the result array, you need to find the number of values that will be in the result. Assign all values from in array to results array except v value. Return the array result. (JAVA) the main method and the class should be in 2 separate files
//RemoveValueFromArray.java public class RemoveValueFromArray { public static int[] remove(int v, int[] in){ int count = 0; for(int i = 0;i<in.length;i++) { if(in[i] != v){ count += 1; } } int result[] = new int[count]; int k = 0; for(int i = 0;i<in.length;i++) { if(in[i] != v){ result[k++] = in[i]; } } return result; } }
///////////////////////////////////////////////////////////////////////
//TestCode.java public class TestCode { public static void main(String[] args) { int arr[] = {0, 1, 3, 2, 3, 0, 3, 1}; int res[] = RemoveValueFromArray.remove(3, arr); for(int i = 0;i<res.length;i++){ System.out.print(res[i]+" "); } } }