# Rotate a column

Given an integer k and either a block of text, or a 2d array that the inner arrays may have unequal lengths (that resembles a block of text), rotate every character or element in the k-th column up or down to the next position that exists.

### Example

Rotate the 20th column of the following text (1-based):

A line with more than k characters.
A longer line with more than k character.
A short line.
Rotate here: ------v--
This is long enough.

This is not enough.
Wrapping around to the first line.


Output:

A line with more thtn k characters.
A longer line with aore than k character.
A short line.
Rotate here: ------m--
This is long enoughv

This is not enough.
Wrapping around to .he first line.


Rotating the k-th column of the same input where 35 < k < 42 would yield the input text unchanged.

### Rules

• You may use raw text, an array of lines, a 2d array of characters, or any reasonable format to represent the data. You may also use data types other than characters.
• The number of possible values of the data type of the elements must be at least 20 if your code length depends on it, otherwise at least 2. This could be a subset of the characters or other values supported in the native type.
• Spaces and any kind of null values are just normal values, if you allow them in the input. You may also simply exclude them in the element type.
• Rule change: You are allowed to pad the shorter arrays with a generic default value (such as spaces), if you prefer using arrays with equal lengths to store the data.
• k could be 0-based or 1-based. It is guaranteed to be inside the longest line in the input (implying the input has at least one non-empty line).
• You may choose whether it rotates up or down.
• Either just rotate one position, or rotate n positions where n is a positive integer given in the input.
• Shortest code wins.

# Python 2, 111110109999896 94 bytes

lambda a,n:[l[:n]+(l[n:]and[L[n]for L in a[i:]+a if L[n:]][1]+l[n+1:])for i,l in enumerate(a)]


Try it online!

Takes input as a list of lines and 0-index column, and returns a list of strings.

Column is rotated up 1.

-11 bytes, thanks to Jo King

# APL (Dyalog Extended), 9 bytesSBCS

Full program. Prompts stdin for 2D block of text, then k (0-based or 1-based, depending on APL's current setting), then n. Positive n rotate up, negative n rotate down.

The domain consists of either one of the following:

1. all Unicode characters, except spaces, leaving 1114111 allowed values, which is more than the required 20.

2. all numbers, except 0, leaving approximately 2129 allowed values, which is more than the required 20.

Since APL requires 2D blocks to be rectangular, the input must be padded with spaces/zeros. This can be done automatically by entering ↑ to the left of a list of strings/numerical lists.

⎕⌽@≠@⎕⍢⍉⎕


Try it online! (the apparent spaces are actually non-breaking spaces)

⎕ prompt for text block

⍢⍉ while transposed:

@⎕ apply the following on the input'th row:

@≠ at elements different from their prototype (space for characters, zero for numbers):

⎕⌽ rotate "input" steps left

# APL (Dyalog Unicode), 22+ bytesSBCS

This version allows the full character set by using zeros as identifiable fill element.

0~¨⍨↓⍉⎕⌽@(0≠⊢)@⎕⍉↑0,¨⎕


Try it online!

This of course means that zeros are not allowed in numeric arguments. The corresponding program for all numbers would have the three occurrences of 0 replaced by ' ' and thus use space as fill:

' '~¨⍨↓⍉⎕⌽@(' '≠⊢)@⎕⍉↑' ',¨⎕


If we truly want the full ranges of (even a mixture of) both characters and numbers, we could use null as fill:

n~¨⍨↓⍉⎕⌽@(n≠⊢)@⎕⍉↑⎕,¨⍨n←⎕NULL


And finally, if we wanted to include nulls and objects in the input domain, we could define a fill class and use instances of this as fills:

~∘I¨⍨↓⍉⎕⌽@(~⊢∊I←⎕INSTANCES⊢∘C)@⎕⍉↑⎕,¨⍨⎕NEW⎕FIX':Class C' ':EndClass'

• Now officially declare this (and the new answers like this) as a valid answer. Sorry if this has bothered you too much. Mar 28, 2019 at 23:55
• Shorter than your null version: n~¨⍨↓⍉⎕⌽@(≢¨)@⎕⍉↑⎕,¨⍨n←⊂⊂⍬. Maybe you could add modded ↑ ↓ in your extension to help further golfing (but I'm not exactly sure how useful they are). Mar 29, 2019 at 0:09
• @jimmy23013 Yeah, I thought of that, but then it can't take lists of arbitrarily nested stuff. The last one is the ultimate solution, especially if C and I are localised so they don't pollute: {~∘I¨⍨↓⍉⎕⌽@(~⊢∊I←⎕INSTANCES⊢∘C)@⎕⍉↑⎕,¨⍨⎕NEW⎕FIX I←C←':Class C' ':EndClass'}
Mar 29, 2019 at 0:43

# Zsh, 94 87 78 74 69 68 bytes

-7 bytes by changing to an arithmetic ternary, -9 bytes by changing the character in-place (TIL), -4 bytes by inputting the index on stdin and the strings as arguments, -5 bytes by using a string instead of an array to store the rotating characters, -1 byte thanks to @pxeger letting me know ${c[]) allows arithmetic ternary. read i for s;c+=$s[i]
c=$c[-1]$c
for s;s[i]=${c[$#s<i?0:++j]}&&<<<$s  Here are the keys to making this answer work: • $array[0] or $string[0] is always empty • $array[n] or $string[n] is empty if n is larger than the length of the array/string • array[i]=c or string[i]=c will replace the element/character. • In $[$#s<i?0:++j], j is not incremented if $#s<i.

In the original 94 byte answer, there was an interesting issue I came across involving using <<< to print. I had to use echo to get around it:

for s;echo $s[0,i-1]$c[$[$#s<i?0:++j]]${s:$i}


The reason for this can be seen here:

echo $ZSH_SUBSHELL # prints 0 <<<$ZSH_SUBSHELL    # prints 1


Here-strings are run in subshells because they are given as stdin to another program. If there is no program given, it is implicitly given to cat. You can see this with <<< $_. <<<$ZSH_SUBSHELL is similar to echo $ZSH_SUBSHELL | cat. Since we need to increment j, we can't be in a subshell. • -1 byte by changing $c[$[...]] to ${c[...]}: ato.pxeger.com/… Nov 15, 2021 at 20:17
• Ah, so ${ } works as well, thanks. Dec 27, 2021 at 19:42 # Java 8, 107106135 107 bytes k->m->{int s=m.length,i=-1;for(char p=0,t;i<s;t=m[i%s][k],m[i%s][k]=p<1?t:p,p=t)for(;m[++i%s].length<=k;);}  +29 bytes for a bug-fix.. 0-indexed; rotates down like the example. Input as a character-matrix; modifies the char-matrix instead of returning a new one to save bytes. Try it online. Explanation: k->m->{ // Method with integer and char-matrix parameters and no return-type int s=m.length, // Amount of lines in the matrix s i=-1; // Index-integer i, starting at -1 for(char p=0, // Previous-character, starting at 0 t; // Temp-char, uninitialized i<s // Loop as long as i is smaller than s: ; // After every iteration: t=m[i%s][k], // Set the temp to the kth character of the i'th line m[i%s][k]= // Replace the k'th character of the i'th line with: p<1? // If p is still 0: t // Set it to the temp we just set : // Else: p, // Set it to the previous-character instead p=t) // And then replace p with the temp for the next iteration for(;m[++i // Increase i by 1 before every iteration with ++i, %s].length // And continue this loop until the length of the i'th line <=k;);} // is smaller than or equal to the input k  • One thing I noticed is that you make an assumption that the first line has enough characters - char p=m[0][k] - if it doesn't, won't this throw an exception? Nice job btw. You are beating my C# attempt by a large margin :) – dana Mar 28, 2019 at 13:31 • @dana Ah, shit, you're right.. I'm probably beating you by this large of a margin because I accidentally make that assumption.. Will try to fix it. Mar 28, 2019 at 13:33 • @dana Fixed, thanks for noticing. Mar 28, 2019 at 13:44 • @dana And back to 107 again. ;) Mar 28, 2019 at 19:45 • @EmbodimentofIgnorance Ah, forgot to change that n to k. I usually use n for integer-inputs, but since the question uses $k$ I later on changed it (but apparently not everywhere). As for int p=0,t; then I will need a cast to char when assigning p to a cell (m[i%s][k]=(char)(p<1?t:p)). And although I could take the input as an integer-matrix, I personally think int-matrix =/= string/string-list/char-matrix.. Mar 29, 2019 at 7:21 # R, 62 bytes function(L,n){L[A,n]<-rep(L[A<-L[,n]!=' ',n],2)[1+1:sum(A)];L}  Try it online! Takes input as a space-padded matrix of characters. Rotates upwards. All thanks to Kirill L.! # R, 74 bytes function(L,n){substr(L[A],n,n)=rep(substr(L[A<-nchar(L)>=n],n,n),2)[-1] L}  Try it online! This submission predates the allowance of padded lines. Aliasing substr here won't work because we're calling substr and substr<- in the first line. I/O as a list of non-padded lines; rotates upwards. • Since consensus allows modifying inputs, we can do this crazy thing Mar 29, 2019 at 9:49 • Also, OP relaxed the rules, so that it is now possible to work with space-padded matrices, something like this Mar 29, 2019 at 9:50 • @KirillL. I don't think that R passes by reference so we probably aren't allowed to do that; it strikes me that this only works if the argument is named L in the parent environment. I'll happily update to the space-padding, though! Mar 29, 2019 at 14:42 • Ah, I see, you're right. I came up with this idea looking at my Ruby answer (which saves a whole 1 byte this way :)), but the languages indeed behave differently in this situation. Mar 29, 2019 at 15:16 # C# (Visual C# Interactive Compiler), 82 bytes k=>a=>{var c='0';a.Where(b=>b.Count>k&&((b[k],c)=(c,b[k])).c>0).ToList()[0][k]=c;}  Try it online! Credit to @ASCIIOnly for suggesting foreach which led to a 12 byte savings! -8 bytes thanks to @someone! -1 byte thanks to @EmbodimentofIgnorance! • 184 bytes Mar 28, 2019 at 14:41 • Maybe 183 if using ints instead of chars Mar 28, 2019 at 14:46 • @ExpiredData ew int instead of char Mar 29, 2019 at 6:05 • too bad you can't use a foreach since it's the opposite order :( Mar 29, 2019 at 6:08 • Use dynamic to merge declarations and save 2 bytes (I've never seen this before!)Try it online! Mar 30, 2019 at 7:25 # Ruby, 57 bytes ->a,k{b=a.map{|i|i[k]}-[p];c=-2;a.map{|i|i[k]&&=b[c+=1]}}  Try it online! Takes input as an array of lines a. Rotates the text down at 0-based position k. Returns by modifying the input a. # K4, 22 41 bytes ## New Rules: Solution: {+@[+x;y;.q.rotate 1]}  If the input is already padded to the maximum length, then this becomes much shorter. ## Old Rules: Solution: {.[x;i;:;.q.rotate[1;x . i:(&y<#:'x;y)]]}  Explanation: Not sure if I'm missing something... 0 index, rotates up (change the 1 to -1 for rotate down) {.[x;i;:;.q.rotate[1;x . i:(&y<#:'x;y)]]} / the solution { } / lambda taking implicit x and y .[x; ;:; ] / index apply assignment back into x .q.rotate[1; ] / left rotate 1 character ( ; ) / two item list y / index to rotate #:'x / count (#:) each (') input y< / index less than ? & / indexes where true i: / assign to variable w x . / index into x i / indexes we saved as i earlier  # 05AB1E, 21 bytes ʒg‹}U¹εXyk©diX®<èIèIǝ  Can definitely be golfed some more.. 0-indexed; input and output both as a list of strings. It rotates down like the example, but < can be replaced with > to rotate up instead. Try it online (footer joins the list by newlines, remove it to see the actual list output). Explanation: ʒ } # Filter the (implicit) input-list by: g # Where length of the current string ‹ # is larger than the (implicit) input-integer U # Pop and store this filtered list in variable X ¹ε # Map over the first input-list again: Xyk # Get the index of the current string in variable X © # Store it in the register (without popping) di # If the index is not -1, so the current string is present in variable X X®<è # Get the (index-1)'th string in variable X Iè # Get the character at the index of the input-integer Iǝ # And insert it at the index of the input-integer in the current string  # Japt v2.0a0, 18 bytes 0-based with input & output as a multi-line string. Rotates up by 1. There's gotta be a shorter method! yÈr\S_Y¦V?Z:°TgXrS  Try it yÈr\S_Y¦V?Z:°TgXrS :Implicit input of string U & integer V y :Transpose È :Pass each line X at 0-based index Y through the following function & transpose back r : Replace \S : RegEx /\S/g _ : Pass each match Z through the following function Y¦V : Test Y for inequality with V ?Z: : If true, return Z, else °T : Increment T (initially 0) g : Index into XrS : X with spaces removed  • I haven't looked closely at the comments and new rules (so perhaps it's somewhere mentioned it's allowed now, while it wasn't before), but is it allowed to skip spaces of the initial input? Let's say you change the input-index to 6, your answer would skip the space at line with in the first line and at Rotate here in the fourth line, whereas most of the other answers would rotate that space as well. Mar 29, 2019 at 14:30 • @KevinCruijssen, I'm a bit confused by all the additional rules & allowances but, if it is an issue, it looks like I can get around that by not allowing spaces in the input. I think. Mar 29, 2019 at 15:12 • "I think" This part is indeed how I would also respond, haha. I have no idea what is mandatory and optional anymore, but I think you can indeed choose to omit spaces in the in- and output; I think you can choose to count spaces or not; and I think you can use trialing spaces in the output or not; etc. All on all rather confusing. Ah well.. Mar 29, 2019 at 17:04 # Jelly, 16 bytes z⁷⁹ịỴFṙ-ṁƲY⁸ṛ⁹¦"  A dyadic Link accepting a list of lines (lists of characters containing no newline characters) on the left and an integer on the right which returns a list of lines. Try it online! (footer splits on newlines, calls the Link, and joins by newlines again) ### How? z⁷⁹ịỴFṙ-ṁƲY⁸ṛ⁹¦" - Link: lines L; index I e.g. example in question; 20 z⁷ - transpose L with filler '\n' ['AAART\nTW', ' oh\nhr', ...] ⁹ị - Ith item 'am\nv.\n\nt' Ỵ - split at newlines ['am', 'v.', '', 't'] Ʋ - last four links as a monad - i.e. f(X): F - flatten 'amv.t' - - -1 ṙ - rotate left by 'tamv.' ṁ - mould like X ['ta', 'mv', '', '.'] Y - join with newlines 'ta\nmv\n\n.' - -- call this C ⁸ - chain's left argument, L " - zip with - i.e. [f(L1,C1), f(L2,C2), ...]: ¦ - sparse application... ⁹ - ...to indices: chain's right argument, I ṛ - ...of: right argument, Cn  # perl 5 (-p), 75 bytes k is 0-indexed, rotate down s/.*//;$r="^.{$&}";s/ //;/$r(.)/;$c=$1;s/$r\K.(?=(?s:.)*?$r(.)|)/$1||$c/gme


TIO

# Perl 6, 38 33 bytes

Modifies the array in place (rules don't disallow)

{@^a.grep(*>$^b+1)[*;$b].=rotate}


Try it online!

• @joking At first I thought storing it rather than outputting it would be a bit cheating, but rereading the rules, there's no actual stipulation to output so … hooray. Doing a (…)(…) to get 31 like you have definitely seems to be cheating though, since it's effectively hoisting a call out of the block, but it can still be done with 33 passing them simultaneously with a single call so I'm going go with that. Mar 30, 2019 at 2:25
• ah oops, i pasted the wrong link. you got what I mean to comment though. Currying input is perfectly fine though (though it doesn't work in this case), and modifying an argument passed by reference is a standard forn of allowed input
– Jo King
Mar 30, 2019 at 3:54

# JavaScript (Node.js), 52 bytes

k=>a=>a.filter(b=>b[k]&&([b[k],a]=[a,b[k]]))[0][k]=a


Try it online!

-7 bytes thanks to Shaggy!

• 63 bytes. Can probably be golfed further. Mar 30, 2019 at 15:02
• @Shaggy - nice :) most of the time I see JS answers doing all sorts of crazy things. Figured this time I'd give it a shot since I had a strategy.
– dana
Mar 30, 2019 at 15:12
• Oh, nicely golfed! :) Mar 31, 2019 at 2:01

# Charcoal, 3428 21 bytes

θＪη⁰≔ΦＫＤＬθ↓℅ιζＵＭζ§ζ⊖κ


Try it online! Link is to verbose version of code. Takes an array of strings as input. 0-indexed. Edit: Now that PeekDirection has been fixed, I can manipulate it directly. Explanation:

θ


Print the input strings.

Ｊη⁰


≔ΦＫＤＬθ↓℅ιζ


Extract the cells that have been printed in.

ＵＭζ§ζ⊖κ


Replace each printed cell with the value of the previous cell (cyclically). Conveniently the cell values are read at the time of the PeekDirection call so the fact that the MapCommand call writes new values into the cells doesn't matter.

# Pip-rn, 32 bytes

POgY#(g@_)>aFI,#gFiyAE@ySsg@i@ag


0-indexed, rotates down. Try it online!

Filters to find the indices of all rows that are long enough to participate in the rotation. Then loops over those rows, swapping the appropriate character on each row with a temp variable s. Visiting the first row again at the end swaps the dummy value back out again.

# Jelly, 19 bytes

ZnÄ×\$ịḟ¹ṙ-;ɗɗʋ€⁹¦⁶Z


Try it online!

1-indexed. Rotates down. A monadic link that takes a right-padded list of Jelly strings (a list of lists of characters) as the first argument and k as the second. Spaces are forbidden in the input except as right padding, but all other characters are permitted.

As implemented on TIO, the footer splits a single string input into a list of strings and right-pads it, but this is for convenience; as I understand it, the result of that step is permitted input for the main link per the rules.

# GFortran, 182 bytes

Requires user to input k and n on the first line, where k is the column to rotate, and n is the number of rows of text. Subsequent inputs are the lines of text to be rotated. This was a pain to write! Fortran is so pedantic! Try it Online.

character(99),allocatable::A(:);character(1)r,s
if(r.ne.' ')then;A(i)(k:k)=s;s=r;endif;enddo
A(1)(k:k)=s;print'(A)',A;end


Original, ungolfed program here, with comments and compilation notes: rotcol.f

Saved 20B by reading from stdin rather than a file. Saved 14B by using implicit integers for i k n. Saved 4B by cleanup of spaces and ::. Saved 17B by simplfying logic, and cutting i/o formatting guff.
203 bytes
199 bytes

# APL (Dyalog Unicode), 19 chars

{⍉¯1⌽@{' '≠⍵}@⍺⍉↑⍵}

{                  ↑⍵} ⍝ from nested vector of char vectors to char matrix (padding=space)
{                ⍉   } ⍝ transpose
{              @⍺     } ⍝ apply on row ⍺ (left argument)
{  ¯1⌽@{' '≠⍵}       } ⍝ rotation towards the right only elements that are note spaces
{⍉                   } ⍝ transpose back


Try it online!

# T-SQL, 195 bytes

WITH C as(SELECT rank()over(order by i)r,sum(1)over()c,*FROM @t
WHERE len(x)>=@)SELECT
isnull(stuff(c.x,@,1,substring(e.x,@,1)),t.x)FROM @t t
LEFT JOIN c ON t.i=c.i
LEFT JOIN c e ON e.r%c.c+1=c.r


Try it online ungolfed version