【问题标题】:How to create single dimensional, two dimensional,three dimensional as well as multi dimensional array using C#?如何使用 C# 创建一维、二维、三维以及多维数组?
【发布时间】:2016-04-20 19:29:03
【问题描述】:

我试图将 1、2、3、4、5 的所有组合(5C1、5C2、5C3、5C4、5C5)保存到单独的数组中。所以我需要在 c# 中使用 for 循环创建动态数组。

比如说, 这里 n = 5 和 r = 1 到 5。 如果 r = 1 那么 我的数组将是一维数组,当 r = 2 时,它将是二维数组,当 r = 3 时,然后是三维,当 r = 4 时,然后是四维数组,它将一直持续到 5 的末尾。 我的代码如下所示

string[] ShipArrayObj;
  public frmResult( string[] ShipArray )
    {
        InitializeComponent();           
        ShipArrayObj = ShipArray;
    }

    private void frmResult_Load(object sender, EventArgs e)
    {
        string[] arr = ShipArrayObj;           
        int n = ShipArrayObj.Count();
        for (int r = 1; r <= n; r++)
        {                
            StoreCombination(arr, n, r);
            richTextBox1.Text = richTextBox1.Text + "/";                
        }

    }

    void StoreCombination(string[] arr, int n, int r)
    {           
        string[] data = new string[r];            
        createCombination (arr, data, 0, n - 1, 0, r);
    }


   private void createCombination(string[] arr, string[] data, int start, int end, int index, int r)
    {
        if (index == r)
        {
            int j = 0;
            for (j = 0; j < r; j++)
             richTextBox1.Text = richTextBox1.Text + data[j].ToString();//Where I want to set array to keep combination values
             return;
        }

        int i = 0;
        for (i = start; i <= end && end - i + 1 >= r - index; i++)
        {
            data[index] = arr[i];
            CreateCombination(arr, data, i + 1, end, index + 1, r);
        }
    }

我将所有组合存储到富文本框中,但想保留在数组中。如果有人帮助我,我将不胜感激。

【问题讨论】:

    标签: c# arrays combinations


    【解决方案1】:

    如果您习惯于 Java 之类的东西,那么多维数组在 C# 中的语法会有些不同。

    Here's a page describing how to do them in C#.这是来自该页面的sn-p:

    // Two-dimensional array.
    int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    // The same array with dimensions specified.
    int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    // A similar array with string elements.
    string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                            { "five", "six" } };
    
    // Three-dimensional array.
    int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                     { { 7, 8, 9 }, { 10, 11, 12 } } };
    // The same array with dimensions specified.
    int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                           { { 7, 8, 9 }, { 10, 11, 12 } } };
    

    If you're interested in different combinations of things with a fixed number of them, something like this should be all you need.

    If you're interested in different combinations of things with a dynamic number of them, something like this should be all you need.

    (除非你试图优化性能,一般来说,可读性/表达性会更好。)

    您可能需要考虑顺序是否重要(无序集与有序列表)。我会假设它不是来自您的代码(在这种情况下,排序可以很好地消除“重复”),但我无法确定。


    这是一个很好的例子,它易于阅读和修改变化,对于小数字也不错:

    // -1, 0, ..., 5
    var choices = Enumerable.Range(-1, 6); 
    
    var possibleChoices = 
        from a in choices
        from b in choices
        from c in choices
        from d in choices
        from e in choices
        select (IEnumerable<int>)new [] { a, b, c, d, e };
    
    // Remove -1's because they represent not being in the choice.
    possibleChoices =
        possibleChoices.Select(c => c.Where(d => d >= 0));
    
    // Remove choices that have non-unique digits.
    possibleChoices =
        possibleChoices.Where(c => c.Distinct().Count() == c.Count());
    
    // Sort the choices to indicate order doesn't matter
    possibleChoices =
        possibleChoices.Select(c => c.OrderBy(d => d));
    
    // Remove duplicates
    possibleChoices = 
        possibleChoices.Select(c => new 
                               {
                                   Key = string.Join(",", c),
                                   Choice = c
                               }).
        GroupBy(c => c.Key).
        Select(g => g.FirstOrDefault().Choice);
    
    foreach (var choice in possibleChoices) {
        Console.Out.WriteLine(string.Join(", ", choice));
    }
    

    输出:

    0
    1
    2
    3
    4
    0, 1
    0, 2
    0, 3
    0, 4
    1, 2
    1, 3
    1, 4
    2, 3
    2, 4
    3, 4
    0, 1, 2
    0, 1, 3
    0, 1, 4
    0, 2, 3
    0, 2, 4
    0, 3, 4
    1, 2, 3
    1, 2, 4
    1, 3, 4
    2, 3, 4
    0, 1, 2, 3
    0, 1, 2, 4
    0, 1, 3, 4
    0, 2, 3, 4
    1, 2, 3, 4
    0, 1, 2, 3, 4
    

    这可能更容易理解,硬编码到这种特定的组合变体并涉及递归,但更通用/没有硬编码为5(并在dotnetfiddle上采用0.047s .net 而不是 0.094s)。也完全是懒惰的/IEnumerable

    public static void Main()
    {       
        var possibleChoices = Choose(5);
    
        foreach (var choice in possibleChoices) {
            Console.Out.WriteLine(string.Join(", ", choice));
        }
    }
    
    public static IEnumerable<IEnumerable<int>> Choose(int max) 
    {       
        var remaining = Enumerable.Range(0, max); 
    
        return ChooseRecursive(remaining, Enumerable.Empty<int>());
    }
    
    public static IEnumerable<IEnumerable<int>> ChooseRecursive(IEnumerable<int> remaining, IEnumerable<int> chosen) 
    {       
        yield return chosen;
    
        foreach (var digit in remaining) 
        {
            var choices = ChooseRecursive(
                remaining.Where(d => d > digit), 
                chosen.Concat(new [] { digit })
            );
            foreach (var choice in choices)
            {                   
                yield return choice;
            }
        }
    }
    

    输出:

    0
    0, 1
    0, 1, 2
    0, 1, 2, 3
    0, 1, 2, 3, 4
    0, 1, 2, 4
    0, 1, 3
    0, 1, 3, 4
    0, 1, 4
    0, 2
    0, 2, 3
    0, 2, 3, 4
    0, 2, 4
    0, 3
    0, 3, 4
    0, 4
    1
    1, 2
    1, 2, 3
    1, 2, 3, 4
    1, 2, 4
    1, 3
    1, 3, 4
    1, 4
    2
    2, 3
    2, 3, 4
    2, 4
    3
    3, 4
    4
    

    【讨论】:

    • 你给定的输出没问题。从此列表中,我想通过使用循环或其他方式选择随机值行,以便我可以将这些值用于操作。如果可以,请给个方法,我怎样才能将这些值保存到数组或列表中? @WLJ
    • @PritamJyotiRay 在 IEnumerable 上调用 ToArray(),然后在随机索引处选择一个。如果您需要多次执行此操作,请为每个唯一整数缓存 ToArray 调用。如果要循环,则创建一个数据结构,该结构会随机播放,然后连续返回每个项目,直到它遍历每个项目,在这种情况下,它会重新随机播放。如果您想要一个实现,请提出一个新问题:)
    猜你喜欢
    • 2016-12-27
    • 2017-07-07
    • 2020-07-25
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多