I wrote a code to search for the closest value to the given one, they told me that it was bad, but why they didn’t answer, actually, maybe someone will say.

static int nearest(int n, int...args) { int nearest = 0; for(int i = 0; i < 1; i++) { int r1 = 0; int r2 = n; for(int j = 0; j < args.length; j ++) { r1 = n - args[j]; if(r1 < 0) { r1 *= -1; } if((r1) == 0) { nearest = args[j]; break; } else { if(r2 > r1) { r2 = r1; nearest = args[j]; } } } } return nearest; } 
  • five
    Well ... So why do you need, for example, an outer loop with one iteration? .. - Yuriy SPb
  • nearest( 1, 100, 200 ) will return 0 - zRrr

1 answer 1

  static int nearest(int n, int...args) { //тут мы храним значение ближайшего числа int nearest = 0; //очевидно же, что максимальное значение типа int - это одновременно максимальная удаленность двух чисел //Умножаем на два и приводим к типу long, так как в Java нет беззнаковых типов long value = 2*Integer.MAX_VALUE; //дальше просто проходим по массиву и сравниваем разницу //сравнение по модулю, т.е. чем меньше разница - тем ближе числа for(int arg : args) if (value > Math.abs(n - arg)){ value = Math.abs(n-arg); nearest = arg;} return nearest; } 

Regarding your method - a lot of unnecessary variables, an extra cycle, a lot of comparisons. In short - a lot of unnecessary operations.

  • By the way, now I ran into it - in java, there are no unsigned ones, which means that we must take a type that is twice the int, at least. The maximum difference between Integer.MAX_VALUE and Integer.MIN_VALUE is twice Integer.MAX_VALUE. Therefore, the long type is here - FoeNicks
  • With a long truth, there were problems, I took just the value as int equal Integer.MAX_VALUE and then everything started working without problems; Is it possible that when comparing, there were any problems with casting or something like that ? Well, I don’t know why it didn’t work - DuckImMud
  • I took a long, since negative values ​​can be transmitted and then the algorithm does not work correctly. Strange, type conversion should work out. You can explicitly give: long value = (long) (2 * Integer.MAX_VALUE). Simply, if you create a function that searches for the nearest number and uses the same type, then the algorithm is somewhat more complicated, but the essence is the same - the distance is simply calculated and compared. - FoeNicks