33
\$\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
  • 38
    \$\begingroup\$ This is the elementwise maximum of the strings, right? That doesn't seem anything like multiplying. \$\endgroup\$
    – xnor
    Jun 8 '17 at 22:34
  • 5
    \$\begingroup\$ Nitpick: PPCG has graduated, we just didn't get a new design yet. \$\endgroup\$
    – Dennis
    Jun 9 '17 at 4:02
  • 1
    \$\begingroup\$ Possible relevant: codegolf.stackexchange.com/questions/74809/merging-two-strings/… \$\endgroup\$
    – nmjcman101
    Jun 9 '17 at 11:40
  • 2
    \$\begingroup\$ The first test case is wrong. It should be "input1","input2" => "input2". \$\endgroup\$
    – user92069
    Mar 14 '20 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 '20 at 9:40

62 Answers 62

2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\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\$
2
\$\begingroup\$

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

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Can you provide a Try It Online or similar? At the moment, K doesn't produce the correct output on Kona or oK \$\endgroup\$ Jul 14 '17 at 19:36
  • \$\begingroup\$ 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 (kparc.com/k.txt), which doesn't have a reference implementation from kx yet. \$\endgroup\$
    – skeevey
    Jul 14 '17 at 19:46
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ unfortunately my idea f=:{.@/:~"1@|:@,: has trailing spaces and fails when one or other string is one character long \$\endgroup\$
    – jayprich
    May 25 '18 at 2:34
2
\$\begingroup\$

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.

\$\endgroup\$
0
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – 0 '
    Dec 8 '17 at 2:18
2
\$\begingroup\$

Prolog (SWI), 55 bytes

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

Try it online!

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

Japt, 9 bytes

Can't seem to do better than 9. Takes input as a 2D array of characters, outputs an array of characters

ñÊÕfÎËñ Ì

Try it (header formats the input)

ñÊÕfÎËñ Ì     :Implicit input of 2D array
ñ             :Sort by
 Ê            :  Length
  Õ           :Transpose, padding the shorter array with null if necessary
   f          :Filter by
    Î         :  First element (removing the arrays that contain null)
     Ë        :Map
      ñ       :  Sort
        Ì     :  Last element
\$\endgroup\$
2
\$\begingroup\$

Python 3, 29 bytes

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

Try it online!


Coconut, 17 bytes

''.join<..map$max

Try it online!

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

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

\$\endgroup\$
1
  • \$\begingroup\$ L@a~Min~L@b saves one byte \$\endgroup\$ Jun 9 '17 at 0:00
1
\$\begingroup\$

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:\
\$\endgroup\$
1
\$\begingroup\$

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

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

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

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to our site! This contest is a 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. \$\endgroup\$
    – Wheat Wizard
    Jun 12 '17 at 13:49
  • 1
    \$\begingroup\$ As 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) \$\endgroup\$ Jun 12 '17 at 14:13
  • \$\begingroup\$ shortened. Good find on the extra paren. fixed. In MP, I added iff() to mimic ?(eval,true,false). \$\endgroup\$
    – Ozz Nixon
    Jun 13 '17 at 17:39
1
\$\begingroup\$

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η¹⌈⟦ι§ηκ⟧
\$\endgroup\$
1
  • \$\begingroup\$ 9 bytes instead of 15, not sure if I had this back in June so maybe it's valid lol :P tio.run/##S85ILErOT8z5/… \$\endgroup\$
    – ASCII-only
    Aug 28 '17 at 15:41
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

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

Common Lisp, 59 bytes

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

Try it online!

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

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]
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
0
1
\$\begingroup\$

Swift, 66 bytes

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

Straight forward solution

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

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

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

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!

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

GolfScript, 23 bytes

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

Try it online!

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

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.

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

Burlesque, 9 bytes

lnp^q>]Z[

Try it online!

Returns a list of characters add 2 bytes for concat (\[)

ln  # Split on newlines
p^  # Push to arr
q>] # Boxed maximum
Z[  # ZipWith
\$\endgroup\$
1
\$\begingroup\$

Kotlin, 23 17 bytes

{zip(it,::maxOf)}

Try it online!

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

Erlang (escript), 46 bytes

t([I|M],[E|S])->[max(I,E)]++t(M,S);t(_,_)->[].

Try it online!

Explanation

t([I|M],[E|S])->               % Extract the head of both operands
[max(I,E)]                     % Take the max of the heads
++t(M,S);                      % Recurse with the remaining strings
t(_,_)                         % If head-extraction fails for either of these operands:
->[].                          % Return the empty string
\$\endgroup\$
1
\$\begingroup\$

Husk, 2 bytes

zY

Try it online!

zip using maximum.

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

Perl 5 -lF, 88 67 bytes

@b=<>=~/./g;$#F=$#b=@F>@b?$#b:$#F;say map{($q=shift@b)gt$_?$q:$_}@F

Try it online!

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

05AB1E, 3 bytes

ø€à

Try it online!

ø€à  # full program
ø    # list of...
  à  # maximums of...
 €   # each element of...
ø    # code points of...
     # implicit input...
ø    # with each element paired with the corresponding element in second sub-list
     # implicit output
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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