I have an array of positive/negative ints
int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers
public int getClosestToTarget(int target, int[] values) {
if (values.length < 1)
throw new IllegalArgumentException("The values should be at least one element");
if (values.length == 1) {
return values[0];
}
int closestValue = values[0];
int leastDistance = Math.abs(values[0] - target);
for (int i = 0; i < values.length; i++) {
int currentDistance = Math.abs(values[i] - target);
if (currentDistance < leastDistance) {
closestValue = values[i];
leastDistance = currentDistance;
}
}
return closestValue;
}
you are very close. I think the initial value of 'distance' should be a big number instead of 0. And use the absolute value for the cdistance.
Kotlin is so helpful
fun List<Int>.closestValue(value: Int) = minBy { abs(value - it) }
val values = listOf(1, 8, 4, -6)
println(values.closestValue(-7)) // -6
println(values.closestValue(2)) // 1
println(values.closestValue(7)) // 8
List doesn't need to be sorted BTW
public class Main
{
public static void main(String[] args)
{
int[] numbers = {6,5,10,1,3,4,2,14,11,12};
for(int i =0; i<numbers.length; i++)
{
sum(numbers, i, numbers[i], 12, String.valueOf(numbers[i]));
}
}
static void sum(int[] arr, int i, int sum, int target, String s)
{
int flag = 0;
for(int j = i+1; j<arr.length; j++)
{
if(arr[i] == target && flag==0)
{
System.out.println(String.valueOf(arr[i]));
flag =1;
}
else if(sum+arr[j] == target)
{
System.out.println(s+" "+String.valueOf(arr[j]));
}
else
{
sum(arr, j, sum+arr[j], target, s+" "+String.valueOf(arr[j]));
}
}
}
}
int valueToFind = 490;
Map<Integer, Integer> map = new HashMap();
for (int i = 0, i < numbers.length; i++){
map.put(Math.abs(numbers[i] - valueToFind), numbers[i]);
}
List<Integer> keys = new ArrayList(map.keySet());
Collections.sort(keys);
return map.get(keys.get(0));
In Java 8:
List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());
int n = 490;
int c = list.stream()
.min(Comparator.comparingInt(i -> Math.abs(i - n)))
.orElseThrow(() -> new NoSuchElementException("No value present"));
Initially, you can use a List
instead of an Array
(lists have much more functionality).