# Apply gravity to this matrix

This was inspired by this question. Given an $$\m\times n\$$ matrix of $$\0\$$'s and $$\1\$$'s, apply "gravity" to it. This means to drop down all the $$\1\$$'s as if they were affected by gravity.

For example

[[1,0,1,1,0,1,0]
[0,0,0,1,0,0,0]
[1,0,1,1,1,1,1]
[0,1,1,0,1,1,0]
[1,1,0,1,0,0,1]]


Should result in

[[0,0,0,0,0,0,0]
[0,0,0,1,0,0,0]
[1,0,1,1,0,1,0]
[1,1,1,1,1,1,1]
[1,1,1,1,1,1,1]]


As all $$\1\$$'s have been dropped down.

## input

Input will be atleast $$\1\times 1\$$. You may take input in all reasonable forms (Bitsets, arrays, Lists) and either output the result, return a new Bitset, array or list or simply modify the input.

This is code golf, so the answer with the fewest bytes wins!

## test-cases

More test-cases:

[[1,0]                   [[0,0]
[0,0]            ->      [1,0]
[1,0]]                   [1,0]]

[[1,1,1,1,1]            [[1,0,1,1,0]
[1,0,1,1,0]      ->     [1,1,1,1,0]
[1,1,1,1,0]]            [1,1,1,1,1]]

[[1]]             ->    [[1]]


The brackets are just there to visualize arrays, they are not required in your output!

• I think we've had this before, with a multi-line string as input and outputting each step of the characters dropping into place. Commented Sep 18, 2021 at 11:31
• This is the one I was thinking of. I had the input format wrong but, to me, they're still sufficiently similar. As my vote is a hammer, though, I'll hold off on VTCing in case someone can show that working with a binary matrix and only outputting the final matrix allows for different solutions. Commented Sep 18, 2021 at 11:36
• @Shaggy Another difference is that there's never any hole in the patterns of the other challenge. Commented Sep 18, 2021 at 11:40
• A 'Bitset' seems to be a Java and/or C++ thing. May we just work on integers whose binary representations are the rows of the matrix? Commented Sep 18, 2021 at 11:50
• Can we take input as 11111-10110-11110 for a 3×4 matrix (the second testcase). And assuming so, can - be replaced by any delimiter aside from 0 & 1? Commented Sep 26, 2021 at 1:01

# Japt v2.0a0, 2 bytes

Transposes, sorts each row and automatically transposes back.

yn


Try it

## Japt, 3 bytes

Transpose, sort rows, transpose.

yÍy


Try it

• @LuisMendo, when you pass a function or method (n for sort in this case) to the y transpose method in v2.x it automatically transposes back after. In v1.x you would have to transpose, map, sort and transpose again. Commented Sep 18, 2021 at 23:38
• Thanks for clarifying! (+1) Commented Sep 19, 2021 at 17:10

import Data.List
t=transpose
t.map sort.t


Try it online!

This is the same boring answer you've already seen in this thread. Unfortunately it's quite short. Here's a fun answer that doesn't import anything:

# No imports, 53 49 bytes

q=foldr.zipWith
e=[]:e
q(:)e.q([(0:),(++[1])]!!)e


Try it online!

This answer is a little odd.

# Explanation

Let's first solve an easier problem. Instead of having gravity acting down it will act to the right.

Here each row acts independently so we can just solve it on 1 row and map it across the whole thing. We start by making a function

0#x=0:x
1#x=x++[1]


This takes a list and a value, adds it to the front if it is 0 and the end if it's 1. This will always insert new values to the proper place in the row, so to build the row we can just do:

foldr(#)[]


and to make the complete thing we just add the map

f=map$foldr(#)[]  Ok, now we want to solve the original problem. How can we make this act on the columns? The idea is to use zipWith. zipWith acts independently on the columns of two lists to combine them. So zipWith(#) will take a list of columns and a list of values and add each value to the corresponding column. To do this repeatedly we use foldr e=[]:e foldr(zipWith(#))e  The issue however arises that because we are treating the columns as lists the output is transposed. So we need to transpose it back. If we take a look at the short way to transpose in Haskell here e=[]:e foldr(zipWith(:))e  we instantly notice that this is extremely similar to the code we have already written, so we can abstract it. When we do that and add in our transpose we get nearly the final answer 0#x=0:x 1#x=x++[1] q=foldr.zipWith e=[]:e f=q(:)e.q(#)e  The last change is that we can express our original function (#) in pointfree as ([(0:),(++[1])]!!) and substitute it where (#) goes. q=foldr.zipWith e=[]:e f=q(:)e.q([(0:),(++[1])]!!)e  # R, 26 bytes Or R>=4.1, 19 bytes by replacing the word function with \. function(m)apply(m,2,sort)  Try it online! # Python 3, 34 bytes lambda a:zip(*map(sorted,zip(*a)))  Try it online! -3 bytes thanks to pxeger • You don't need the outer [*] - returning an iterable is perfectly acceptable Commented Sep 18, 2021 at 12:23 # C (clang), 80 79 73 64 bytes i;f(*a,w,h){for(i=w;i<w*h;)i=a[i-w]>a[i]?a[i-w]---a[i]+++w:i+1;}  Try it online! This is essentially a strided sort looped over all columns except instead of swapping out of order elements, both elements are xor'ed by one out of order elements are decremented and incremented until they are in order. Thanks to @jdt for the -9! Slightly less golfed x,*u; f(*a,w,h){ for(x=w*h*--h;x--;) w[u=a+x%h*w-x/h/~h]<*u? u[w]^=1, *u^=1 : 0; }  # APL (Dyalog Extended), 5 bytes ∧⍤1⍢⍉  Try it online! Sort ∧ each row ⍤1 while transposed ⍢⍉ # APL (Dyalog Unicode), 9 bytes ⊖⍳∘≢∘.≤+⌿  Try it online! +⌿ sum of each column ⍳∘≢ indices from 1 to the number of rows ∘.≤ ≤-table between these two vectors ⊖ vertically reverse the resulting matrix # MATLAB / Octave, 13 bytes @(M)sort(M,1)  Try it online! ### How it works Anonymous function that sorts along the 1st dimension, i.e. vertically. # Vyxal, 6 bytes ÞTvsÞT  Try it Online! There's probably something cleverer / shorter. ÞT # Transpose vs # Sort each ÞT # Transpose  # Jelly, 4 bytes ZṢ€Z  Try it online! A monadic link which takes a 2d array of booleans. Z # Transpose € # For each Ṣ # Sort Z # Transpose back  # Factor, 34 bytes [ flip [ natural-sort ] map flip ]  Try it online! Transpose (flip), sort each row, transpose. # JavaScript (ES6), 53 bytes Suggested by @l4m2: counting the number of 1's on each column, using .filter(). Returns a matrix of Boolean values. m=>m.map((r,y)=>r.map((_,x)=>!m.filter(r=>!r[x])[y]))  Try it online! # JavaScript (ES6), 55 bytes Sorting the columns. m=>m.map((r,y)=>r.map((_,x)=>m.map(r=>r[x]).sort()[y]))  Try it online! # JavaScript (ES6), 57 bytes Counting the number of 1's on each column, using .some(). Returns a matrix of Boolean values. m=>m.map((r,y)=>r.map((_,x)=>m.some(r=>!m[n+=r[x]],n=y)))  Try it online! • 53 – l4m2 Commented Sep 19, 2021 at 19:57 # Python 3 + NumPy, 18 bytes lambda a:a.sort(0)  Try it online! Input a np.array, output by modify it in-place. # Minecraft, 0 bytes This is a bit cheaty, but the question does state you can take input in "all reasonable forms" and a grid of Minecraft blocks seems reasonable enough. Input is given as a vertical grid of sand and air blocks, with 1 represented by a sand block and 0 represented by an air block. The output is available in the same format and location a moment after the input is given. This works, of course, because sand blocks are affected by gravity. • Fair enough I think. Commented May 27 at 17:13 # MY, 11 bytes ⎕⍉86ǵ'ƒ⇹(⍉←  Try it online! ⎕⍉86ǵ'ƒ⇹(⍉← ⎕ - Input ⍉ - Transpose 86ǵ'ƒ⇹( - Sort each ⍉ - Transpose again ← - Output  # RAD, 4 bytes ⍉<⍉⍵  Try it online! Transpose the input (⍉⍵), sort each (<), then retranspose ⍉. # jq, 28 bytes [transpose[]|sort]|transpose  Try it online! # Pyth, 4 bytes CSMC  Try it online! CSMC C # transpose the matrix SM # sort each row C # transpose again  # C (clang), 92 bytes c,x,y,*p;f(*a,w,h){for(x=0;x<w;x++)for(c=y=0;y<h*2;y++)p=a+x+y%h*w,y<h?c+=*p:(*p=y-h>=h-c);}  Try it online! • 111 bytes Commented Sep 18, 2021 at 13:12 • If you drop the comma separators 109 bytes Commented Sep 18, 2021 at 13:18 • The !! in c+=!!a[x+r++*w] seems useless. Commented Sep 18, 2021 at 13:26 • Suggest x=w;x--; instead of x=0;x<w;x++ Commented Sep 29, 2021 at 20:02 # Ruby, 38 bytes ->l{l.transpose.map(&:sort).transpose}  Try it online! # 05AB1E, 4 bytes ø€{ø  Similar as some of the other answers. Explanation: ø # Zip/transpose the (implicit) input-matrix, swapping rows/columns €{ # Sort each inner list ø # Zip/transpose back # (after which the result is output implicitly)  # JavaScript, 142 Bytes for(j=0,l=a.length,w=a[0].length,c=new Array(l),e=1;j<w;j++){for(i=0;i<l;i++){if(a[i][j]){p=l-e++;!c[p]&&(c[p]=new Array(w));c[p][j]=1}}e=1;}  Where a is the input array and c is the output array. Might be cheating since I am pulling a vacuum on all the 0s rather then applying gravity to all the 1s. It works similar to the rest of the solutions where you need to rotate the array and sort it but it does it all in one go and without using any of the built in sort/rotate functions. # Pari/GP, 15 bytes a->vecsort(a~)~  Try it online! # TI-Basic, 54 bytes Input [A] dim([A] For(I,1,Ans(2 Matr►list([A],I,A SortA(ʟA For(J,1,dim(ʟA ʟA(J→[A](J,I End End  Output is stored in [A], which was the inputted matrix. # Swift 5.5/Xcode 13.0, 215 bytes var c=[Int:Int]();let d=m.count;let e=m[0].count;for i in 0..<e{for j in 0..<d{c[i,default:0]+=m[j][i]}};var r=Array(repeating:Array(repeating:1,count:e),count:d);for k in c{for i in 0..<d-k.1{r[i][k.0]=0}};return r  Try it online! # Retina 0.8.2, 39 bytes +(?<=(.)*)1(.*¶(?<-1>.)*(?(1)^))0 0$+1


Try it online! Takes input as a list of digit strings although commas can be redundantly included as per the example link. Explanation: .NET's balancing groups are used to ensure that the regular expression matches a 1 directly above a 0; the digits are thus exchanged. $+ is used instead of $2 due to the following digit which would otherwise be interpreted as part of the substitution name. The + modifier repeats the substitutions until all of the gravity has been applied.

# Charcoal, 3520 18 bytes

ＷＳ⊞υι↑Ｅθ⭆01⁻⭆υ§νκλ


Try it online! Link is to verbose version of code. Takes input as a list of digit strings. Explanation:

ＷＳ⊞υι


↑Ｅθ⭆01⁻⭆υ§νκλ


Map over each column, taking the transpose and removing the 0s and 1s each time, so that the 1s are effectively sorted to the front, but then print the whole lot vertically which rotates the result so that the mapped rows turn back into columns but also the 1s end up at the bottom as desired.

Previous 35-byte canvas-based version:

ＷＳ⟦ι⟧↑ＷＫＫ«ＷＫＫ«Ｆ⁼⪫ＫＤ²↓ω10↓01↑»↓ＷＫＫ↓↗


Try it online! Link is to verbose version of code. Takes input as a list of digit strings although commas can be redundantly included as per the example link. Explanation:

ＷＳ⟦ι⟧


Copy the input to the canvas.

↑


Start at the bottom of the first column.

ＷＫＫ«


Repeat while there are still columns to process.

ＷＫＫ«


Repeat until this column has been processed.

Ｆ⁼⪫ＫＤ²↓ω10


If this column contains a 1 above a 0, then...

↓01


... switch the characters, moving down so that the 1 gets considered for gravity again on the next pass.

↑


Try the next digit.

»↓ＷＫＫ↓↗


Locate the bottom of the next column.

# Arturo, 59 bytes

$=>[f:$->m->map size m\0'i->map m'r->r\[i-1]f map f&=>sort]


Try it!

# Perl 5-lF, 69 bytes

$a=0;map$r[$a++]+=$_,@F}{say@$_ for reverse map[map$_-->0|0,@r],1..\$.


Try it online!

# UiuaSBCS, 8 bytes

⍜⍉≡(⊏⍏.)


Try it!

• ⍉≡⊕⊂.⍉ for 6 bytes, based on RomanPro100’s solution to the align-to-top-left challenge Commented May 29 at 17:22

# K (ngn/k), 12 bytes

Solution:

{+{x@<x}'+x}


Try it online!

Explanation:

{+{x@<x}'+x} / the solution
{         x} / function taking implicit x argument
+   / flip (transpose) input matrix
{    }'    / apply function to each (') row of the matrix
<x      / get indices to sort row ascending (<)
x@        / apply (@) these indices to the row
+           / flip (transpose) matrix back again
`