views:

386

answers:

5

Here are the constraints

  • I have three buckets (water) capacities 10 litre, 2 liters and 50 litres.
  • I will be given another bucket of water from 0 to 100 litres
  • I have to fill buckets in order 10 first, 2 next and 50 last. Anything extra can be disposed.

How best can this be done with the least lines of code? while loop? ideas please.

A: 

If you don't want to generalize this problem to an arbitrary number of buckets with arbitrary capacities, then you don't need a loop at all:

Name the buckets a = 10, b = 2, c = 50 and d = 100 respectively. Subtract a from d, b from d and c from d while d is bigger than 0. That's all.

Stephan202
+1  A: 

I don't get it , Why can't you simply fill the buckets? Can you explain the problem better? I don't see the limitation , please explain the limitations , if there are any...

If there aren't limitation you can just use stephan202 answer

+3  A: 

Each time you fill a bucket of 10 liters, you will have 10 fewer liters in your source bucket.

Each time you fill a bucket of 2 liters, you will have 2 fewer liters in your source bucket.

Each time you fill a bucket of 50 liters, you will have 50 fewer liters in your source bucket.

Can we generalize this?

Each time you fill a bucket of N liters, you will have N fewer liters in your source bucket.

You can't have fewer than zero liters in your source bucket, so what you'll actually fill is the lesser of what's in the source bucket and what the capacity of the destination bucket is.

Since that's the amount you filled,

Each time you fill a bucket of N liters, you will have min(N, source_bucket_capacity) fewer liters in your source bucket.

While you have water in the source bucket, keep filling buckets. Stop when the source bucket is empty or you have no more destination buckets.

So

  • set up the source bucket.
  • set up a list of destination buckets.
  • while the source bucket is not empty and you have unfilled buckets in the destination list
    • get the next destination bucket.
    • fill it to min(N, source_bucket_capacity)
    • decrement the source bucket by min(N, source_bucket_capacity)
tpdi
A: 
<?php echo (($i = rand(1,100) - 62) > 0) ? $i : 0; ?>

The above code will output how much liters are left in a bucket randomly filled with 1-100 litres when it is poured into the total capacity of the other three buckets (62).

As the others have already pointed out, the way you posed your question reveals little about the actual problem that you are trying to solve. I doubt the solution above is what you are supposed to deliver. But since you only asked for the shortest solution, well, this is it. One line.

+5  A: 

Webber, this is professor Jenkins. See me in my office after you hand in this homework assignment on Monday.

gaoshan88