22
\$\begingroup\$

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!

\$\endgroup\$
9
  • 2
    \$\begingroup\$ I think we've had this before, with a multi-line string as input and outputting each step of the characters dropping into place. \$\endgroup\$
    – Shaggy
    Sep 18, 2021 at 11:31
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – Shaggy
    Sep 18, 2021 at 11:36
  • 3
    \$\begingroup\$ @Shaggy Another difference is that there's never any hole in the patterns of the other challenge. \$\endgroup\$
    – Arnauld
    Sep 18, 2021 at 11:40
  • 2
    \$\begingroup\$ 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? \$\endgroup\$
    – Arnauld
    Sep 18, 2021 at 11:50
  • 1
    \$\begingroup\$ 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? \$\endgroup\$
    – AviFS
    Sep 26, 2021 at 1:01

25 Answers 25

12
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ @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. \$\endgroup\$
    – Shaggy
    Sep 18, 2021 at 23:38
  • 7
    \$\begingroup\$ @Downvoter, care to leave a comment? :\ \$\endgroup\$
    – Shaggy
    Sep 18, 2021 at 23:38
  • \$\begingroup\$ Thanks for clarifying! (+1) \$\endgroup\$
    – Luis Mendo
    Sep 19, 2021 at 17:10
8
\$\begingroup\$

Haskell, 41 bytes

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
\$\endgroup\$
7
\$\begingroup\$

R, 26 bytes

Or R>=4.1, 19 bytes by replacing the word function with \.

function(m)apply(m,2,sort)

Try it online!

\$\endgroup\$
7
\$\begingroup\$

C (clang), 80 79 74 73 bytes

x,y,*u;f(*a,w,h){for(x=w*h*--h;x--;u[w]^=y)*u^=y=w[u=a+x%h*w-x/h/~h]<*u;}

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.

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;
}
\$\endgroup\$
0
6
\$\begingroup\$

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

\$\endgroup\$
1
  • 3
    \$\begingroup\$ BQN translation: ∧˘⌾⍉ \$\endgroup\$
    – Razetime
    Sep 18, 2021 at 14:17
6
\$\begingroup\$

Python 3, 34 bytes

lambda a:zip(*map(sorted,zip(*a)))

Try it online!

-3 bytes thanks to pxeger

\$\endgroup\$
1
  • \$\begingroup\$ You don't need the outer [*] - returning an iterable is perfectly acceptable \$\endgroup\$
    – pxeger
    Sep 18, 2021 at 12:23
5
\$\begingroup\$

Vyxal, 6 bytes

ÞTvsÞT

Try it Online!

There's probably something cleverer / shorter.

ÞT     # Transpose
  vs   # Sort each
    ÞT # Transpose
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

Python 3 + NumPy, 18 bytes

lambda a:a.sort(0)

Try it online!

Input a np.array, output by modify it in-place.

\$\endgroup\$
3
\$\begingroup\$

Factor, 34 bytes

[ flip [ natural-sort ] map flip ]

Try it online!

Transpose (flip), sort each row, transpose.

\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 53 \$\endgroup\$
    – l4m2
    Sep 19, 2021 at 19:57
2
\$\begingroup\$

C (clang), 92 89 bytes

c,x,y,*p;f(*a,w,h){for(x=0;x<w;x++)for(c=y=0;y<h*2;y++<h?c+=*p:(*p=y-h>h-c))p=a+x+y%h*w;}

-3 bytes thanks to ceilingcat!!

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ 111 bytes \$\endgroup\$
    – Noodle9
    Sep 18, 2021 at 13:12
  • \$\begingroup\$ If you drop the comma separators 109 bytes \$\endgroup\$
    – Noodle9
    Sep 18, 2021 at 13:18
  • \$\begingroup\$ The !! in c+=!!a[x+r++*w] seems useless. \$\endgroup\$
    – Arnauld
    Sep 18, 2021 at 13:26
  • \$\begingroup\$ Suggest x=w;x--; instead of x=0;x<w;x++ \$\endgroup\$
    – ceilingcat
    Sep 29, 2021 at 20:02
2
\$\begingroup\$

MY, 11 bytes

⎕⍉86ǵ'ƒ⇹(⍉←

Try it online!

⎕⍉86ǵ'ƒ⇹(⍉←
⎕              - Input
 ⍉             - Transpose
   86ǵ'ƒ⇹(     - Sort each
           ⍉   - Transpose again
             ←  - Output
\$\endgroup\$
2
\$\begingroup\$

RAD, 4 bytes

⍉<⍉⍵

Try it online!

Transpose the input (⍉⍵), sort each (<), then retranspose .

\$\endgroup\$
2
\$\begingroup\$

jq, 28 bytes

[transpose[]|sort]|transpose

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Ruby, 38 bytes

->l{l.transpose.map(&:sort).transpose}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 4 bytes

ø€{ø

Similar as some of the other answers.

Try it online or verify all test cases.

Explanation:

ø     # Zip/transpose the (implicit) input-matrix, swapping rows/columns
 €{   # Sort each inner list
   ø  # Zip/transpose back
      # (after which the result is output implicitly)
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Pari/GP, 15 bytes

a->vecsort(a~)~

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 35 20 bytes

WS⊞υι↑Eθ⭆²Φ⭆υ§νκ⁻Iνλ

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

WS⊞υι

Read the input.

↑Eθ⭆²Φ⭆υ§νκ⁻Iνλ

Map over each column, taking the transpose and filtering out 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:

WS⟦ι⟧↑WKK«WKK«F⁼⪫KD²↓ω10↓01↑»↓WKK↓↗

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:

WS⟦ι⟧

Copy the input to the canvas.

Start at the bottom of the first column.

WKK«

Repeat while there are still columns to process.

WKK«

Repeat until this column has been processed.

F⁼⪫KD²↓ω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.

»↓WKK↓↗

Locate the bottom of the next column.

\$\endgroup\$
0
\$\begingroup\$

Pyth, 4 bytes

CSMC

Try it online!

CSMC

   C  # transpose the matrix
 SM   # sort each row
C     # transpose again
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.