1

The following is an exercise from my algorithms and datastructures course that aims to teach something about analysis of algorithms using loop-invariants.

The setup is the following; We have a jar with n marbles. A marble is either RED or BLUE. We also have an infinite pile of RED marbles. We aim to empty the jar by the use of this algorithm

The algorithm is as follows:

input: Jar with *n* marbles each of color RED or BLUE
i <- n
while i > 1 do
  Pick two arbitrary marbles m1, m2 from the jar.
  if Color(m1) == Color(m2) then
    Throw the two marbles away
    Place a RED marble in the jar
  end
  else
    Throw away the RED marble
    Put the BLUE marble back in the jar
  end
  i = i - 1
end

1) Argue that at the end of the algorithm we are left with 1 marble in the jar. My idea is here to say that we have a loop-invariant that is the following

At the beginning of an iteration of the while loop there are n-(n-i) marbles left

Then show that the invariant is true during Initialization, Maintenance and Termination however i am unsure as to how i should approach this could anyone help here?

E.g at initialization it is clear that the loop-invariant is the since we have n marbles in the jar and thus n-0 = n from the invariant but how should i approach the rest?

sn3jd3r
  • 496
  • 2
  • 18

1 Answers1

1

Since this is homework, I do not want to do the entire problem for you, but I can get you started in the right direction.

Let's start with the one of the easiest forms of the question: n = 2

Now there are 3 possibilities:

  1. 2 Red
  2. 2 Blue
  3. 1 Red and 1 Blue

Cases 1 and 2:

Pull both marbles out, they are the same color, so put discard both and pull a red marble from the pile and put it in the jar. There is one marble remaining in the jar so we stop.

Case 3:

Pull both marbles out, they are not the same color, so discard the red one and put the blue one back in. There is one marble remaining in the jar so we stop.

Now that the n = 2 is accounted for, prove that you can get to this state from 3, 4, 5 ... n marbles. For n = 1, obviously there will only be one marble in the jar because you will never enter the loop. I do not know what you want to do for n = 0, that would be the only case you can get the jar empty.

Jedi_Maseter_Sam
  • 753
  • 4
  • 24