[英]Why does my algorithm not check the last element of the linkedlist?
我制作了一個小型系統,它使用seatCount來填充一定數量的座位(沒有行)。 現在我做了一個填充座位並返回地圖的方法,地圖返回一定數量的座位空閑的位置(例如3-2意味着在地點3處開始有兩個座位。
這很好用,但是如果我說最多有5個座位而座位5是免費的,那么該方法不會將其返回到地圖。
這是使用的代碼:
對象座位
public class Seat {
public Integer availability;
public Integer seatNumber;
public boolean IsFree() {
if(availability == 0){
return true;
}
else return false;
}
public String toString() {
return "{ " + seatNumber + ", free: " + IsFree() + " } ";
}
}
此方法創建一個LinkedList,並通過giveRandomAvailability()方法填充'1'(take)或'0'(可用)的可用性
static LinkedList fillList(int seats){
LinkedList<Seat> list = new LinkedList<Seat>();
seats = seatCount;
for(int i = 0; i < seats; i++){
Seat seat = new Seat();
seat.availability = giveRandomAvailability();
seat.seatNumber = (i + 1);
list.add(seat);
}
return list;
}
這是無法正常工作的方法,它應該用可用的座位填充地圖,但是當最后一個元素可用時,它不會映射。 這是一個示例輸出:
[{ 1, free: true } , { 2, free: true } , { 3, free: false } , { 4, free: true } , { 5, free: true } ]
{1=2}
您可以看到第一部分處理得很好但它也應該包含4 = 2。
方法:
static Map fillSeats(){
int n = 3;
LinkedList<Seat> newList = fillList(seatCount);
int consecutiveLength = 0; // Consecutive free seats length
int index = 0;
int startIndex = -1; // Store the start of consecutive free seats
System.out.println(newList.toString());
Map<Integer, Integer> consecutiveMap = new HashMap<>(); // Store startIndex -> length
for (Seat seat : newList) {
if (seat.IsFree()) {
if (startIndex < 0) {
startIndex = index;
}
consecutiveLength ++;
} else {
consecutiveMap.put(startIndex + 1, consecutiveLength);
if (consecutiveLength == n) {
// Found, do something here
}
// Reset
startIndex = -1;
consecutiveLength = 0;
}
index++;
}
return consecutiveMap;
}
我在這里找不到問題,非常感謝幫助。
好吧,如果該組包含List
的最后一個元素,則您的循環不會添加最后一組連續席位。 您應該在循環后添加邏輯以添加最后一個組:
for (Seat seat : newList) {
if (seat.IsFree()) {
if (startIndex < 0) {
startIndex = index;
}
consecutiveLength ++;
} else {
consecutiveMap.put(startIndex + 1, consecutiveLength);
if (consecutiveLength == n) {
// Found, do something here
}
// Reset
startIndex = -1;
consecutiveLength = 0;
}
index++;
}
// added logic:
if (startIndex >= 0) {
consecutiveMap.put(startIndex + 1, consecutiveLength);
}
return consecutiveMap;
您對consecutiveMap.put
調用僅存在於循環的else
子句中,並且由於列表中的最后一個元素是空閑的,因此最終的兩個席位永遠不會執行此代碼。
seat.IsFree() == true
,增量計數器 seat.IsFree() == true
,增量計數器 seat.isFree() == false
,為map添加值,重置計數器 seat.isFree() == true
,增量計數器 seat.isFree() == true
,增量計數器 然后循環終止,因此最終計數器不會添加到地圖中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.