-1

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MGL
  • 33
  • 6
    `int arr[] = new int[100];arr[0]=1;arr[1]=2;arr[2]=3` ..... – Matteo Umili Dec 02 '16 at 11:11
  • 5
    This sounds like a horrible interview question, surely they'd want you to do it with a loop... – TheLethalCoder Dec 02 '16 at 11:12
  • 3
    @TheLethalCoder Next level: Can you write a C compiler with only your elbows. – Evan Trimboli Dec 02 '16 at 11:13
  • int arr[100] = {1, 2, 3, 4, 5, ......, 100}; – instance Dec 02 '16 at 11:16
  • 3
    Or something like: `int[] notTheArrayYouWantMeToInitialize = new[] {1,2,3...100}; int[] definitelyTheArrayYouWantMeToInitialize = notTheArrayYouWantMeToInitialize;` – Matteo Umili Dec 02 '16 at 11:18
  • Without loop you need write all values manually line by line(same as initialization examples). – Fabio Dec 02 '16 at 11:29
  • Seems weird to me. Every Linq-method will internally use a loop, so the only *true* alternative would be to set every single element manually as suggested by Matteo. Obviously again an interviewer that has no clue on internals of .NET-framework. – MakePeaceGreatAgain Dec 02 '16 at 11:54
  • The interviewer hinted me about creation of a new class and "think about the constructor". I concur = it's very weird, but this is exactly what I got. – MGL Dec 02 '16 at 13:12
  • Do you think my interviewer was on LSD and it is impossible? – MGL Dec 02 '16 at 13:14
  • 2
    Ugh, these are the kind of stupid interview questions that hire programmers that produce terrible code. There is no reason why you would ever want to hire someone who would even *consider* writing code to initialize an integer array by doing something *other* than looping. As others have said, even if you used LINQ, it would use a loop internally. There is such a thing as being too clever. Writing code that is obtuse generally goes hand-in-hand with writing code that is broken. You dodged a bullet there; try your hand in applying elsewhere. (Or so goes my way of thinking!) – Cody Gray - on strike Dec 02 '16 at 16:18

3 Answers3

10

One-Liner:

Enumerable.Range(1,100).ToArray();
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
1

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];
}
Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
  • In `C#` when you do `foo x[100];`, the elements are not automatically initialized with the default constructor, so you'll have an array with 100 null elements. (and no side effect). Still +1 because I like the idea – Matteo Umili Dec 02 '16 at 14:44
  • @MatteoUmili Not even when you allocate structs (values) and not references? I don't know enough C#, but what [I'm reading says otherwise](http://stackoverflow.com/a/29669763/620908). (yes, I know, the trick won't work as it is for Java, where all objects are 'by reference') – Adrian Colomitchi Dec 02 '16 at 14:55
  • In C# `Structs` cannot contain explicit parameterless constructors ([CS0568](https://msdn.microsoft.com/en-us/library/x2xcf8ft.aspx)) – Matteo Umili Dec 02 '16 at 15:02
0

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);
      }

    }
  }
}
Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
  • If you wrote this in an interview, and you got hired instead of laughed out of the room, the company is not one that you want to work for. There would not be enough spirits in the world to get you through your initial browsing of the code base. – Cody Gray - on strike Dec 02 '16 at 16:20
  • 1
    @CodyGray "the company is not one that you want to work for" this simple OP question is an enough sign I wouldn't like to work for them. To a stupid question, a stupid answer is the best answer. – Adrian Colomitchi Dec 02 '16 at 21:40