Search This Blog

Saturday, February 17, 2018

The Heavy Pill Task. Solution in Swift

There are 20 bottles of pills. 19 bottles have pills of weight 1.0 gram, but one has pills of weight 1.1 grams. How to find heavy bottle? There is constraint: you can make only one measurement.

In order to find a bottle with heavy pills let's take 1 pill from a first bottle 2 from the second and so on up to 20. Also, we know in advance the total weight of pills in this calculation if in all bottles the pills weigh 1 gram. It will be 1 + 2 + 3 + ... + 20 = 210 grams. Thus, we need to deduct the summary weight of all normal pills from the summary weight of pills with heavy pills and divide by the difference between the weight of the heavy and normal pills(1.1 - 1 = 0.1 grams).

So, formula is

bottleNumber = (summaryWeightWithHeavy - summaryWeightNormal) / (diff)

where summaryWeightNormal = 210 grams, diff = 0.1 grams

bottleNumber = (summaryWeightWithHeavy - 210) / 0.1

Coding algorithm for checking solution and formula:

  1. Generate random number for heavy bottle
  2. In loop from 1 to number of bottles we calculate normal weight and "heavy" weight(when one of bottles has heavy pills)
  3. According to our formula: We take the normal total weight from the heavy total weight and divide this difference by the difference between the weights for one pill
  4. Check that found bottle number equals initial bottle number


Source code
import Foundation

let bottlesCount = 20
let normalPill = 1.0
let heavyPill = 1.1
let diff = heavyPill - normalPill

let heavyBottleNumber = 1 + Int(arc4random_uniform(UInt32(bottlesCount)))
print(heavyBottleNumber)

var normalWeight = 0.0
var heavyWeight = 0.0

for i in 1...bottlesCount {
    normalWeight += Double(i)
    if i == heavyBottleNumber {
        heavyWeight += (Double(i) * heavyPill)
    } else {
        heavyWeight += Double(i)
    }
}


let result = Int(round((heavyWeight - normalWeight) / diff))
print(result)
assert(heavyBottleNumber == result, "failed")

4 comments:

  1. After a long time i found a unique and on purpose information about Custom Designed Websites. Can't wait to have more from you.

    ReplyDelete
  2. You've written a pretty interesting article. I was on the lookout for information like this. Please share more related information with me so that I can learn more. Best Custom Websites

    ReplyDelete
  3. Thank you Sir, you made it easy as pie. Now i am able to understand and have enough knowledge about this. It is only because of you.
    Custom Designed Websites

    ReplyDelete
  4. This is a great article! Thank you very much. I really need these suggestions. An in-depth explanation is of great benefit. Incredibly inspiring to see how you write. Custom Website

    ReplyDelete