# Tag Info

## New answers tagged matrix

1

Ruby, 73 bytes ->l{l.permutation.map{|x|x*=?_;1while x.sub!(/(.*)_\1/,'\1');x.size}.min} Try it online! Assuming I can accept a list of columns in input Ruby, 108 bytes ->l{l.map(&:chars).transpose.map(&:join).permutation.map{|x|x*=?_;1while x.sub!(/(.*)_\1/,'\1');x.size}.min} Try it online! Otherwise

4

Jelly, 24 bytes ZWṖ€ṛ¦Ɱ0ịⱮĠƊ$€Ẏ$Ẹ€Ạ$Ð¿L’ Try it online! A monadic link taking a list of Jelly strings (a list of lists of characters) and returning an integer. Explanation Z | Transpose W | Wrap in a list$Ð¿ | While the following is true: Ẹ€ | - Any list is non-empty ...

1

J, 55 bytes (1+[:<./$:"1)@((]}.~1{.=)&.>"0/~' '-.~{.&>)0:@.(''-:;) Try it online! Brute force recursion taking away boxes until none are left, and returning the minimum number of steps. 8 Pyth, 22 bytes L&lbhSmhyfT>RqhkhdbbyC Try it online! Or run all test cases at once. This is basically ovs's Python solution translated verbatim to Pyth (it seems that their solution's exact algorithm is also shortest in Pyth), so I'm posting it as community wiki. Doesn't time out thanks to Pyth's memoization. 5 Brachylog, 31 bytes ∧≜.&z{{⟨k≡t⟩|;X}ᵐRtᵛ∧Rhᵐ}ⁱ↖.zĖ∧ Try it online! It's a bit less efficient than even the other two answers so far (it does the classic recompute everything if it hasn't reached the end in as many steps as it's trying), so I might just delete this when I wake up if it still hasn't spit something out for the second-to-last test case. 9 Python 2, 103 91 bytes -12 bytes thanks to PurkkaKoodari! lambda s:f(zip(*s)) f=lambda s:len(s)and-~min(f({r[r[0]==x[0]:]for r in s}-{()})for x in s) Try it online! The last testcase times out. The first function just transposes the input, if we can take input as a list of columns it can be omitted. 8 Charcoal, 57 bytes ＷＳ⊞υι≔⟦Ｅθ⮌⭆υ§λκ⟧η≔⁰ζＷ⌊η«≦⊕ζ≔ηθ≔⟦⟧ηＦθＦκ⊞ηΦＥκΦμ∨π¬⁼ξ§λ⁰μ»Ｉζ Try it online! Link is to verbose version of code. Uses brute force so too slow for the last test case on TIO. Explanation: ＷＳ⊞υι Input the pile. ≔⟦Ｅθ⮌⭆υ§λκ⟧η Rotate the pile by 90° and put it into a list. ≔⁰ζ Start counting the number of steps. Ｗ⌊η« Repeat until there is at ... 1 Julia 1.0, 30 bytes Adapted from @flawr !x=[(t=x[1]).^0 x[2:end]...]\t Try it online! 1 K (ngn/k), 29 bytes {(*>#'=,/)''2((0N;y)#/:+:)/x} Try it online! Based off of @Shaggy's Japt answer. Takes the input matrix as x and the chunk size as y. 2(...)/x set up a do-reduce, seeded with x and run twice ((0N;y)#/:+:) transpose the input, then slice each row into y-length chunks (...)'' run the code in (...) on each chunk in the transformed ... 1 Wolfram Language (Mathematica), 41 bytes BlockMap[Commonest[Join@@#,1]&,#2,{#,#}]& Try it online! Input [n, m]. Returns a matrix of singleton lists. 0 Charcoal, 54 bytes Ｆ⪪Ｅθ⪪ιηη«≔⟦⟧ζＦＬ§ι⁰«≔⟦⟧εＦι≔⁺ε§λκε≔Ｅε№ελδ⊞ζ§ε⌕δ⌈δ»⊞υζ»Ｉυ Try it online! Link is to verbose version of code. Explanation: Ｆ⪪Ｅθ⪪ιηη« Split each column into chunks of size n, then split the rows into chunks of size n and loop over the chunks. ≔⟦⟧ζ Start collecting the results for this chunk of rows. ＦＬ§ι⁰« Loop over the number of chunks of ... 2 R, 130 124 121 116 111 bytes -5 bytes and another 3 thanks to @Dominic function(M,n,k=dim(M))array(Map(function(x)el(names(sort(-table(x))):0),split(M,t(a<-(row(M)-1)%/%n)*k+a)),k/n) Try it online! Longer approach than @Dominic's, but I thought it's worth a try. Builds matrix mask t(a<-(row(M)-1)%/%n)*dim(M)+a used then in split, for example for ... 0 Python 3.8 (pre-release), 96 bytes Takes as input an integer matrix $m$, and an integer $n$ denoting the chunk size. lambda m,n:[[max(x:=sum(j,()),key=x.count)for j in zip(*[zip(*i)]*n)]for i in zip(*[iter(m)]*n)] Try it online! Very messy use of the split into chunks golfing tip. 1 Python 2, 174 bytes Quite long, very ugly, possibly the most comprehensions I've used in one statement. There is undoubtedly a better way to do this but I can't look at this thing anymore. def f(m,n):l=len(m);r=range(0,l,n);b=l/n;print('%s '*b+'\n')*b%tuple(max(v,key=v.count)for v in[sum([x[k][j:j+n]for k in range(n)],[])for x in[m[i:i+n]for i in r]for j in ... 2 Jelly, 12 bytes sZ€FÆṃḢƊ⁹ÐƤ€ Try it online! After several 13s, I found a 12. A dyadic link taking the grid as a list of lists of integers on the left side and the size of the split on the right. Explanation s | Split into sublists of the length specified by the right argument Z€ | Transpose each Ɗ⁹ÐƤ€ | For each sublist, do the ... 1 R, 113 111 108 bytes Edit: -2 bytes, and then -3 more bytes, thanks to pajonk (or 105 bytes by outputting a matrix of text strings representing the integers) function(m,n)outer(o<-0:(nrow(m)/n-1)*n,o,Vectorize(function(x,y)el(names(sort(-table(m[x+1:n,y+1:n]))):0))) Try it online! 1 JavaScript (ES6), 136 135 bytes Expects (matrix)(chunk_size). m=>n=>m.slice(-m.length/n).map((_,y,a)=>a.map((_,x)=>eval("for(o=K={},i=n*n;i--;)(o[v=m[y*n+i/n|0][x*n+i%n]]=-~o[v])<K?0:K=o[V=v];V"))) Try it online! Commented This is a version without eval() for readability. m => n => // m[] = matrix; n = ... 0 JavaScript (Node.js), 159 bytes n=>k=>n.flatMap((e,i)=>i%k?[]:e.flatMap((h,j)=>j%k?[]:(M=n.slice(i,i+k).map(K=>K.slice(j,j+k)).flat()).sort((a,b)=>(X=Y=>M.map(Z=>z+=Z==Y,z=0)|z)(b)-X(a))[0])) Try it online! Golfing languages which have built-ins for occurrence count or chunks have concise programs. Mine is 159 bytes long. 3 Japt -h, 17 bytes 2Æ=yòV)ËËc ü ñÊÌÌ Try it 2Æ=yòV)ËËc ü ñÊÌÌ :Implicit input of 2D-array U and integer V 2Æ :Map the range [0,2) = :Reassign to U y : Transpose òV : Partition rows to length V ) :End reassignment Ë :Map Ë ... 1 APL (Dyalog Extended), 37 (SBCS) Anonymous tacit infix function taking chunk count as right argument and the input matrix as right argument. ((∪⊃⍨∘⊃∘⍒⊢∘≢⌸)∘,⍤2)1 3 2 4⍉⊣⍴⍨4⍴⊢,≢⍛÷ Try it online! {…} dfn; ⍺ is matrix and ⍵ is chunk size: ⎡0,1,0,1⎤ ⎢0,0,1,1⎥ ⎢0,0,0,0⎥ ⎣0,0,1,1⎦ and 2 ≢⍛÷ the matrix size divided by the chunk size 2 ⊢, prepend ... 4 J, 23 bytes (0{~.\:1#.=)@,;.3~2 2&$ Try it online! J's u;.3 is pretty handy for this. It splits a matrix into rectangles. You just need to give the size of the rectangles and the offset between rectangles. So for 3x3-tiles the input would be [[3 3],[3 3]]. That is handled by 2 2&$(if we can take width and height of a tile as input, that would be ;.~... 2 MATL, 11 bytes thZCtvXM[]e Try it online! Or verify all test cases. How it works th % Implicit input: number n. Horizontally concatenate with itself to give [n n] ZC % Implicit input: matrix m. Im2col: arrange each [n n] block as a column of % length n*n tv % Vertically concatenate with itself. This makes columns twice as long without ... 5 APL (Dyalog Unicode), 40 38 bytes (SBCS) Anonymous tacit infix function taking chunk size as left argument and the input matrix as right argument. {(∪⊃⍨∘⊃∘⍒⊢∘≢⌸)∘,¨↑(⊂⊂¨⊂[1]∘⍵)(≢⍵)⍴⍺↑1} Try it online! {…} dfn; ⍺ is chunk size and ⍵ is matrix: 2 and ⎡0,1,0,1⎤ ⎢0,0,1,1⎥ ⎢0,0,0,0⎥ ⎣0,0,1,1⎦ ⍺↑1 take "chunk size" elements from 1, padding ... 2 Jelly, 13 bytes Zs€Zs€ẎF€ÆṃḢ€ Try it online! How it works Zs€Zs€ẎF€ÆṃḢ€ - Main link. Takes M on the left and n on the right Z - Transpose M s€ - Slice each row into n pieces Z - Transpose s€ - Split each group of columns into n pieces Ẏ - Flatten into a list of n x n matrices F€ - Flatten ... 1 Risky, 21 bytes 00?+0*_?-1/_?-1+_0+02-0?+0+_]+]+_]+]+_]+] Try it online! 2 Python 3.8 (pre-release), 154 144 bytes lambda a:1-any([len({*a})>8,{(s:={sum(a[i%7:i%5*3:i%4])-a[4]for i in b"\r@@@+?"}).pop()}-{a[0]+a[8],a[2]+a[6]},s,sum(i<0 or i**.5%1for i in a)]) @ represents unprintables chars Outputs 1 for Parker, 0 for not Parker Try it online! A pretty messy solution ^^ How it works: 1-any([...]) will return 1 if all ... 1 Python 3, 51 49 bytes lambda n:mgrid[:n,:n].max(0)+1 from numpy import* Try it online! 4 J, 59 57 bytes ((<.@%:-:%:)*]>&#~.)@,*3>+/(2#.{.~:])@,1&#.,],&(2{+//.)|. Try it online! (<.@%:-:%:) All are perfect squares. ]>&#~. Length of uniq is less than length (ie, has repeats) The remainder first creates a single list of all 8 relevant sums (cols, rows, diagonals): ],&(2{+//.)|. Get the / diagonal sum of both ... 3 MATL, 30 bytes t!GXdGPXd&hsdXB2>GX^1\=Gun9<vA Input is a 3×3 matrix. Output is 1 if it is a Parker square, 0 if not. Try it online! Or verify all test cases. Explanation t! % Implicit input: 3×3 matrix. Duplicate GXd % Push input again. Diagonal as a column vector GPXd % Push input, flip vertically. Diagonal as a column vector (this is the ... 7 05AB1E, 25 23 bytes -1 byte thanks to Grimmy! Â‚εÅ\ªIø«OË}àI˜ÐÙÊsÅ²PP Try it online! or Try all cases! Commented: Â‚ # pair the input with its reverse ε } # map over each of them: Å\ # take the main diagonal ª # append this to the input Iø # push the input transposed « ... 4 Jelly, 27 25 bytes S;§fƑⱮ,UŒDḢ$€§ƲẸȧÆ²Ȧȧ⁸FQƑ Parker: 0, non-Parker: 1 - just like it always seems to be! ;p Try it online! How? S;§fƑⱮ,UŒDḢ$€§ƲẸȧÆ²Ȧȧ⁸FQƑ - Link: 3 by 3 matrix, M S - column sums (M) § - row sums (M) ; - (column sums) concatenate (row sums) Ʋ - ... 7 JavaScript (ES7), 129 120 bytes Expects a flat array of 9 values. Returns 0 for Parker, or 1 for non-Parker. a=>new Set([A,B,C,D,E,F,G,H,I]=a).size>8|a.some(x=>x**.5%1)|[D+E+F,G+H+I,A+D+G,B+E+H].some(x=>x-A-B-C)|E+I!=B+C&E+G!=A+B Try it online! Or 117 bytes if we can just return truthy / falsy values. How? We split the input array into 9 ... 3 JavaScript (Node.js), 165 163 161 bytes l=>l.some(e=>e**.5%1)|(I=([c,i=3])=>l[c]+l[c+=i]+l[c+=i]!=l[0]+l[1]+l[2])([0,4])&I([2,2])|[[0],[1],[2],[3,1],[6,1]].some(I)|l.every(e=>l.map(g=>z+=g==e,z=0)|z<2) Try it online! This feels too long. Outputs 1 for non-Parker and 0 for Parker. +38 to fix bug 6 R, 106 105 104 bytes function(m,?=colSums)all(table(m)<2)|sd(c(?m,s<-?t(m)))|any(m^.5%%1)|sum(diag(m))-s&&sum(m[1:3*2+1])-s Try it online! Output is reversed*: TRUE if it is not a Parker square, FALSE otherwise. Ungolfed code (still the right way around): is_parker_square= function(m){ twice=any(table(m)-1) # some number must appear ... 6 Vyxal, 34 bytes Ṙ"vÞDƛh∑;??øTJv∑$Mƛf≈;a?fDU≠$∆²AWΠ Try it Online! Bug fixes make it even messier. 2 Python 3, 67 bytes lambda n:[print(*(max(y,x)+1 for y in range(n))) for x in range(n)] Try it online! 5 Wolfram Language (Mathematica), 16 bytes Max~Array~{#,#}& Try it online! 1 Haskell, 28 bytes f n=(<$>[1..n]).max<$>[1..n] Try it online! Generates each row by taking the max of each element of [1..n] and a fixed value equal to the row number. map(max 3)[1,2,3,4,5] = [3,3,3,4,5] We use <$> as an infix synonym for map. It would be nice to reuse the <$>[1..n], but it runs into type-checking issues 26 bytes, ... 0 05AB1E, 6 bytes Lã€àsä Try it online! Outputs as a 2D list. Link includes a footer to format the output. Lã€àsä # full program € # list of... à # maximum... € # s... à # of... € # each element of... ã # list of distinct combinations of two elements in... L # [1, 2, 3, ..., # ..., implicit input... L # ... 5 <>^v, 93 89 bytes i,tTv vj1< >I)iIT‹!0jv v < >J)jJI≥v_~ v >~ v ^ v≤TJ<\23< ` ^ < Explanation i pops the top of the stack (by default 0) and stores it into the variable i. , reads an integer from stdin, then t pops it and stores it into variable t. T pushes to the stack the value of the variable t and ... 0 PHP -F, 80 69 bytes for(;++$i<=$argn;)echo str_pad('',$i-1,$i).join(range($i,$argn))." "; Try it online! Quite naive solution, but I think it can be golfed more.. EDIT: saved 11 bytes by having a shorter str_pad so that the join(range( is no longer conditional 3 Python 2, 48 bytes r=range(1,input()+1) for x in r:print[x]*x+r[x:] Try it online! Prints a list for each row. 2 C# (Visual C# Interactive Compiler), 70 bytes a => new int[a][].Select((x,p)=>new int[a].Select((y,q)=>p>q?p+1:q+1)) I'm sure there is a shorter way to do this, but I can't find it. Try it online! 0 Husk, 4 bytes ´ṪYḣ Try it online! Outputs as a 2d matrix. ´ # argdup: apply a funciton to two copies of the same argument Ṫ # Ṫable: make a 'multiplication table' ... Y # ... using function Y = maximum of two values ḣ # with (duplicated) argument ḣ = range from 1 to input number 7 bytes - ¶mw´ṪYḣ - to ouput in the exact same format ... 0 Java (JDK), 84 bytes n->{for(int i=0;i<n*n;)System.out.printf("%d%c",i%n>i/n?i%n+1:i/n+1,++i%n<1?13:32);} Try it online! Alternative, 84 bytes too n->{for(int i=1,j=0;i<=n;)System.out.printf("%d%c",i>++j?i:j,(j%=n)<1?13+i-i++:32);} Try it online! 1 Ruby, 35 bytes ->x{(1..x).map{|y|[y]*y+[*y+1..x]}} Try it online! 4 Vyxal, 6 bytes ƛ£⁰ƛ¥∴ Try it Online! Returns an array of arrays ƛ # (1...input) Map... £ # Push to register ⁰ƛ # (1...input) Map... ¥ # Register ∴ # Maximum of the two Or, for grid output, 10 bytes: ƛ£⁰ƛ¥∴;Ṅ;⁋ Try it Online! ƛ ; # (1...input) Map... £ # Push to register ⁰ƛ ; # (1...input) Map... ¥ # ... 3 Python 3, 49 bytes f=lambda x:x*[x]and[a+[x]for a in f(x-1)]+[[x]*x] Try it online! 2 PowerShell Core, 40 bytes param($a)1..$a|%{"$(,$_*($_-1)+$_..$a)"} Try it online!

5

Factor, 35 bytes [ [1,b] dup [ max ] cartesian-map ] Try it online! cartesian-map Takes two sequences (in this case, both are [1, n]) and applies a quotation to each pair of elements, resulting in a matrix. In effect, we are mapping max over a coordinate matrix.

Top 50 recent answers are included