【问题标题】:Find closest number in array to a number not in the array在数组中查找与不在数组中的数字最接近的数字
【发布时间】:2014-04-14 10:44:09
【问题描述】:

标题中提出的问题已经得到解答,但是我受到一些限制,需要不同的解决方案。

在数组中找到最接近数字的值的答案:

     int myNumber = 490;
int distance = Math.abs(numbers[0] - myNumber);
int idx = 0;
     for(int c = 1; c < numbers.length; c++)
     {
          int cdistance = Math.abs(numbers[c] - myNumber);
          if(cdistance < distance)
          {
               idx = c;
               distance = cdistance;
          }
}
int theNumber = numbers[idx];

关于是什么让我的问题足够具体的一些背景知识:

我的程序接收医院患者的 PriorityQueue。有 3 间手术室,程序将输出这 3 间手术室的 8 小时(一个工作日)时间表,以及我的“推迟”数组,其中包含当天没有参加手术的患者。我有一个名为 roomCapacity 的数组,其中包含每个房间的剩余时间。这是我的问题比标题更具体的地方。上面的答案使用每个数字之间的距离,在我的情况下,选择距离最短(最合适)的 roomCapacity。但有时 DIFFERENCE 为 -1。我意识到 Math.abs 确保 DISTANCE 为正,但在这种特殊情况下,我没有理由使用绝对值,因为如果操作的持续时间长于容量,则可能无法在房间内安排操作房间。 DISTANCE(差的绝对值)必须大于或等于零。我已经花费了我认为适得其反的尝试来寻找解决方案,并且非常感谢一些提示。

为了完成这项工作,我将上面的代码添加到我的方法中,并且只有在使用调试器后才意识到我将患者放置在容量小于操作持续时间的房间中,但最适合忽略说约束。

(编辑)具体问题:如何使用与上面显示的方法类似的方法在我的 roomCapacity 数组中找到最接近值(int d)的数字,同时考虑到差异可能不小于 0?

(这是我的第一个问题,对歧义表示歉意)

我的方法:

public int getBestRoom(int d)//int d = currentOperationDuration
{
     int roomNumber;
     /**
      *int distance = Math.abs(roomCapacity[0] - d);
      *int idx = 0;
      *for(int c = 1; c < 3; c++)
      *{
      *     int cdistance = Math.abs(roomCapacity[c] - d);
      *     if(cdistance < distance)
      *     {
      *          idx = c;
      *          distance = cdistance;
      *     }
      *roomNumber = idx;
      *}
      **/
return roomNumber;
}

【问题讨论】:

  • 您能否将其改写为一个具体问题,而不是“我不知道,我需要提示吗?”如果没有,代码审查请求将发送到 Stack Exchange 的不同部分。
  • "距离(差的绝对值)必须大于或等于零。" - 除了Math.abs(),你为什么不检查一下呢?只需检查roomCapacity[c] - d &gt;= 0。当然,您必须考虑无法占用任何空间的情况,并且可能返回 -1 或其他值。
  • 如果没有适合当前患者的房间,我的代码甚至不会达到这一点。我也尝试使用 >= 0 但导致过度使用 if 语句,我试图避免这种情况,它变得混乱且难以跟踪我的代码在做什么。

标签: java arrays


【解决方案1】:

简单,删除所有Math.abs 并仅测试正距离:

int myNumber = 490;
int distance = Integer.MAX_VALUE;
int idx = 0;
for(int c = 0; c < numbers.length; c++)
{
    int cdistance = numbers[c] - myNumber;
    if (cdistance < distance && cdistance >= 0)
    {
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];

【讨论】:

  • 这不起作用。考虑 myNumber = 4,我的数组 roomCapacity{3,8,8}...我希望我的方法返回的索引是 1,因为它不能放入 0,并且无论我将它放在 1 还是 2 中都没有关系因为它们是平等的,而且重点是找到最合适的。您的解决方案将其放置在 roomCapacity[0]
  • 仍然未能通过相同的测试用例,但确实给了我一个想法,从今天开始我太油腻了,无法进一步调查,所以明天检查一下。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
相关资源
最近更新 更多