Desafio
Dado um número inteiro positivo Emita (K)
um número inteiro aleatoriamente uniforme (Y)
entre [0, K)
.
Se Y > 0
assumir K = Y
e repita o processo até Y = 0
.
Regras
- A entrada deve ser impressa primeiro
- Formato de saída como desejar
- Seu programa deve terminar.
0
deve ser a saída final. Opcionalmente, uma linha vazia0
Respostas:
Pitão ,
6 54 bytesExperimente aqui!
Como funciona
fonte
C (gcc) , 42 bytes
Experimente online!
Usa lógica e curto-circuito.
C (gcc) , 40 bytes (sem imprimir o valor inicial)
Experimente online!
Usa lógica e curto-circuito.
fonte
rand()%_
não é uniformeR,
66 60 56 4341 bytesTry it online!
fonte
>0
andcat(n,"")
(empty string) will also work.print
is more efficient here, as it returns its argument: 56 bytesk=scan();while(x<-sample(1:k-1,1))k=c(x,k);cat(rev(k),0)
n=scan();while(print(n))n=sample(n,1)-1
MATL, 6 bytes
Try it online!
Explanation
fonte
Pepe, 25 bytes
Pepe is a programming language made by user Soaku.
Try it online!
Explanation:
fonte
Perl 6, 18 bytes
Try it online!
Anonymous code block that returns a list of values. If you don't mind the numbers being ranges, you can do:
for 17 bytes. Funnily enough, another builtin random function,
roll
, has the same behaviour in this instance for the same amount of bytes.fonte
Perl 5.10.0
-pl
, 26 bytesTry it online!
fonte
Jelly,
43 bytesThis is a monadic link (function) that prints an array and returns 0.
Try it online!
How it works
fonte
Brachylog, 8 bytes
Try it online!
Explanation
The recursion will stop once
?ℕ₁
fails, that is, when the input is0
.fonte
05AB1E,
87 bytesTry it online!
Explanation
fonte
Δ=ݨΩ0M
is equivalent.J, 13 bytes
On the subway, so apologies for lack of TIO (hopefully there isn’t a lack of correctness).
Outputs a list of values.
Presumably the APL approach will be shorter, but this is what I thought of.
How it works
^:a:
apply repeatedly until convergence, storing intermediate results in an array.?
random integer in range[0, K)
forK
greater than 0. For 0, it gives a random integer in range(0,1)
. For a floating point number, it errors.::]
catch an error for an input to?
and instead of erroring, output the input that caused the error.}:
get rid of the last value in the array (this is so that a floating point number isn’t output).Try it online!
fonte
?.
, but I don’t think I’m using that.JavaScript (ES6),
3837 bytes-1 byte thanks to @Arnauld
Show code snippet
fonte
new Date%n
doesn't really work here, since it doesn't change fast enough to be useful for generating multiple random numbersC, 38 bytes
Try it online
Ungolfed
fonte
&&
; also, you may want to consider seeding the RNG in yourmain
function: Try it online!Pyth, 4 bytes
Try it online!
This basically implements the algorithm:
To translate the Pyth into the algorithm, we can mostly just examine what each character means. Since Pyth is written in prefix notation (i.e.
* + 1 2 3
is(1 + 2) * 3
) we can start from the left and fill in the arguments as we go.W
begins a traditional while loop. The first statement after it is the loop condition and the second statement after it is the loop body. If the second statement is empty it becomes a no-op. This while works exactly like the Python while, so it will evaluate non-zero integers as True and zero as false.The first statement after the while begins with the newline character. This corresponds to Pyth's "print and return with a newline" function. This takes one argument, which is then printed and also returned unmodified. This allows us to print the intermediate steps while also performing the needed operations.
The argument passed to this print function begins with
~
which is a bit special. If the character immediately after~
is a variable it takes two arguments, otherwise it takes one. SinceO
is not a variable~
will consume only one argument.~
functions a bit like+=
does in many conventional languages, though the closest operator would be the post-increment operator++
fromC
. You may know thatx++
will be like usingx
as the current value, but thereafterx
will bex+1
.~
is the same idea, but generalised to whatever the result of the first argument is. How it picks what variable to assign to will be addressed later.The argument of
~
isO
which is very simple. When its one argument is an integerO
returns a value from 0 to one less than that integer uniformly at random.Now you may have noticed
O
does not have an argument. Here the Pyth interpreter kindly fills in a guess, which here is the variableQ
.Q
has a special meaning in Pyth: whenever it is present in a program the Pyth program begins with assigningQ
to the input of the program. Since this is the first variable occurring in~
's argumentQ
is also now the variable that~
will assign a value to.Summed up our "readable" program might look like:
And one sample "run-through" might look like:
O
returns 3,~
returns 5,\n
returns and prints 5 which is trueO
returns 0,~
returns 3,\n
returns and prints 3 which is trueO
returns something irrelevant,~
returns 0,\n
returns and prints 0 which is falsefonte
APL (Dyalog Unicode),
129 bytesAnonymous tacit prefix function. Assumes
⎕IO
(Index Origin) to be0
, which is default on many systems. Returns the final value (0) in addition to printing while run.Try it online!
{
…}⍣=
apply the following function until stable:⎕←⍵
output the argument?
return a uniformly distributed random number in the range 0 through that–1⌊
round down (because?0
gives a (0,1) float)fonte
C (gcc),
4042 bytesSome idiot™ forgot to print the initial value first.
Don't panic.
fonte
f(K){while(K)printf("%d\n",K),K=rand()%K;}
. Still you got my +1 for an equal solution!f(K){while(K)printf("%d\n",K,K=rand()%K);}
x86 + rdrand, 19 bytes
Straightforward implementation. Takes input K in
ecx
and outputs to a buffer inebx
.fonte
Python 3, 39 bytes
Probably not the most cryptographically secure random number generator but to the human eye it looks random enough...
Try it online!
fonte
k=0
is acceptable.hash()
tries to maintain but doesn't guarantee this property. For that task you should use therandom
module.random.randrange()
:from random import*;f=lambda k:print(k)or f(randrange(k))
TI-Basic (TI-84 Plus CE),
1713 bytes-4 bytes from Misha Lavrov
Takes input in
Ans
as50:prgmNAME
.TI-Basic is a tokenized language. All tokens used here are one byte.
Explanation:
An 11-byte solution suggested by Misha Lavrov that requires pressing
enter
after each line following the first.fonte
int(Ansrand
is shorter. Also, usingPause
instead ofDisp
, you can make the only statement in the loop bePause int(Ansrand
, which also updatesAns
.Python 2,
646260 bytesTry it online!
Saved
fonte
while 1:print k;k=randint(0,~-k)
should work (with an error at the end)while 1:print k;k=randrange(k)
saves two.C++ (gcc), 98 bytes
Try it here!
Usage
This is my first code golf attempt. Any feedback or remarks are welcome.
Edit: Removed the main function as suggested to make it valid.
fonte
-Dd='printf("%i,",x'
instead of the#define
would save you some bytes (-4), and is allowed as long as you count the bytes towards your result (because it is a non-standard preprocessor directive. You can also leave out the imports (at least with-std=c++98
and-w
, which don't count for bytes), and the variable types. So, you'd havep(x){d);while(x>0)d=rand()%x;}
and-Dd='printf("%i,",x'
.><>, 92+2 Bytes
+2B for -v flag
Try it online!
><>'s only source of randomness comes from the 'x' instruction, which sets the instruction pointer's direction to a random value. As such, generating a random number from 0 to n isn't trivial.
I first calculate how many bits are required to represent a number in the range [0,n), then generate random bits to generate a random number. This leaves the possibility that it'll generate a number slightly larger than n, in which case we just discard it and try again.
Explanation:
fonte
MATLAB (
4946 bytes)Sample output:
fonte
k=randi(k)-1
for a few bytes less.Retina, 21 bytes
Try it online! Explanation:
Repeat until the value stops changing (i.e. 0).
Print the value before each pass through the loop.
Convert to unary.
Create the range and convert to decimal.
Pick a random element.
fonte
Pyth,
67 bytesTry it online!
+1 to print the initial input value.
While Q is truthy, set Q to be a random integer between 0 and Q and print Q.
Not the shortest Pyth answer but I'm just learning and only posting because of the recent discussion about no-one using Pyth any more :)
fonte
=
and~
use the first variable of an expression as the variable that will be assigned if one isn't specified. For example~hT
will setT
to 11 while returning 10. The only other fancy trick is that the newline character prints its input and then returns that value unmodified, so we can have an empty loop body. Let me know if something else is confusing :)Haskell,
7471 bytes-3 bytes by actually doing what the specs say it should do.
Try it online!
fonte
IBM/Lotus Notes Formula, 48 bytes
Field formula that takes input from another field
i
.There's no TIO for formula so here's a screenshot of a sample output:
fonte
Powershell,
3632 bytes-4 bytes thanks AdmBorkBork
Testscript:
Output:
fonte
Get-
is implied, so you can remove it for -4 bytes Try it online!PowerShell, 35 bytes
Try it online!
Full program. Takes input
$args
, stores it into$a
, and enters afor
loop. Each iteration we're checking whether$a
is still positive (as0
is falsey in PowerShell). Then we leave$a
on the pipeline and move to the next iteration, where we set$a
to be the result ofGet-Random $a
, which returns an integer in the range0..($a-1)
.(Ab)uses the fact that PowerShell outputs an additional trailing newline in lieu of outputting the final zero (allowed by the rules as currently written).
fonte
"$args"
- nice. I was stuck on$args[0]
in this caseLua, 58 bytes
Try it online!
For some more Lua love here :)
fonte
r
declaration and move it to ther
on the while statement, by doing so you'll use 1 less byte for the space (p,r=print,...p(r)while
).