Sunday, August 31, 2008

Write an algorithm to remove balls out of a box....

Q : Given a box with n number of balls. Write an algorithm to remove the balls from the box.

Answer :

public class Box
{
Ball[] balls;
int ballCount;
public Box(int ballCount)
{
this.ballCount = ballCount;
balls = new Ball[ballCount];
}
public bool RemoveBall()
{
if(0 < this.ballCount)
{
int deleteThis = Random() % this.ballCount;
for(int index = deleteThis; index < this.ballCount - 1; index++)
{
a[index] = a[index + 1];
}
this.ballCount--;
return true;
}
else
{
return false;
}
}
}

public class Ball
{
int id;
public Ball(int id)
{
this.id = id;
}
public int ID
{
get { return this.id; }
set { this.id = value; }
}
}
static void Main()
{
Box box = new Box(100);
while(true == box.RemoveBall());
}

Note : int rand(void) is the function used in C++ to generate random numbers…..which returns a psuedo-random integral number in the range of 0 to RAND_MAX ( ~ 32767 )
To generate any random number in the range of a to a+x ...
( ( Value % x ) + a ) where value is rand()

No comments: