"Problem description"
With 100 cents to buy 100 chickens, of which the Rooster 5 text Money 1 only, hen 3 text Money 1 only, chicken 1 text Money 3 only. Q: How many cocks, hens and chickens have you bought?
"Design Ideas"
The number of cocks, hens, and chickens, respectively, is x, Y, Z, and according to test instructions, the following equations can be set:
x + y + z = 100
5x + 3y + Z/3 = 100
If you buy a rooster for 100 cents, you can buy up to 100/5 = 20, so the value range of x is between 0~20; if you buy a hen for 100, you can buy up to 100/3 = 33, so the value of y is between 0~33; if you buy chickens for 100, you can buy up to 99. So Z's value range is between 0~99 and Z% 3 = 0.
The values of x, Y, and Z are exhaustive by a triple loop. In the process of exhaustive, if x, Y, and z satisfy the above equations, a set of qualified solutions are obtained.
"Swift Programming Implementation"
hundred dollars to buy hundred chickens
Func buyOneHundredChickens1 () {
The values of x, Y, and Z are lifted by the triple cycle
For x in 0...20 {//If you buy a rooster for 100 cents, you can buy up to 100/5 = 20, so the value range of x is between 0~20
For y in 0...33 {//If you buy a hen for 100 cents, you can buy up to 100/3 = 33, so the value range of Y is between 0~33
For z in 0...99 where z% 3 = = 0 {//If you buy chicken for 100 cents, you can buy up to 99, so the Z value range is between 0~99 and Z% 3 = 0
/*
In the process of exhaustive, if x, Y and Z meet the following equations:
x + y + z = 100
5x + 3y + Z/3 = 100
A set of qualified solutions is obtained.
*/
If x + y + z = = && 5 * x + 3 * y + Z/3 = = 100 {
Print ("Rooster: \ (x) only, hen: \ (y) only, chick \ (z) only")
}
}
}
}
}
BUYONEHUNDREDCHICKENS1 ()
Hundred money to buy hundred chickens (program improvement)
Func BuyOneHundredChickens2 () {
The value of x, y through the double cycle of the exhaustive
For x in 0...20 {//If you buy a rooster for 100 cents, you can buy up to 100/5 = 20, so the value range of x is between 0~20
For y in 0...33 {//If you buy a hen for 100 cents, you can buy up to 100/3 = 33, so the value range of Y is between 0~33
Let z = 100-x-y
If z >= 0 && z% 3 = = 0 && 5 * x + 3 * y + Z/3 = = 100 {
Print ("Rooster: \ (x) only, hen: \ (y) only, chick :\ (z) only")
}
}
}
}
BuyOneHundredChickens2 ()
"Run Results"
Rooster: 0, Hen: 25, Chicken :75
Rooster: 4, Hen: 18, chicken :78
Rooster: 8, Hen: 11, chicken :81
Rooster: 12, Hen: 4, chicken :84
This article from "Super elder brother Video lecture" blog, declined reprint!
Swift Fun Case hundred money buy hundred chicken