I am just a beginner in the world of programming, thus I have a simple question. Is it possible to randomly execute functions? If so, how would you do it? It is just a curiosity based on a thread I've read in another forum. Basically, the discussion was on how to generate random events for a game, and they commented about a "hack" used in some languages (especially AS3). The hack is to treat functions as variables. Example:
//Make an array of the functions
public function makeEarthquake():void{}
public function causePlague():void{}
public function spaceZombieAttack():void{}
//select at random
var selection:uint = Math.random() * eventArrray.length;
//Call it
eventArray[selection]();
I hope this is clear. I will be happy with any answer that can explain how to randomly call methods. Thank you.
EDIT: Thank you guys, all the answers were helpful!!!
It's certainly possible. A direct way is to have a list or array of delegates:
In C# it looks like this: (In a basic console app)
class Program
{
// Create the functions:
static void Beep()
{
Console.Beep();
}
static void SayHello()
{
Console.WriteLine("Hello!");
}
// Create the function delegate:
private delegate void RandomFunction();
static void Main(string[] args)
{
// Create a list of these delegates:
List<RandomFunction> functions = new List<RandomFunction>();
// Add the functions to the list:
functions.Add(Beep);
functions.Add(SayHello);
// Make our randomizer:
Random rand = new Random();
// Call one:
functions[rand.Next(0, 2)](); // Random number either 0 or 1
// This is just here to stop the program
// from closing straight away should it say "Hello"
Console.ReadKey();
}
}
Getting these functions to have varying numbers of parameters takes a bit more effort, though.
You can have a List<Action> and randomly select from it.
class Program
{
static void Main(string[] args)
{
List<Action> actions = new List<Action>();
actions.Add(() => Program.MakeEarthquake());
actions.Add(() => Program.CausePlague());
actions.Add(() => Program.SpaceZombieAttack());
Random random = new Random();
int selectedAction = random.Next(0, actions.Count());
actions[selectedAction].Invoke();
}
static void MakeEarthquake()
{
Console.WriteLine("Earthquake");
}
static void CausePlague()
{
Console.WriteLine("Plague");
}
static void SpaceZombieAttack()
{
Console.WriteLine("Zombie attack");
}
}
You can create list of actions then choosing one the items inside the list randomly like below code
List<Action> actions = new List<Action>();
actions.Add(() => makeEarthquake());
actions.Add(() => causePlague());
actions.Add(() => spaceZombieAttack());
var random=new Random();
int rndNumber = random.Next(actions.Count);
actions[rndNumber].Invoke();
Why don't you pick a random number like usual, then use that number within a common function which in turn calls a function based on what you got?
public void DoRandomThing()
{
switch(new Random().Next(1,4))
{
case 1:
makeEarthquake();
break;
case 2:
causePlague();
break;
case 3:
spaceZombieAttack();
break;
}
}
Related
I have been reading some C# interview questions and found a permutation of a popular one about delegates the code of which puzzles me.
The question was:
Predict the output of the code below.
delegate void Iterator();
static void Main(string[] args)
{
List<Iterator> iterators = new List<Iterator>();
for (int i = 0; i < 15; i++)
{
iterators.Add(delegate { Console.WriteLine(i); });
}
foreach (var iterator in iterators)
{
iterator();
}
Console.Read();
}
The normal version of this question I've seen declares the i variable before the for loop, thus making it method-wide and from there it's easy to see why the output is "15" 15 times.
However when I debugged the code the i variable is out of scope in the foreach loop and does not exist, anymore. Yet, when I step into the iterator() method it exists for the Console.WriteLine(i) line.
This I cannot understand.
The compiler translates your code to the following code, this is why i variable is not out of scope.
private delegate void Iterator();
[CompilerGenerated]
private sealed class CompGenCls
{
public int i;
internal void CompGenFunc()
{
Console.WriteLine(i);
}
}
private static void Main(string[] args)
{
List<Iterator> iterators = new List<Iterator>();
CompGenCls obj = new CompGenCls();
obj.i = 0;
for (; obj.i < 15; obj.i++)
{
iterators.Add(obj.CompGenFunc);
}
foreach (Iterator item in iterators)
{
item();
}
Console.Read();
}
To put it very simply, closures allow you to encapsulate some
behaviour, pass it around like any other object, and still have access
to the context in which they were first declared. This allows you to
separate out control structures, logical operators etc from the
details of how they're going to be used. The ability to access the
original context is what separates closures from normal objects,
although closure implementations typically achieve this using normal
objects and compiler trickery.
In your example you've only actually declared a single i variable -
so that same i variable is captured by all the Action instances. The
result is the number 15 being printed on every line. o "fix" the code
to make it display the output most people would expect (i.e. 0 to 14)
we need to introduce an extra variable inside the loop:
delegate void Iterator();
static void Main(string[] args)
{
List<Iterator> iterators = new List<Iterator>();
for (int i = 0; i < 15; i++)
{
int copy = i;
iterators.Add(delegate { Console.WriteLine(copy); });
}
foreach (var iterator in iterators)
{
iterator();
}
Console.Read();
}
Each time we go through the loop we're said to get a different
instance of the copy variable - each Action captures a different
variable. This makes perfect sense if you look at what the compiler's
actually doing behind the scenes, but initially it flies in the face
of the intuition of most developers (including me).
via
I'm fairly new to C# and trying to figure out how to invoke a function from a list. I thought that List would do the job I need it to. I can get my functions into the list, but I can't seem to actually invoke them.
First I tried this:
List<Action> randEvent = new List<Action>();
void Test()
{
randEvent.Add(Test2);
Invoke(randEvent(0), 0f);
}
void Test2()
{
print("This is a test of the random event system");
}
Then this
List<Action> randEvent = new List<Action>();
void Test()
{
randEvent.Add(Test2);
randEvent(0);
}
void Test2()
{
print("This is a test of the random event system");
}
But neither works. What am I doing wrong? Is this even possible? The reason I want to do it this way is basically that I have 100 functions that I want my program to chose through at random when I call another function.
Any solution appreciated, though keep in mind I'm very new to C# and code in general still. Thanks in advance.
In C#/.NET, different method signatures have different delegate types that represent them. Action represents functions that take no arguments and return no value, like void Foo(). If the functions you want to represent take a float parameter and return nothing, you would need to use Action<float>. Functions with return values are represented with the Func family of types (Func<T>, Func<T1, T2>...).
You can only put one kind of delegate in a List<T>, so you can't mix Actions and Action<float>s.
To get an item out of a list in C#, use [n]. Like
List<Action> actions = new List<Action>();
actions.Add(Foo);
Action a = actions[0];
To invoke a delegate instance in C#, call the Invoke method on it, or just use () which is shorthand for calling Invoke. For Action, Invoke takes 0 parameters, for Action<T> it takes a single T parameter, etc.
So for your whole example:
List<Action> actions = new List<Action>();
void Test()
{
actions.Add(PrintStuff);
actions[0]();
//or
actions[0].Invoke();
//or
foreach (var a in actions) a();
}
void PrintStuff()
{
print("This is a test of the random event system");
}
You could declare sort of a list of Action and each object will point to a specific method. Example;
IList<Action> actionList = new List<Action>();
actionList.Add(() => Test2());
Then you can loop through the list and Invoke each method.
foreach(var method in actionList)
{
method.Invoke();
}
I'm assuming randEvent is a List<EventHandler> or List<Action<Int32>>.
Use Delegate.Invoke( args ) (as EventHandler and Action<T> are both Delegate sub-types).
randEvent[0].Invoke( 123 );
In C#, you can use () on a Delegate directly too:
randEvent[0]( 123 );
I want to have a static (global) pool of calculators which are going to be accessed by a lot of different threads.
After some researching I found out that the elements of Arrays are threadsafe.
I thought that it would be good idea to store the diffrent calculators (amount unknown until runtime) in a static array (calculator[] calculators).
How do I ensure that only one calculator is being used by one calculator?
I read the whole msdn documentation so don't post "only" links please.
I have also thought about a bool array "locked" but I can't find a way to implement this threadsafe.
My code so far:
internal static class Calculators
{
private static Semaphore pool;
private static bool[] locked;
private static calcs[] neuralNetworks;
private static Thread[] threads;
internal static Calculators(){
int number = Globals.Number;
pool = new Semaphore(number, number);
locked = new bool[number];
calcs = new calcs[number];
threads = new Thread[number];
for (int index = 0; index < number; index++)
{
// all neuralNetworks are unlocked by default
locked[index] = false;
// generate one network per "countThreads"
calcs[index] = Globals.CalcObj;
// generate one thread for each neural network
threads[index] = new Thread(new ThreadStart());
}
}
private int WhichCalculators()
{
int index;
for (index = 0; index < countThreads; index++)
{
if (locked[index] == false)
{
locked[index] = true;
return index;
}
}
throw new Exception("Calculators was called, but there weren't any networks unused");
}
}
Code Update:
So should it work, if I call "WhichCalculator()" in this method?
private static void doStuff()
{
pool.WaitOne();
Monitor.Enter(thisLock);
try
{
int whichCalculator = WhichCalculator();
locked[whichCalculator] = true;
lock (calculators[whichCalculator])
{
Monitor.Exit(thisLock);
// do stuff
locked[whichCalculator] = false;
}
}
catch
{
Monitor.Exit(thisLock);
}
//Calculate();
pool.Release();
}
Question 2:
Am I right to assume, that the static constructor is going to be executed as soon as (but before) the first time this class or any member of it is going to be accessed?
Yes you have to use lock. But the array and every instance of calculator again.
If you can fill the array before you start the multithreaded section of your code you need not lock the array as well (only reading doesn't make problems due to the static content) but with resizing the array you need to lock every access to it (writing AND reading).
So your code could look like this:
Calculator calc = null;
lock(calculators)
{
calc = calculators[0];
}
lock(calc)
{
// ... do stuff
}
This way the array isn't longer locked then needed and you can lock the calculator itself.
You can lock your array. That would ensure that every array-operation is executed thread-safe.
To ensure, that each object is only used once at a time you can add a flag to it, like calculator.InUse. If you can't add a flag to the class, you can use an extension method.
I've seen countless posts on how variable capture pulls in variables for the creation of the closure, however they all seem to stop short of specific details and call the whole thing "compiler magic".
I'm looking for a clear-cut explanation of:
How local variables are actually captured.
The difference (if any) between capturing value types vs. reference types.
And whether there is any boxing occurring with respect to value types.
My preference would be for an answer in terms of values and pointers (closer to the heart of what happens internally), though I will accept a clear answer involving values and references as well.
Is tricky. Will come onto it in a minute.
There's no difference - in both cases, it's the variable itself which is captured.
Nope, no boxing occurs.
It's probably easiest to demonstrate how the capturing works via an example...
Here's some code using a lambda expression which captures a single variable:
using System;
class Test
{
static void Main()
{
Action action = CreateShowAndIncrementAction();
action();
action();
}
static Action CreateShowAndIncrementAction()
{
Random rng = new Random();
int counter = rng.Next(10);
Console.WriteLine("Initial value for counter: {0}", counter);
return () =>
{
Console.WriteLine(counter);
counter++;
};
}
}
Now here's what the compiler's doing for you - except that it would use "unspeakable" names which couldn't really occur in C#.
using System;
class Test
{
static void Main()
{
Action action = CreateShowAndIncrementAction();
action();
action();
}
static Action CreateShowAndIncrementAction()
{
ActionHelper helper = new ActionHelper();
Random rng = new Random();
helper.counter = rng.Next(10);
Console.WriteLine("Initial value for counter: {0}", helper.counter);
// Converts method group to a delegate, whose target will be a
// reference to the instance of ActionHelper
return helper.DoAction;
}
class ActionHelper
{
// Just for simplicity, make it public. I don't know if the
// C# compiler really does.
public int counter;
public void DoAction()
{
Console.WriteLine(counter);
counter++;
}
}
}
If you capture variables declared in a loop, you'd end up with a new instance of ActionHelper for each iteration of the loop - so you'd effectively capture different "instances" of the variables.
It gets more complicated when you capture variables from different scopes... let me know if you really want that sort of level of detail, or you could just write some code, decompile it in Reflector and follow it through :)
Note how:
There's no boxing involved
There are no pointers involved, or any other unsafe code
EDIT: Here's an example of two delegates sharing a variable. One delegate shows the current value of counter, the other increments it:
using System;
class Program
{
static void Main(string[] args)
{
var tuple = CreateShowAndIncrementActions();
var show = tuple.Item1;
var increment = tuple.Item2;
show(); // Prints 0
show(); // Still prints 0
increment();
show(); // Now prints 1
}
static Tuple<Action, Action> CreateShowAndIncrementActions()
{
int counter = 0;
Action show = () => { Console.WriteLine(counter); };
Action increment = () => { counter++; };
return Tuple.Create(show, increment);
}
}
... and the expansion:
using System;
class Program
{
static void Main(string[] args)
{
var tuple = CreateShowAndIncrementActions();
var show = tuple.Item1;
var increment = tuple.Item2;
show(); // Prints 0
show(); // Still prints 0
increment();
show(); // Now prints 1
}
static Tuple<Action, Action> CreateShowAndIncrementActions()
{
ActionHelper helper = new ActionHelper();
helper.counter = 0;
Action show = helper.Show;
Action increment = helper.Increment;
return Tuple.Create(show, increment);
}
class ActionHelper
{
public int counter;
public void Show()
{
Console.WriteLine(counter);
}
public void Increment()
{
counter++;
}
}
}
I am generally not very fond of refactoring tools. No need to get into details. Still, I occasionally try out new versions. Here is what I was trying to do while evaluating resharper 4.5 :
I needed to replace all usages of a method with a wrapper method (to be created) but I could not. I usually suck at noticing an obvious feature, is this the case? If resharper does not have this feature, do you know such tools?
Edit 2: Sample has been improved to include instance method calls.
Edit:
Here is a simple case to play.
static void Main(string[] args)
{
while(true)
{
if (Console.ReadKey().Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
Console.Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Console.Beep(250, 150);
return false;
}
return true;
}
What I need is something like: (Edit2: added an instance sample)
private static StringBuilder _builder = new StringBuilder();
static void Main(string[] args)
{
while(true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
_builder.Append(" (").Append(key.KeyChar).Append(") ");
Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Beep(250, 150);
_builder.Append('#');
return false;
}
return true;
}
static void Beep(int frequency, int duration)
{
// finally cursor ends up here
Console.Beep(250, 50);
}
Console.Beep calls are refactored. Next lets refactor StringBuilder.Append(char) :
class Program
{
private static StringBuilder _builder = new StringBuilder();
static void Main(string[] args)
{
while(true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
_builder.Append(" (").AppendUpper(key.KeyChar).Append(") ");
Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Beep(250, 150);
_builder.AppendUpper('n');
return false;
}
return true;
}
static void Beep(int frequency, int duration)
{
// finally cursor ends up here
Console.Beep(250, 50);
}
}
static class StringBuilderExtensions
{
public static StringBuilder AppendUpper(this StringBuilder builder, char c)
{
return builder.Append(char.ToUpper(c));
}
}
Selecting from usages and maybe omitting common parameters (such as 250 above) or common instance parameters for non-extension statics shall make this feature more valuable. Hopefully, this clears up the question.
ReSharper doesn't have this as a single refactoring. I might do it as follows:
Select the contents of the method to be wrapped, and use Extract Method to create a new private method from the contents.
The original method is now a trivial wrapper around "itself". Rename it if you like, or manipulate it as you like (make it static, move to a different class, surround with try/catch, whatever).
EDIT:
Based on your edit, it seems you have an additional problem. Not only is Console.Beep not in the same class, it's not even in your class.
But if you don't mind a little search and replace, then you can put it into your own class, then proceed with the refactoring:
namespace Temporary {
public class Console {
public static void Beep(int x, int y) {System.Console.Beep(x,y);}
}
}
Then do a "Replace in Files" to replace Console.Beep with Temporary.Console.Beep, and proceed as above.
It's not included in any .NET refactoring IIRC, the tool which has such a refactoring is Eclipse, but not for .NET/C#
Assuming the wrapper method will be in the same class you can rename the current method to the name of the new wrapper method (ctrl+R+R in Resharper). This will rename all calls to this method in the solution as well. Then rename the original method back by hand (don't use Resharper or all the calls will get renamed back too) and add the wrapper method.
Based on your edit I think you will be out of luck to get the functionality that you want from any Visual Studio add-in that I've seen (beyond the simple find and replace which will get you some of the way there I guess).
Depending on how much time and effort you are willing to devote to this I'd imagine it's possible to use the DXCore framework and write a plugin that will do this kind of refactoring.
Resharper has a Search and Replace with Pattern feature. It can search and replace on patterns and expressions.
This would refactor all calls to Console.Beep() to your own method. It only replaces the usage if 250 is the first parameter:
However this would replace the usage of Console.Beep() within your own Beep method. You would have to manually replace that one usage.