Skip to content

Instantly share code, notes, and snippets.

@hoangong
Created December 8, 2015 18:01
Show Gist options
  • Save hoangong/7a8ffed11d65e35b7ef2 to your computer and use it in GitHub Desktop.
Save hoangong/7a8ffed11d65e35b7ef2 to your computer and use it in GitHub Desktop.
Fruit basket challenge
/**
* Challenge: https://www.reddit.com/r/dailyprogrammer/comments/3v4zsf/20151202_challenge_243_intermediate_jennys_fruit/
* Description
Little Jenny has been sent to the market with a 5 dollar bill in hand, to buy fruits for a gift basket for the new neighbors. Since she's a diligent and literal-minded kid, she intends to spend exactly 5 dollars - not one cent more or less.
The fact that the market sells fruits per piece at non-round prices, does not make this easy - but Jenny is prepared. She takes out a Netbook from her backpack, types in the unit prices of some of the fruits she sees, and fires off a program from her collection - and voil\u00e0, the possible fruit combinations for a $5 purchase appear on the screen.
Challenge: Show what Jenny's program might look like in the programming language of your choice.
The goal is aways 500 cents (= $5).
Solutions can include multiple fruits of the same type - assume they're available in unlimited quantities.
Solutions do not need to include all available types of fruit.
Determine all possible solutions for the given input.
Input Description
One line per available type of fruit - each stating the fruit's name (a word without spaces) and the fruit's unit price in cents (an integer).
Output Description
One line per solution - each a comma-separated set of quantity+name pairs, describing how many fruits of which type to buy.
Do not list fruits with a quantity of zero in the output. Inflect the names for plural (adding an s is sufficient).
Sample Input
banana 32
kiwi 41
mango 97
papaya 254
pineapple 399
Sample Output
6 kiwis, 1 papaya
7 bananas, 2 kiwis, 2 mangos
Challenge Input
apple 59
banana 32
coconut 155
grapefruit 128
jackfruit 1100
kiwi 41
lemon 70
mango 97
orange 73
papaya 254
pear 37
pineapple 399
watermelon 500
Note: For this input there are 180 solutions.
*/
object JennyFruitBasket {
def calculate(ItemStack: Seq[Int]) {
var solution = 1
var extendedStack: Seq[Int] = Seq()
ItemStack.sorted.filter(_ == 500).foreach { i =>
println(s"${solution}: ${i.toString}")
solution = solution + 1
}
ItemStack.sorted.filter(_ < 500).foreach { i =>
for (j <- 0 to (500 / i).toInt - 1) {
extendedStack = extendedStack ++ Seq(i)
}
}
var foundLast = 1
(1 to extendedStack.length foreach { x =>
if (foundLast > 0) {
foundLast = 0
extendedStack.combinations(x).toStream.foreach { i =>
if (i.sum == 500) {
println(s"${solution}: ${i.toString}")
solution = solution + 1
}
if (i.sum <= 500) {
foundLast = foundLast + 1
}
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment