New answers tagged

0

Python 3, 147 bytes lambda a:[*zip(*sorted(((j+l.index(k)+random()/5-.1)/len(l),k)for j,l in((random(),sample(m,len(m)))for m in a)for k in l))][1] from random import* Try it online! Assumes no duplicates


3

J, 52 42 32 bytes /:&;(%~_.1+?~+?@0+5%~?@#&0)@#&.> Try it online!


1

Charcoal, 60 bytes Fθ«≔⟦⟧ηW⁻ιη⊞η‽κ≔∕‽⁵¦⁴ιFEη⟦∕⁺λ⁺ι∕⊖⊘‽⁵χLηκ⟧⊞υκ»W⌊υ«≔Φυ¬⁼ικυ⟦⊟ι Try it online! Link is to verbose version of code. Uses 5 distinct equally-spaced random numbers each time as allowed by the question. Explanation: Fθ« Loop over each category. ≔⟦⟧η Start with no shuffled items. W⁻ιη Repeat until the set difference between the items and ...


1

Ruby, 93 bytes Another straightforward implementation. -9 bytes from borrowing ideas from Arnauld's value generation code, which I saw right before I posted my answer. ->a{v=a.flat_map{|e|i=rand-1;e.shuffle.map{|s|[(rand/5-0.1+i+=1)/e.size,s]}}.sort.map &:last} Try it online!


1

R, 104 101 bytes function(x,`!`=unlist,`+`=runif)(!x)[order(!lapply(lengths(x),function(l)(sample(l)-+1--+l/5-.1)/l))] Try it online! A function taking a list of character vectors and returning a character vector. Thanks to @RobinRyder for saving 3 bytes!


3

Jelly, 28 bytes ‘9xX€’÷8Ḣ__.÷5ƊƊ_@Ẋ÷ ẈÇ€FỤịẎ Try it online! A pair of links that is called monadically with input and output as described in the question. Jelly doesn’t generate random uniform numbers so a random rational number between 0 and 1 in increments of 0.125 is used instead. Incidentally, per the question’s quote, I’ve implemented it in a ...


1

05AB1E, 37 bytes ε.rDg©т*ÝΩVεN®/тD(ŸΩY‚₄/O+‚]˜2ôΣθ}€¨ Port of @Arnauld's JavaScript answer, so make sure to upvote him as well! Try it online (feel free to remove the last 2 or 3 bytes (}€¨) to see the resulting \$v[k]\$ values it sorts on). Explanation: ε # Map each group of the (implicit) 2D integer-list to: .r # Randomly ...


2

Red, 180 bytes func[b][random/seed now extract next sort/skip collect[forall b[i: random 1.0 /(d: length? t: random b/1)repeat n d[keep n - 1.0 / d + i +(0.1 / d - random 0.2 / d)keep t/:n]]]2 2] Try it online! Just a straightforward implementation of the algorithm


3

Python 3, 244 218 200 bytes from random import* l,r,u=len,range,uniform def f(x): I,v=[],[] for i in r(l(x)):shuffle(x[i]);I+=x[i];n=l(x[i]);t=0.1/n;v+=[k/n+u(0,1/n)+u(-t,t)for k in r(n)] return[s[1]for s in sorted(zip(v,I))] Try it online! Literally just a golfed version of the algorithm in the challenge. I mean, someone had to do it! Thanks to ...


7

JavaScript (Node.js),  125  124 bytes Saved 1 byte thanks to @KevinCruijssen a=>a.flatMap(a=>a.sort(_=>R()-.5).map(v=>[(o++-.1+R()/5)/a.length,v],o=R()),R=Math.random).sort(([a],[b])=>a-b).map(a=>a[1]) Try it online! Commented a => // a[] = input a.flatMap(a => // for each ...


0

Burlesque, 43 bytes pe"LRK"jCB{J?+gw)-]>]3.<}f[sa0#Rx/x/jrn-]!! Try it online! Made trickier by the fact there is no "select random element from list" as far as I am aware. 15 bytes are just trying to select a random element. pe # Push inputs onto stack takes "SEED N" "LRK" # Literal LRK jCB # Form all combinations of length N { J?+ #...


0

Java 10, 140 139 bytes v->{var r=" 1\n x x\nx 9 x\n x x\n x";for(int d=9,m=3;m<511;r=r.replaceFirst("x",d+""))for(;m==(m|=1<<(d*=Math.random()));d=9);return r;} Port of @Arnauld's JavaScript answer, so make sure to upvote him as well! Try it online. Explanation: v->{ // Method with empty unused parameter and String return-...


1

PHP, 83 81 bytes 83 bytes <?=($l=range(2,8))&&shuffle($l)?vsprintf(" 1\n %d%2d\n%d 9 %d\n%2d%2d\n%3d",$l):0; Try it online! 81 bytes Splitting code into 2 fragments to save 2 characters. Thanks for the comment @manatwork. <?$l=range(2,8);shuffle($l)?><?=vsprintf(" 1\n %d%2d\n%d 9 %d\n%2d%2d\n%3d",$l); Try it online!


1

APL, 37 chars/bytes 2⌽t⌽↑⍕¨((t←1 2 3 2 1)/⍳5)⊆1,5⌽9,1+?⍨7 permutation of numbers from 2 to 8 1+?⍨7 add leading 9, shift 5 positions to the left, add leading 1 1,5⌽9, replicate numbers from 1 to 5, 1-2-3-2-1 times respectively (t←1 2 3 2 1)/⍳5 make 5 nested vectors of length 1-2-3-2-1 respectively ((t←1 2 3 2 1)/⍳5)⊆ transform numerical arrays into ...


1

C (GCC) 161 158 bytes -3 bytes from ceilingcat #define B,b[i++] b[]=L"";main(a,t,i){srand(time(0));for(i=b;--i;b[a]=t)*b=b[a=rand(t=*b)%7];printf(" 1\n %d %d\n%d 9 %d\n %d %d\n %d"B B B B B B B);} L"" has non-printing characters that I can't get to show in SE is equivalent to {2,3,4,5,6,7,8} this code makes the assumption that the address of b is at ...


2

SAS, 160 Bytes data;array j[9](1:9);do i=1to 1e4;l=int(2+7*ranuni(0));m=int(2+7*ranuni(0));n=j[l];j[l]=j[m];j[m]=n;end;put+2j[1]/+1j[2]j[3]/j[4]j[9]j[5]/+1j[6]j[7]/+2j[8];run; Ungolfed: data _null_; array j[9] (1:9); **Define and populate an array; do i = 1 to 1e4; **Iterate ten thousand times; l=int(2+7*ranuni(0)); **make a random ...


1

Python 3, 180 bytes from random import* r=range s=sample a=s(s([x for x in r(32)if x%4],16)+[x*8+4 for x in r(4)],20) print([[i in t for i in r(32)]for t in[[0,16,a[0]],[8,24],a[1:7],a[7:15],a[15:]]]) Try it online! Prints a logical matrix representing the drum loop.


0

R, 138 bytes s=sample y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16))) z=matrix(0,5,32) z[1,c(1,17,y[1])]=z[2,c(9,25)]=z[3,y[2:7]]=z[4,y[8:15]]=z[5,y[16:20]]=1 Try it online! A full program that implicitly prints the drum loop as a matrix of 1s and 0s. Alternative using a third party package: R + DescTools, 130 bytes s=sample y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)]...


1

Jelly, 43 bytes 32s8Zs4ZḢ;FẊḣ⁴ƲƊḢŒœ;FẊ$ƲFṙ-“¥©€Þı‘œṖ;¹Ṭz0ZṖ Try it online! A niladic link that returns a 32x5 matrix of 1s and 0s representing the drum loop. The footer simply prints it concatenated and separated by newlines. Explanation 32 | 32 s8 | Split into groups of 8 ...


0

Python 3, 400 \$\cdots\$ 361 338 bytes from random import* r=randrange p=65537 def h(b=p): while b==p:b=p|1<<r(32) l=[b,16777472] for i in[6,8,5]: while bin(b).count('1')!=i:b=sum(1<<r(32)for j in[1]*i) l+=[b] return l g=1 while g: l,g=h(),0 for i in range(32): b=sum(j&1<<i!=0for j in l) if i%4:g|=b>1 else:g|=b!=1 ...


1

Perl 6, 55 bytes {({S:g{.}=<R L K>.pick}...{!/(.)$0$0/}o*x 2).tail}o\*x* Try it online! Anonymous code block that takes an integer and returns a string of RKLs. Explanation: o\*x* # Generate a string of n *s { } # And pass to code block ( ...


3

Ruby, 57 bytes ->x{0while /(.)\1\1/=~(w=(%w(L K R)*x).sample(x)*'')+w;w} Try it online!


1

05AB1E, 65 bytes 31Ý©8ˆ24ˆ40¯ǝ0ˆ16ˆ®¯KΩˆ48¯¦¦ǝ•Wk¤]•3ôεćи}˜.ržw8и«®¯K.r.¡4Ö}é˜ǝb€¦ Outputs as a transposed list of strings. Try it online. (The footer pretty-prints this as the intended rows/columns. Feel free to remove the footer to see the actual result.) Explanation: 31Ý # Push a list in the range [0,31] © # Store it ...


2

Ruby, 97 bytes ->x,y=->{[*1..x].map{%w[L R K].sample}}{a=y[];a=y[]while(a+a).chunk{|n|n}.any?{|_,e|e[2]};a.join} Try it online! This is a lambda function, which takes the length input as x. It creates a function y which generates a list of length x containing random characters from the list ["L", "R", "K"]. It then checks to see if there are any ...


1

Red, 141 112 bytes func[n][until[s: copy""loop n[append s random/only"LRK"]parse rejoin[s s][any[copy t skip opt t ahead not t]]]s] Try it online!


6

R, 67 bytes n=scan();while(max(rle(c(x<-sample(c("L","R","K"),n,T),x))$l)>2)0;x Try it online! A full program taking an integer, n and implicitly printing the drum pattern.


3

JavaScript (ES6),  194 193  189 bytes Returns \$M^T\$. _=>(g=n=>n?g(/1/.test(c=m[R()*32|0])?n:n-=c[h()]=1):m)(16,a=[1,,6,8,5],R=Math.random,h=_=>a[y=R()*5|0]?a[y]--&&y:h(),m=[...Array(32)].map((_,x)=>(c=[0,0,0,0,0],x&3?0:c[x&7?h():x/8&1]=1,c))) Try it online! How? Note: Columns and rows in the following ...


3

C (gcc) 413 394 389 379 378 360 342 327 307 299 298 bytes #define F;for(b[8]=b[v=24]=3,n=0;n #define B,b[n]== a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(time(0))F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B ...


2

Perl 5 -pa, 86 bytes $_=R x("@F"+2);1while s|(.)(?=\1\1)|(R,L,K)[rand 3]|e;s/..$//;($_.$_)=~/(.)\1\1/&&redo Try it online!


3

R, 75 bytes `?`=diff;n=scan();while(!all(??c(x<-sample(9+c(2,3,9),n,T),x)))0;LETTERS[x] Try it online! Rejection sampling until an allowable pattern is found. Samples \$x_i\$ from the set \$\{11, 12, 18\}\$ (the positions in the alphabet of K, L, R). Agreeably, these numbers are such that a pattern is allowable iff \$\forall i, (x_{i+1}-x_i)-(x_i-x_{i-...


3

APL (Dyalog Unicode), 30 bytesSBCS Anonymous tacit prefix function. {'LRK'[?⍺⍴3]}⍣{~1∊≢¨3∪/⍺,2↑⍺}⍨ Try it online! {…}…⍨ apply the following function using the single argument also as left argument:  'LRK'[…] index into the string "LRK" using the following indices:   ⍺⍴3 reshape the number three into the length indicated by the left argument   ? random ...


7

Jelly, 15 bytes “LRK”ṗ;`E3Ƥ$ÐṂX A monadic Link accepting an integer which yields a list of characters. Try it online! How? Pretty similar to Nick Kennedy's Jelly answer... “LRK”ṗ;`E3Ƥ$ÐṂX - Link: integer, n “LRK” - "LRK" ṗ - Cartesian power (all length n strings with alphabet "LRK") ÐṂ - keep those entries which are ...


4

Jelly, 16 bytes “LRK”ṗ;`ŒɠṀ<ʋƇ3X Try it online! A monadic link taking the length \$n\$ and returning a Jelly string of the drum pattern. Like the other answers, assumes that \$n > 1\$ Explanation “LRK”ṗ | Cartesian power of "LRK" and n ʋƇ | Keep those where the following is true: ;` | - Concatenate to itself ...


2

Charcoal, 26 bytes Nθ≔KηW⊙KLR№×η³×κ³≔⭆θ‽KLRηη Try it online! Link is to verbose version of code. Hangs for an input of 1 (could be changed to output a random hit at a cost of 1 byte). Explanation: Nθ Input the number of hits. ≔Kη Initialise the output to an illegal value. W⊙KLR№×η³×κ³ Repeat while the output is illegal, determined by tripling the ...


3

Python 3, 115 \$\cdots\$ 112 104 bytes from random import* f=lambda n,s='L':any(b*3in s*3for b in'LRK')and f(n,''.join(choices('LRK',k=n)))or s Try it online! Saved a byte thanks to Chas Brown!!! Saved 8 bytes thanks to Jonathan Allan!!!


2

JavaScript (ES6),  77  74 bytes Assumes that the input is greater than \$1\$. n=>(g=s=>s[n-1]?/(.)\1\1/.test(s+s)?g``:s:g(s+'LRK'[Math.random()*3|0]))`` Try it online!


6

05AB1E, 15 bytes …LRKãʒDJÅγà3‹}Ω Try it online! …LRK # literal "LRK" ã # strings made of `input` of those letters ʒ } # filter: DJ # concatenate the string with itself Åγ # run-length encode à # maximum (largest run length) 3‹ # less ...


3

PowerShell, 60 bytes ' 1 {0} {1} {2} 9 {3} {4} {5} {6}'-f(2..8|Sort{Random}) Try it online! -17 bytes thank you @Veskah for cleaning up whitespaces Originally: ' 1 {0} {1} {2} 9 {3} {4} {5} {6} ' -f (2..8 | Sort {Get-Random})


3

05AB1E, 18 16 bytes Y8L.r1†9ª•26Ià•Λ -2 bytes thanks to @Grimmy by using a fixed length of 2 with some directions duplicated. Try it online. Explanation: Y # Push 2 8L # Push a list in the range [1,8] .r # Randomly shuffle it 1† # Filter the 1 to the front 9ª # Append a trailing 9 (i.e. [1,3,4,8,5,2,6,7,...


5

Ruby, 66 52 bytes $><<" 1 %d %d %d 9 %d %d %d %d"%[*2..8].shuffle Try it online! Also quite a boring answer, similar to the Perl and Bash solutions. Saved 14 bytes thanks to Value Ink!


4

Perl 6, 51 bytes printf ' 1 %s %s %s 9 %s %s %s %s',pick *,2..8 Try it online! I'm not really happy with how boring this solution is.


1

Red, 90 bytes t: random[2 3 4 5 6 7 8]foreach c{ 1 ; ; ; 9 ; ; ; ;}[prin either c >#":"[take t][c]] Try it online!


6

Python 3, 128 bytes from random import* l=[1]+sample(range(2,9),7) l.insert(4,9) for i in[1,2,3,2,1]:print(f"{' '.join(map(str,l[:i])):^5}");l=l[i:] Try it online! Unfortunately not even close to the straightforward solution, but I spent so much time on this that I still wanted to share it. Ungolfed: from random import * # Generate random sampling and ...


1

Keg, 62 bytes 2345678(~z%|&(~z%|')&^) ,,1. , ,. ,. ,. ,9. ,. , ,. ,. , ,,. Try it online! Remove the z%' s for -4 bytes but a really long execution time. This: Pushes the numbers 2-8 onto the stack. Shuffles everything in a very interesting way. Prints out the required shape.


11

Python 3, 91 87 bytes from random import* print(" 1\n %d %d\n%d 9 %d\n %d %d\n%3d"%(*sample(range(2,9),7),)) Try it online! -4 bytes thanks to xnor (final \n %d -> \n%3d and tuple(...) -> (*...,))


10

Bash or any Bourne Shell, with modern coreutils, 54 52 bytes printf ' 1 %s %s %s 9 %s %s %s %s' `shuf -i2-8` Try it online! -2 bytes thanks to @dzaima (use shuf -i option for an implicit seq) Originally: printf ' 1 %s %s %s 9 %s %s %s %s' `seq 2 8|shuf` Try it online! I saved one byte by not including a newline at the end of the source, and ...


4

Jelly, 24 bytes 7ẊŻŒHj8‘;€⁶⁽¦ỵD¤œṖz⁶ZṚ€Y A full program which prints the result. Try it online! How? 7ẊŻŒHj8‘;€⁶⁽¦ỵD¤œṖz⁶ZṚ€Y - Main Link: no arguments 7 - seven Ẋ - shuffle (implicit range [1..7]) Ż - prepend a zero ŒH - split in half j8 - ...


2

Dyalog APL Extended, 38 bytes {5 5⍴(~2⊤29010619)⍀∊⍕¨∊,∘9¨@4⊢1,1+?⍨7} Try it online!


3

Perl 5, 62 bytes printf" 1 %d %d %d 9 %d %d %d %d",sort{int(rand 3)-1}2..8 Try it online!


6

Charcoal, 27 25 bytes F⁷⊞υ‽⁻E⁷⁺²κυ↖⪪⁺⪫⪪⪫υω⁴9¦1³ Try it online! Link is to verbose version of code. Explanation: F⁷ Loop 7 times. ⊞υ‽⁻E⁷⁺²κυ Create a list of the integers from 2 to 8, perform set difference with the list of integers collected so far, select a random integer, and push it to the empty list. This shuffles the integers from 2 to 8. ⁺⪫⪪⪫υω⁴...


Top 50 recent answers are included