【发布时间】:2018-05-08 09:10:53
【问题描述】:
我制作了一个小型系统,该系统需要一个座位数来为电影院填充一定数量的座位(无排)。现在我做了一个方法来填充座位并返回一个地图,地图返回在什么位置有一定数量的座位是空闲的(例如 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'(采用)或 '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;
}
我在这里找不到问题,不胜感激。
【问题讨论】:
-
与我下面的答案无关,而是一些代码改进提示:我认为这些方法不需要是静态的。
IsFree应该以小写字母开头,并且您的返回值还应该包括泛型类型。 -
谢谢@JeroenSteenbeeke 的提示总是受欢迎的,我还是个初学者。
标签: java algorithm linked-list