我想解決一個問題,如下所示:給定一個集合段和一組點,計算每個點包含多少個段。比較for循環中兩個有符號整數的奇怪行爲
我遇到的問題是當我不得不計算一個點包含點的次數時。當我有一個確定的輸入時,內部循環會正確地遞增每個點的計數器,當我有另一個數據集時天氣正常,將零與負數進行比較併發生非負數,它會表現得很奇怪。
以下只是一個腳本,用於查找我面臨的問題,並不代表實際的實施。
測試用例得到輸出如下:
情況1:
String debug = "Test case 1: \n ";
debug += " \n - 2 Segments with coordinates [0, 5] and [7, 10].";
debug += " \n - 3 points at the coordinates 1, 6, and 11.";
int [] starts = new int[]{0, 7};
int [] ends = new int[]{5, 10};
int [] points = new int[]{1, 6, 11};
debug += "\n \n Calculating the coverage of the points: ";
for (int i=0; i<starts.length; i++) {
for (int j=0; j<points.length && (starts[i] <= points[j] && points[j] <= ends[i]); j++) {
debug += " \n * Point with coordinate " + points[j] + ", is between " + starts[i] + " and " + ends[i];
}
}
debug += "\n \n FINISHED the calculation!";
int start = 0, point = 1, end = 5;
debug += "\n \n Custom check for the 1st point: ";
debug += "\n - Is (" + start + " <= " + point + " and " + point + " <= " + end + ")? " + (start <= point && point <= end);
System.out.println(debug);
輸出:
測試用例1:
- 2段具有座標[0,1 5]和[7,10]。
3點在座標1,6和11
計算的點的範圍內:
點與座標1,是0-5
FINISHED計算!
爲第一點定製檢查:
- 是(0 < = 1和1 < = 5)?真
情況2:
String debug = "Test case 2: \n ";
debug += " \n - 1 Segment with coordinates [-10, 10].";
debug += " \n - 3 points at the coordinates -100, 100, and 10.";
int [] starts = new int[]{-10};
int [] ends = new int[]{10};
int [] points = new int[]{-100, 100, 0};
debug += "\n \n Calculating the coverage of the points: ";
for (int i=0; i<starts.length; i++) {
for (int j=0; j<points.length && (starts[i] <= points[j] && points[j] <= ends[i]); j++) {
debug += " \n * Point with coordinate " + points[j] + ", is between " + starts[i] + " and " + ends[i];
}
}
debug += "\n \n FINISHED the calculation!";
int start = -10, point = 0, end = 10;
debug += "\n \n Custom check: ";
debug += "\n - Is (" + start + " <= " + point + " and " + point + " <= " + end + ")? " + (start <= point && point <= end);
System.out.println(debug);
輸出:
測試用例2:
- 1段具有座標[-10,10]。
3點的座標-100,100和10
計算點的覆蓋範圍:
完成計算!
定製檢查:
- 是(-10 < = 0和0 < = 10)? true
正如您所看到的,內部循環的條件在某種程度上不適合計算座標爲0的點相對於段[-10,10]的情況。
在此先感謝, Endrit。
int [] points = new int [] { - 100,100,0};你有0,而不是10,並且你寫了。並且-10 <0 <10成立。 –