Long story short, I have an xlsx file that has the following data shape, but with a long more data.
Date | Barns |
---|---|
14/May/2024 | 13 |
15/May/2024 | 14 |
16/May/2024 | 16 |
The file might contain 200-300 entries.
They represent that number of chickens that come out of the eggs hatchers farm.
I managed to convert these data into JSON and then I stored them in my database, but now I need find how many farms do I need to house these chickens.
Here they have some rules, each farm can house 16 barns, each barn can keep the chickens for 33 days then sell them.
After selling them a barn needs to be empty for 22 days after being used again.
My problem is I can’t find a way to calculate how many farms do I need, and when each farm is going to be used and when it’s empty (for 22 days duration).
This is the code I have right now:
const settings = { BARNS_PER_FARM: 16 }
const totalBarns = planDays.reduce((acc, day) => acc + day.barns, 0)
const firstDate = planDays[0]?.date
const lastDate = planDays[planDays.length - 1]?.date
const farmsNeeded = Math.ceil(totalBarns / settings.BARNS_PER_FARM)
const copy = [...planDays]
const farms: Farm[] = Array.from({ length: farmsNeeded }).map((_, i) => {
return {
name: `Farm ${i + 1}`,
housing: [],
lastUsedDate: null, // Track last used date for reusability
}
})
const current = {
farm: 0,
}
for (const day of copy) {
const barns = day.barns
if (barns === 0) {
continue
}
const farm = farms[current.farm]
const available = settings.BARNS_PER_FARM - farmUsedBarns(farm)
const needed = barns
if (available >= needed) {
addHousing(farm, needed, day.date)
}
else {
if (available > 0) {
addHousing(farm, available, day.date)
}
let remaining = needed - available
while (remaining > 0) {
current.farm++
const farm = farms[current.farm]
const available = settings.BARNS_PER_FARM - farmUsedBarns(farms[current.farm])
const needed = remaining
if (available >= needed) {
addHousing(farm, needed, day.date)
remaining = 0
}
else {
addHousing(farm, available, day.date)
remaining -= available
}
}
}
}
return {
status: 200,
body: {
data: {
farms: farms.filter(farm => farm.housing.length > 0),
totalBarns,
firstDate,
lastDate,
farmsNeeded,
},
},
}
function addHousing(farm: Farm, numberOfBarns: number, startDate: Date) {
if (farm.housing.length === 0) {
farm.housing.push({
name: 'A',
startDate: startDate,
numberOfBarns,
})
return
}
const previousHousing = farm.housing[farm.housing.length - 1]
const newStartDate = new Date(previousHousing.startDate)
newStartDate.setDate(newStartDate.getDate() + 1)
farm.housing.push({
name: String.fromCharCode(previousHousing.name.charCodeAt(0) + 1),
numberOfBarns,
startDate: startDate,
})
}
function farmUsedBarns(farm: Farm) {
return farm.housing.reduce((acc, housing) => {
return acc + housing.numberOfBarns
}, 0)
}
It doesn’t take into account that the barn can be used after 56 days. and keeps adding farms when the previous one is filled.