大富翁中的每条街道都由 2 或 3 个不同的房产组成。
当用户升级街道时,它将在适当的地产上建造 3 栋建筑物中的 1 栋。
房子 - 最不值钱,默认情况下会建造它,每处房产最多 16 个。
酒店 - 需要建造 3 栋房屋。每处房产最多 8 个。
摩天大楼 - 最有价值,需要 2 家酒店才能建造,每家酒店最多 1 家。
每种类型的建筑都需要均匀分布。例如,如果有 2 个属性,则升级顺序为:
只有在摩天大楼和酒店都满了之后,一处房产上才会有超过 3 栋房屋,然后每处房产上的房屋会堆积到 16 栋。
我需要一个函数来计算这个。该函数的参数是 numOfProperties、numOfSkyScrapers、numOfHotels、numOfHouses,它需要输出下一个应该是哪个建筑物。
该函数不能使用循环。我认为 mod 运算符会很有用。
下面的代码在有 1 个属性时有效。但升级 8 号拥有 2 处房产,它本应是一家酒店,但它只是一栋别墅。因为第一次酒店升级后,删除了3栋房子,所以总数又是3栋,又建了一个房子。
我不知道如何才能使这种动态并适用于所有数量的属性
function nextBuilding(numProperties, numHouses, numHotels, numSkyscrapers) {
// Maximum limits per property
const maxHousesPerProperty = 16;
const maxHotelsPerProperty = 8;
const maxSkyscrapersPerProperty = 1;
// Conversion ratios
const housesPerHotel = 3;
const hotelsPerSkyscraper = 2;
// Calculate the number of buildings per property
const housesPerProperty = Math.floor(numHouses / numProperties);
const hotelsPerProperty = Math.floor(numHotels / numProperties);
const skyscrapersPerProperty = Math.floor(numSkyscrapers / numProperties);
// Calculate remainders to help balance the properties
const housesRemainder = numHouses % numProperties;
const hotelsRemainder = numHotels % numProperties;
const skyscrapersRemainder = numSkyscrapers % numProperties;
// Determine the position for the next building
const nextPropertyIndex = (numHouses + (numHotels * housesPerHotel) + (numSkyscrapers * hotelsPerSkyscraper * housesPerHotel)) % numProperties;
// Determine the next building to construct
if ((skyscrapersPerProperty < maxSkyscrapersPerProperty) && (numHotels >= hotelsPerSkyscraper)) {
// Check if there are enough hotels for the next skyscraper
return "skyscraper";
}
if ((hotelsPerProperty < maxHotelsPerProperty) && (numHouses >= housesPerHotel)) {
// Check if there are enough houses for the next hotel
return "hotel";
}
if (housesPerProperty < maxHousesPerProperty) {
return "house";
}
return "No building needed";
}
红宝石代码:
def f(numOfHouses, numOfHotels, numOfSkyScrapers, numOfProperties)
return "skyScraper" if numOfSkyScrapers % numOfProperties != 0
return "skyScraper" if numOfSkyScrapers == 0 && numOfHotels == numOfProperties * 2
return "hotel" if numOfHotels % numOfProperties != 0
return "hotel" if numOfHotels < 8 && numOfHouses == numOfProperties * 3
return "house" if numOfHouses < 16
return "no building needed"
end
输出示例:
> f(3,0,0,2)
=> "house"
> f(4,0,0,2)
=> "house"
> f(5,0,0,2)
=> "house"
> f(6,0,0,2)
=> "hotel"
> f(3,1,0,2)
=> "hotel"
> f(0,2,0,2)
=> "house"
> f(1,2,0,2)
=> "house"
> f(2,2,0,2)
=> "house"
> f(6,2,0,2)
=> "hotel"
> f(3,3,0,2)
=> "hotel"
> f(0,4,0,2)
=> "skyScraper"