Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Related to Question at:
- //http://groups.google.com/group/dotnetdevelopment/browse_thread/thread/7e6a6815d8d855f9
- using System;
- using System.Threading;
- interface IFoo
- {
- void foo(int a, int b);
- }
- class Factory : IFoo
- {
- private enum Operation
- {
- add = 1,
- subtract = 2,
- multiply = 3,
- divide = 4,
- }
- private int _a, _b;
- private int randomSeed = 0;
- public virtual void foo(int a, int b)
- {
- this._a = a;
- this._b = b;
- Random rand = new Random(randomSeed);
- Operation op = (Operation)rand.Next(1, 5);
- switch (op)
- {
- case Operation.add:
- plus();
- break;
- case Operation.subtract:
- minus();
- break;
- case Operation.multiply:
- multiplier();
- break;
- case Operation.divide:
- dividor();
- break;
- }
- //if (rand.Next(4) % 4 == 0)
- // plus();
- //else if (rand.Next() % 4 == 1)
- // minus();
- //else if (rand.Next() % 4 == 2)
- // dividor();
- //else multiplier();
- }
- public void plus()
- {
- Console.WriteLine("{0}+{1}={2}", _a, _b, _a + _b);
- }
- public void minus()
- {
- Console.WriteLine("{0}-{1}={2}", _a, _b, _a - _b);
- }
- public void dividor()
- {
- Console.WriteLine("{0}/{1}={2}", _a, _b, _a / _b);
- }
- public void multiplier()
- {
- Console.WriteLine("{0}*{1}={2}", _a, _b, _a * _b);
- }
- public int RandomSeed
- {
- set { randomSeed = value; }
- }
- }
- class MainClass
- {
- static void Main(string[] args)
- {
- IFoo[] df = new IFoo[10];
- for (int i = 0; i < 10; i++)
- {
- Factory f = new Factory();
- // Uncomment only one of the below 3 approaches at a time:
- //SleepingWithRandom(ref f, i);
- LoopingRandom(ref f, i);
- //ComplementingRandom(ref f, i);
- df[i] = f;
- }
- }
- private static void SleepingWithRandom(ref Factory f, int i)
- {
- // Generate a seed from the current time and set the seed value of the Random to be created.
- f.RandomSeed = unchecked((int)(DateTime.Now.Ticks));
- f.foo(i + 1, i + 1);
- // Initiate a delay so as to increase randomness.
- Thread.Sleep(20);
- }
- private static void LoopingRandom(ref Factory f, int i)
- {
- // Generate a different seed using the loop variable itself.
- f.RandomSeed = i;
- f.foo(i + 1, i + 1);
- }
- private static void ComplementingRandom(ref Factory f, int i)
- {
- // Generate a different seed based on whether the loop variable is even or odd.
- if (i % 2 == 0)
- f.RandomSeed = ~unchecked((int)(DateTime.Now.Ticks));
- else
- f.RandomSeed = unchecked((int)(DateTime.Now.Ticks));
- f.foo(i + 1, i + 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment