c# - 根据位置为列表中的数字分配颜色

标签 c# arrays list

<分区>

所以在这里我需要一个数组来填充 1 到 100 之间的数字。 然后他们还需要随机化。

现在我尝试为列表中的每个项目分配颜色、红色、黄色和白色。这是基于数组中的位置,1=红色、2=黄色、3=白色,并且需要在整个数组中重复(4=红色、5=黄色等)

我在尝试找到执行此操作的方法时遇到了麻烦。

我研究了多维数组,但我不太确定它是否会按我需要的方式工作。我还认为也许 for 循环可以实现这一点。

或者我是否需要使用不同的枚举来为数组中的数字分配其他值。

class Program
{
    static void Main(string[] args)
    {
        int[] x = new int[101];
        Random r = new Random();

        int i;
        for (i = 0; i < x.Length; i++)
        {
            var next = 0;
            while (true)
            {
                next = r.Next(101);
                if (!Contains(x, next)) break;
            }

            x[i] = next;
            Console.WriteLine("x[{0}] = {1}", i, x[i]);
        }

        Console.ReadLine();
    }

    static bool Contains(int[] array, int value)
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] == value) return true;
        }
        return false;
        }
    }
}

最佳答案

您不需要生成随机数 - 只需生成 1 到 100 的数字并将它们洗牌即可。这比生成数百个随机数并丢弃许多随机数要快得多(尤其是在最后你通过随机变化“抽取”了很多已经存在的随机数并且不使用它们)。

我通过生成 100 个 Guid 使用穷人洗牌,获取它们的 HashCode 并排序生成的 他们的数字 - 我认为这已经足够半随机了。

我通过生成映射每个生成的数字(按顺序)的字典解决了颜色映射 到表示为枚举值的颜色。当前枚举值通过我在每次赋值后调用的静态扩展方法进行移动。

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

public enum Col { Red, Yellow, White }

public static class ColExtension
{
    // Poor mans wrap around iterator for this enum: Red -> Yellow -> White -> Red ...
    public static Col Next(this Col col)
    {
        if (col == Col.Red)
            return Col.Yellow;
        if (col == Col.Yellow)
            return Col.White;
        return Col.Red;
    }
}

internal class Program
{
    public static void Main(string[] args)
    { 
        // create numbers ranging from 1 to 100. Pseudo-randomize order by ordering 
        // after randomized generated value
        var numbers = Enumerable
          .Range(1, 100).OrderBy(n => Guid.NewGuid().GetHashCode())
          .ToArray();

        // start-color for the first one
        var aktCol = Col.Red;
        var mapping = new Dictionary<int, Col>();
        foreach (var number in numbers)
        {
            // assign first color
            mapping[number] = aktCol;
            // advance color 
            aktCol = aktCol.Next(); 
        }

        foreach (var num in numbers)
            Console.WriteLine($"{num}, {mapping[num]}");

        Console.ReadLine();
    }
}

输出:

66, Red
24, Yellow
36, White
17, Red
86, Yellow
58, White
44, Red
27, Yellow
47, White
91, Red
15, Yellow
31, White
18, Red
25, Yellow
3, White
64, Red
32, Yellow
41, White
67, Red
11, Yellow
72, White
43, Red
9, Yellow
42, White
84, Red
23, Yellow
95, White
14, Red
59, Yellow
22, White
2, Red
76, Yellow
81, White
57, Red
19, Yellow
49, White
80, Red
55, Yellow
13, White
98, Red
1, Yellow
51, White
12, Red
90, Yellow
37, White
65, Red
26, Yellow
83, White
82, Red
61, Yellow
56, White
99, Red
78, Yellow
38, White
71, Red
40, Yellow
29, White
34, Red
93, Yellow
85, White
96, Red
39, Yellow
100, White
33, Red
74, Yellow
87, White
75, Red
92, Yellow
5, White
79, Red
60, Yellow
30, White
77, Red
4, Yellow
70, White
50, Red
16, Yellow
97, White
94, Red
63, Yellow
10, White
7, Red
73, Yellow
46, White
28, Red
45, Yellow
88, White
69, Red
62, Yellow
53, White
54, Red
89, Yellow
8, White
68, Red
20, Yellow
6, White
21, Red
48, Yellow
35, White
52, Red

本质上,您有一个根据数字和数字数组快速查找颜色的字典。我会切换到列表 - 但那是偏好 - 你可能有理由使用数组。


如果您想避免显式存储颜色值,您还可以利用 linq and Select 来“即时”转换位置使用提供值及其索引的重载:

    // local converter function - %3 gets the rest of div by 3 so 0=red, 1=yellow,...
    // the %3 makes it wrap around and the enum parse converts it to the enum
    Col ByIndexPos(int pos) => (Col)Enum.Parse(typeof(Col), $"{pos % 3}");

    // On the fly color creation from index position:
    foreach (var anon in numbers.Select( (v, pos) => 
        new { Color = ByIndexPos(pos), Value = v })
    )
        Console.WriteLine($"{anon.Value}, {anon.Color}");

如果您修改基本数组,第二种方法会改变颜色 - 所以如果您需要它们保持连接,您可以使用字典方法。


编辑阅读部分问题评论后:

如果您需要对您的数据进行后处理,您应该创建一个 POCO(结构/类)来保存:数字、位置、颜色和您以后排序/操作所需的任何其他属性以及操作此数据的方法 - OOP 到救援:)

关于c# - 根据位置为列表中的数字分配颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49659068/

相关文章:

java - 使用扫描器 hasNext() 循环 while

python - 如何将包含列表列表的文件转换为字符串?

python-3.x - 根据输入整数查找 Python List 的子集 List

c++ - 如何在 C++ 中将字符串拆分为字符数组?

java - 获取列表中出现多个的值?

c# - 调试 asp.net mvc 应用程序时出现 "Source information is missing from the debug information for this module"

c# - 带有 DapperExtensions 的谓词

c# - 如何从 github 运行 ASP.NET web api

javascript - 尝试让一个 iframe 在另一个 iframe 之前加载

c - 为什么不能将 c 指针视为数组?