1
Name:
Anonymous
2012-01-19 12:22
Fellow Progs,
any idea to nicely implement this ?
First idea...ugly
get random value
if value is zero
get random value
done
Second idea
get random positive value
make coin toss
if coin shows head
value *= -1
But there must be something easiert / nicer
thanks alot.
2
Name:
Anonymous
2012-01-19 12:47
from random import randrange
def randrange_nonzero(x, y):
n = randrange(x, y-1)
return n + (not n)
3
Name:
Anonymous
2012-01-19 12:49
>>2
Sorry, disregard that, I fucked up. Here's the correct one:
def randrange_nonzero(x, y):
n = randrange(x, y-1)
return n + (0 if n < 0 else 1)
4
Name:
Anonymous
2012-01-19 13:04
>>3
hmmm looks like a bigger version then my first idea
why the -1 on y ?
but thanks anyway :)
btw using C nothing fancy like if's in my return :P
5
Name:
Anonymous
2012-01-19 13:24
>>4
Your first variant may not be constant time.
/* returns a random range between x and y, both inclusive, that's not 0 */
int randrange_nonzero(int x, int y)
{
int n = rand() % (y - x) + x;
return n + (n>=0);
}
6
Name:
Anonymous
2012-01-19 13:27
something like pow(rand(2),2)*(1+rand(x)) would work, where rand gives you a ranged random from 0 to x, and pow is the power function (in this case x*x would also be sufficient).
7
Name:
Anonymous
2012-01-19 13:27
>>5
Ahh thanks alot ,now i actually can see what u did there.
I know that my first attempt may not be finished in const. time.
Thus i wrote "ugly" on it ;)
Thanks for the help!
10
Name:
Anonymous
2012-01-19 13:52
>>8,9
The numero uno trolling operator, the conditional operator.
12
Name:
Anonymous
2012-01-19 14:50
>>11
Because it confuses mental midgets.
13
Name:
Anonymous
2012-01-20 13:01
def randnot0(x): return randint(-x, x) or randnot0(x)
15
Name:
Anonymous
2013-09-01 11:23
,.へ. ,.--、ノL
Σ____,.>'-‐'ー-'─- 、.,_
,..::''"´:::::::::::::::::::::::::::::::::::::::::`':,
,:'´::::::::::::::::::__,.:::::-r::::ー-::::、__:::::::〉
';:::::_,.::-:_,ゝ -‐''"´ ̄ ̄`"'' <イ┐
r>,ゝ'" , ; ! ヾ7
Y´ / ,' /-‐i‐ /| ,イ__ハ ! ',
|. ,' ,.ィ| ,'-;=!、/ レ' 'ァ'ハ`Y ハ|
_!_レi.-‐!'7 .i ri i リ !/',フ
`iヽ、__ハ.ヽ_`'ー' __`´ ⊂i ヽ. ト,
! ! `⊂⊃ i'´ ̄ ァ'-:、 ,.イハ. i ノ i
ト.、 ', ', i !>.、.,_'、_ 〈::::::::;:〉ァ-、!/_,.イ ,'
iヘ'ヽ. ヽハ ハァ'´ ̄`ヽT7´ヾ:-r7 ヽ ,V
∠_ ゝ_`"''┐ レ' ,' Y:.}>く{,.r'- 、___r、ソ,.イ
`ゝ、  ̄ヽヽ、_,イ〈 、 ! ヽ、_:/ ´ ̄ヽ」-'ヽ'、.,__., -、
!へ/ `/ ハ `ヽ,'_ `i /:、へ! )
へr、/ ,' ', `ヘ>、.,_ _,,..イ `''ー-、__
レへ!^ヽ!'⌒´:〉:::::::::7 ̄::::i:::::'、 _i {`ヽ.
,:'::::/::}_>く{::::::';::::::',ヽ、.,___,ノ/_つ'
/::::::_∠::::::::i::::::::':,:::::ヽ.  ̄´
r,':::::::::[ンヽ」:::::::ハ::::::::::::::::::::ヽ.
r'>、:;´:::::::::::::::/::::';:::::::::::::::::::::::ト、
`'-7!>、:;_:::::::;'::::::::i:::::::::::';::::ン_ノ
/:::::ヽ∠コ>くコニ>ヘ'ニン-「
Σ7:::::::/ rヽ:::::::';7
7`ー/┘ └へ>'i'
!___/ `ー'