是否有可能(甚至是值得)尝试编写下面的代码块而没有var?它适用于一个变种。这不是面试,这是我第一次尝试scala(来自java)。在纯函数中使用var的工作scala代码。这可能没有var?
问题:尽可能地让人们靠近剧院的前面,同时保持每个请求(例如Jones,4张门票)在一个剧院区域。从前面开始的剧院部分的大小为6,6,3,5,5 ......等等。我试图通过将所有潜在的票务请求组放在一起来完成此任务,然后选择每个部分中最适合的组。
这里是类。一个SeatingCombination是SeatingRequest(只是标识)的一个可能的组合及其ticketCount(S)的总和:
class SeatingCombination(val idList: List[Int], val seatCount: Int){}
class SeatingRequest(val id: Int, val partyName: String, val ticketCount: Int){}
class TheatreSection(val sectionSize: Int, rowNumber: Int, sectionNumber: Int) {
def id: String = rowNumber.toString + "_"+ sectionNumber.toString;
}
通过我们得到以下功能的时间... 1)所有可能的SeatingRequest的组合在SeatingCombination的列表中并按降序排列。 2.)所有TheatreSection按顺序列出。
def getSeatingMap(groups: List[SeatingCombination], sections: List[TheatreSection]): HashMap[Int, TheatreSection] = {
var seatedMap = new HashMap[Int, TheatreSection]
for (sect <- sections) {
val bestFitOpt = groups.find(g => { g.seatCount <= sect.sectionSize && !isAnyListIdInMap(seatedMap, g.idList) })
bestFitOpt.filter(_.idList.size > 0).foreach(_.idList.foreach(seatedMap.update(_, sect)))
}
seatedMap
}
def isAnyListIdInMap(map: HashMap[Int, TheatreSection], list: List[Int]): Boolean = {
(for (id <- list) yield !map.get(id).isEmpty).reduce(_ || _)
}
我写了没有var的程序的其余部分,但在这个迭代部分,它似乎是不可能的。也许我的实施策略是不可能的。从我读过的内容看,纯函数中的var仍然有效。但它一直困扰着我,我想不出如何去除var,因为我的教科书告诉我要尽量避免它们,而我不知道我不知道什么。
它看起来像'foldLeft'工作。 – Nebril