本文介绍了得到对X独特的人数从一组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最优雅的方式来抓住独特的随机数我深思?

目前,我需要随机的唯一编号,我检查,看看如果它不是用whil​​e循环,看看我以前使用的随机数是唯一的。

所以它看起来像:

  INT N = getRandomNumber的%[数组大小];

每个(previously使用的n个列表中)
    检查我用前N,如果我有......再试一次。
 

有许多办法来解决这个线性为O(n / 2)的问题,我只是不知道是否有一个优雅的方式来解决它。试着回想一下MATH115离散数学和记得,如果旧的讲师包括任何与一个看似微不足道的问题。

我不认为此刻,所以也许一旦我有一些咖啡因我的大脑会苏斯它与提高智商的咖啡引起的。

解决方案
  1. 请N个独特元素的数组(在范围内0..N-1,例如整数),存储n为ARRAYSIZE和initialArraySize(ARRAYSIZE = N; initialArraySize = N)
  2. 当请求随机数:
    2.1如果ARRAYSIZE是零,则ARRAYSIZE = initialArraySize
    2.1生成指数= getRandomNuber()%ARRAYSIZE
    2.3结果=数组[索引]。不要返回的结果呢。
    2.2交换阵列[指数]与阵列[ARRAYSIZE-1]。交换的意思是交换C =数组[索引]数组[索引] =阵列[ARRAYSIZE-1];阵列[ARRAYSIZE-1] = C
    2.3减少ARRAYSIZE 1。
    2.4返回结果。

您会得到随机数,不会重复,直到你用完了唯一值的列表。 O(1)复杂性。

What is the most elegant way to grab unique random numbers I ponder?

At the moment I need random unique numbers, I check to see if it's not unique by using a while loop to see if I've used the random number before.

So It looks like:

int n = getRandomNumber % [Array Size];

for each ( Previously used n in list)
    Check if I've used n before, if I have...try again.

There are many ways to solve this linear O(n/2) problem, I just wonder if there is a elegant way to solve it. Trying to think back to MATH115 Discrete mathematics and remember if the old lecturer covered anything to do with a seemingly trivial problem.

I can't think at the moment, so maybe once I have some caffeine my brain will suss it with the heightened IQ induced from the Coffee.

解决方案
  1. Make an array of N unique elements (integers in range 0..N-1, for example), store N as arraySize and initialArraySize (arraySize = N; initialArraySize = N)
  2. When random number is requested:
    2.1 if arraySize is zero, then arraySize = initialArraySize
    2.1 Generate index = getRandomNuber()%arraySize
    2.3 result = array[index]. Do not return result yet.
    2.2 swap array[index] with array[arraySize-1]. Swap means "exchange" c = array[index]; array[index] = array[arraySize-1]; array[arraySize-1] = c
    2.3 decrease arraySize by 1.
    2.4 return result.

You'll get a list of random numbers that won't repeat until you run out of unique values. O(1) complexity.

这篇关于得到对X独特的人数从一组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 10:06