【问题标题】:Is there a way to get a unique hash code from an arry of colors?有没有办法从一组颜色中获取唯一的哈希码?
【发布时间】:2016-05-20 22:08:26
【问题描述】:

我正在尝试从一组颜色中获取唯一的哈希码。根据数组的设置方式,代码必须是唯一的。最终我想使用这个哈希码与另一个从另一个生成的哈希码进行比较(检查它们在同一个索引中是否具有相同的颜色)。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    public class Test
    {
        public Color[] GridMap { get; set; }

        private Color[] ColorSet
        {
            get
            {
                var colors = new[]
                {
                    Color.Aquamarine,
                    Color.Azure,
                    Color.Red,
                    Color.Blue
                };
                return colors;
            }
        }

        public Test()
        {
            GridMap = new Color[24];
            var random = new Random();
            for (int i = 0; i < GridMap.Length; i++)
            {
                GridMap[i] = ColorSet[random.Next(0,3)];
            }
        }

        public ulong GetUniqueCodeFromGridMap()
        {
            // Dont Know how to implement this yet !
            return 0;
        }

    }
}

【问题讨论】:

    标签: c# arrays hash compare unique


    【解决方案1】:

    一个简单的方法是使用Enumerable&lt;Color&gt;.SequenceEqual like

    bool b = colors1.SequenceEqual(colors2);
    

    如果你真的想创建一个哈希码,你可以写一个类似的代码

    var bytes = new Color[] { Color.Red, Color.Blue }
                    .Select(x => BitConverter.GetBytes(x.ToArgb()))
                    .SelectMany(x => x)
                    .ToArray();
    var hashCode = SHA256.Create().ComputeHash(bytes);
    

    现在你应该比较hashCodes....(你可以再次使用SequenceEqual

    【讨论】:

    • 非常感谢,我会尝试它们,只是为了检查它们是如何工作的,也许设置一个计时器来检查比较这些数组的最佳方法,但是第一种方法看起来更简单,更便宜比另一个。感谢您指出第一个解决方案!
    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2018-02-04
    • 2021-07-29
    相关资源
    最近更新 更多