"Multiply" two strings

29

3

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!

caird coinheringaahing

Posted 2017-06-08T22:31:14.363

Reputation: 13 702

35This is the elementwise maximum of the strings, right? That doesn't seem anything like multiplying. – xnor – 2017-06-08T22:34:48.897

5Nitpick: PPCG has graduated, we just didn't get a new design yet. – Dennis – 2017-06-09T04:02:27.943

1

Possible relevant: https://codegolf.stackexchange.com/questions/74809/merging-two-strings/123187#123187

– nmjcman101 – 2017-06-09T11:40:09.810

Answers

53

Haskell, 11 bytes

zipWith max

Try it online!

Nothing much to explain.

nimi

Posted 2017-06-08T22:31:14.363

Reputation: 34 639

7And I thought Mathematica had strange built-ins – Mr. Xcoder – 2017-06-10T10:15:02.373

@Mr.Xcoder Mathematica has zipWith, it's called MapThread – michi7x7 – 2017-07-14T16:38:08.430

2@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 – 2017-08-11T08:56:30.480

8

05AB1E, 4 bytes

øΣà?

Uses the 05AB1E encoding. Try it online!

Adnan

Posted 2017-06-08T22:31:14.363

Reputation: 41 965

I feel like ø€à should work, but it don't. – Magic Octopus Urn – 2017-08-11T19:03:59.317

Looks more like a question than an answer lol – Stan Strum – 2017-12-08T01:44:23.143

6

Perl 6, 22 bytes

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

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

Sean

Posted 2017-06-08T22:31:14.363

Reputation: 4 136

6

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

ETHproductions

Posted 2017-06-08T22:31:14.363

Reputation: 47 880

6

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

Jörg Hülsermann

Posted 2017-06-08T22:31:14.363

Reputation: 13 026

1Slightly golfed: for(;$t=min(~$argv[1][$i],~$argv[2][$i++]);)echo~$t;. – user63956 – 2017-06-09T09:05:46.247

6

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.

Dennis

Posted 2017-06-08T22:31:14.363

Reputation: 196 637

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 – 2017-06-09T06:48:39.483

1I've added a worked example. – Dennis – 2017-06-09T07:10:25.560

6

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.

Neil

Posted 2017-06-08T22:31:14.363

Reputation: 95 035

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 – 2017-11-09T08:25:39.843

@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 – 2017-11-09T08:43:22.367

6

C, 58 bytes

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

Try Online

  • -8 bytes @Steadybox

Khaled.K

Posted 2017-06-08T22:31:14.363

Reputation: 1 435

Darn, f(s,t)char*s,*t;{ gives the same length. – aschepler – 2017-06-11T11:24:48.963

6

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.

Martin Ender

Posted 2017-06-08T22:31:14.363

Reputation: 184 808

6

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.

Martin Ender

Posted 2017-06-08T22:31:14.363

Reputation: 184 808

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 – 2017-07-26T09:31:52.277

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 – 2017-07-26T09:41:39.290

@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 – 2017-07-26T11:04:16.753

5

Jelly, 6 bytes

żḊ€ṁ@»

Try it online!

Leaky Nun

Posted 2017-06-08T22:31:14.363

Reputation: 45 011

1żṢ€Ḋ€ and żṢ€ZṪ both save a byte. – Dennis – 2017-06-09T04:13:47.400

@Dennis very clever. – Leaky Nun – 2017-06-09T08:26:29.777

5

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)

user202729

Posted 2017-06-08T22:31:14.363

Reputation: 14 620

5

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

Kevin Cruijssen

Posted 2017-06-08T22:31:14.363

Reputation: 67 575

4

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'

Luis Mendo

Posted 2017-06-08T22:31:14.363

Reputation: 87 464

4

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!

totallyhuman

Posted 2017-06-08T22:31:14.363

Reputation: 15 378

4

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

James

Posted 2017-06-08T22:31:14.363

Reputation: 54 537

Is the dG necessary? Don't all of the newlines get removed with the Íî anyways? – nmjcman101 – 2017-06-09T15:37:19.107

@nmjcman101 It's needed in case the strings are different lengths. – James – 2017-06-09T15:38:31.587

4

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

LiefdeWen

Posted 2017-06-08T22:31:14.363

Reputation: 3 381

1Beat 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 – 2017-06-09T09:02:17.537

Side note: C# has implicit char to int conversion is true because a char is an int underneath. – TheLethalCoder – 2017-06-09T09:04:12.993

@TheLethalCoder: Not quite. sizeof(int) == 4 but sizeof(char) == 2. – recursive – 2017-11-08T21:54:56.443

4

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.

djhurio

Posted 2017-06-08T22:31:14.363

Reputation: 1 113

Huh? Max works like that? TIL – JAD – 2017-06-09T13:36:49.557

179 bytes! – Giuseppe – 2017-12-07T19:05:55.140

3

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

Luis Mendo

Posted 2017-06-08T22:31:14.363

Reputation: 87 464

3

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.

NikoNyrh

Posted 2017-06-08T22:31:14.363

Reputation: 2 361

max doesn't work, but max-key does. #(map(partial max-key int)% %2) It's the exact same byte count, though. – madstap – 2017-06-11T22:43:03.053

Oh cool, I had forgotten about that. A lot simpler than for example (ffirst (sort-by second ...). – NikoNyrh – 2017-06-11T23:24:00.343

3

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.

Neil

Posted 2017-06-08T22:31:14.363

Reputation: 95 035

3

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

andrewarchi

Posted 2017-06-08T22:31:14.363

Reputation: 408

Welcome to PPCG! Nice first post! – Rɪᴋᴇʀ – 2017-06-09T15:05:56.433

3

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

Redrield

Posted 2017-06-08T22:31:14.363

Reputation: 131

Here's a try.kotlinlang.org link: https://try.kotlinlang.org/#/UserProjects/ulm4nriigeio44jq1sdqer9sg2/spr3ucr6j9dr45e3od7nepsoie

– Kirill Rakhman – 2017-06-12T07:31:02.943

3

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"

ბიმო

Posted 2017-06-08T22:31:14.363

Reputation: 15 345

2

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.

caird coinheringaahing

Posted 2017-06-08T22:31:14.363

Reputation: 13 702

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 – 2017-06-09T06:31:01.800

12@FlipTack did you read the first line of the question? Even if this was 0 bytes, it wouldn't win. – caird coinheringaahing – 2017-06-09T06:33:38.987

1@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 – 2017-06-09T14:16:33.050

2

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]})

TessellatingHeckler

Posted 2017-06-08T22:31:14.363

Reputation: 2 412

2

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.

Nathan Merrill

Posted 2017-06-08T22:31:14.363

Reputation: 13 591

2

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!

Jonah

Posted 2017-06-08T22:31:14.363

Reputation: 8 729

121 bytes [:>./&.(3&u:)<.&#$&>; – miles – 2017-08-11T19:06:38.053

@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 – 2017-08-11T19:38:52.787

1

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"]

J42161217

Posted 2017-06-08T22:31:14.363

Reputation: 15 931

L@a~Min~L@b saves one byte – Greg Martin – 2017-06-09T00:00:48.033

1

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

}

Adám

Posted 2017-06-08T22:31:14.363

Reputation: 37 779

1

Micro, 119 bytes

{R b i m+:R}:X{R a i m+:R}:Y
""\\:a:b:R
{b:M}:N
a:M
b a<if(N,)
0:i{i1+:i
a i m C b i m C~:> if(X,Y)
i M=if(,Z)}:Z
Z
R:\

raddish0

Posted 2017-06-08T22:31:14.363

Reputation: 91

1

C#, 71, 67 bytes

saved a few bytes by using string.Join() instead of new string()

added 18 bytes to both versions for needing using System.Linq;

67 bytes

(a,b)=>string.Join("",(a.Zip(b,(x,y)=>x>y?x:y)));

71 bytes:

(a,b)=>new string(a.Zip(b,(x,y)=>x>y?x:y).ToArray());

DotNetFiddle

grabthefish

Posted 2017-06-08T22:31:14.363

Reputation: 161

1

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!'));

Rick Hitchcock

Posted 2017-06-08T22:31:14.363

Reputation: 2 461

1

Python 3, 29 bytes

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

Try it online!

ovs

Posted 2017-06-08T22:31:14.363

Reputation: 21 408

1

Julia 0.5, 33 bytes

Pretty much the same concept as Python2, but shorter.

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

Try it online!

pasbi

Posted 2017-06-08T22:31:14.363

Reputation: 411

1

k, 14 bytes

{|/(&/#:'x)$'x}

Examples:

k)F:{|/(&/#:'x)$'x}
k)F("hello,";"world!")
"worlo,"

q translation:

{max(min count each x)$/:x}

Free interpreter available here

skeevey

Posted 2017-06-08T22:31:14.363

Reputation: 4 139

1

Can you provide a Try It Online or similar? At the moment, K doesn't produce the correct output on Kona or oK

– caird coinheringaahing – 2017-07-14T19:36:04.783

I added a link to download the interpreter. Kona is an implementation of an old version of k. oK is an implementation of the k6 spec (http://kparc.com/k.txt), which doesn't have a reference implementation from kx yet.

– skeevey – 2017-07-14T19:46:12.650

1

J, 22 bytes

0({"1\:~@,"0/)<.&#$&>;

Try it online!

Explanation

0({"1\:~@,"0/)<.&#$&>;  Input: string x (LHS), string y (RHS)
                 #      Get length of x and y
              <.&       Minimum of those
                     ;  Link x and y as a pair of boxed strings
                  $&>   Shape each to the minimum length
         ,"0/           Reduce by joining elementwise
     \:~@               Grade down each pair
0 {"1                   Select the value at index 0 from each

miles

Posted 2017-06-08T22:31:14.363

Reputation: 15 654

unfortunately my idea f=:{.@/:~"1@|:@,: has trailing spaces and fails when one or other string is one character long – jayprich – 2018-05-25T02:34:59.717

1

Acc!!, 186 bytes

N
Count i while _/128^i/32 {
_+128^(i+1)*N
}
_*128+N
Count i while _%128/32*(_/4096) {
Count j while _/128%128/(_%128+1) {
_/128^2*128^2+_/128%128+_%128*128
}
Write _%128
_/128^2*128+N
}

Input strings should be given on stdin, newline-separated. Try it online!

Explanation

We conceptually partition the accumulator into 7-bit registers, each of which can hold an input character. The first Count i loops until the input's ASCII code is smaller than 32, storing the first line of input into the accumulator, with the first character in the least-significant position:

, o l l e h
5 4 3 2 1 0
Accumulator value = asc(h) + 128*asc(e) + 128^2*asc(l) + ... = 1541853098728

Next, we shift everything left by one register, read the first character of the second line, and store it into register 0:

, o l l e h w
6 5 4 3 2 1 0

We Count i again while register 0 (_%128) and register 1 (_/128%128, though the formula can be golfed a bit in this context) are both >= 32. Inside the loop, we use a nested Count j loop to check if register 1 is strictly greater than register 0. (Comparisons are done via integer division: if a/(b+1) is 0, then a<=b; if a/(b+1) is nonzero, then a>b.) If it is greater, we swap the registers' contents. This loop executes at most once, because after swapping, the condition is guaranteed not to be true anymore.

After the (potential) swap, the larger of the two characters is in register 0, which we output. We then shift two registers to the right (_/128^2), shift one register back to the left (*128), and store the next input character in register 0 (+N):

, o l l e o
5 4 3 2 1 0

The Count i loop exits once one or both strings reach the newline at their end.

DLosc

Posted 2017-06-08T22:31:14.363

Reputation: 21 213

1

Java, 158 151 bytes

Golfed:

String s(String a,String b){String r="";for(int i=0;i<Math.min(a.length(),b.length());i++){char c=a.charAt(i);char d=b.charAt(i);r+=c>d?c:d;}return r;}

Ungolfed:

String s(String a,String b) {
    String r = "";
    for(int i=0; i < Math.min(a.length(),b.length()); i++) {
        char c = a.charAt(i);
        char d = b.charAt(i);
        r += c > d ? c : d; //absolute ternary abuse
    }
    return r;
}

Takes two strings in a and b.

Kitten

Posted 2017-06-08T22:31:14.363

Reputation: 161

I think you could save a few bytes by getting rid of the outside ternary if statement (r+=c==d?c:) since if they are equal you can add either c or d to the string and it won't make a difference. – 0 ' – 2017-12-08T02:18:35.113

1

Prolog (SWI), 55 bytes

[A|T]*[B|U]-[C|R]:-(A>B,C=A;C=B),T*U-R.
[]*_-[].
_*L-L.

Try it online!

ASCII-only

Posted 2017-06-08T22:31:14.363

Reputation: 4 687

0

Aceto, 43 bytes

]w(x^
o|p
d(
do
X0l)x
`=`X(
€(=0p
rr€l<

Explanation:

First, we read the first string, and explode it, then we move a stack to the left, read the second string, and explode it:

€(
rr€

Now, we check for emptiness of either of the stacks and exit if that is the case:

X0l)
`=`X
  =0
   l

Next, we duplicate the top letter of both stacks, and convert them to code points, then move them both (and us) on the right stack:

]
o
d(
do

The w tests if something is less or equal. If so, we get mirrored to the right. Otherwise, we print the top letter, go on the left stack, drop the top element (the other letter) and move up (^), which moves us on the bottom <, which moves us back to the length check.

 w(x^
 |p

If however, the test was truthy, we get mirrored into the emptiness on the right, and we need to do the opposite. Eventually we reach the three commands that now drop, then move to the left stack and print its top element. The < is the same symbol we land on in the other case, so here too we are lead back to the length check.

x
(
p
<

This repeats until one of the length checks succeeds, i.e. if one of the input strings is exhausted.

L3viathan

Posted 2017-06-08T22:31:14.363

Reputation: 3 151

0

Charcoal, 17 bytes

F⌊⟦LθLη⟧⌈⟦§θι§ηι⟧

Try it online! Link is to verbose version of code. Edit: Slice got added a few days later, which would have allowed the following code for 15 bytes: Try it online!

↑E✂θ⁰Lη¹⌈⟦ι§ηκ⟧

Neil

Posted 2017-06-08T22:31:14.363

Reputation: 95 035

9 bytes instead of 15, not sure if I had this back in June so maybe it's valid lol :P https://tio.run/##S85ILErOT8z5/z8tv0hBI7UsMacssUhDqUpJRyG6UEchI1ZTUyGgKDOvRMM3sSIztzRXI1NT0/r//@zMvHSu/KSs1OSS/7pl/3WLcwA

– ASCII-only – 2017-08-28T15:41:51.733

0

Modern Pascal

version 1 of algorithm (func:139bytes)

   for var l:=1 to min(length(paramstr(1)),length(paramstr(2))) do
      result+=iif(paramstr(1)[l]>paramstr(b)[l],paramstr(1)[l],paramstr(2)[l]);

Explanation The for loop is designed to crawl to the length of the shortest string. The output is compared appending to result the highest ASCII value of each letter crawled. Since we are using shortest length, we can access the strings elements directly - see v2 below, uses Copy() to be safer.

version 2 of algorithm (func:166bytes)

   for var l:=1 to max(length(paramstr(1)),length(paramstr(2))) do
      result+=iif(copy(paramstr(1),l,1)>copy(paramstr(2),l,1),copy(paramstr(1),l,1),copy(paramstr(2),l,1));

// Author of Modern Pascal

Ozz Nixon

Posted 2017-06-08T22:31:14.363

Reputation: 21

Welcome to our site! This contest is a [tag:code-golf] contest. You should aim to minimize the number of bytes in the source code. I don't know pascal at all so this may be well golfed already but I suspect there is some whitespace that can be removed. Once you are satisfied with your golfs you can add the byte count of your program to your header. If you have any questions you can ping me with @wheatwizard. – Post Rock Garf Hunter – 2017-06-12T13:49:13.367

1As Wheat Wizard said, I'm sure this can be golfed to reduce your score but I think that there is at least one typo in your first code, maybe two. Should iif(a[l]>b[l]),a[l] be if(a[l]>b[l],a[l]? (there is definitely an extra ) but I don't know about iif and if) – caird coinheringaahing – 2017-06-12T14:13:18.407

shortened. Good find on the extra paren. fixed. In MP, I added iff() to mimic ?(eval,true,false). – Ozz Nixon – 2017-06-13T17:39:18.950

0

Pip, 9 bytes

DQSS_MaZb

Try it online!

Pip doesn't have a string max operator, so I used SS (Sort String) instead:

      aZb  Zip the two cmdline args together, truncating to shorter length
     M     To that list of 2-element lists of characters, map a function:
  SS_       Sort each pair of characters stringwise
DQ          and dequeue the second (larger) one
           Autoprint the resulting list of characters

DLosc

Posted 2017-06-08T22:31:14.363

Reputation: 21 213

0

Perl 5, 88 bytes

@a=<>=~/./g;@b=<>=~/./g;$#a=$#b=$#a>$#b?$#b:$#a;say map{ord($b[++$#i])>ord?$b[$#i]:$_}@a

Try it online!

Xcali

Posted 2017-06-08T22:31:14.363

Reputation: 7 671

0

Axiom, 67 20 bytes

f(a,b)==map(max,a,b)

And with this we now surpass JavaScript, Lisp until perhaps J and APL too.

The previous solution:

f(a,b)==concat[max(a.x,b.y)::String for x in 1..#a for y in 1..#b]

RosLuP

Posted 2017-06-08T22:31:14.363

Reputation: 3 036

0

Common Lisp, 59 bytes

(lambda(x y)(map'string(lambda(a b)(if(char> a b)a b))x y))

Try it online!

Renzo

Posted 2017-06-08T22:31:14.363

Reputation: 2 260

0

Whispers, 49 bytes

> Input
> Input
>> L»R
>> Each 3 1 2
>> Output 4

Try it online!

How it works

Each line consists of (line no.) (> or >>) (command) (the line numbers are implicitly added in the actual program)

1 > Input        - Retrieve the first input

2 > Input        - Retrieve the second input

3 >>  »          - Take the maximum of...
     L           -   the left argument and...
       R         -   the right argument

4 >> Each        - For each value in...
            1    -   the first line zipped with...
              2  -   the second input,
          3      -   call the third line

5 >>        4    - Run the fourth line, then...
     Output      - Output the result

caird coinheringaahing

Posted 2017-06-08T22:31:14.363

Reputation: 13 702

0

Swift, 66 bytes

func f(a:String,b:String){print(String(zip(a,b).map{max($0,$1)}))}

Straight forward solution

Herman L

Posted 2017-06-08T22:31:14.363

Reputation: 3 611

0

Japt v2.0a0, 13 bytes

ÊmVl)îUcÈwVcY

Try it online!

Unpacked & How it works

Ul mVl)îUcXYZ{XwVcY

Ul      Length of 1st input (U)
mVl)    Minimum of above and length of 2nd input (V)
î       Take this length out of the following string...
UcXYZ{    Map on charcodes of U and convert back to string...
Xw          Maximum of this and...
VcY         V's charcode at the same index.

Japt doesn't have min/max on strings, but does have one on numbers. Turns out that it helped reduce bytes on both "Compute minimum length of two strings" and "Map on two strings to take higher chars".

Bubbler

Posted 2017-06-08T22:31:14.363

Reputation: 16 616

0

Cjam, 3 bytes

This is so easy...

.e>

Pretty much the same as the Haskell answer, . takes an operator and performs "zipWith", and e> means take the max of the two inputs.

Try it online!

Chromium

Posted 2017-06-08T22:31:14.363

Reputation: 201

0

GolfScript, 23 bytes

~zip{.,({$1=}{;}if}%''+

Try it online!

wastl

Posted 2017-06-08T22:31:14.363

Reputation: 3 089

0

R, 96 bytes

for(i in 1:min(lengths(m<-sapply(scan(,""),utf8ToInt))))cat(intToUtf8(max(m[[1]][i],m[[2]][i])))

Try it online!

Using ASCII code.

JayCe

Posted 2017-06-08T22:31:14.363

Reputation: 2 655