Julia : generating unique random integer array

匿名 (未验证) 提交于 2019-12-03 08:39:56

问题:

I am trying to create 10 element array of unique random integers. However I am unable to create array with unique values. Is there in Julia something like Pythons sample function ?

numbers = zeros(Array(Int64, 10)) rand!(1:100, numbers) 

Thanks.

回答1:

There is a sample function in StatsBase:

using StatsBase a = sample(1:100, 10, replace = false) 

This will draw a sample of length 10 from 1:100 without replacement.



回答2:

If performance is not an issue (i.e. the sample range isn't too large, or the sample count is close to the sample range), and if you don't want to use an additional package for whatever reason, try:

a = randperm(100)[1:10]



回答3:

unique(itr[, dim])

Returns an array containing only the unique elements of the iterable itr

unique([rand(1:100) for r in 1:20])[1:10] 

Set()

A set is a collection of elements, just like an array or dictionary, with no duplicated elements.

{rand(1:100) for r in 1:20}[1:10] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!