Overlapping String-Blocks

22

1

Challenge:

Given a list of multi-line strings, overlap them (in the top-left) and output the result.

Example:

Input: ["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]
Output:

cbaa
bbaa
bbaa
aaaa

Challenge rules:

  • Input-format is flexible. You are allowed to get the input as a 2D list of lines (i.e. [["aaaa","aaaa","aaaa","aaaa"],["bb","bb","bb"],["c"]]) or 3D list of characters (i.e. [[["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"]],[["b","b"],["b","b"],["b","b"]],[["c"]]]). You are allowed to take all the inputs one by one through STDIN. Etc.
  • Output format is strict. You can choose to print or return the multi-line string. (If your language doesn't have any strings, outputting as a 2D list of characters is allowed as alternative. But only if your language doesn't have strings at all.)
  • The order of the input-list is of course important (but you are allowed to take the input in reverse if you choose to).
  • Inputs will only contain printable ASCII in the unicode range \$[33,126]\$ (!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~).
  • Inputs will only be rectangles (so no weird shapes). The output aren't necessary rectangles, though.
  • Trailing spaces and a single trailing newline is allowed. Leading spaces and/or newlines not.

General rules:

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code (i.e. TIO).
  • Also, adding an explanation for your answer is highly recommended.

Test cases:

Input: ["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]
Output:

cbaa
bbaa
bbaa
aaaa

Input: ["12345\n54321","00\n00\n00\n00","001\n011\n012"]
Output:

00145
01121
012
00

Input: ["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]
Output:

this%^
is_a_+
testty
uiopas
t!
h_
i_
n_
g_

Kevin Cruijssen

Posted 2019-06-04T12:57:02.340

Reputation: 67 575

Are trailing newlines allowed? Or more specifically, is an arbitrary amount of trailing newlines allowed? – JAD – 2019-06-05T14:29:53.840

@JAD Yeah sure, why not. As long as the rest is output without any leading spaces/newlines. Trailing newlines/spaces aren't really important, so can optionally be added. – Kevin Cruijssen – 2019-06-05T17:29:42.003

Answers

6

Jelly, 3 bytes

a/Y

Try it online!

Hadn't used Jelly in a while but I thought the challenge in the comments was beatable. Very directly uses logical and (a) to perform the stacking operation between each element of the input (/). Y is used to print in the required format.

FryAmTheEggman

Posted 2019-06-04T12:57:02.340

Reputation: 16 206

Ah nice! I'm pretty bad with Jelly tbh. My prepared solution was ḷ""/Y with a reversed input-list. Didn't even knew about a..

– Kevin Cruijssen – 2019-06-04T17:10:03.813

11

JavaScript (Node.js), 24 bytes

Saved 2 bytes thanks to @Grimy

Assumes that the returned string is printed on a terminal that supports ANSI escape codes. Contains the unprintable character ESC, which is escaped (no pun intended) as \x1B below.

a=>`\x1B[2J\x1B[H`+a.join`\x1B[H`

This doesn't work on TIO, but you can Try it online! to see the raw output instead.

How?

The CSI sequences used are:

  • ED (Erase in Display):

    ESC[2J

    where \$2\$ means "clear entire screen"

  • CUP (Cursor Position):

    ESC[H

    which means "moves the cursor to row \$n\$, column \$m\$" where both \$n\$ and \$m\$ are omitted and implicitly set to \$1\$ (top-left corner of the screen).

Example output

output

Arnauld

Posted 2019-06-04T12:57:02.340

Reputation: 111 334

Assuming an ECMA-48 compliant terminal, you can omit both ;. Also, I think this should be "JavaScript + terminal" or something similar that doesn't compete with pure JavaScript. – Grimmy – 2019-06-04T15:12:19.127

@Grimy Thanks! (For anyone interested, here is the ECMA-48 specification -- but I didn't find where it's mentioned that the semicolon can be omitted -- if it's mentioned at all.)

– Arnauld – 2019-06-04T15:27:49.370

15.4.2.h is somewhat confusingly worded, but the interesting bit is: if the last parameter sub-string(s) is empty, the separator preceding it may be omitted. Since there are only two sub-strings, the separator preceding the last substring is the only one, and it can be omitted. – Grimmy – 2019-06-04T15:36:15.240

I don't know ANSI, but is the first \x1B[H+ necessary? Isn't it starting at the top-left by default, and you only need to reset it after each input (which is what join does)? Or does it initially start somewhere else by default, and you have to explicitly let it start at that cursor position for it to successfully reset to that position in the join? – Kevin Cruijssen – 2019-06-04T15:46:23.247

@KevinCruijssen By default it starts wherever the cursor is, typically at the start of a new line after the current prompt + command. Just try on TIO and copy-paste the output to a terminal to see what I mean. – Grimmy – 2019-06-04T15:48:03.840

@Grimy Ah ok. I indeed saw the CUP mentioned, but didn't knew it was the mouse cursor. Thought it might have been the typing cursor. I don't know the meta, but I guess we can't assume the mouse cursor is at the top-left, can we? ;) – Kevin Cruijssen – 2019-06-04T15:51:44.200

@KevinCruijssen I do mean the typing cursor, not the mouse cursor. Running a command in a terminal typically requires typing it, which leaves the typing cursor not at the top left. – Grimmy – 2019-06-04T15:56:52.917

Isn't meta-consensus that functions should be reusable? Since the ANSI escape sequence sets the cursor to the top left corner, future calls to the function will overlay the new output on top of old outputs, producing invalid output – Embodiment of Ignorance – 2019-06-04T16:12:53.220

@EmbodimentofIgnorance Chances are that the terminal is not fully cleared on the first call either, so this is not really a problem of reusability, but rather a problem of output readability. I honestly don't know which rule(s) should be applied here. Also, I was half-tempted to omit the print() in the function entirely and just return the string -- but I don't know if that would be allowed. – Arnauld – 2019-06-04T16:20:19.993

1@Arnauld Since you probably will always have something else on the terminal when executing this function, I guess the initial reset is required after all. As for ommitting print, I guess f=a=>print(`\x1B[H`+a.join`\x1B[H`) with f(input_here) would produce the same output as print(f(input_here))? So I don't see why you wouldn't be allowed to omit the print and simply return a string. – Kevin Cruijssen – 2019-06-04T16:29:43.597

@KevinCruijssen Thank you. I've updated the answer accordingly. (The screen is now cleared.) – Arnauld – 2019-06-04T16:37:19.013

7

R, 120, 111 110 107 bytes

function(x,`!`=ncol,M=array('',Reduce(pmax,Map(dim,x)))){for(m in x)M[1:!t(m),1:!m]=m
write(t(M),1,!M,,'')}

Try it online!

A function accepting a list of matrix of characters (3D input is accepted).

(as you can notice from the byte count, this is not very easy to do in R...)

  • -9 bytes thanks to @Giuseppe
  • -4 bytes thanks to @RobinRyder

digEmAll

Posted 2019-06-04T12:57:02.340

Reputation: 4 599

4I was really expecting a 200+ byte solution! I'll be giving this a nice bounty whenever this question becomes bounty eligibile – Giuseppe – 2019-06-04T20:19:08.183

@Giuseppe: still much longer than other languages ... :( – digEmAll – 2019-06-04T20:21:26.413

2111 bytes using array instead of matrix! – Giuseppe – 2019-06-04T20:35:09.283

@Giuseppe: neat ! – digEmAll – 2019-06-04T20:41:28.747

110 by switching back to good old ncol and nrow. – Robin Ryder – 2019-06-04T20:42:20.807

@RobinRyder: thanks ! I started using dim everywhere in order to replace it with some alias, but I ended up with more bytes :D – digEmAll – 2019-06-04T20:45:59.977

3107 with an alias for ncol (you can transpose to get nrow). – Robin Ryder – 2019-06-04T20:51:54.760

107, different solution, same bytecount. :) – JAD – 2019-06-05T12:28:58.320

5

Python 2, 88 bytes

n,f=None,filter
for l in map(n,*input()):print''.join(f(n,x)[-1]for x in map(n,*f(n,l)))

Try it online!


Explanation (with example):

Takes a 2D list as input.

Input: [["12345","54321"],["00","00","00","00"],["001","011","012"]]

First the input list is zipped, to get the rows of each input rectangle (map(None,l) is the same a zip longest):

map(n,*input())   gives:

('12345', '00', '001')
('54321', '00', '011')
(None, '00', '012')
(None, '00', None)

Each of these rows are then filtered to removed Nones, and zipped again:

map(None,*filter(None,l))

filter(None,l) for each l gives:

('12345', '00', '001')
('54321', '00', '011')
('00', '012')
('00',)

map*... gives:

[('1', '0', '0'), ('2', '0', '0'), ('3', None, '1'), ('4', None, None), ('5', None, None)]
[('5', '0', '0'), ('4', '0', '1'), ('3', None, '1'), ('2', None, None), ('1', None, None)]
[('0', '0'), ('0', '1'), (None, '2')]
['0', '0']

Which is a list of characters for each position of the desired result. These lists are filtered again, and the last one is taken:

filter(None,x)   gives:

[('1', '0', '0'), ('2', '0', '0'), ('3', '1'), ('4',), ('5',)]
[('5', '0', '0'), ('4', '0', '1'), ('3', '1'), ('2',), ('1',)]
[('0', '0'), ('0', '1'), ('2',)]
['0', '0']

and with [-1]:

['0', '0', '1', '4', '5']
['0', '1', '1', '2', '1']
['0', '1', '2']
['0', '0']

Lastly the resulting lists are joined and printed:

print''.join(..)

00145
01121
012
00

TFeld

Posted 2019-06-04T12:57:02.340

Reputation: 19 246

RE "Returns a list of strings", the rules state "Output format is strict. You can choose to print or return the multi-line string. 2D or 3D lists as outputs aren't allowed.". The 88 byte full program seems fine though – Jonathan Allan – 2019-06-04T17:00:11.137

@JonathanAllan, welp, I misread the strict output (or forgot? :p) – TFeld – 2019-06-04T18:30:28.337

5

R, 107 97 bytes

function(x)for(i in 1:max(lengths(x))){for(m in x)if(i<=length(m))cat(m[i],'\r',sep='');cat('
')}

Doesn't appear to work on TIO, which might be related to the use of the \r carriage return character. It does work on my local installation of R.

Takes input as a list containing a vector of rows:

x <- list(c("aaaa","aaaa","aaaa","aaaa"),c("bb","bb","bb"),c("c"))

Loops over the rows of each rectangle, printing a carriage return after each, restarting the line.

If we stretch the rules a little, we can do away with checking the length of the input and just loop infinitely, printing a huge amount of newlines:

R, 85 bytes

function(x)for(i in 1:8e8){for(m in x)if(i<=length(m))cat(m[i],'\r',sep='');cat('
')}

JAD

Posted 2019-06-04T12:57:02.340

Reputation: 2 898

106 bytes Nice to see you doing a golf here and there! – Giuseppe – 2019-06-05T14:05:46.390

Possibly 97 bytes; unclear if this actually works since I'm only testing in TIO

– Giuseppe – 2019-06-05T14:08:21.537

@Giuseppe Hi! Your suggestion works for me. If we are allowed to print trailing newlines, it's also possible to just use an arbitrarily big for loop instead, but I guess that's pushing the limits of the challenge. – JAD – 2019-06-05T14:32:32.313

@JAD: great idea using \r, and welcome back! Just a note, I think this works only in interactive R sessions (when interactive() returns true) – digEmAll – 2019-06-05T19:06:50.210

@digEmAll It works on my machine using rscript from commandline. I suspect it's a Windows/Linux thing, since Windows uses \r\n for newlines and Linux \n. – JAD – 2019-06-06T06:25:04.513

@JAD: oh, I would have bet on the interactive thing... but then it's probably that – digEmAll – 2019-06-06T06:32:01.633

@digEmAll it might also depend on the console it's being ran in. CMD and powershell deal with the \r as intended. It might be that other environments (like TIO) interpret it as a newline. May I ask what you are running it in? – JAD – 2019-06-06T06:35:19.100

@digEmAll: rstudio on windows – digEmAll – 2019-06-06T06:36:24.860

@digEmAll well..... that's odd. It works for me there :O – JAD – 2019-06-06T06:36:49.063

@JAD: yes, it works for me too... I was just trying to understand why it does not work on TIO ;) – digEmAll – 2019-06-06T06:37:51.437

@digEmAll ah, right. – JAD – 2019-06-06T06:38:05.880

Let us continue this discussion in chat.

– digEmAll – 2019-06-06T06:41:22.420

4

APL (Dyalog Unicode), 22 bytesSBCS

Anonymous tacit prefix function taking list of 2D character arrays as argument. Prints.

(⊃{⍺@(⍳⍴⍺)⊢⍵}/)⌽,∘⊂1⌷↑

Try it online!

This works by creating a canvas, then appending that to the list of blocks, and reducing (folding) with a function that places blocks in the corner.

 mix the 2D block to create an orthogonal 3D block, padding them with spaces as needed

1⌷ take the first layer

 enclose that
 then
⌽, prepend the reversed list of blocks

() apply the following tacit function:

{}/ reduce using the following anonymous lambda:

  ⊢⍵ with the right argument as canvas…

  ⍺@() amend with the elements of the left argument, placed at the following indices:

   ⍴⍺ the shape of the left argument

    the ɩndices of an array of that shape

 disclose (because the reduction enclosed to reduce rank)

Adám

Posted 2019-06-04T12:57:02.340

Reputation: 37 779

4

Haskell, 66 bytes

unlines.foldl((const?)?)[]
(g?(a:b))(c:d)=g a c:(g?b)d;(_?a)b=a++b

Input is taken as a list of list of strings in reverse order, e.g. for the first test case: [["c"],["bb","bb","bb"],["aaaa","aaaa","aaaa","aaaa"]].

Try it online!

nimi

Posted 2019-06-04T12:57:02.340

Reputation: 34 639

3

05AB1E, 12 bytes

Port of TFeld's python solution
2 bytes saved thanks to Grimy

ζεðKζðδK€θJ,

Try it online!

Explanation

ζ             # transpose input with space as filler
 ε            # apply to each
  ðK          # remove spaces
    ζ         # transpose with space as filler
     ðδK      # deep remove spaces
        €θ    # get the tail of each
          J   # join each
           ,  # print

Alternative 14 byte version

õζεÅ»DŠg.$J}θ,

Try it online!

Explanation

õζ              # zip with empty string as filler
  ε             # apply to each
   Å»      }    # cumulative reduce by
     D          # duplicate second input
      Š         # move down twice on stack
       g.$      # remove len(other_copy) elements from the other input
          J     # join with other copy
            θ,  # print the last element

Emigna

Posted 2019-06-04T12:57:02.340

Reputation: 50 798

1Oh, need to remember that --no-lazy is the fix to still use a map/filter with print for the implicit y, to save a byte in comparison to vy..., :) I knew that worked in the legacy version, but in the new version it would also output the [...]. Didn't knew that was due to the lack of --no-lazy. ;) As for the answer itself, very nice! I knew a cumulative reduce was necessary, but couldn't really work it out when I tried it myself. You make it look so easy.. – Kevin Cruijssen – 2019-06-04T14:04:54.647

I had it mentioned in the rules, but forgot to apply it to the test cases.., but spaces won't be in the input. So you can probably save some bytes there since the zip-filler is a space by default. (Not sure if it saves anything in your first answer, but in the port it might.) – Kevin Cruijssen – 2019-06-04T14:40:34.567

2õζεõK can be ζεðK, õζõδK can be ζðδK. – Grimmy – 2019-06-04T15:06:22.007

@Grimy: Oh yeah, spaces can no longer be in the input. Thanks! – Emigna – 2019-06-04T15:53:27.943

2

Canvas, 5 bytes

H11╋╋

Try it here!

If overlapping /+\X, - + |+, etc. would be fine, 2 bytes would work.

dzaima

Posted 2019-06-04T12:57:02.340

Reputation: 19 048

2

Python 2, 77 bytes

for t in map(None,*input()):
 r=''
 for s in t:
	if s:r=s+r[len(s):]
 print r

Try it online!

xnor

Posted 2019-06-04T12:57:02.340

Reputation: 115 687

2

PowerShell 6, console only, 20 bytes

based on Arnauld's answer. This work with console only and doesn't work on TIO.

cls
$args-join"`e[H"

Try it online!


PowerShell, 103 bytes

$args|%{$l=$_-split'
';$r=&{$r+($l|%{''})|%{($x=$l[$j++])+($_-replace"^.{0,$("$x"|% Le*)}")}|?{$_}}}
$r

Try it online!

Unrolled:

$args|%{
    $l=$_-split"`n"
    $r=&{                           # run this scriptblock in a new scope
        $r+($l|%{''})|%{
            $x=$l[$j++]             # a new line or $null
            $w="$x"|% Length
            $y=$_-replace"^.{0,$w}" # remove first chars from the current line
            $x+$y                   # output the new line plus tail of the overlapped line
        }|?{$_}                     # filter out not empty lines only
    }                               # close the scope and remove all variables created in the scope
}
$r

mazzy

Posted 2019-06-04T12:57:02.340

Reputation: 4 832

1

C# (.NET Core), 68 + 23 = 91 bytes

n=>{C.Clear();n.ForEach(k=>{C.SetCursorPosition(0,0);C.Write(k);});}

23 bytes is for the import, using C=System.Console;

Does not work in TIO, since it isn't a console.

Try it online!

Embodiment of Ignorance

Posted 2019-06-04T12:57:02.340

Reputation: 7 014

1

Ruby, 67 bytes

Input is a list of lines. Builds a list of lines and does overwriting as it goes through the inputs, then joins them with a newline (represented by the variable $/) at the end to match the strict output.

->i,*r{i.map{|e|j=-1;e.map{|l|r[j+=1]||='';r[j][0,l.size]=l}};r*$/}

Try it online!

Value Ink

Posted 2019-06-04T12:57:02.340

Reputation: 10 608

1

C (GCC, MinGW) 138 bytes

Assumes that CR puts the cursor at the start of the current line.

d,i,l;f(S,n,p,t)char**S,*p,*t;{for(d=i=0;i<n;d+=l)p=strchr(t=S[i],10),printf("\n%.*s\r"+!!i,l=p?p-t:strlen(t),t),S[i++]+=l+!!p;d&&f(S,n);}

Tested with:

int main()
{
    char *test1[] = {"aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"};
    char *test2[] = {"12345\n54321","00\n00\n00\n00","001\n011\n012"};
    char *test3[] = {"sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"};

    f(test1, 3);
    f(test2, 3);
    f(test3, 3);
}

gastropner

Posted 2019-06-04T12:57:02.340

Reputation: 3 264

1

Octave, 71 67 bytes

function y=f(x)
for k=1:size(x)
y(1:(t=size(x{k})),1:t(2))=x{k};end

Function that takes a vertical cell array of char matrices, and returns a char matrix.

Try it online! Or verify all test cases.

Luis Mendo

Posted 2019-06-04T12:57:02.340

Reputation: 87 464

1

Japt -P, 7 bytes

Takes input as an array of multi-line strings, outputs a single multi-line string.

ú y_¸¬Ì

Try it

ú y_¸¬Ì     :Implicit input of array
ú           :Right pad each line of each element with spaces to the length of the longest
  y         :Transpose
   _        :Map
    ¸       :  Split on spaces
     ¬      :  Join
      Ì     :  Last character
            :Implicitly join and output

Shaggy

Posted 2019-06-04T12:57:02.340

Reputation: 24 623

1

Javascript (browser), 216 208 204 bytes

My attempt at this. I'm not happy about the size, and there must certainly be more for improvement, but I'm not that experienced at golfing.

var n='\n',x=s=>s.split``.reverse().join``,i,j,f=a=>a.map(s=>s.split(n).map(y=>x(y))).reduce((a,b)=>{for(i=0;i<b.length;i++){j=a[i];if(!j)j=b[i];a[i]=b[i].padStart(j.length,j)}return a}).map(s=>x(s)).join(n)

Anyways, what it does is first split all the strings, then reverse all the strings, then whilst looping in a reduce operation padStart all the strings together. Then reverse all the strings again and then join them back with newlines.

Special thanks to Kevin Cruijssen for reminding me that the last part in a for loop happens at the end and a total byte savings of 8 bytes.

var n='\n',x=s=>s.split``.reverse().join``,i,j,f=a=>a.map(s=>s.split(n).map(y=>x(y))).reduce((a,b)=>{for(i=0;i<b.length;a[i]=b[i++].padStart(j.length,j))if(!(j=a[i]))j=b[i];return a}).map(s=>x(s)).join(n)

console.log(f(["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]));
console.log(f(["12345\n54321","00\n00\n00\n00","001\n011\n012"]));
console.log(f(["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]));

Tschallacka

Posted 2019-06-04T12:57:02.340

Reputation: 147

1Both ('') can be two ` to save four bytes :) – Kevin Cruijssen – 2019-06-05T13:43:52.373

1Also, you can replace the for(i=0;i<b.length;i++){j=a[i];if(!j)j=b[i];a[i]=b[i].padStart(j.length,j)} with for(i=0;i<b.length;a[i]=b[i++].padStart(j.length,j))if(!(j=a[i]))j=b[i];. – Kevin Cruijssen – 2019-06-05T13:45:42.867

@KevinCruijssen In your modification j doesn't get assigned. And it will fail because the if needs to happen before padStart, otherwise you get a[i](j in this case) is undefined and cannot get property length of undefined. Thanks for the four bytes saved. Didn't know you could do that. – Tschallacka – 2019-06-05T13:49:09.093

1The j is first assigned with (j=a[i]), then the if-statement is done with if(!...)j=b[i]; (where ... is the (j=a[i]), so the updated value of j), and then the ;a[i]=b[i++].padStart(j.length,j)) is done at the end of the for-loop iteration.. Not sure where the problem is, and it seems to work? – Kevin Cruijssen – 2019-06-05T13:51:15.887

1ooohhh.... * big eyes * that unlocked something – Tschallacka – 2019-06-05T13:52:56.517

1

Btw, if you haven't seen them yet, tips for golfing in <all languages> and tips for golfing in JavaScript might both be interesting to read through. :)

– Kevin Cruijssen – 2019-06-05T13:54:15.060

1

C (gcc), 51 47 bytes

f(char**s){for(;*s;printf("\e[s%s\e[u",*s++));}

Try it online!

-4 bytes thanks to ceilingcat.

Uses the CSI sequences for save/restore cursor position. Just iterates over the passed string array (in the same format as argv) and prints <save position>string<restore position> for each.

This does leave the cursor at the top left, so when running at the terminal it is important to leave enough newlines afterwards so that the prompt doesn't clobber the input.

LambdaBeta

Posted 2019-06-04T12:57:02.340

Reputation: 2 499

1

T-SQL query, 297 295 bytes

Using ¶ as separator and a table variable as input.

DECLARE @ table(a varchar(max),k int identity(1,1))
INSERT @ values('aaaa¶aaaa¶aaaa¶aaaa'),('bb¶bv¶bb'),('c');

WITH c as(SELECT k,row_number()over(partition
by k order by k)s,value v FROM @ CROSS APPLY
string_split(a,'¶')s),m(i,l,e)as(SELECT*FROM c
WHERE k=1UNION ALL
SELECT k,s,STUFF(e,1,len(v),v)FROM m
JOIN c ON-~i=k and s=l)SELECT
top 1with ties e FROM m
ORDER BY rank()over(partition by l order by-i)

Try it online

t-clausen.dk

Posted 2019-06-04T12:57:02.340

Reputation: 2 874

1

Javascript (browser), 129 124 bytes

My first attempt at code golfing. I read the links given in the rules (loopholes, standard rules...), so I hope I did anything wrong!


I kept the inputs as they are in the first post (flat array form).

_=o=>{o=o.map(i=>i.split`\n`),r=o.shift();for(a of o)for(l in a)b=a[l],r[l]=r[l]?b+r[l].slice(b.length):b;return r.join`\n`}

Thanks to Kevin Cruijssen for saving 5 bytes.


Tests:

_=o=>{o=o.map(i=>i.split`\n`),r=o.shift();for(a of o)for(l in a)b=a[l],r[l]=r[l]?b+r[l].slice(b.length):b;return r.join`\n`}

console.log(_(["aaaa\naaaa\naaaa\naaaa","bb\nbb\nbb","c"]));
console.log(_(["12345\n54321","00\n00\n00\n00","001\n011\n012"]));
console.log(_(["sm\noo\nmr\nee\nt!\nh_\ni_\nn_\ng_","!@#$%^\n&*()_+\nqwerty\nuiopas","this\nis_a\ntest"]));

Kévin Bibollet

Posted 2019-06-04T12:57:02.340

Reputation: 111

1Welcome to PPCG! Nice first answer, +1 from me. Some small things to golf: for(a of o){for(l in a){b=a[l],r[l]=(r[l])?b+r[l].slice(b.length):b}} can be for(a of o)for(l in a)b=a[l],r[l]=r[l]?b+r[l].slice(b.length):b; :) – Kevin Cruijssen – 2019-06-12T16:11:31.953

Also, if you haven't seen it yet, tips for golfing in JavaScript and tips for golfing in <all languages> might be interesting to read through. Enjoy your stay!

– Kevin Cruijssen – 2019-06-12T16:23:21.453

1@KevinCruijssen - Thanks, I updated my post! I read these two guides before posting, they were both useful. But I possibly miss some tricks that could improve even more my attempt! – Kévin Bibollet – 2019-06-12T16:33:31.343

1One other thing from my first comment you missed are the parenthesis around the =(r[l])? which can be removed to =r[l]? :) – Kevin Cruijssen – 2019-06-12T16:39:14.760

@KevinCruijssen - Oops, corrected! – Kévin Bibollet – 2019-06-12T16:41:50.173

@Shaggy - Nice, however I don't get the purpose of &&r at end? – Kévin Bibollet – 2019-06-13T08:33:48.647

1@KévinBibollet, it's needed in order to return the final result of r. Without it, the result of the mapping would be returned instead. – Shaggy – 2019-06-13T20:38:44.153

1

If you want to retain the I/O format used in the test cases, though, you can still get down to 85 bytes but you should note that I/O is flexible.

– Shaggy – 2019-06-13T20:41:48.037

1

Pyth, 18 bytes

L.tb0VyQsme #dy #N

Try it online! (note: the code itself evaluates only one block, the interpreter's test suite mode runs the program once for each line of input)

Based on TFeld's Python 2 solution.

Explanation:

L.tb0         # define a lambda function called y which does a transpose, padding with integer 0's
VyQ           # loop over transposed first input line (Q = eval(input()) ) (loop index = N)
   s          # concatenate array of strings (implicitly printed)
    m         # map over
         y #N # transpose of non-falsy values of N
     e        # for each item: last element of array
       #d     # relevant space at the start! filter with identity function, removes falsy values

for an explanation of why the algorithm itself works, see TFeld's answer.

randomdude999

Posted 2019-06-04T12:57:02.340

Reputation: 789

0

Charcoal, 4 bytes

FθPι

Try it online (verbose) or try it online (pure).

Explanation:

Loop over the input-list of multi-line strings:

For(q)
Fθ

And print the multi-line string without moving the cursor:

Multiprint(i);
Pι

Kevin Cruijssen

Posted 2019-06-04T12:57:02.340

Reputation: 67 575