2017-12-25 17 views
-12

C#言語でコードを作成します。(メソッド/関数) 呼び出し時に渡される数字を除いて、1 &の間のランダムな値を返します。。 。以下はランダム値を返します

// Definition 

private int rdm (int []) { 
    // need code 

    return int 
} 

//calling 

rdm(new int[] {3,5}) 

//output 
4 
Or 
2 
Or 
6 
Or 
1 

CodeOutput_1Output_2

+0

一つの言語を選択してください。 – coderredoc

+0

コードを書式化してコンパイル可能にしてください – Backs

+0

Fyi、ここをクリックしてください。https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx –

答えて

1

私はあなたが均一に分散値を望んでいることを提供する

private int rdm(int[] except) 
{ 
    var source = new List<int>() { 1, 2, 3, 4, 5, 6 }; 
    var i = new Random().Next(source.Count - except.Count()); 
    var result = source.Except(except).Skip(i).First(); 
    return result; 
} 
+0

ありがとう私の友人を大いに.. –

+0

あなたのコードは私の問題を解決する –

1

を行いたいものです。すべて(すなわち[1..6])のものからsubrract禁じられた値を試すことができます。

// Simplest, but not thread safe 
static Random s_Generator = new Random(); 

// static: you don;t want this in the method 
// IEnumerable<int> let's accept generic interface, not specific type (array) 
private static int rdm(IEnumerable<int> forbidden) { 
    int[] allowed = Enumerable       // Allowed values are 
    .Range(1, 6)          // [1..6] 
    .Except(forbidden == null ? new int[0] : forbidden) // except forbidden ones 
    .ToArray(); 

    //DONE: What if allowed is empty? E.g. forbidden = {1, 2, 3, 4, 5, 6}? 
    if (!allowed.Any()) 
    throw new ArgumentException("All possibilities are forbidden.", "forbidden"); 

    // We want random uniform distributed value from allowed 
    return allowed[s_Generator.Next(allowed.Length)]; 
} 

コール:

int result = rdm(new int[] {3, 5}); 
関連する問題