I had a .NET C# job interview and one of the questions was "Initialize array of integers with values 1,2,3...100 WITHOUT a loop, without recursion and without initialization such as
int[] arr = new [] {1, 2, 3, ...100};
Is it possible?
I had a .NET C# job interview and one of the questions was "Initialize array of integers with values 1,2,3...100 WITHOUT a loop, without recursion and without initialization such as
int[] arr = new [] {1, 2, 3, ...100};
Is it possible?
One-Liner:
Enumerable.Range(1,100).ToArray();
C++ solution (sorry, never been in bed with C#) - side effect of some other operations.
struct foo {
static std::vector<int> bar;
// constructor
foo() {
bar.push_back(bar.size());
}
};
// C++ style of initialization of class/static variables
std::vector<int> foo::bar;
int main() {
do {
foo x[100]; // this initializes the foo::bar, goes out of scope and the memory
// is freed, but the side effects persist
} while(false);
std::cout << foo::bar.size() << std::endl; // yeap, 100
int* myArray=foo::bar.data();
// ^
// +--- use it before I change my mind and do...
foo::bar.clear();
foo y[200];
}
C# solution - not a cycle, no recursion, not initialization as such, a great method to take a break... uses event queuing provided by the framework/OS - of course one will never use something like this in practice but it is obeying the requirements to the letter (I'll talk about the spirit juuust a bit later). Also, may be ported on many languages, javascript included (see setinterval).
Now, excuse me for a moment, I need to uninstall Mono (and take a shot or two of some strong spirit to get over the trauma):
using System;
using System.Timers;
using System.Threading;
namespace foo
{
class MainClass
{
public static void Main (string[] args)
{
int[] a=new int[100];
a [99] = 0;
int count = 0;
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Interval = 36000; // so that we can have a beer by the time we have our array
tmr.Elapsed += async ( sender, e ) =>
{ if(count<a.Length) a[count]=count++; }
;
tmr.Start ();
while (a [99] < 99) {
Thread.Sleep (10);
}
foreach(int i in a) {
Console.WriteLine (i);
}
}
}
}