# 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.

# 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. – jimmy23013 Mar 28 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). – jimmy23013 Mar 29 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'} – Adám Mar 29 at 0:43

# 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

# 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 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. – Kevin Cruijssen Mar 28 at 13:33
• @dana Fixed, thanks for noticing. – Kevin Cruijssen Mar 28 at 13:44
• @dana And back to 107 again. ;) – Kevin Cruijssen Mar 28 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.. – Kevin Cruijssen Mar 29 at 7:21

# Zsh, 94 87 78 74 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.

read i
for s;c+=($s[i]) c=($c[-1] $c) for s;s[i]=$c[$[$#s<i?0:++j]]&&<<<$s  So, my previous comment about the subshell printing is now outdated, but here it is with the old last line for posterity: for s;echo$s[0,i-1]$c[$[$#s<i?0:++j]]${s:$i}  Hey, Gamma, why did you use echo in that last command instead of <<<? Wouldn't <<< save you two bytes? I'm glad you asked! Go ahead and give it a try. See if you can figure out what's happening. (Hint: Run echo$ZSH_SUBSHELL; <<< $ZSH_SUBSHELL.) You get 0 for echo, but 1 for <<<. 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.

Anyway, on to the main event:

i=$1 shift for s c+=($s[i])                       # without "", empty strings aren't added
c=($c[-1]$c)                        # add the last element onto the start
for s
echo $s[0,i-1]$c[$[$#s<i?0:++j]]${s:$i}
$s[0,i-1]${s:$i} # before and after the replacement point$c[              ] # insert from char array
$[$#s<i?0    ]  # Sting is too small: at index 0: empty string
$[$#s<i  :++j]  # Increment j and insert from there
# j is unset, so ++j initially sets j to 1


# 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 – Kirill L. Mar 29 at 9:49
• Also, OP relaxed the rules, so that it is now possible to work with space-padded matrices, something like this – Kirill L. Mar 29 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! – Giuseppe Mar 29 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. – Kirill L. Mar 29 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 – Expired Data Mar 28 at 14:41
• Maybe 183 if using ints instead of chars – Expired Data Mar 28 at 14:46
• @ExpiredData ew int instead of char – ASCII-only Mar 29 at 6:05
• too bad you can't use a foreach since it's the opposite order :( – ASCII-only Mar 29 at 6:08
• Use dynamic to merge declarations and save 2 bytes (I've never seen this before!)Try it online! – someone Mar 30 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.

# 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


# K4, 41 bytes

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


# 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. – Kevin Cruijssen Mar 29 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. – Shaggy Mar 29 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.. – Kevin Cruijssen Mar 29 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']
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. – guifa Mar 30 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 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! Didn't see a JavaScript answer yet! Port of my C# answer. • 63 bytes. Can probably be golfed further. – Shaggy Mar 30 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 at 15:12 • Oh, nicely golfed! :) – Shaggy Mar 31 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. Ｊη⁰  Jump to the top of the column to be rotated. ≔ΦＫＤＬθ↓℅ιζ  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, 199 bytes

-20 or so by reading from stdin rather than a file
-14 by using implicit integers for i, k, n
-4 by removal of spaces and ::

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!

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


# 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