# “Multiply” two strings

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!

• This is the elementwise maximum of the strings, right? That doesn't seem anything like multiplying. – xnor Jun 8 '17 at 22:34
• Nitpick: PPCG has graduated, we just didn't get a new design yet. – Dennis Jun 9 '17 at 4:02
• Possible relevant: codegolf.stackexchange.com/questions/74809/merging-two-strings/… – nmjcman101 Jun 9 '17 at 11:40

zipWith max


Try it online!

Nothing much to explain.

• And I thought Mathematica had strange built-ins – Mr. Xcoder Jun 10 '17 at 10:15
• @Mr.Xcoder Mathematica has zipWith, it's called MapThread – michi7x7 Jul 14 '17 at 16:38
• @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. – Jonah Aug 11 '17 at 8:56

# 05AB1E, 4 bytes

øΣà?


Uses the 05AB1E encoding. Try it online!

• I feel like ø€à should work, but it don't. – Magic Octopus Urn Aug 11 '17 at 19:03
• Looks more like a question than an answer lol – Stan Strum Dec 8 '17 at 1:44

# Perl 6, 22 bytes

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


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

# 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


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

• 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 – Leo Jun 9 '17 at 6:48
• I've added a worked example. – Dennis Jun 9 '17 at 7:10

# PHP>=7.1, 52 Bytes

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


PHP Sandbox Online

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

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

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


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

• 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... – Neil Jul 26 '17 at 9:31
• 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. – Neil Jul 26 '17 at 9:41 • @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 \). – Martin Ender Jul 26 '17 at 11:04 # C, 58 bytes f(char*s,char*t){putchar(*s>*t?*s:*t);*++s&&*++t&&f(s,t);}  Try Online • -8 bytes @Steadybox • Darn, f(s,t)char*s,*t;{ gives the same length. – aschepler Jun 11 '17 at 11:24 ## 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. • 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? – RosLuP Nov 9 '17 at 8:25 • @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. – Neil Nov 9 '17 at 8:43 # Jelly, 6 bytes żḊ€ṁ@»  Try it online! • żṢ€Ḋ€ and żṢ€ZṪ both save a byte. – Dennis Jun 9 '17 at 4:13 • @Dennis very clever. – Leaky Nun Jun 9 '17 at 8:26 ## 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) # Java 8, 124120117 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  # 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 • 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. – TheLethalCoder Jun 9 '17 at 9:02 • Side note: C# has implicit char to int conversion is true because a char is an int underneath. – TheLethalCoder Jun 9 '17 at 9:04 • @TheLethalCoder: Not quite. sizeof(int) == 4 but sizeof(char) == 2. – recursive Nov 8 '17 at 21:54 # 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'  ## 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.  • Huh? Max works like that? TIL – JAD Jun 9 '17 at 13:36 • 79 bytes! – Giuseppe Dec 7 '17 at 19:05 # Python 2, 4744 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! # 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  • Is the dG necessary? Don't all of the newlines get removed with the Íî anyways? – nmjcman101 Jun 9 '17 at 15:37 • @nmjcman101 It's needed in case the strings are different lengths. – DJMcMayhem Jun 9 '17 at 15:38 # 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  ## 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. • max doesn't work, but max-key does. #(map(partial max-key int)% %2) It's the exact same byte count, though. – madstap Jun 11 '17 at 22:43 • Oh cool, I had forgotten about that. A lot simpler than for example (ffirst (sort-by second ...). – NikoNyrh Jun 11 '17 at 23:24 # Javascript (ES2015), 6663 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  • Welcome to PPCG! Nice first post! – Rɪᴋᴇʀ Jun 9 '17 at 15:05 # 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. # 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"  # Kotlin, 5041 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 ## PowerShell, 75 bytes -join(1..(($a,$b=$args)|sort l*)[0].length|%{(,$a[$_-1],$b[$_-1]|sort)[1]})
#            ^input array unpack
#       ^string index generation offset by 1
#                         ^sort by length property, so output length matches shorter input
#                                           ^loop over indices
#                                       max of the two characters^
# ^output join


Save as .ps1 file and run

PS C:\> .\Get-MultipliedString.ps1 'hello,' 'world!'
worlo,


Previously, 78 bytes:

$i=0;-join$(while(($a=$args[0][$i])-and($b=$args[1][$i++])){($a,$b)[$b-gt$a]})


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

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

# Java 8 + Eclipse Collections, 70 64 bytes

a->b->a.zip(b).collect(p->(char)Math.max(p.getOne(),p.getTwo()))


a and b are both MutableList<Character> from eclipse collections.

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.

• 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. – FlipTack Jun 9 '17 at 6:31
• @FlipTack did you read the first line of the question? Even if this was 0 bytes, it wouldn't win. – caird coinheringaahing Jun 9 '17 at 6:33
• @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. – Martin Ender Jun 9 '17 at 14:16

# Mathematica, 102 bytes

T=ToCharacterCode;L=Length;(a=T@#;b=T@#2;FromCharacterCode@Table[Max[a[[i]],b[[i]]],{i,L@a~Min~L@b}])&


input

["blended ", "bold"]

• L@a~Min~L@b saves one byte – Greg Martin Jun 9 '17 at 0:00

# APL (Dyalog), 22 bytes

Takes two (or more!) strings as right argument.

{⎕UCS⌈⌿⎕UCS↑⍵↑¨⍨⌊/≢¨⍵}


Try it online!

{ an anonymous function where the right argument is represented by

⎕UCS the symbols from the Unicode Character Set which correspond to the

⌈⌿ maximum value in each column of

⎕UCS the code points from the Unicode Character Set for the

↑ matrified (matrix from list of strings)

⍵ arguments

↑¨⍨ each capped at the

⌊/ minimum of

≢¨ the lengths

⍵ of the arguments

}