#4

Day 4

Photo by Viktor Forgacs on Unsplash

The Problem

An imminent hurricane threatens the coastal town of Codeville. If at most two people can fit in a rescue boat, and the maximum weight limit for a given boat is k, determine how many boats will be needed to save everyone.

For example, given a population with weights [100, 200, 150, 80] and a boat limit of 200, the smallest number of boats required will be three.

https://dailycodingproblem.com

My Solution

const weights = [100, 200, 150, 80]
const otherWeights = [30, 70, 40, 200, 100, 150, 80]
const limit = 200

const numberOfBoats = (w, k) => {
	return recursiveBoats(w, k)
}

const recursiveBoats = (w, k, i = 1, max = 1, boats = 0) => {
	const element = w[0]

	if (w.length === 0) {
		return boats
	} else if (i >= w.length || element + w[max] === k) {
		// Remove the element that was the maximum under the limit if it exists
		let newWeights
		if (element + w[max] <= k) {
		  newWeights = w.slice(1, max).concat(w.slice(max + 1))
		} else {
			newWeights = w.slice(1)
		}

		return recursiveBoats(newWeights, k, 1, 1, boats + 1)
	}

	const comparison = w[i]
	
	if (element + comparison < k && (element + w[max] > k || comparison > w[max])) {
		return recursiveBoats(w, k, i + 1, i, boats)
	}

	return recursiveBoats(w, k, i + 1, max, boats)
}

const result1 = numberOfBoats(weights, limit)
console.log('Number of boats for first weights:')
console.log(result1)

const result2 = numberOfBoats(otherWeights, limit)
console.log('Number of boats for second weights:')
console.log(result2)

 

Leave a Reply

Your email address will not be published. Required fields are marked *