简体   繁体   English

有没有更好的方法将熵添加到整数数组?

[英]Is There A Better Way to Add Entropy to Array of Ints?

I needed to take an array of (C#) integers and randomly reassign values to make the values "feel" more randomized, without changing the length or sum of the array. 我需要采用一个(C#)整数数组并随机重新分配值,以使值“感觉”更加随机化,而不更改数组的长度或总和。 But this array can get quite large, so I'm wondering if anyone has a better way to do this. 但是这个数组会变得很大,所以我想知道是否有人有更好的方法来做到这一点。 Basically, the array initially contains values that are roughly the sum divided by the length, with one element having the remainder. 基本上,数组最初包含的值大约是总和除以长度,剩下一个元素。 What I am using now is: 我现在使用的是:

    static int[] AddEntropy(int[] ia)
    {

        int elements = ia.Length;
        int sum = ia.Sum();

        for (int runs = 0; runs < (elements * 2); runs++)
        {

            Random rnd = new Random(int.Parse(Guid.NewGuid().ToString().Substring(0, 8), System.Globalization.NumberStyles.HexNumber));
            int rndi = rnd.Next(0, (sum / elements));
            int rnde1 = rnd.Next(0, elements);
            int rnde2 = rnd.Next(0, elements);
            if (rndi < 1 ) rndi = 1;

            if (ia[rnde1] > (rndi + 2))
            {
                ia[rnde1] = ia[rnde1] - rndi;
                ia[rnde2] = ia[rnde2] + rndi;
            }

        }

        return ia;
    }

Any thoughts on making this perform better would be appreciated. 任何有关使此性能更好的想法将不胜感激。 It seems to perform "well", but if the array are larger than my sample of five elements (up to 1000 elements), and there are several arrays that may be modified in quick succession, a speedier option would be great. 它似乎执行得很好,但是如果数组比我的五个元素的样本大(最多1000个元素),并且有几个数组可以快速连续地修改,那么更快的选择将是不错的选择。

If I understood everything correctly the task requires the sum of the elements to be preserved. 如果我正确理解了所有任务,则该任务需要保留所有元素的总和。 Then there is no need in initial array elements values, the two thing that matter are the sum of the elements and the number of the elements. 这样就不需要初始数组元素的值,重要的两件事是元素的总和和元素的数目。

public static int[] GetArray(int sum, int n)
{
    if(sum < n)
        throw new ArgumentException("sum is lower than n");
    Random rnd = new Random();

    // reserve 1 for each of the elements
    sum -= n;

    // generate random weights for every element in sum
    int[] w = new int[n];
    int sw = 0;             
    for (int i = 0; i < n; i++)
    {
        w[i] = rnd.Next(0, 100);
        sw += w[i];
    }

    // generate element values based on their weights
    int[] result = new int[n];
    int tsum = 0;
    int psum = 0;
    for (int i = 0; i < n; i++)
    {
        tsum += w[i] * sum;
        result[i] = tsum / sw - psum;
        psum += result[i];
    }

    // restore reserved ones
    for (int i = 0; i < n; i++)
        result[i]++;

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM