Donc, je me suis écrit un one-liner qui a imprimé un serpent sur la console. C'est un peu amusant, et je me suis demandé comment condenser mon code ...
Voici un exemple (court) de sortie:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Voici les spécifications:
- Dans chaque ligne, un seul caractère non-blanc (celui que vous préférez) est imprimé sur la console, avec initialement 29 à 31 espaces de remplissage à gauche de celui-ci.
- A chaque itération, une décision aléatoire est prise entre ces trois actions
- La quantité de rembourrage diminue de 1
- La quantité de rembourrage reste la même
- La quantité de rembourrage augmente de 1
Faites cela 30 fois, pour imprimer un serpent de 30 segments sur la console.
La réponse la plus courte en octets l'emporte.
Réponses:
05AB1E ,
1514 octetsEssayez-le en ligne!
Utilisations
0
.Explication
la source
Brainfuck aléatoire ,
123 122121 octetsEssayez-le en ligne!
Random Brainfuck est une extension de brainfuck, avec l'ajout utile de la
?
commande, qui définit la cellule actuelle sur un octet aléatoire. Ceci imprime un serpent fait de!
s, qui ressemble plus à un pas de serpent assez curieusement.Comment ça marche:
Une autre solution qui colle à la lettre de la question, plutôt que de l’esprit.
87 octets
Essayez-le en ligne!
Celui-ci est fortement enclin à laisser le rembourrage seul, mais il est également possible d'augmenter ou de diminuer le rembourrage. Chacun a un peu moins de 1 chance sur 256 de se produire.
la source
?
commande. +1?
est uniquement disponible en Brainfuck aléatoire , pas classiqueC (gcc) ,
615856 octetsRéponse modifiée pour refléter les changements de règles ...
Essayez-le en ligne!
la source
s+=1-rand()%3
à la fonction printf.i;f(s){for(s=i=31;--i;)printf("%*c\n",s+=1-rand()%3,43);}
Retina, 24 bytes
Try it online!
Explanation
Initialise the working string to the first line, i.e. 30 spaces and a
+
.There's a space on the second line.
-29{
wraps the remainder of the program in a loop, which is run 29 times.¶<
prints the working string at the beginning of each loop iteration with a trailing linefeed. The atomic stage itself inserts a space at the beginning of the string (the basic idea is to insert one space, and then randomly remove 0–2 spaces, because that's a byte shorter than randomly choosing between deletion, inserting and no-op).This matches the empty regex against the input, which gives us every position between characters (and the start and end of the string). Then
,2
keeps only the first three matches, i.e. the matches after zero, one and two spaces.@
selects a random one of those three matches. Then the split stage (S
) splits the input around that match. And the1
tells it to keep only the second part of the split. In other words, we discard everything up to our random match.The 30th line, which is the result of the final loop iteration, is printed implicitly at the end of the program.
la source
VBA,
605949 BytesPaste it in the Immediate window and hit enter. (Make sure explicit declaration is turned off!)
Far more likely to move than to stay in a line (i.e. actions are not equally weighted) but that was not a specified requirement (Fortunately!)
{EDIT} Saved 1 byte by removing the space between
=1
andTo
{EDIT2} Saved 10 bytes thanks to remoel's comment
Old Versions:
la source
String(i," ")
toSpc(30+i)
then removei=30:
. Or -1 byte by removing&
. :)C# (.NET Core),
1121101061009998 bytes-1 byte thanks to @raznagul.
-1 byte thanks to @auhmaan.
Explanation:
Try it online.
la source
new Random().Next()
multiple times locally (.net Framework Version 4.6.1) I always get the same result. I need to add aThread.Sleep(10)
between the call to reliably get different results. With a sleep time of less than 10ms I sometimes still get the same result. So .net-Framework and TIO (.net-Core) have different PRNGs or at least use different seeds. If I switch your program in TIO to C#-mono I get the same behavior as I get locally in .net-Framework.new Random()
uses the time as the seed so in a tight loop the time is the same and so the result is the same.Thread.Sleep(10)
to reliably get different results andThread.Sleep(1)
or even 9ms is not enough.C, 56 bytes
Try it online!
Explanation:
C (gcc), 55 bytes
Depends on f "returning" the value assigned to n in the function, which is undefined behaviour, but works consistently with gcc when no optimizations are enabled.
Try it online!
la source
JavaScript (ES8),
636260 bytesIncludes a trailing newline.
*2-1
could be replaced with-.5
for a 1 byte saving but the chances of each line being the same length as the previous line would be greatly increased. Of course, as "random" isn't defined in the challenge, the RNG could be replaced withnew Date%3-1
for a total byte count of 55.Saved a byte thanks to someone who deleted their comment before I could catch the name. I'd actually tried it this way with
repeat
andpadStart
but didn't think to trypadEnd
- don't know why!Show code snippet
Bonus
For the same number of bytes, here's a version that takes the number of starting spaces & iterations as input.
Show code snippet
la source
f=(x=y=30)=>x?`+\n`.padStart(y+=Math.random()*2-1)+f(--x):``
is one byte shorter. (Note: Since SO doesn't allow line breaks in comments, I had to type \n instead of actually using a line break.)y=31
, there would be a possibility of the first line being too short. tio.run/##BcFLDsIgEADQvSeZkUCs7kzQE7hyqSYzKfRjKBCYGHp6fO/…Java 8,
8987 bytesFirst golf, I'm sure it could be much better..
Edit: Fixed first line thanks to Steadybox.
Try it online!
la source
Python 2 ,
836564 bytesStraightforward approach:
Try it online!
Thanks to @Rod for saving some bytes! Thanks to @ovs for -1 byte!
Edit: changed variable name and output string to the letter 's'
More snake-like output for 88 bytes:
la source
APL (Dyalog), 20 bytes
1 byte saved thanks to ngn
Try it online!
la source
¯2+
--->2-
Charcoal, 14 bytes
Try it online! Link is to verbose version of code. Explanation:
Would be only 10 bytes if there was no initial indentation requirement.
la source
PHP, 61 bytes
Try it online!
la source
$i<30;$i++
can be$i++<30;
to save 2 bytes.for($p=30;$i++<30;$p+=rand(-1,1))printf("%{$p}s\n",'+');
(the\n
is counted as 1 char, and should be replaced by a real newline)for($i=$p=30;$i--;$p+=rand(-1,1))printf("%{$p}s\n",'+');
Java 8,
131129127126119108101 bytesExplanation:
Try it online.
Old 119 byte answer:
Explanation:
Try it online.
la source
R,
726967 bytesThanks to Zahiro Mor for 2 extra bytes!
Try it online!
la source
sample(3,29,T)-2
torunif(29,-1,1)
will reduce byte count by 2 but moves are not equally likely anymore. And could you also switch topaste("%"
instead ofpaste0("% "
or am I missing something here?% 30 s
instead of% 30s
. As you saidrunif
would mess up the probabiities.sprintf("%30s")
,sprintf("% 30s")
andsprintf("% 30 s")
return the same results for me. But on TIO only the first two have identical results, sopaste0("%"
should save a byte. And there is no requirement that every move has the same probability.Japt, 13 bytes
Returns an array of lines.
Test it
Explanation
Bonus
For 2 bytes less, here's a version that takes the number of starting spaces & iterations as input.
Try it
Alternative RNGs
The last 4 bytes can be replaced with any of the following:
la source
-1
is returned by the RNG on the first iteration, we'll end up with a total line length of29
when it should be30
,31
or32
.30
and then add-1
,0
or1
giving us29
,30
or31
- add the"
and that gives us a total length of30
,31
or32
for the first line.Swift, 101 bytes
Explanation
A full program. This uses a rather odd trick:
arc4random()
is a member of theDarwin
module, butUIKit
also comes with this function installed, so it saves a byte :) Also uses one of my Swift golfing tips for repeating strings an arbitrary number of times.la source
for _ in 0 ... g
execute the code block 29 times now instead of 30 (loop from 0 to 29 (exclusive))?0...g
generates all the integers in [0; g]. My bad, fixed the explanation.0..<g
would generate the integers in [0; g) :P[0; g)
you've edited to[0; g]
indeed confused me. :) Hmm, but isn't it possible to start atg=30
and loop[1; g]
in that case?[0; g)
or[1; g]
would definitely be possible if I chooseg=30
instead, but thenprint(...,0)
needs to be changed toprint(...+"0")
, because an additional (extraneous) space would be prepended before the 0 otherwise. Either way, the byte count remains the same.Perl, 36 bytes
la source
say
for subtraction. Am I right in thinking it doesn't change the number of runs when$#a
is incremented because it's not a reference?map
which seems to first lay out the elements on the stack.for
does not and would have had an unpredictable loop lengthperl -E 'map{$#a+=rand(3)-say"@a -"}@a=1..30'
, but that sometimes (not every time) resulted in segmentation fault. Could it be a bug in perl v5.22.1 and v5.16.3?R,
5453 bytesSimilar idea as above, but with shortened
sprintf
code and a shorter character string literal. Instead of\n
(two bytes) I’m using a literal line break (one byte).Try it online!
la source
A field width or precision (but not both) may be indicated by an asterisk *: in this case an argument specifies the desired number.
I've been usingsprintf
for years and somehow always missed that part... Thanks for the reminder!Ruby,
4539 bytesTry it online!
Modifying
x
during the loop does not affect the loop counter. I chose S as a particularly snakelike output character.-6 bytes: Use
rand(3)-1
instead of[-1,0,1].sample
. Thanks, Eric Duminil!la source
x.map
instead ofx.times
(equivalent since you don't use the return value)rand -1..1
is five bytes shorter than[-1,0,1].sample
rand(3)-1
for 6 bytes less.(x=30).times{puts' '*x+?+;x+=rand(3)-1}
(same size) will print exactly 30 spaces for the head of the snake as requested by the challengeSenseTalk,
237198 BytesThis is a language that I came to know and love about a decade ago. It's the scripting language that drives the automated testing tool Eggplant Functional. I was an avid user of the tool for many years before joining the company for a while. It's not the most golf-capable language, but I find it very enjoyable to write in. Golfing in it is actually quite challenging as the language is meant to be verbose and English-like... took me quite a while to get it down to 237 bytes.
Ungolfed/Explanation
Edit: Saved 36 bytes thanks to @mustachemoses
la source
J, 23 bytes
Try it online!
la source
PowerShell, 42 bytes
Try it online!
Loops from
1
to$l=30
. Each iteration we put$l
spaces plus anx
onto the pipeline as a string, then+=
either of-1, 0, 1
based onGet-Random
into$l
for the next loop. Those strings are gathered from the pipeline and an implicitWrite-Output
gives us a newline-separated list for free.la source
Bash, 53
Try it online.
la source
p+=RANDOM%3-1
works too.Jelly, 18 bytes
Try it online!
The chosen character is 0. If returning a list of list of characters is allowed, then the
Y
can be dropped and the submission can be turned into a niladic chain for 17 bytes. Alternative.How it works
Jelly, 16 bytes
Combining mine, Erik’s and Jonathan’s solutions, we can golf this down to 16 bytes. The chosen character is 1.
Try it online!
Thanks to Jonathan Allan for the heads-up (on
Ṭ€o⁶
).la source
Ṭ€o⁶
in place of⁶ẋ;€0
like my 18 byter does and get to down to 17.Octave,
53 51 5049 bytesTry it online!
Saved 1 byte by no longer doing any looping. Saved another as Octave has
printf
as well asfprintf
.This new code creates an array of 30 random integers in the range
-1:1
. It then cumulatively sums the array and adds 30, which gives the desired sequence.The result is printed using
fprintf
with a format that says "A decimal number, padded to a specified width, followed by a new line. The width will be the first value input, and the decimal number will be the second value input. If the number of values input is more than this, Octave will keep repeating the print automatically to get the desired output.To achieve the looping then, we need only interleave zeros between the sequence array so the
fprintf
function uses each value in the sequence as a width, and each zero as the digit to be printed.Prints an output like:
The above code doesn't always print exactly 30 spaces on the first line. It will be either 29, 30, or 31. To correct that, you would use this 53 byte version:
la source
x=31;for i=2:x;fprintf('%*d\n',x+=randi(3)-2,0);end
Lua,
8175 bytesIn
for i=1,n ...
the to_expn
is evaluated only once before entering the loop, saving one byte.-6 thanks to @user202729
Try it online!
la source
Python 3.6,
847369 bytesThanks to @WheatWizard for -11 bytes. Thanks to @JoKing for -4 bytes.
la source
i
you can usefor i in[1]*30
instead to save bytes.from random import*
so that you don't need therandom.
later on. And you can remove the newline space after your:
.30
to29
the"+".rjust(x)
can be replaced with" "*x+"+"
.[1]*30
to[1]*x
because it's one byte shorter.ES5,
979581 bytesES5,
11298 bytes if function format is needed:la source
_=>{p=30;for(i=0;i<p;i++){console.log(Array(p).join(" ")+"+\n");r=~~(Math.random()*3);p+=r==2?-1:r}}
join(" ")
withjoin` `
Red, 54 bytes
Try it online!
la source