Return farthestK from val: Can't import anything other than java.util.Arrays -


need return k elements a[i] such abs(a[i] - val) k largest evaluation. code works integers greater val. fail if integers less val. can without importing other java.util.arrays? appreciated!

import java.util.arrays;  public final class selector {  private selector() {  }  public static int[] farthestk(int[] a, int val, int k) {// line should not change                     int[] b = new int[a.length];   (int = 0; < b.length; i++) {      b[i] = math.abs(a[i] - val);   }   arrays.sort(b);   int[] c = new int[k];   int w = 0;   (int = b.length-1; > b.length-k-1; i--) {             c[w] = b[i] + val;      w++;        }   return c;     } 

test case:

import org.junit.assert; import static org.junit.assert.*; import org.junit.before; import org.junit.test;   public class selectortest {    /** fixture initialization (common initialization   *  tests). **/  @before public void setup() {  }   @test public void farthestktest() {        int[] = {-2, 4, -6, 7, 8, 13, 15};        int[] expected = {15, -6, 13, -2};        int[] actual = selector.farthestk(a, 4, 4);        assert.assertarrayequals(expected, actual);      }  }   there 1 failure:  1) farthestktest(selectortest)  arrays first differed @ element [1]; expected:<-6> was:<13>  failures!!!  tests run: 1,  failures: 1 

by storing distance absolute value, destroy last loop recalculates original value abs-value.

how using comparator using abs value comparison, storing difference of array value search value in array b?

this here:

public static int[] farthestk(int[] a, int val, int k) {// line should not change     integer[] b = new integer[a.length];     (int = 0; < b.length; i++) {       b[i] = a[i] - val;     }     arrays.sort(b, new comparator<integer>() {        @override       public int compare(integer arg0, integer arg1) {         return integer.valueof(math.abs(arg0)).compareto(math.abs(arg1));       }     });     int[] c = new int[k];     int w = 0;     (int = b.length - 1; > b.length - k - 1; i--) {       c[w] = b[i] + val;       w++;     }     return c;   } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -