数组包含性能 [英] Array Contains Performance

查看:156
本文介绍了数组包含性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与数组配合使用的程序,有时我必须检查数组中是否包含值的lsit,执行此操作的函数大约占用程序CPU时间的70%,所以我想知道是否有一种更有效地执行此操作的方法.

I have a program which works with arrays and at some point I have to check if a lsit of values are inside an array, the function that does this takes about 70% of the program CPU time, so I was wondering if there's a way to do this more efficiently.

这些是我的功能:

private static int[] GenerateRow(int length, Random RNG)
    {
        int[] row = InitalizeRow(length);
        int index = 0;
        while (!AreAllNumbersGenerated(row))
        {
            int value = RNG.Next(0, length);
            if (!RowContains(row, value))
            {
                row[index] = value;
                index++;
            }
        }
        return row;
    }  

    private static bool AreAllNumbersGenerated(int[] row)
    {           
        for (int i = 0; i < row.Length; i++)            
           if(!RowContains(row, i))
                return false;           
        return true;
    }

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

所有工作都是通过AreAllNumbersGenerated(),然后是RowContains(),最后是这一行:

All the work is by AreAllNumbersGenerated(), then by RowContains() and finally by this line:

if (row[i] == value)

此功能大部分时间都是正常的,因为它们需要大量的工作,但我想知道是否有更好的方法可以做到这一点.

That this functions take most of the time is normal, since they do heavy work, but I wanted to know if there's a better way to do this.

   private static int[] InitalizeRow(int length)
    {
        int[] row = new int[length];
        for (int i = 0; i < length; i++)
            row[i] = -1;
        return row;
    }

推荐答案

多亏了 @ sous2817 评论,我找到了一种非常适合我的方法.

I found a method, thanks to @sous2817 comment, that works perfectly for me.

public static int[] GetRandomNumbers(int count, Random RNG)
    {
        HashSet<int> randomNumbers = new HashSet<int>();
        for (int i = 0; i < count; i++)
            while (!randomNumbers.Add(RNG.Next(count))) ;
        return randomNumbers.ToArray();
    }

这比我的工作快10倍,并且可以与程序的其余部分很好地工作.我需要代码是线性的",以便其他解决方案使我的程序混乱.无论如何,感谢所有人的帮助:)

This works ~10 times faster then what I was doing and works nicely with the rest of my program.I needed the code to be "linear" so other solutions mess my program. Anyway, thanks to everyone that helped :)

这篇关于数组包含性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆