34
\$\begingroup\$

This was inspired by a function I recently added to my language Add++. Therefore I will submit an short answer in Add++ but I won't accept it if it wins (it wouldn't be fair)

Don't you hate it when you can multiply numbers but not strings? So you should correct that, right?

You are to write a function or full program that takes two non-empty strings as input and output their multiplied version.

How do you multiply strings? I'll tell you!

To multiply two strings, you take two strings and compare each character. The character with the highest code point is then added to the output. If they are equal, simply add the character to the output.

Strings are not guaranteed to be equal in length. If the lengths are different, the length of the final string is the length of the shortest string. The input will always be lowercase and may contain any character in the printable ASCII range (0x20 - 0x7E), excluding uppercase letters.

You may output in any reasonable format, such as string, list etc. Be sensible, integers aren't a sensible way to output in this challenge.

With inputs of hello, and world!, this is how it works

hello,
world!

w > h so "w" is added ("w")
o > e so "o" is added ("wo")
r > l so "r" is added ("wor")
l = l so "l" is added ("worl")
d < o so "o" is added ("worlo")
! < , so "," is added ("worlo,")

So the final output for hello, and world! would be worlo,.

More test cases

(without steps)

input1
input2 => output

programming puzzles & code golf!?
not yet graduated, needs a rehaul => prtgyetmirgduuzzlesneedsde rolful

king
object => oing

blended
bold => boln

lab0ur win.
the "super bowl" => the0usuwir.

donald j.
trumfefe! => trumlefj.

This is a so shortest code wins! Luok!

\$\endgroup\$
5
  • 46
    \$\begingroup\$ This is the elementwise maximum of the strings, right? That doesn't seem anything like multiplying. \$\endgroup\$
    – xnor
    Jun 8, 2017 at 22:34
  • 5
    \$\begingroup\$ Nitpick: PPCG has graduated, we just didn't get a new design yet. \$\endgroup\$
    – Dennis
    Jun 9, 2017 at 4:02
  • 1
    \$\begingroup\$ Possible relevant: codegolf.stackexchange.com/questions/74809/merging-two-strings/… \$\endgroup\$
    – nmjcman101
    Jun 9, 2017 at 11:40
  • 2
    \$\begingroup\$ The first test case is wrong. It should be "input1","input2" => "input2". \$\endgroup\$
    – user92069
    Mar 14, 2020 at 7:26
  • 1
    \$\begingroup\$ @a'_' That‘s not a test case; it’s a Demonstration of the Format of the other test cases \$\endgroup\$ Mar 14, 2020 at 9:40

72 Answers 72

55
\$\begingroup\$

Haskell, 11 bytes

zipWith max

Try it online!

Nothing much to explain.

\$\endgroup\$
3
  • 7
    \$\begingroup\$ And I thought Mathematica had strange built-ins \$\endgroup\$
    – Mr. Xcoder
    Jun 10, 2017 at 10:15
  • \$\begingroup\$ @Mr.Xcoder Mathematica has zipWith, it's called MapThread \$\endgroup\$
    – michi7x7
    Jul 14, 2017 at 16:38
  • 3
    \$\begingroup\$ @Mr.Xcoder actually, zipWith isn't too strange. It's a fairly common functional primitive. The idea of "zipping" two lists together comes up in many problems, and once you do that, you often want to apply some function to the resulting 2-element items, hence the "with" part. \$\endgroup\$
    – Jonah
    Aug 11, 2017 at 8:56
10
\$\begingroup\$

05AB1E, 4 bytes

øΣà?

Uses the 05AB1E encoding. Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I feel like ø€à should work, but it don't. \$\endgroup\$ Aug 11, 2017 at 19:03
  • 1
    \$\begingroup\$ Looks more like a question than an answer lol \$\endgroup\$
    – Stan Strum
    Dec 8, 2017 at 1:44
  • \$\begingroup\$ @MagicOctopusUrn ø€à does work now (in the legacy version of 05AB1E), but the output will be a list of characters instead of a string: try it online. \$\endgroup\$ Jan 12, 2023 at 10:09
7
\$\begingroup\$

Japt, 16 bytes

ñl g îUy ®¬ñ oÃq

Test it online! Takes input as an array of two strings.

Lack of min and max built-ins hurt Japt here, but it still manages to pull off a somewhat decent score...

Explanation

 ñl g îUy ®   ¬ ñ oà q
Uñl g îUy mZ{Zq ñ o} q
                        // Implicit: U = input array     ["object", "king"]
       Uy               // Transpose the strings of U.   ["ok", "bi", "jn", "eg", "c ", "t "]
          mZ{      }    // Map each string Z to
             Zq ñ o     //   the larger of the two chars. (Literally Z.split().sort().pop())
                        //                               ["o", "i", "n", "g", "c", "t"]
                     q  // Join into a single string.    "oingct"
Uñl g                   // Sort the two input strings by length and take the shorter.
      î                 // Trim the previous result to this length.
                        //            "king"î"oingct" -> "oing"
                        // Implicit: output result of last expression
\$\endgroup\$
7
\$\begingroup\$

Jelly, 5 bytes

żœ-"«

Try it online!

How it works

żœ-"«  Main link. Arguemts: s, t (strings)

ż      Zipwith; form all pairs of corresponding characters from s and t.
       If one of the strings is longer than the other, its extra characters are 
       appended to the array of pairs.
    «  Dyadic minimum; get all minima of corresponding characters.
       This yields the characters themselves for unmatched characters.
 œ-"   Zipwith multiset subtraction; remove a single occurrence of the minimum from
       each character pair/singleton.
       This yields the maximum for pairs, but an empty string for singletons.

Example

Let s = blended and t = bold.

ż yields ["bb", "lo", "el", "nd", 'd', 'e', 'd']. The last three elements are characters.

« is the vectorizing, dyadic minimum, so it yields ['b', 'l', 'e', 'd', 'd', 'e', 'd'].

œ-" removes exactly one occurrence of the nth character in the second array from the nth string/character in the first array, yielding ["b", "o", "l", "n", "", "", ""]. œ- is the multiset subtraction atom, and the quick " makes it vectorize.

When printed, this simply reads boln.

\$\endgroup\$
2
  • \$\begingroup\$ So, this is zipping, then taking the multiset difference of something, then there are some nice double quotes of misterious meaning, and finally the minimum. Nice... Explanation, please? :D \$\endgroup\$
    – Leo
    Jun 9, 2017 at 6:48
  • 1
    \$\begingroup\$ I've added a worked example. \$\endgroup\$
    – Dennis
    Jun 9, 2017 at 7:10
7
\$\begingroup\$

PHP>=7.1, 52 Bytes

for(;$t=min(~$argv[1][$i],~$argv[2][$i++]);)echo~$t;

PHP Sandbox Online

PHP>=7.1, 69 Bytes

for([,$a,$b]=$argv;(~$c=$a[$i])&&~$d=$b[$i++];)$r.=max($c,$d);;echo$r;

PHP Sandbox Online

PHP>=7.1, 70 Bytes

for([,$a,$b]=$argv;(~$c=$a[$i])&&~$d=$b[$i++];)$r.=$c>$d?$c:$d;echo$r;

PHP Sandbox Online

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Slightly golfed: for(;$t=min(~$argv[1][$i],~$argv[2][$i++]);)echo~$t;. \$\endgroup\$
    – user63956
    Jun 9, 2017 at 9:05
7
\$\begingroup\$

Alice, 8 bytes

/oI\
@m+

Try it online!

Explanation

Alice also has this operator (which I called superimpose) but it doesn't limit the output to the shorter string's length (instead, the remaining characters of the longer string are appended). However, it also has an operator to truncate the longer of two strings to the length of the shorter one.

/   Reflect to SE, switch to Ordinal. The IP bounces diagonally up and down
    through the code.
m   Truncate, doesn't really do anything right now.
I   Read a line of input.
    The IP bounces off the bottom right corner and turns around.
I   Read another line of input.
m   Truncate the longer of the two input lines to the length of the shorter.
+   Superimpose: compute their elementwise maximum. 
o   Output the result.
@   Terminate the program.
\$\endgroup\$
7
\$\begingroup\$

JavaScript (ES6), 47 45 bytes

f=
(a,b)=>a.replace(/./g,(c,i)=>c>b[i]?c:[b[i]])
<div oninput=o.textContent=f(a.value,b.value)><input id=a><input id=b><pre id=o>

Conveniently c>b[i] returns false past the end of b. Edit: Saved 2 bytes thanks to @ETHproductions.

\$\endgroup\$
2
  • \$\begingroup\$ Here in my cellphone that above code can not be executed. In the PC desktop the above examples I say can run ok, but not allow to change input for functions... Why not use Tio instead? \$\endgroup\$
    – user58988
    Nov 9, 2017 at 8:25
  • \$\begingroup\$ @RosLuP When the input is simple (2 stings in this case) I prefer to use a Stack Snippet that normally makes it easier to change the inputs and the output updates dynamically too. \$\endgroup\$
    – Neil
    Nov 9, 2017 at 8:43
6
\$\begingroup\$

Perl 6, 22 bytes

{[~] [Zmax] @_».comb}

As a bonus, it accepts any number of multiplicands, not just two.

\$\endgroup\$
6
\$\begingroup\$

Jelly, 6 bytes

żḊ€ṁ@»

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ żṢ€Ḋ€ and żṢ€ZṪ both save a byte. \$\endgroup\$
    – Dennis
    Jun 9, 2017 at 4:13
  • \$\begingroup\$ @Dennis very clever. \$\endgroup\$
    – Leaky Nun
    Jun 9, 2017 at 8:26
6
\$\begingroup\$

Retina, 28 bytes

{O^`
G`.
^.+$

M!\*`^.
Rm`^.

Try it online!

Explanation

{O^`

The { tells Retina to run the entire program in a loop until it fails to change the working string. O makes this a sorting stage which sorts non-empty lines by default. The ^ option reverses the result. So in effect, we get a reverse sort of the two lines if they're non-empty, putting the line with the larger leading character at the top.

G`.

Discard empty lines if there are any.

^.*$

If only one line is left, one of the lines was empty, and we remove the other one as well to stop the process.

M!\*`^.

Lots of configuration going on here. This matches (M) the first character in the working string (^.), returns it (!), prints it without a trailing linefeed (\) and then reverts the working string to its previous value (*). In other words, we simply print the first character of the working string (which is the maximal leading character) without actually changing the string.

Rm`^.

Finally, we remove the first character from each line, so that the next iteration processes the next character.

\$\endgroup\$
3
  • \$\begingroup\$ When you commented on my how tall are the monoliths answer, it occurred to me that my answer to this question was far too long, and that perhaps I was transposing inefficiently. After looking at how your transposition suggestion worked I decided that it wasn't appropriate for this question after all. I then came up with a new approach that saved me 19 bytes... and then scrolled down to find you'd already come up with a better version... \$\endgroup\$
    – Neil
    Jul 26, 2017 at 9:31
  • \$\begingroup\$ You can save 3 bytes since the G`. is unnecessary, although this does output an extra newline which you can remove by using ^.+¶$ or by prefixing a \ to the start of the answer. \$\endgroup\$
    – Neil
    Jul 26, 2017 at 9:41
  • \$\begingroup\$ @Neil Oh good point. I could also use the latest commit (which isn't on TIO yet and probably isn't gonna be for a while) where I've made printing without trailing linefeeds the default (I could then also drop the other \). \$\endgroup\$ Jul 26, 2017 at 11:04
6
\$\begingroup\$

C, 58 bytes

f(char*s,char*t){putchar(*s>*t?*s:*t);*++s&&*++t&&f(s,t);}

Try Online

  • -8 bytes @Steadybox
\$\endgroup\$
1
  • \$\begingroup\$ Darn, f(s,t)char*s,*t;{ gives the same length. \$\endgroup\$
    – aschepler
    Jun 11, 2017 at 11:24
6
\$\begingroup\$

Husk, 2 bytes

z▲

Try it online!

"Ungolfed"/Explained

Makes use of zip f that truncates the shorter list such that there are always two arguments for f, e.g. zip f [1,2] [3,4,5] == zip f [1,2] [3,4] == [f 1 3, f 2 4]:

z   -- zip the implicit lists A,B with  - e.g. "ab" "bcd" (lists of characters)
 ▲  -- maximum                          -      [max 'a' 'b', max 'b' 'c']
    -- implicitly print the result      -      "bc"
\$\endgroup\$
5
\$\begingroup\$

Mathematica, 78 bytes

FromCharacterCode[Max/@Thread[#~Take~Min[Length/@x]&/@(x=ToCharacterCode@#)]]&

There is another answer in Mathematica already. This answer take input as a list of strings, so /@ can be used on # instead of {##}. And we can just Map the long function name on object instead of assigning it to variables. (in fact, each Mathematica built-in symbol name is used at most once in the function)

\$\endgroup\$
5
\$\begingroup\$

Python 2, 47 44 34 bytes

-3 bytes thanks to musicman523. -10 bytes thanks to Blender.

Takes input as a list of strings.

lambda a:''.join(map(max,zip(*a)))

Try it online!

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

V, 28, 24, 21 bytes

Í./&ò
dd{JdêHPÎúúx
Íî

Try it online!

Hexdump:

00000000: cd2e 2f26 f20a 6464 7b4a 64ea 4850 cefa  ../&..dd{Jd.HP..
00000010: fa78 0acd ee                             .x...

Three bytes saved thanks to @nmjcman101!

Explanation:

Í             " Globally substitute:
 .            "   Any character
  /           " With:
   &          "   That character
    ò         "   And a newline
dd            " Delete this line
  {           " Move to the first empty line
   J          " Delete this line
    dê        " Columnwise delete the second word
      HP      " Move to the first line, and paste the column we just deleted
        Î     " On every line:
         úú   "   Sort the line by ASCII value
           x  "   And delete the first character
Í             " Remove all:
 î            "   Newlines
\$\endgroup\$
2
  • \$\begingroup\$ Is the dG necessary? Don't all of the newlines get removed with the Íî anyways? \$\endgroup\$
    – nmjcman101
    Jun 9, 2017 at 15:37
  • \$\begingroup\$ @nmjcman101 It's needed in case the strings are different lengths. \$\endgroup\$
    – DJMcMayhem
    Jun 9, 2017 at 15:38
5
\$\begingroup\$

Javascript (ES2015), 66 63 49 bytes

a=>b=>[...a].map((c,i)=>c>b[i]?c:b[i]||'').join``

Explanation:

a=>b=>                       // Function with two string parameters
  [...a]                     // Split a into array of characters
    .map((c, i) =>           // Iterate over array
      c>b[i] ? c : b[i]||'') //   Use the character with the larger unicode value until the end of the larger string
    .join``                  // Join the array into a string

Previous Versions:

//ES2015
a=>b=>[...a].map((c,i)=>c>b[i]?c:b[i]).slice(0,b.length).join``    //63
a=>b=>a.split``.map((c,i)=>c>b[i]?c:b[i]).slice(0,b.length).join`` //66
a=>b=>a.split``.map((c,i)=>c>b[i]?c:b[i]).slice(0,Math.min(a.length,b.length)).join``   //85
a=>b=>{for(i=-1,c='';++i<Math.min(a.length,b.length);)c+=a[i]>b[i]?a[i]:b[i];return c}  //86
a=>b=>{for(i=-1,c='';++i<Math.min(a.length,b.length);)c+=a[d='charCodeAt'](i)>b[d](i)?a[i]:b[i];return c}   //105
a=>b=>a.split``.map((c,i)=>c[d='charCodeAt']()>b[d](i)?c:b[i]).slice(0,Math.min(a.length,b.length)).join``  //106

//With array comprehensions
a=>b=>[for(i of a.split``.map((c,i)=>c>b[i]?c:b[i]))i].slice(0,b.length).join``                             //79
a=>b=>[for(i of a.split``.map((c,i)=>c>b[i]?c:b[i]))i].slice(0,Math.min(a.length,b.length)).join``          //98
a=>b=>[for(i of ' '.repeat(Math.min(a.length,b.length)).split``.map((_,i)=>a[i]>b[i]?a[i]:b[i]))i].join``   //105
a=>b=>[for(i of Array.apply(0,Array(Math.min(a.length,b.length))).map((_,i)=>a[i]>b[i]?a[i]:b[i]))i].join`` //107
a=>b=>[for(i of a.split``.map((c,i)=>c[d='charCodeAt']()>b[d](i)?c:b[i]))i].slice(0,Math.min(a.length,b.length)).join``        //119
a=>b=>[for(i of ' '.repeat(Math.min(a.length,b.length)).split``.map((_,i)=>a[d='charCodeAt'](i)>b[d](i)?a[i]:b[i]))i].join``   //124
a=>b=>[for(i of Array.apply(0,Array(Math.min(a.length,b.length))).map((_,i)=>a[d='charCodeAt'](i)>b[d](i)?a[i]:b[i]))i].join`` //127
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG! Nice first post! \$\endgroup\$
    – Riker
    Jun 9, 2017 at 15:05
5
\$\begingroup\$

Java 8, 124 120 117 63 bytes

a->b->{for(int i=0;;i++)System.out.print(a[i]>b[i]?a[i]:b[i]);}

-4 bytes thanks to @Khaled.K.
-3 bytes thanks to @Jakob.

Inputs are two character-arrays, and it stops with an ArrayIndexOutOfBoundsException.

Explanation:

Try it here.

a->b->{                       // Method with two char-array parameters and no return-type
  for(int i=0;;i++)           //  Loop `i` from 0 up indefinitely (until an error is given)
    System.out.print(         //   Print:
      a[i]>b[i]?a[i]:b[i]);}  //    The character that has the highest unicode value
\$\endgroup\$
0
4
\$\begingroup\$

C#, 81 78 bytes

a=>b=>{var s="";try{for(int q=0;;q++)s+=a[q]>b[q]?a[q]:b[q];}catch{}return s;}

C# has implicit char to int conversion (because a char is actually an int underneath) which is nice, and instead of looking for shortest string just try until failure

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Beat me to it! However, save one byte with currying a=>b=> by compiling to a Func<string, Func<string, string>>. You can remove the braces around the for loop to save 2 bytes. \$\endgroup\$ Jun 9, 2017 at 9:02
  • \$\begingroup\$ Side note: C# has implicit char to int conversion is true because a char is an int underneath. \$\endgroup\$ Jun 9, 2017 at 9:04
  • \$\begingroup\$ @TheLethalCoder: Not quite. sizeof(int) == 4 but sizeof(char) == 2. \$\endgroup\$
    – recursive
    Nov 8, 2017 at 21:54
4
\$\begingroup\$

MATL, 8 bytes

otX>cwA)

Input is a cell array of strings, in the format {'abcd' 'efg'}

Try it online!

As an aside, this also works for more than two strings.

Explanation

Consider input {'blended' 'bold'}. The stack is shown upside down, with more recent elements below.

o    % Implicitly input a cell array of strongs. Convert to numeric
     % vector of code points. This right-pads with zeros if needed
     %   STACK: [98 108 101 110 100 101 100;
                 98 111 108 100   0   0   0]
tX>  % Duplicate. Maximum of each column
     %   STACK: [98 108 101 110 100 101 100;
                 98 111 108 100   0   0   0],
                [98 111 108 110 100 101 100]
c    % Convert to char
     %   STACK: [98 108 101 110 100 101 100;
                 98 111 108 100   0   0   0],
                'bolnded'
w    % Swap
     %   STACK: 'bolnded'
                [98 108 101 110 100 101 100;
                 98 111 108 100   0   0   0]
A    % All: gives true (shown as 1) for columns containing only nonzeros
     %   STACK: 'bolnded'
                [1 1 1 1 0 0 0]
)    % Use as logical index (mask). Implicitly display
     %   STACK: 'boln'
\$\endgroup\$
4
\$\begingroup\$

R, 103 bytes

Code:

n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="")

Test cases:

> n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="")
1: programming puzzles & code golf!?
2: not yet graduated, needs a rehaul
3: 
Read 2 items
prtgretmirgduuzzlesneedsde rolful
> x <- scan(,"",sep=NULL)
1: asd asd 
3: 
Read 2 items
> n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="")
1: king
2: object
3: 
Read 2 items
oing
> n=min(sapply(y<-strsplit(scan(,"",sep="\n"),""),length));cat(mapply(max,el(y)[1:n],y[[2]][1:n]),sep="")
1: lab0ur win.
2: the "super bowl"
3: 
Read 2 items
the0usuwir.
\$\endgroup\$
2
  • \$\begingroup\$ Huh? Max works like that? TIL \$\endgroup\$
    – JAD
    Jun 9, 2017 at 13:36
  • 1
    \$\begingroup\$ 79 bytes! \$\endgroup\$
    – Giuseppe
    Dec 7, 2017 at 19:05
4
\$\begingroup\$

Kotlin, 50 41 37 bytes

-9 bytes with function reference syntax -4 bytes with extension function

fun String.x(o:String)=zip(o,::maxOf)

If s, and x are in scope, and not in a function, this method is only 16 bytes

s.zip(x,::maxOf)

Demo

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

Excel, 86 bytes

=LET(x,SEQUENCE(MIN(LEN(A1),LEN(A2))),d,MID(A1,x,1),e,MID(A2,x,1),CONCAT(IF(d>e,d,e)))
\$\endgroup\$
2
  • \$\begingroup\$ ah, another actuary on code golf! Are you FSA or FCAS? I'm still working my way towards my ACAS. Also, I don't have the courage to golf in Excel. \$\endgroup\$
    – Giuseppe
    Mar 10, 2021 at 2:55
  • 1
    \$\begingroup\$ I'm an ASA health actuary. Excel will never be the shortest but it's an interesting challenge to get it to work on these problems. \$\endgroup\$
    – Axuary
    Mar 10, 2021 at 11:38
3
\$\begingroup\$

CJam, 12 bytes

q~z{1/~e>o}%

Input is a list of two strings. The program exits with an error (after producing the right output) if the two strings have different lengths.

Try it online!

Explanation

q~              e# Read input and evaluate
  z             e# Zip: list of strings of length 2, or 1 if one string is shorter
   {      }%    e# Map this block over list
    1/          e# Split the string into array of (1 or 2) chars
      ~         e# Dump the chars onto the stack
       e>       e# Maximum of two chars. Error if there is only one char
         o      e# Output immediately, in case the program will error
\$\endgroup\$
3
\$\begingroup\$

Clojure, 31 bytes

#(map(comp last sort list)% %2)

Yay for function composition :) Returns a sequence of characters instead of a string, but they mostly work the same way in Clojure except when printing or regex matching.

Sadly max does not work with characters.

\$\endgroup\$
2
  • \$\begingroup\$ max doesn't work, but max-key does. #(map(partial max-key int)% %2) It's the exact same byte count, though. \$\endgroup\$
    – madstap
    Jun 11, 2017 at 22:43
  • \$\begingroup\$ Oh cool, I had forgotten about that. A lot simpler than for example (ffirst (sort-by second ...). \$\endgroup\$
    – NikoNyrh
    Jun 11, 2017 at 23:24
3
\$\begingroup\$

JavaScript (ES6), 47 bytes

f=([S,...s],[T,...t])=>S&&T?(S>T?S:T)+f(s,t):''

A recursive solution, which walks the string, always outputting the largest character.

Snippet:

f=([S,...s],[T,...t])=>S&&T?(S>T?S:T)+f(s,t):''

console.log(f('programming puzzles & code golf!?','not yet graduated, needs a rehaul'));
console.log(f('king','object'));
console.log(f('blended','bold'));
console.log(f('lab0ur win.','the "super bowl"'));
console.log(f('donald j.','trumfefe!'));

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

Julia 0.5, 33 bytes

Pretty much the same concept as Python2, but shorter.

a->join(map(maximum,(zip(a...))))

Try it online!

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

Retina, 55 36 bytes

^
¶
{O`¶.*
}`¶.(.*)¶(.)
$2¶$1¶
1!`.*

Try it online! Explanation: A line is prefixed to hold the result. While both strings still have characters left the inputs are sorted and the leading character with the highest code point is moved to the result while the other leading character is deleted. Finally the result is printed.

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

J, 25 bytes

>./&.(a.&i.)@(<.&#{."1,:)

explanation

half the bytes go to solving ensuring both inputs have the shorter inputs length (would love to see an improvement on this portion, if anyone has one):

(<.&#{."1,:)

<.&# is the minimum of the two lengths, and {."1,: takes that many characters from both rows of the 2-row table consisting of the left string stacked on top of the right one.

>./&.(a.&i.)

Use the Under verb &. to convert each character to its ascii index, take the maximum of the two numbers, and then convert back to characters.

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 21 bytes [:>./&.(3&u:)<.&#$&>; \$\endgroup\$
    – miles
    Aug 11, 2017 at 19:06
  • \$\begingroup\$ @miles, elegant combination of train and conjunction -- i need to use that trick more to avoid parens. also u: was a TIL for me. \$\endgroup\$
    – Jonah
    Aug 11, 2017 at 19:38
3
\$\begingroup\$

Add++, 8 bytes

D,f,@@,^

Try it online!

In versions 0.4 through 1.11, ^ exponents two numbers or "multiplies" two strings, depending on the type of the arguments.

\$\endgroup\$
3
  • \$\begingroup\$ This is rather against the spirit of code-golf, to post a question knowing that your own language (that nobody else uses) has a built-in which gives it a monopoly. Thankfully, Jelly's conciseness wins again. \$\endgroup\$
    – FlipTack
    Jun 9, 2017 at 6:31
  • 14
    \$\begingroup\$ @FlipTack did you read the first line of the question? Even if this was 0 bytes, it wouldn't win. \$\endgroup\$ Jun 9, 2017 at 6:33
  • 2
    \$\begingroup\$ @StephenS It seems that the feature inspired the challenge, not the other way round. The non-competing label is reserved for answers which use languages or features that were only implemented after the challenge. \$\endgroup\$ Jun 9, 2017 at 14:16
3
\$\begingroup\$

Python 3, 29 bytes

lambda*a:''.join(map(max,*a))

Try it online!


Coconut, 17 bytes

''.join<..map$max

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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