2016-12-02 84 views
-2

我有一個.NET C#工作面試,其中一個問題是「初始化整數數組1,2,3,沒有循環,沒有遞歸和沒有初始化作爲初始化一個數組的成員沒有一個循環

int[] arr = new [] {1, 2, 3, ...100}; 

是否有可能

+6

'詮釋ARR [] =新INT [ 100]; arr [0] = 1; arr [1] = 2; arr [2] = 3' ..... –

+5

這聽起來像一個可怕的面試問題,肯定他們會希望你用循環... – TheLethalCoder

+3

@TheLethalCoder下一關:你可以用只有你的手肘編寫一個C編譯器。 –

回答

10

一行代碼:?

Enumerable.Range(1,100).ToArray(); 
+0

我在術語方面有點差,所以如果我在說一些白癡,請原諒我:這是一個初始化,還是隻做一項任務? –

+0

它返回一個數組,你需要分配給你的變量 – cokceken

+1

@MatteoUmili當然,爲什麼不呢?你當然可以把'int [] array ='放在它的前面,使它更加明顯。 –

1

C++解決方案(對不起,從來沒有在牀上,用C#) - 一些其他操作的副作用

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]; 
} 
+0

在'C#'中,當你執行'foo x [100];'時,元素不會被默認的構造函數自動初始化,所以你將擁有一個包含100個空元素的數組。 (並且沒有副作用)。仍+1,因爲我喜歡這個想法 –

+0

@MatteoUmili即使你分配結構(值)而不是引用?我不知道C#足夠,但是[我正在讀的其他內容](http://stackoverflow.com/a/29669763/620908)。 (是的,我知道,這個技巧不會像Java那樣工作,因爲所有對象都是通過引用的方式) –

+0

在C#中'Structs'不能包含顯式無參數構造函數([CS0568](https://msdn.microsoft.com/) .com/en-us/library/x2xcf8ft.aspx)) –

0

C#的解決方案 - 而不是一個循環,沒有遞歸,未初始化因爲如此,休息一會...一個偉大的方法使用事件由框架/ OS提供排隊 - 當然,人們永遠不會使用類似這在練習,但它是服從信的要求(我會談論精神juuust稍後)。此外,可能會移植到多種語言,包括javascript(請參閱setinterval)。現在

,原諒我一會兒,我需要卸載單(並採取了一些強有力的精神或兩杆拿到過創傷):

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

    } 
    } 
} 
+0

如果你在一次採訪中寫到這件事,而你被僱用而不是從房間裏笑出來,那麼公司就不是你想要的工作。世界上沒有足夠的精神讓你通過你最初的代碼庫瀏覽。 –

+1

@CodyGray「公司不是你想要工作的公司」這個簡單的OP問題是一個足夠的標誌,我不想爲他們工作。對於一個愚蠢的問題,一個愚蠢的答案是最好的答案。 –

相關問題