Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created June 6, 2015 22:11
Show Gist options
  • Save VegaFromLyra/f5951a40e491db5eaea7 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/f5951a40e491db5eaea7 to your computer and use it in GitHub Desktop.
Bag of marbles
using System;
using System.Collections.Generic;
// Say you have a bag of marbles. The marbles can
// either be Yellow, Blue of Green.
// Implement Add, Get operations from this bag
// The 'Get' method should be a weighted random operation
// aka if there are more blue marbles then there should be
// a higher probability of picking a blue on
namespace BagOfMarbles
{
public class Program
{
public static void Main(string[] args)
{
Bag bag = new Bag();
addYellow(bag);
addBlue(bag);
addBlue(bag);
addYellow(bag);
addYellow(bag);
addGreen(bag);
addYellow(bag);
addYellow(bag);
addBlue(bag);
addGreen(bag);
pick(bag);
pick(bag);
pick(bag);
}
static void addYellow(Bag bag) {
Console.WriteLine("Adding Yellow");
bag.Add(MARBLE_COLOR.YELLOW);
}
static void addBlue(Bag bag) {
Console.WriteLine("Adding Blue");
bag.Add(MARBLE_COLOR.BLUE);
}
static void addGreen(Bag bag) {
Console.WriteLine("Adding Green");
bag.Add(MARBLE_COLOR.GREEN);
}
static void pick(Bag bag) {
var marble = bag.Get();
String color = String.Empty;
switch(marble) {
case MARBLE_COLOR.YELLOW:
color = "yellow";
break;
case MARBLE_COLOR.BLUE:
color = "blue";
break;
case MARBLE_COLOR.GREEN:
color = "green";
break;
}
Console.WriteLine("Picked up a {0} marble", color);
}
}
enum MARBLE_COLOR {
YELLOW,
BLUE,
GREEN
};
class Bag {
List<MARBLE_COLOR> marbles;
public Bag() {
marbles = new List<MARBLE_COLOR>();
}
public void Add(MARBLE_COLOR marble) {
marbles.Add(marble);
}
public MARBLE_COLOR Get() {
Random randomGenerator = new Random();
int index = randomGenerator.Next(marbles.Count);
var marble = marbles[index];
marbles.RemoveAt(index);
return marble;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment