title: "Multiply" two strings

text:
# Question
Title: "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!

# Answer
> 55 votes
## Haskell, 11 bytes

```
zipWith max

```

Try it online!

Nothing much to explain.

# Answer
> 10 votes
# 05AB1E, 4 bytes

```
øΣà?

```

Uses the **05AB1E** encoding. Try it online!

# Answer
> 7 votes
# 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

```

# Answer
> 7 votes
# 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

# Answer
> 7 votes
# 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 **n**th character in the second array from the **n**th 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**.

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

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

```

# Answer
> 6 votes
# Perl 6, 22 bytes

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

```

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

# Answer
> 6 votes
# Jelly, 6 bytes

```
żḊ€ṁ@»

```

Try it online!

# Answer
> 6 votes
# C, 58 bytes

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

```

**Try Online**

* -8 bytes @Steadybox

# Answer
> 6 votes
## 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.

# Answer
> 6 votes
# 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"

```

# Answer
> 5 votes
# 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!

# Answer
> 5 votes
# , ~~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

```

# Answer
> 5 votes
## 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)

# Answer
> 5 votes
# 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

```

# Answer
> 5 votes
# 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

```

# Answer
> 4 votes
# 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'

```

# Answer
> 4 votes
# 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

# Answer
> 4 votes
## 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.

```

# Answer
> 4 votes
# 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

# Answer
> 4 votes
# 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)))

```

# Answer
> 3 votes
# 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

```

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
## 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.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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!'));
```

# Answer
> 3 votes
# Python 3, 29 bytes

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

```

Try it online!

---

# Coconut, 17 bytes

```
''.join<..map$max

```

Try it online!

# Answer
> 3 votes
# Julia 0.5, 33 bytes

Pretty much the same concept as Python2, but shorter.

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

```

Try it online!

# Answer
> 3 votes
# 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!

# Answer
> 2 votes
## 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]})

```

# Answer
> 2 votes
# 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 **U**nicode **C**haracter **S**et which correspond to the

`⌈⌿` maximum value in each column of

`⎕UCS` the code points from the **U**nicode **C**haracter **S**et for the

matrified (matrix from list of strings)

arguments

`↑¨⍨` each capped at the

`⌊/` minimum of

`≢¨` the lengths

of the arguments

`}`

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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

# Answer
> 2 votes
# , 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

```

# Answer
> 2 votes
# 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`.

# Answer
> 2 votes
# Prolog (SWI), 55 bytes

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

```

Try it online!

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# Knight, ~~70~~ ~~51~~ 48 bytes

```
;=aP;=bP W&a b;O+A I>a bAaAb"\";=aGa 1La=bGb 1Lb

```

Try it online!

Ungolfed & explained:

```
; = a PROMPT                                  # a = input()
; = b PROMPT                                  # b = input()
: WHILE & a b                                 # while a != "" and b != "":
    ; OUTPUT + ASCII IF > a b ASCII           #
               a ASCII b "\"                  #    print(a[0] if a > b else a[1]) # (without newline)
    ; = a GET a 1 LENGTH a                    #    a = a[1:]
    : = b GET b 1 LENGTH b                    #    b = b[1:]

```

-19 bytes thanks to Adam.

-3 bytes thanks to Bubbler.

# Answer
> 2 votes
# Go, ~~131~~ 121 bytes

```
func f(a,b string)(o string){
if""==a||b==""{o=""}else{A,B:=a[:1],b[:1]
if A>B{o+=A}else{o+=B}
o+=f(a[1:],b[1:])}
return}

```

Attempt This Online!

* -10 by @The Thonnu

# Answer
> 2 votes
# Rust, 34 bytes

```
|a,b|a.zip(b).map(|(i,j)|i.max(j))

```

which takes in two iterators over `char`s and returns another. This only works by shunting the following obscene type into the header code:

```
for<'a> fn(std::str::Chars<'a>, std::str::Chars<'a>) -> std::iter::Map<std::iter::Zip<std::str::Chars<'a>, std::str::Chars<'a>>, fn((char, char))->char>

```

Attempt This Online!

If iterators over chars do not count as reasonable input/output I can instead manage

# 60 bytes

```
|a,b|a.chars().zip(b.chars()).map(|(i,j)|i.max(j)).collect()

```

which has the much more reasonable type of

```
fn(&str, &str) -> String

```

Attempt This Online!

# Answer
> 2 votes
# tinylisp 2, 28 bytes

```
(\(S T)(,(zip-with max S T)"

```

Try it at Replit! Example session:

```
tl2> (\(S T)(,(zip-with max S T)"
(() (S T) (, (zip-with max S T) ""))
tl2> (d F _
F
tl2> (F "hello," "world!")
"worlo,"

```

### Explanation

The library functions `zip-with` and `max` do almost the entire task.\* The only catch is that `zip-with` returns a list of codepoints, and we want a string. The easiest way to convert is to concatenate an empty string using `,` (short for `concat`).

---

* When I first answered this challenge, I had not yet implemented `zip-with` and `max` in the standard library. Here's my original **46-byte** solution without those functions:

```
(\(S T)(,(m(p a(\(C D)(?(< C D)D C)))(z S T))"

```

Explanation:

```
(\(S T)(,(m(p a(\(C D)(?(< C D)D C)))(z S T))""))
(\                                              ) ; Lambda function
  (S T)                                           ; taking two strings S and T:
                                     (z S T)      ; Zip (-> list of pairs of codepoints)
         (m                                 )     ; Map to each pair:
           (p a                     )             ; Apply to its two items:
               (\                  )              ; Lambda function
                 (C D)                            ; taking two integers C and D:
                      (?(< C D)D C)               ; If C < D, then D, else C (i.e. max)
                                                  ; Now we have a list of codepoints...
       (,                                    "")  ; Concat "", converting to string

```

# Answer
> 1 votes
# 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"\]

# Answer
> 1 votes
# 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:\

```

# Answer
> 1 votes
# 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

# Answer
> 1 votes
# Charcoal, 17 bytes

```
Ｆ⌊⟦ＬθＬη⟧⌈⟦§θι§ηι⟧

```

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!

```
↑Ｅ✂θ⁰Ｌη¹⌈⟦ι§ηκ⟧

```

# Answer
> 1 votes
# 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

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# *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.

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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]

```

# Answer
> 1 votes
# Common Lisp, 59 bytes

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

```

Try it online!

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Swift, 66 bytes

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

```

Straight forward solution

# Answer
> 1 votes
# 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".

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# GolfScript, 23 bytes

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

```

Try it online!

# Answer
> 1 votes
# , 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.

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Kotlin,  ~~23~~  17 bytes

```
{zip(it,::maxOf)}

```

Try it online!

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Husk, 2 bytes

```
zY

```

Try it online!

zip using maximum.

# Answer
> 1 votes
# Vyxal, 3 bytes

```
ZvG

```

Try it Online!

That is: the maximum function (`G`) `v`ectorised over the inputs `Z`ipped together (`abc` and `def` turn into `[["a", "d"], ["b", "e"], ["c", "f"]]`. Takes a single string (alternatively, a list of characters) and outputs a list of characters.

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Factor, ~~16~~ 4 bytes

```
vmax

```

Try it online!

Element-wise maximum. It's a builtin.

# Answer
> 1 votes
# Pyth, 5 bytes

```
eCSMC

```

Test suite

# Answer
> 1 votes
# Thunno `J` `B`, \\$ 5 \log\_{256}(96) \approx \\$ 4.12 bytes

```
ZZeMC

```

(No ATO link since it's not on a new enough version)

#### Explanation

```
ZZeMC  # Implicit input. The B flag converts the strings to codepoints.
ZZe    # Zip together and loop through:
   M   #   Get the maximum
    C  #   And get chr of that
       # Implicit output, with the J flag joining everything together

```

### Thunno `J`, \\$ 9 \log\_{256}(96) \approx \\$ 7.41 bytes

```
ZZeO.AJMC

```

(No ATO link since it's not on a new enough version)

#### Explanation

Unfortunately the `max` command (`M`) doesn't work with strings, otherwise this would have been a lot simpler.

```
ZZeO.AJMC  # Implicit input
ZZe        # Zip together and loop through:
   O.AJ    #   Get the ordinals of both characters
       M   #   Get the maximum
        C  #   And get chr of that
           # Implicit output, with the J flag joining everything together

```

#### Screenshots

# Answer
> 1 votes
# Python 3, 26 bytes

```
lambda*a:list(map(max,*a))

```

Try it online!

Similar to another Python 3 answer, only that I use `list` instead of `''.join`, which shaves 3 bytes off.

# Answer
> 1 votes
# C (gcc), 51 bytes

```
f(char*s,char*t){(*s=*s>*t|!*s?*s:*t)&&f(s+1,t+1);}

```

Try it online!

# C (gcc), 51 bytes

```
f(char*s,char*t){(*s=0u-*s<-*t?*s:*t)&&f(s+1,t+1);}

```

Try it online!

# Answer
> 1 votes
# Arturo, 22 bytes

```
$=>[couple&&|map=>max]

```

Try it

Takes and outputs a list of characters.

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
Z€G

```

Output as a list of characters. Add the `J` flag if you want a string.

#### Explanation

```
Z€G  # Implicit input
Z    # Zip the two inputs together
 €   # For each pair:
  G  #  Get the maximum of the pair
     # Implicit output

```

#### Screenshot

---
Tags: code-golf, string
---


# Question
Title: Longest Repeating Subsequence of a Single Digit
## Challenge:

Given a positive integer, output the longest single-digit subsequence that occurs at least twice, AND has boundaries of another digit (or the start/end of the integer).

**An example:**

Input: `7888885466662716666`
The longest subsequence of a single digit would be `88888` (`7[88888]5466662716666`) with a length of 5. However, this subsequence only occurs once in the integer.
Instead, the result for input `7888885466662716666` should be `6666` (`78888854[6666]271[6666]`), since it occurs (at least) twice.

## Challenge rules:

* Length of the subsequences takes priority over the amount of times it occurs. (I.e. with input `8888858888866656665666`, we output `88888` (`[88888]5[88888]66656665666`; length 5, occurs twice), and not `666` (`88888588888[666]5[666]5[666]`; length 3, occurs thrice).
* If the length of multiple subsequences are equal, we output the one with the largest occurrence-count. I.e. with input `3331113331119111`, we output `111` (`333[111]333[111]9[111]`; length 3, occurs thrice), and not `333` (`[333]111[333]1119111`; length 3 as well, but occurs twice)
* If the occurrence-count and length of multiple subsequences are equal, you can output either of them, or all (in any order). I.e. with input `777333777333`, the possible outputs are: `777`; `333`; `[777, 333]`; or `[333, 777]`.
* The subsequence must have boundaries of other digits (or the start/end of the integer). I.e. with input `122222233433` the result is `33` (`1222222[33]4[33]`; length 2, occurs twice) and not `222` (`1[222][222]33433`, length 3, occurs twice with both invalid).
    + This applies to all numbers that are counted towards the occurrence-counter. I.e. with input `811774177781382` the result is `8` (`[8]117741777[8]13[8]2`; length 1, occurs thrice) and not `77` (`811[77]41[77]781382` / `811[77]417[77]81382`; length 2, occurs twice with one invalid) nor `1` (`8[1][1]774[1]7778[1]382`; length 1, occurs four times with two invalid).
* You can assume the input won't contain any digits `0` (it will match `[1-9]+`). (This is to avoid having to deal with test cases like `10002000` that should output `000`, where most languages would output `0` by default.)
* You can assume the input will always contain at least one valid output.
* I/O are both flexible. Can be a list/array/stream of digits/bytes/characters or as string instead of a single integer.

## General rules:

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

## Test cases:

```
Input:  7888885466662716666 / [7,8,8,8,8,8,5,4,6,6,6,6,2,7,1,6,6,6,6]
Output: 6666                / [6,6,6,6]

Input:  3331113331119111 / [3,3,3,1,1,1,3,3,3,1,1,1,9,1,1,1]
Output: 111              / [1,1,1]

Input:            777333777333                   / [7,7,7,3,3,3,7,7,7,3,3,3]
Possible outputs: 777; 333; [777,333]; [333;777] / [7,7,7]; [3,3,3]; [[7,7,7],[3,3,3]]; [[3,3,3],[7,7,7]]

Input:  122222233433 / [1,2,2,2,2,2,2,3,3,4,3,3]
Output: 33           / [3,3]

Input:  811774177781382 / [8,1,1,7,7,4,1,7,7,7,8,1,3,8,2]
Output: 8               / [8]

Input:  555153333551 / [5,5,5,1,5,3,3,3,3,5,5,1]
Output: 1            / [1]

Input:            12321              / [1,2,3,2,1]
Possible outputs: 1; 2; [1,2]; [2,1] / [1]; [2]; [[1],[2]]; [[2],[1]]

Input:  944949949494999494 / [9,4,4,9,4,9,9,4,9,4,9,4,9,9,9,4,9,4]
Output: 4                  / [4]

Input:  8888858888866656665666 / [8,8,8,8,8,5,8,8,8,8,8,6,6,6,5,6,6,6,5,6,6,6]
Output: 88888                  / [8,8,8,8,8]

Input:  1112221112221111               / [1,1,1,2,2,2,1,1,1,2,2,2,1,1,1,1]
Output: 111; 222; [111,222]; [222,111] / [1,1,1]; [2,2,2]; [[1,1,1],[2,2,2]]; [[2,2,2],[1,1,1]]

Input:  911133111339339339339339 / [9,1,1,1,3,3,1,1,1,3,3,9,3,3,9,3,3,9,3,3,9,3,3,9]
Output: 111                      / [1,1,1]

```

# Answer
# Vyxal `o`, 68 bitsv2, 8.5 bytes

```
Ġ:UÞ⊍⁽LO∆M

```

Try it Online!

groups by identical adjacent digits, finds the duplicated elements, then takes the most common of the longest runs.
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
γÐ¢1›ÏD€gZQÏ.M

```

Try it online!

**Explanation**

```
γ                # group consecutive equal elements
 Ð¢              # count the occurrence of each group among the list of groups
   1›Ï           # keep only groups with a count greater than 1
      D€gZQÏ     # keep only those with a length equal to the greatest length
            .M   # get the most common item

```
> 6 votes

# Answer
# Jelly, 12 bytes

```
Œgœ-Q$LÐṀÆṃ'

```

Try it online!

### Previous version – 14 bytes

```
ŒgŒQ¬TịƲLÐṀÆṃ'

```

Try it online!

### How it works?

```
Œgœ-Q$LÐṀÆṃ' – Full program. Receives a list of digits as input.
Œg           – Group equal adjacent values.
  œ-Q$       – Multiset difference with itself deduplicate.
      LÐṀ    – Keep those that are maximal by length.
         Æṃ' – Mode. Returns the most common element(s).
-------------------------------------------------------------------------
ŒgŒQ¬TịƲLÐṀÆṃ' – Full program. Receives a list of digits as input.
Œg             – Group equal adjacent values.
  ŒQ           – Distinct sieve. Replace the first occurrences of each value by 1.
                 and the rest by 0. [1,2,3,2,3,2,5]ŒQ -> [1,1,1,0,0,0,1]
    ¬T         – Negate and find the truthy indices.
      ịƲ       – Then index in the initial list of groups.
               – This discards the groups that only occur once.
        LÐṀ    – Find all those which are maximal by length.
           Æṃ' – And take the mode.

```
> 5 votes

# Answer
# JavaScript (ES6), ~~79~~ ~~73~~ 68 bytes

Takes input as a string. Returns an integer.

```
s=>[...s,r=q=0].map(o=d=>q=s^d?o[!o[q]|r[q.length]?q:r=q]=s=d:q+d)|r

```

Try it online!

### Commented

```
s =>                      // s = input string, also used as the current digit
  [ ...s,                 // split s into a list of digit characters
    r =                   // r is the final result
    q =                   // q is the current digit sequence
    0                     // append a final dummy entry to force the processing of the last
  ]                       // sequence
  .map(o =                // o is an object used to keep track of encountered sequences
       d =>               // for each digit d in the array defined above:
    q =                   //   update q:
      s ^ d ?             //     if d is not equal to the current digit:
        o[                //       this statement will ultimately update o[q]
          !o[q] |         //         if q has not been previously seen
          r[q.length] ?   //         or the best result is longer than q:
            q             //           leave r unchanged
          :               //         else:
            r = q         //           set r to q
        ] = s = d         //       reset q to d, set the current digit to d
                          //       and mark q as encountered by setting o[q]
      :                   //     else:
        q + d             //       append d to q
  ) | r                   // end of map(); return r, coerced to an integer

```
> 5 votes

# Answer
# Retina, 56 bytes

```
L`(.)\1*
O`
L$m`^(.+)(¶\1)+$
$#2;$1
N`
.+;

N$`
$.&
-1G`

```

Try it online! Link includes test cases. Explanation:

```
L`(.)\1*

```

List all the maximally repeated digit subsequences.

```
O`

```

Sort the list into order.

```
L$m`^(.+)(¶\1)+$
$#2;$1

```

List all the multiple subsequences with their "count".

```
N`

```

Sort in ascending order of count.

```
.+;

```

Delete the counts.

```
N$`
$.&

```

Sort in ascending order of length. (Where lengths are equal, the previous order due to count is preserved.)

```
-1G`

```

Keep the last i.e. longest value.
> 4 votes

# Answer
# Perl 6, ~~58~~ 56 bytes

```
*.comb(/(.)$0*/).Bag.max({.value>1,+.key.comb,.{*}}).key

```

Try it online!
> 4 votes

# Answer
# , 102 bytes

```
function(i)rep(names(sort(-(x=(x=table(rle(i)))[rowSums(x>1)>0,,drop=F])[m<-max(rownames(x)),])[1]),m)

```

Try it online!

Since there wasn't an R answer yet, I decided to give it a try, and well... it wasn't easy. I don't really know whether it is a good approach, but here it goes.

Inputs and outputs vectors of characters.
> 4 votes

# Answer
# Python 2, ~~123~~ 120 bytes

```
import re
def f(s):r=re.findall(r'(\d)(\1*)',s);c=r.count;print max((len(a+b)*(c((a,b))>1),c((a,b)),a+b)for a,b in r)[2]

```

Try it online!
> 3 votes

# Answer
# Powershell, 101 byte

```
($args|sls '(.)\1*'-a|%{$_.Matches}|group|?{$_.Count-1}|sort @{e={$_.Name.Length,$_.Count}})[-1].Name

```

Explanied test script:

```
$f = {

(
    $args|          # for each argument (stings)
    sls '(.)\1*'-a| # searches all
    %{$_.Matches}|  # regex matches
    group|          # group it (Note: Count of each group > 0 by design)
    ?{$_.Count-1}|  # passthru groups with Count not equal 1
    sort @{         # sort all groups by 2 values
        e={$_.Name.Length,$_.Count}
    }
)[-1].Name          # returns name of last group (group with max values)

}

@(
    ,('7888885466662716666', '6666')
    ,('3331113331119111', '111')
    ,('777333777333', '777','333')
    ,('122222233433', '33')
    ,('811774177781382', '8')
    ,('555153333551','1')
    ,('12321', '1','2')
    ,('944949949494999494','4')
    ,('8888858888866656665666','88888')
    ,('1112221112221111','111','222')
) | % {
    $s,$e = $_
    $r = &$f $s
    "$($r-in$e): $r"
}

```

Output:

```
True: 6666
True: 111
True: 777
True: 33
True: 8
True: 1
True: 1
True: 4
True: 88888
True: 111

```
> 3 votes

# Answer
# Python 2, ~~114~~ 113 bytes

-1 byte thanks to TFeld.

```
p='';r=[];C=r.count
for c in input():r+=['']*(c!=p);r[-1]+=c;p=c
print max((len(w),C(w),w)for w in r if~-C(w))[2]

```

Try it online!
> 3 votes

# Answer
## Haskell, 72 bytes

```
import Data.Lists
g!x|y<-countElem x g=(y>1,1<$x,y)
(argmax=<<(!)).group

```

How it works

```
(argmax=<<(!)).group       -- expands to: f i = argmax (group i !) (group i)
    group                  -- split the input list into subsequences of equal digits
                           -- e.g. "1112211" -> ["111","22","11"]

                           -- find the element of this list where the function !
                           -- returns the maximum value. First parameter to !
                           -- is the grouped input list, second parameter the
                           -- the element to look at

g!x|
    y<-countElem x g       -- let y be the number of occurrences of x in g
  = (  ,   ,  )            -- return a triple of
     y>1                   -- a boolean y>1  (remember: True > False)
        1<$x               -- length of x (to be exact: all elements in x
                           -- replaced by 1. This sorts the same way as the
                           -- length of x)
             y             -- y
                           -- a triples sorts lexicographical

```
> 3 votes

# Answer
# , 85 bytes

```
function(x,R=rle(x),a=ave(R$v,R,FUN=length))rep(R$v[o<-order(a<2,-R$l,-a)[1]],R$l[o])

```

Try it online!

* **Input :** a vector of separated integer digits e.g. `c(1,8,8...)`
* **Output :** a vector of separated integer digits

Unrolled code with explanation :

```
function(x){                # x is a vector of digits : e.g. c(1,1,8,8,1,1)

R = rle(x)                  # Get the sequences of consecutive repeating digits
                            # doing run length encoding on x, i.e. : R is a list
                            # with the digits (R$values) and the number of their
                            # consecutive occurrencies (R$lengths)
                            # N.B. you can use R$v for R$values and R$l for R$lenghts

a=ave(R$v,R,FUN=length)     # Group R$v by R$l AND R$v, count the occurrencies
                            # for each group and "unroll" the value of each
                            # group to the original R$v length.
                            # Here basically we count the occurrencies of the same
                            # sequence.

o<-order(a<2,-R$l,-a)[1]    # Get the indexes used to order by a < 2 then by -R$l and
                            # finally by -a; store the first index in "o".
                            # Here basically we use order to select the first sequence
                            # repeated at least twice, in case of ties the sequence
                            # with the greatest length and in case of ties the most
                            # repeated sequence.

rep(R$v[o],R$v[o])          # Using the index "o", we reconstruct the sequence repeating
                            # R$l[o] times R$v[o]
}

```

---

Alternative version accepting vector of integer or character digits :

# , 88 bytes

```
function(x,R=rle(x),a=ave(R$v,R,FUN=length))rep(R$v[o<-tail(order(a>1,R$l,a),1)],R$l[o])

```

Try it online!

* **Input :** a vector of separated characters or digits e.g. `c("1","8","8"...)` or `c(1,8,8...)`
* **Output :** a vector of separated characters if the input was a vector of characters, a vector of digits if the input was a vector of digits
> 3 votes

# Answer
# Wolfram Language (Mathematica), 67 bytes

```
#&@@@MaximalBy[Select[Tally@Split@#,Last@#>1&],{Length@#,#2}&@@#&]&

```

Pure function. Takes a list of digits as input and returns a list of subsequences (in no particular order) as output. Not sure if the "must appear at least twice" clause can be handled more cleanly. Try it online!
> 2 votes

# Answer
# Ruby, ~~68~~ 67 bytes

```
->a{(b=a.chunk &:+@).max_by{|x|[(c=b.count x)<2?0:x[1].size,c]}[1]}

```

Try it online!

Inputs and outputs arrays of chars.

The approach is pretty straightforward: we identify the runs of consecutive digits (`chunk` using unary `+` as identity function) and take the maximum - first by the size of the run (reset to zero if its occurrence count is \< 2), then by the count itself.
> 2 votes

# Answer
# Red, 256 250 bytes

```
func[s][p: func[b][sort parse b[collect[any keep[copy a skip thru any a]]]]first
last sort/compare collect[foreach d p p s[if 1 < k: length? to-block d[keep/only
reduce[form unique d k]]]]func[x y][(reduce[length? x/1 x/2])< reduce[length? y/1 y/2]]]

```

Try it online!

Really, realy long solution this time... (sigh)

Takes the input as a string.

## Explanation:

```
f: func [ s ] [
    p: func [ b ] [                        ; groups and sorts the adjacent repeating items
        sort parse b [
            collect [
                any keep[
                    copy a skip thru any a ; gather any item, optionally followed by itself
                ]
            ]
        ]
    ]
    t: copy []
    foreach d p p s [                     ; p p s transforms the input string into a block of sorted blocks of repeating digits
        if 1 < k: length? to-block d [    ; filters only the blocks that occur more than once
            insert/only t reduce [ form unique d k ] ; stores the digits and the number of occurences
                                          ; "8888858888866656665666" -> [["5" 3] ["666" 3] ["88888" 2]]
        ]
    ]
    first last sort/compare t func [ x y ] ; takes the first element (the digits) of the last block of the sorted block of items
        [ (reduce [ length? x/1 x/2 ]) < reduce [ length? y/1 y/2 ] ] ; direct comparison of the blocks
]

```
> 2 votes

# Answer
# Java (JDK 10), 213 bytes

```
s->{int l=99,X[][]=new int[10][l],d,D=0,m=0,M=0;for(var x:s.split("(?<=(.))(?!\\1)"))X[x.charAt(0)-48][x.length()]++;for(;M<1&&l-->1;)for(d=0;d++<9;)if((m=X[d][l])>1&m>M){M=m;D=d;}for(;l-->0;)System.out.print(D);}

```

Try it online!

## Explanation (outdated)

```
s->{                                    // Lambda for Consumer<String>
 int l=99,                              //  Length of token, max is 99.
     X[][]=new int[10][l],              //  Array containing the occurrences per token
     d,                                 //  digit value
     D=0,                               //  digit holder for best sequence candidate
     m=0,                               //  holder of the current candidate
     M=0;                               //  best candidate for the current length of token.
 for(var x:s.split("(?<=(.))(?!\\1)"))  //  Tokenize the string into digit-repeating sequences
  X[x.charAt(0)-48][x.length()]++;      //   Add one occurrence for the token
 for(;M<1&&l-->1;)                      //  While no value has been found and for each length, descending. Do not decrease length if a value has been found.
  for(d=0;d++<9;)                       //   for each digit
   if((m=X[d][l])>1&m>M){               //    if the current occurrence count is at least 2 and that count is the current greatest for the length
    M=m;D=d;                            //     mark it as the current best
   }                                    //
 for(;l-->0;)System.out.print(D);       //  Output the best-fitting subsequence.
}                                       //

```

## Credits
> 2 votes

# Answer
## PCRE, 152 bytes

```
(\d)(?<!(?=\1)..)(?=(\1*)(?!\1).*(?!\1).\1\2(?!\1))(?!(?:(?=\2((\3?+)(\d)(\5*)))){1,592}?(?=\2\3.*(?!\5).\5\6(?!\5))(?:\1(?=\1*\4\5(\7?+\5)))*+(?!\1))\2

```

See it in action on: https://regex101.com/r/0U0dEp/1 (just look at the first match in each test case)

This is just for fun, since regex isn't a real programming language in and of itself, and the solution is limited :P

Because a zero-width group such as `(?:)+` only matches once and doesn't repeat indefinitely, and because PCRE internally makes copies of groups quantified with limits, I've had to use a magic number in there ("{1,592}"), which means we can only look up to 592 contiguous sets of digits ahead to find a competing set that could be longer than the one currently under inspection. More info on this concept here.
> 2 votes

# Answer
# Perl 5, 88 bytes

```
my($m,%s);++$i%2*$s{$_}++&&($n=$s{$_}/9+length)>$m&&($a=$_,$m=$n)for pop=~/((.)\2*)/g;$a

```

Try it online!

Slightly ungolfed, with tests:

```
sub f {
  my($m,%s);
  my($i,$n,$a);           #not needed in golfed version
  ++$i % 2  *  $s{$_}++
  && ($n=$s{$_}/9+length) > $m
  && ($a=$_, $m=$n)
    for pop=~/((.)\2*)/g; #i.e. 7888885466662716666 => 7 88888 5 4 6666 2 7 1 6666
  $a
}
for(map[/\d+/g],split/\n/,join"",<DATA>){ #tests
  my($i,@e)=@$_;
  printf "%-6s   input %-24s   expected %-10s   got %s\n",
    (grep f($i) eq $_, @e) ? "Ok" : "Not ok", $i, join('|',@e), f($i);
}
__DATA__
Input:  7888885466662716666     Output: 6666
Input:  3331113331119111        Output: 111
Input:  777333777333            Output: 777|333
Input:  122222233433            Output: 33
Input:  811774177781382         Output: 8
Input:  555153333551            Output: 1
Input:  12321                   Output: 1|2
Input:  944949949494999494      Output: 4
Input:  8888858888866656665666  Output: 88888
Input:  1112221112221111        Output: 111|222

```
> 1 votes

# Answer
# Japt `-h`, 12 bytes

Input & output are strings.

```
ò¦ ñÊf@ÓZè¶X

```

Try it
> 1 votes

---
Tags: code-golf, number, integer, counting, subsequence
---


title: PHP+C polyglot solution to mixed types

text:
# Question
Title: PHP+C polyglot solution to mixed types
Some built-in functions in PHP return mixed types, like `file_get_contents` that returns both `string` or `false`. Union structs in C can be used to simulate this, but is there a way to make it polyglot, that is, can be run in both PHP *and* C without (major) modification? Macros is often one way.

```
$result === false

```

can be replaced with

```
CHECK_RESULT($result, false)

```

where

```
#define CHECK_RESULT(res, b) res.success == b

```

and in PHP

```
function CHECK_RESULT($res, $b) { return $res === $b; }

```

Maybe C11 generics can help in a macro too? To switch on second argument.

Thankful for any suggestions regarding this. :)

# Answer
> 1 votes
This behaves the same in C and PHP (assuming there's a file named moo.txt with content "hej" in it).

```
//<?php echo "\x08\x08"; ob_start(); ?>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

enum type
{
    STRING = 0,
    BOOL   = 1
};

struct Result
{
    enum type t;
    union {
        char* str;
        bool  b;
    };
};

struct Result file_get_contents(char* filename)
{
    //struct Result r = {.t = BOOL, .b = false};
    char* s = malloc(4);
    strcpy(s, "hej\n");
    struct Result r = {.t = STRING, .str = s};
    return r;
}

bool compare_string(struct Result r, char* val)
{
    printf("compare_string\n");
    return false;
}

#define DO_OP(a, op) a op a
#define COMPARE_MIXED(res, val, op) _Generic(val, int: (res.t == BOOL && res.b op val),\
    char*: (res.t == STRING && strcmp(res.str, val) == 0)\
    )

#define OP_EQUALS ==
#define OP_PLUS +

#if __PHP__//<?php
define("OP_EQUALS", "==");
define("OP_PLUS", "+");
function COMPARE_MIXED($res, $val, $op)
{
    switch ($op) {
        case OP_EQUALS:
            return $res == $val;
            break;
        default:
            assert(false, 'Unkown operation');
    }
}
#endif
//<?php
/**
 * Compile with
 *   cat mixed.c | sed -e "s/#__C__//g" | gcc -g -I. -Wno-incompatible-pointer-types -xc - -lgc
 */
#define function int
function main()
#undef function
{
    #__C__ struct Result
    $r = file_get_contents("moo.txt");
    if (COMPARE_MIXED($r, false, OP_EQUALS)) {
        printf("Is false\n");
    } else if (COMPARE_MIXED($r, "hej\n", OP_EQUALS)) {
        printf("Is hej\n");
    }
    return 0;
}
//?>
//<?php ob_end_clean(); main();

```

---
Tags: tips, polyglot, c, php
---


title: Funny Numbers :D

text:
# Question
Title: Funny Numbers :D
The task is to calculate the average "funniness" of a given number given the following scoring system:

* 1 point for each "420" in it
* 2 points for each "69" in it
* 3 points if its a palindrome (doesn't count if it's just a single digit)
* 4 points if it has (not for each) "800813"
* 5 points for ending in "420"
* 6 points for ending in "69"

Then, divide that total score by the number of digits in the number (round to the nearest tenth)

Test Cases:

* **96942024969: 1.3** (14p/11 digits, 1p for one "420", 4p for two "69"s, 3p since its an palindome, 6p for ending in "69")
* **800813800813: 0.3** (4p/12 digits for having "800813")
* **0: 0** (0p/1 digit)
* **420: 2** (6p/3 digits, 1p for one "420", 5p for ending in "420")
* **2435083240587: 0** (0p/13 digits)

Answers are ranked by lowest program size.

# Answer
# 05AB1E, 35 bytes

```
Ž¥ú2ä©¢IÂQIg≠*I•CΘ=•åI®Å¿)˜ā*OIg/1.ò

```

Try it online or verify all test cases.

**Explanation:**

```
Ž¥ú2ä©¢    # Verify the first two rules:
Ž¥ú        #  Push compressed integer 42069
   2ä      #  Split it into two parts: [420,69]
     ©     #  Store it in variable `®` (without popping)
      ¢    #  Count how many times each occur in the (implicit) input-string
IÂQIg≠*    # Verify the third rule:
I          #  Push the input again
 Â         #  Bifurcate it; short for Duplicate & Reverse copy
  Q        #  Pop both and check if they're the same (aka it's a palindrome)
   Ig      #  Push the input-length
     ≠     #  Check that it's NOT 1 (0 if 1; 1 if >=2)
      *    #  Multiply them together
I•CΘ=•å    # Verify the fourth rule:
I          #  Push the input again
 •CΘ=•     #  Push compressed integer 800813
      å    #  Check if the input contains this number as substring
I®Å¿       # Verify the fifth and sixth rules:
I          #  Push the input yet again
 ®         #  Push pair [420,69] from variable `®`
  Å¿       #  Check whether the input ends with either of these two
)          # Wrap all items on the stack into a list
 ˜         # Flatten the list of pairs and loose values to a single list
  ƶ        # Multiply each value in the list by its 1-based index
   O       # Then sum the list together
    Ig/    # Divide it by the input-length
       1.ò # Round it to 1 decimal after the period
           # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž¥ú` is `42069` and `•CΘ=•` is `800813`.
> 5 votes

# Answer
# Raku, 89 bytes

```
{round (m:g/420/+2*m:g/69/+3*($_>9&&$_
eq.flip)+4*?/800813/+5*?/420$/+6*?/69$/)/.comb,.1}

```

Try it online!

Regex-driven, conveniently.
> 4 votes

# Answer
# Excel, 188 bytes

```
=LET(
    a,800813,
    b,{69,420},
    c,A1,
    d,LEN(c),
    ROUND(
        SUM(
            MMULT(d-LEN(SUBSTITUTE(c,b,"")),1/{1;3}),
            3*(d>1)*(c=0+CONCAT(MID(c,d-SEQUENCE(d)+1,1))),
            4*(FIND(a,c&a)<d),
            (0+RIGHT(c,{2,3})=b)*{6,5}
        )/d,
        1
    )
)

```

Input in cell `A1`.
> 4 votes

# Answer
# Python, ~~136~~ 131 bytes

*-5 from @Jonathan Allan*

```
lambda s:"%0.1f"%(((c:=s.count)(m:="420")+2*c("69")+3*(s[:1]<s*c(s[::-1]))+4*("800813"in s)+5*(e:=s.endswith)(m)+6*e("69"))/len(s))

```

Attempt This Online!

A crappy solution, but a solution nonetheless.
> 3 votes

# Answer
# Vyxal, 302 bitsv2, 37.75 bytes

```
⁺md69"₌vøEvO?₍λḂ⁼n₀>*;‡800813c$WfÞż∑$L/1∆W

```

Try it Online!

Many more bytes added to handle single digits not being a palindrome.
> 3 votes

# Answer
# JavaScript (ES11), 136 bytes

```
s=>~~([/420/g,/69/g,,800813,/420$/,/69$/].reduce((t,r,i)=>t-~i/3*~~s.match(r)?.length,s>9&[...s].reverse().join``==s)*30/s.length+.5)/10

```

Attempt This Online!
> 2 votes

# Answer
# APL(Dyalog Unicode), 65 bytes SBCS

```
1⍕≢÷⍨1⊥4⍸⍤⌽(1<≢×⊢≡⌽),(1∊'800813'⍷,),(,⍤⍉⍤↑'024' '96'(⊃,+/)⍤⍷¨⊂⍤⌽)

```

Try it on APLgolf!
> 2 votes

# Answer
# Charcoal, ~~57~~ ~~56~~ 55 bytes

```
﹪%.1f∕⁺⁺ΣＥ⪪42069³⁺×⁺⁵κ¬⊟⪪θι×⊕κ№θι∧∧⊖Ｌθ⁼θ⮌θ³∧№θ800813⁴Ｌθ

```

Try it online! Link is to verbose version of code. Explanation:

```
         Ｅ⪪42069³                                         Map over `420`,`69`
                  ×⁺⁵κ¬⊟⪪θι                               5 or 6 if ends with
                 ⁺                                        Plus
                           ×⊕κ№θι                         1 or 2 times count
                                 ∧∧⊖Ｌθ⁼θ⮌θ³               3 if palindrome
                                           ∧№θ800813⁴     4 if `800813`
      ⁺⁺Σ                                                 Take the sum
                                                    Ｌθ     Divide by length
﹪%.1f                                                       Round to `0.1`
                                                            Implicitly print

```

Previous ~~57~~ 56 byte solution:

```
﹪%.1f∕ΣＥ⟦№θ420№θ69∧⊖Ｌθ⁼θ⮌θ‹⁰№θ800813¬⊟⪪θ420¬⊟⪪θ69⟧×ι⊕κＬθ

```

Try it online! Link is to verbose version of code. Explanation:

```
         №θ420                                              Count of `420`s
              №θ69                                          Count of `69`s
                  ∧⊖Ｌθ⁼θ⮌θ                                  Is a palindrome
                          ‹⁰№θ800813                        Includes `800813`
                                    ¬⊟⪪θ420                 Ends with `420`
                                           ¬⊟⪪θ69           Ends with `69`
       Ｅ⟦                                        ⟧          Map over values
                                                  ×ι⊕κ      Multiply by index
      Σ                                                     Take the sum
     ∕                                                Ｌθ    Divide by length
﹪%.1f                                                       Round to `0.1`
                                                            Implicitly print

```
> 2 votes

# Answer
# Retina 0.8.2, ~~205~~ ~~201~~ 197 bytes

```
(?=(.*?420)*)(?=(.*?69)*)(?=((.)+.?(?<-4>\4)+$(?(4)^))?)(?=(.*800813)?).+(?<=(420)?)(?<=(69)?)
$#1$*1$#2$*2$#3$*3$#5$*4$#6$*5$#7$*6/$.&$*
\d
$*
\G1
10$*
/(.+)\1
$1$&
r`.*(\3)*(\3{10})*/(1+)
$#2.$#1

```

Try it online! Link includes test cases. Explanation:

```
(?=(.*?420)*)(?=(.*?69)*)(?=((.)+.?(?<-4>\4)+$(?(4)^))?)(?=(.*800813)?).+(?<=(420)?)(?<=(69)?)
$#1$*1$#2$*2$#3$*3$#5$*4$#6$*5$#7$*6/$.&$*

```

Work out how many times `420` and `69` appear, plus also record whether the input is a nontrivial palindrome, whether it contains 800813, and whether it ends with `420` or `69`, plus take its length in unary.

```
\d
$*

```

Convert the scores to unary individually; the length is unaffected, since it is already in unary.

```
\G1
10$*
/(.+)\1
$1$&
r`.*(\3)*(\3{10})*/(1+)
$#2.$#1

```

Divide the total score by the length, rounding to the nearest `0.1`, and converting to decimal.
> 1 votes

# Answer
# JavaScript (Node.js), 123 bytes

```
n=>([s=.5,/420/g,/69/g,n>9&&[...n].reverse().join``,800813,/420$/,/69$/].map((x,i)=>n.replace(x,y=>s+=i*10/n.length))|s)/10

```

Try it online!
> 1 votes

# Answer
# Scala, 289 bytes

Port of @97.100.97.109's Python answer in Scala.

Thanks to @Joseph's help to correct the scala code.

---

Golfed version. Try it online!

```
s=>BigDecimal((s.sliding(3).count(_=="420")+2*s.sliding(2).count(_=="69")+3*(if(s==s.reverse&s.length>1)1 else 0)+(if(s.contains("800813")) 4 else 0)+5*(if(s.endsWith("420"))1 else 0)+6*(if(s.endsWith("69"))1 else 0)).toDouble/s.length).setScale(1,BigDecimal.RoundingMode.HALF_UP).toDouble

```

Ungolfed version. Try it online!

```
object Main extends App {

  def calculateScore(s: String): Double = {
    val count420 = s.sliding(3).count(_ == "420")
    val count69 = s.sliding(2).count(_ == "69")
    val palindromeBonus = if (s == s.reverse && s.length > 1) 1 else 0
    val count800813 = if(s.contains("800813")) 4 else 0  // Adjusted to just check if "800813" exists in the string
    val end420Bonus = if (s.endsWith("420")) 1 else 0
    val end69Bonus = if (s.endsWith("69")) 1 else 0

    val totalScore = count420 + 2 * count69 + 3 * palindromeBonus + count800813 + 5 * end420Bonus + 6 * end69Bonus

    BigDecimal(totalScore.toDouble / s.length).setScale(1, BigDecimal.RoundingMode.HALF_UP).toDouble
  }

  override def main(args: Array[String]): Unit = {
    val inputs = List("96942024969", "800813800813", "0", "420", "2435083240587")
    for (i <- inputs) {
      println(s"$i : ${calculateScore(i)}")
    }
  }
}

```
> 1 votes

# Answer
# Ruby, ~~114~~ 112 bytes

```
->n{b=0;[/420/,/69/,n[1]?n.reverse: ?a,/(800813.*)+/,/420$/,/69$/].sum{|x|n.scan(x).size*b+=1.0/n.size}.round 1}

```

Try it online!
> 1 votes

---
Tags: code-golf, string, math, number
---


# Question
Title: I (rev)?(pal)? the source code, you (rev)?(pal)? the input!
Just because the reverse and palindrome were not too challenging individually :)

Write a program (full program or function) that satisfies the following: given a string input,

* the program *as-is* outputs the input string unchanged.
* the program *reversed* outputs the input string reversed.
* the program *palindromized* outputs the input string palindromized.
* the program *reversed and then palindromized* outputs the input string reversed and then palindromized.

In this challenge, *palindromize* is defined as "concatenate the reverse on the right" (`lambda s: s + s[::-1]` in Python).

For example, if your code is `abc`, when given `"xyz"` as input,

* `abc` should output `"xyz"`.
* `cba` should output `"zyx"`.
* `abccba` should output `"xyzzyx"`.
* `cbaabc` should output `"zyxxyz"`.

You may assume that the input string is nonempty and entirely consists of printable ASCII (32-126, no newlines).

Standard rules apply. The shortest code in bytes wins.

# Answer
> 16 votes
# 05AB1E, 3 bytes

```
?R\

```

**Explanation:**

```
?      # Output the (implicit) input-string (without trailing newline)
 R     # Reverse the (implicit) input-string
  \    # Discard it from the stack
       # (don't output anything implicitly, since we already had an explicit print)

```

```
\      # No-op to discard the top of the stack
 R     # Reverse the (implicit) input-string
  ?    # Pop and output this reversed input
       # (don't output anything implicitly, since we already had an explicit print)

```

```
?R\    # Same as the first program above, outputting the input as is
   \R? # Same as the second program above, outputting the input reversed

```

```
\R?    # Outputs the input reversed
   ?R\ # Outputs the input as is

```

# Answer
> 13 votes
# Charcoal, 3 bytes

```
θ⮌ω

```

Try it online! Reversed:

```
ω⮌θ

```

Try it online! Palindromised:

```
θ⮌ωω⮌θ

```

Try it online! Palindomised Reversed:

```
ω⮌θθ⮌ω

```

Try it online! Explanation:

```
θ

```

Print the input.

```
⮌ω

```

Print the reverse of the empty string.

Reversed explanation:

```
ω

```

Print the empty string.

```
⮌θ

```

Print the reverse of the input.

Palindromised and reversed palindromised follow trivially.

# Answer
> 13 votes
# JavaScript, 70 bytes

```

(x=>x.at?x:y=>y+z(y))//)y+)y(z>=y:``nioj.)(esrever.]x...[?ta.x>=x=z(

```

Try it online!

# Answer
> 10 votes
# Python, 51 bytes

*-2 bytes, thanks to tsh*
*-2 bytes, thanks to Jakque*

```
s=input()#)]1-::[s=dne(tnirp
print(end=s)#)(tupni=s

```

Attempt This Online!

---

# Python, 55 bytes

```
def f(s):#
 print(end=s)#)]1-::[s=dne(tnirp
#:)s(f fed

```

*function accepting string as argument*

Attempt This Online!

# Answer
> 7 votes
# Vyxal, 3 bytes

```
₴Ḃ_

```

Try!

!yrT

Try!!yrT

!yrTTry!

> +1 very hard

You uh sure about that?

## Explained

```
₴Ḃ_
₴    # Print without newline
# The rest has no impact

```

```
_Ḃ₴
 Ḃ₴  # Print the reverse of the input

```

```
₴Ḃ__Ḃ₴
₴       # Print the normal input
    Ḃ₴  # Print the reverse

```

```
_Ḃ₴₴Ḃ_
 Ḃ₴     # Print reversed input
   ₴    # And then normal input

```

Created with the help of Luminespire.

# Answer
> 6 votes
# , ~~92~~ ~~88~~ 86 bytes

*Edit: -2 bytes thanks to Jakque's comment*

```
x=utf8ToInt(scan(,''))#)))x(ver(8ftUoTtni(tac
cat(intToUtf8(x))#))'',(nacs(tnIoT8ftu=x

```

Attempt This Online!

Full program that reads input from and outputs to the R console.

Note that the program(s) should be saved to a file & run in R using `source("myprog.r")`: copy-pasting into a REPL environment will result in incorrect parsing of the input (the program will try to read it's own lines!).
The header/footer in the "Attempt This Online" link mimic this behaviour, instead of the default of running code in a REPL setting.

---

# , ~~118~~ 115 bytes

```
if(!exists('f'))f=\(x)c();body(f)[T<-T+1]=parse(t='x')#)')x(ver'=t(esrap=]1+T-<T[)f(ydob;)(c)x(\=f))'f'(stsixe!(fi

```

Attempt This Online!

Code that defines a function, `f`, that accepts an input of a vector of characters and returns it unchanged.
Reversed code defines `f` to return its input reversed, palindromized code defines `f` to return it palindromized, and reverse-palindromized code defines `f` to return it reverse-palindromized.
It's not completely straightforward to amend an already-complete R function definition, but it can be achieved (as here) by assigning directly into the function `body` if the function already `exists`.

# Answer
> 4 votes
# Bash, 17 bytes

```

rev $1 # 1$ tac

```

Try it online!

# Answer
> 4 votes
# C# Interactive Compiler, ~~80~~ 77 bytes

Based on *@bsoelch*'s Python answer.
-3 bytes implicitly thanks to the suggested golf of *@Jakque* on the ported Python answer.

```
var s=ReadLine();//;))(yarrAoT.)(esreveR.s(etirW
Write(s);//;)(eniLdaeR=s rav

```

Try it online.

```
var s=ReadLine();//;)s(etirW
Write(s.Reverse().ToArray());//;)(eniLdaeR=s rav

```

.enilno ti yrT

```
var s=ReadLine();//;))(yarrAoT.)(esreveR.s(etirW
Write(s);//;)(eniLdaeR=s ravvar s=ReadLine();//;)s(etirW
Write(s.Reverse().ToArray());//;)(eniLdaeR=s rav

```

Try it online..enilno ti yrT

```
var s=ReadLine();//;)s(etirW
Write(s.Reverse().ToArray());//;)(eniLdaeR=s ravvar s=ReadLine();//;))(yarrAoT.)(esreveR.s(etirW
Write(s);//;)(eniLdaeR=s rav

```

.enilno ti yrTTry it online.

**Explanation:**

`//` is a single-line comment and everything after it are no-ops. So if we'll ignore those comments, all four of the REPL-programs will:

1. Start with `var s=ReadLine();`: Read the input as string into variable `s`
2. 1. `Write(s);`: Write string `s` to the output-buffer
    2. `Write(s.Reverse().ToArray());`: Reverse string `s` to a reversed character-iteratator (`Enumerable.ReverseIterator<char>`); then convert it to a character-array (`char[]`); then write all characters in this character-array separately to the output-buffer
    3. `Write(s);Write(s.Reverse().ToArray());`: 1 and 2 combined
    4. `Write(s.Reverse().ToArray());Write(s);`: 2 and 1 combined
3. After which the output-buffer is output implicitly as single string without trailing newline

# Answer
> 3 votes
# Pip, 11 10 bytes

```

.:a  aR.

```

This answer exploits the fact that `.a` does nothing significant, whereas `a.b` is concatenation.

Attempt This Online!

```
[\n].:a  aR.[\n]
[\n]        [\n]  # Newlines for Palindormize/Reverse Palindromize
    .:a           # -, Push input (`:` lowers precedence for Reverse Palindromize)
                  # Comment ("  "), ignore the following characters
         aR.      #

```

Reversed:

```
[\n].Ra  a:.[\n]
    .Ra           # -, Push input reversed
         a:.      # Comment

```

Palindromized:

```
[\n].:a  aR.[\n][\n].Ra  a:.[\n]
    .:a                           # -, Push input
                    .Ra           # Concatenate with input reversed
         aR.             a:.      # Comment

```

Reverse Palindromized

```
[\n\.Ra  a:.[\n][\n].:a  aR.[\n]
    .Ra                           # -, Push input reversed
                    .:a           # Concatenate with input, ":" groups it as .(Ra).a rather than .R(a.a)
         a:.             aR.      # Comment

```

# Answer
> 1 votes
# PHP -F, 31 bytes

```
echo$argn;#;)ngra$(verrts ohce

```

Try it online!

```

echo strrev($argn);#;ngra$ohce

```

Reversed version

```
echo$argn;#;)ngra$(verrts ohce

echo strrev($argn);#;ngra$ohce
```

Palindromed version

```

echo strrev($argn);#;ngra$ohce
echo$argn;#;)ngra$(verrts ohce

```

Reversed and Palindromed version

Actually, my answer to the palindrome question will work here too, because it uses 2 separate `echo` for the palindrome parts ;) Notice the new line at the end which is necessary because of the comment trick. Actually saved one byte here using `#` as comment

---
Tags: code-golf, string, source-layout
---


# Question
Title: I reverse the source code, you reverse the source code!
Write a program that outputs its source code in reverse when run, and outputs its source forwards when I reverse the source. If your program is "abcd", when run with no arguments it should output "dcba", and when I run the program "dcba" it should output "abcd."

This is a challenge, so both your forwards and reverse program must follow the rules of proper quines. Your source code may not be a palindrome.

This is a challenge, so the shortest code by byte count wins.

# Answer
> 2 votes
# \>\<\> (fish), 15 bytes

```
"0:g}!|o|!}g:0'

```

Reversed:

```
'0:g}!|o|!}g:0"

```

Try it

ti yrT

---
Tags: code-golf, quine, source-transformation
---


title: The Area of Rectangles

text:
# Question
Title: The Area of Rectangles
Getting the area covered by a rectangle is really easy; just multiply its height by its width. However in this challenge we will be getting the area covered by multiple rectangles. This is equally easy ... so long as the rectangles don't overlap.

If the rectangles don't overlap the total area covered is the sum of the areas of each individual rectangle. However if they do overlap this method will double count the area they intersect.

For example, in the following picture we have 2 rectangles: A rectangle with opposite corners at \\$(3,7)\\$ and \\$(9,3)\\$ and a rectangle with opposite corners at \\$(8,10)\\$ and \\$(14,4)\\$. On their own they cover \\$24\\$ and \\$36\\$ square units respectively. However they have an overlap area of 3 units so the total area covered by the both of them is \\$24 + 36 - 3 = 57\\$

# Task

Your task is to take a list of positive integer rectangles as input and output the total area covered by those rectangles.

You may take a rectangle as a pair of pairs representing opposite corners, or as a flattened 4-tuple. You may assume a particular pair of corners in a certain order will be given if you please.

This is so answers will be scored in bytes with fewer bytes being the goal.

## Test cases

```
[((3,7),(9,3))] -> 24
[((8,10),(14,4))] -> 36
[((3,7),(9,3)),((8,10),(14,4))] -> 57
[((8,10),(14,4)),((3,7),(9,3)),((5,8),(10,3))] -> 61
[((1,1),(8,8)),((2,3),(3,5))] -> 49

```

# Answer
# Ruby, ~~60~~ 59 bytes

```
->r,*w{r.map{|a,b,c,d|w|=[*a...c].product [*d...b]};w.size}

```

Try it online!

**Input**: array of array of coordinates: \[left, top, right, bottom\]

Convert every rectangle to a set of cells, and calculate the size of the union of the sets.
> 6 votes

# Answer
# Python 3, ~~76~~ ~~74~~ 73 bytes

```
lambda l:len({(x,y)for*a,b,c in l for x in range(*a)for y in range(b,c)})

```

Try it online!

*Saved 2 bytes thanks to att!!!*
*Saved a byte thanks to Jitse!!!*

Inputs a list of rectangles as flattened 4-tuples - `(left, right, bottom, top)`.
Returns the area.
> 5 votes

# Answer
# Jelly, 10 bytes

```
r/Ḋ€p/)ẎQL

```

A monadic Link that accepts a list of rectangles each composed of a list of opposing corner coordinates as specified.

**Try it online!**

### How?

Constructs the coordinates of a corner of each unit square of each rectangle, and counts the unique values found in the resulting collection.

```
r/Ḋ€p/)ẎQL - Link: integer rectagle corner coordinates, R
      )    - for each rectangle, r in R:
 /         -   reduce by:
r          -     inclusive range
  Ḋ€       -   dequeue each (we exclude one edge, consistently, from each dimension, as we
                             want "fences", rather than "fence-posts")
     /     -   reduce by:
    p      -     Cartesian product -> all the coordinates we want for the rectangle
       Ẏ   - tighten -> all coordinates used by all rectangles
        Q  - deduplicate
         L - length

```
> 5 votes

# Answer
# JavaScript (ES6), 96 bytes

A very basic solution that tests whether each cell in the grid belongs to at least one rectangle.

Expects a list of flattened 4-tuples.

```
a=>eval(`for(t=0,x=q=Math.max(${a});x--;)for(y=q;y--;)t+=a.some(([a,b,c,d])=>x<a^x<c&&y<b^y<d)`)

```

Try it online!

### How?

When coerced to a string, an array is always turned into a flattened list of values separated with commas. For instance, `[[3,7,9,3],[8,10,14,4]]` is turned into the string `"3,7,9,3,8,10,14,4"`.

As a consequence, `eval(`q = Math.max(${a})`)` loads in `q` the highest value that can be found in `a[]`, no matter the encapsulation depth of any sub-arrays in there.

For each position \\$(x,y),\\:0\le x\<q,\\:0\le y\<q\\$ and each rectangle tuple \\$(a,b,c,d)\\$, we increment the final result if:

$$((x \< a)\operatorname{XOR}(x \< c)) \operatorname{AND} ((y \< b)\operatorname{XOR}(y \< d))$$

Note that \\$((x \< a)\operatorname{XOR}(x \< c))\\$ is true iff we have either \\$x\in\[a,c\[\\$ or \\$x\in\[c,a\[\\$ (ditto for \\$y\\$, \\$b\\$ and \\$d\\$). This means that the corners can be passed in any order, as suggested by the test cases (it turns out that it's actually not a strict requirement).
> 4 votes

# Answer
# Wolfram Language (Mathematica), 30 bytes

```
Area[RegionUnion@@Cuboid@@@#]&

```

Try it online!

Input a list of `{bottom left, top right}` pairs.
> 4 votes

# Answer
# K (ngn/k), 22 bytes

```
#?,/{+a+!(|/x)-a:&/x}'

```

Try it online!

Or, if we can take corners as (lower-left, upper-right) pairs:

# K (ngn/k), ~~18~~ 15 bytes

```
#?,/{+x+!y-x}/'

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 13 bytes

```
εøεŸ¨}`â}€`Ùg

```

Try it online or verify all test cases.

**Explanation:**

```
ε      # Map over each pair of coordinates in the (implicit) input-list:
 ø     #  Zip/transpose; swapping rows/columns
       #  (so we'll have a list [[Xa,Xb],[Ya,Yb]]
  ε    #  Map both to:
   Ÿ   #   Pop the pair, and push a list in this range
    ¨  #   Remove the last item, so the range is [a,b)
  }`   #  After the inner map: pop and push both lists separated to the stack
    â  #  Get the cartesian product of these two lists
}€`    # After the outer map: flatten this list of list of pairs one level down
   Ù   # Uniquify this list of cell-coordinates
    g  # And pop and push its length
       # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Husk, 11 bytes

```
Luṁ(ΠmhṁẊ…T

```

Try it online!

```
Lu              # length of uniqe elements from
  ṁ(            # mapping over input:
    Π           #  cartesian product of:
       ṁ        #   for each coordinate pair
          T     #    transpose
        Ẋ…      #    and get the range,
     mh         #    (removing the last element)

```
> 2 votes

# Answer
# Julia 1.0, ~~55~~ 52 bytes

```
!t=length(∪([a:~-c.=>(b:d-1)' for(a,b,c,d)=t]...))

```

Try it online!

* input is an array of flattened 4-tuples in the order `(left,bottom,right,top)`
* for each rectangle, we create all their points in the form `x=>y` with `(a:c-1).=>(b:d-1)'`

example with `(1,2),(4,6)`:

```
julia> (1:4-1).=>(2:6-1)'
3×4 Matrix{Pair{Int64, Int64}}:
1=>2  1=>3  1=>4  1=>5
2=>2  2=>3  2=>4  2=>5
3=>2  3=>3  3=>4  3=>5

```
* then  (`union`) removes duplicates
* `length` is self-explanatory I think
> 2 votes

# Answer
# Charcoal, ~~42~~ 40 bytes

```
ＩΣＥ⌈Ｅθ⌈ιΣＥ⌈Ｅθ⌈λ⊙θ∧››§ν²ι›§ν⁰ι››§ν³λ›§ν¹λ

```

Try it online! Link is to verbose version of code. Takes input as a list of 4-tuples (bottom, left, top, right). Edit: Saved 2 bytes after reading @Arnauld's answer. Explanation:

```
    Ｅθ                                      Map over input list
      ⌈ι                                    Get maximum co-ordinate
   ⌈                                        Take the maximum
  Ｅ                                         Map over implicit range
           Ｅθ                               Map over input list
             ⌈λ                             Get maximum co-ordinate
          ⌈                                 Take the maximum
         Ｅ                                  Map over implicit range
                θ                           Input list
               ⊙                            Does any rectangle match
                       ι    ι               Current y value
                  ››§ν² ›§ν⁰                Inside rectangle bounds
                                  λ    λ    Current x value
                             ››§ν³ ›§ν¹     Inside rectangle bounds
                 ∧                          Logical And
        Σ                                   Take the sum
 Σ                                          Take the sum
Ｉ                                           Cast to string
                                            Implicitly print

```

A coordinate `x` is within a half-open range `[a, b)` if it is less than `b` but not less than `a`. In normal logic, this is written `(b>x)&&!(a>x)`, however the `&&!` operator works out as equivalent to the `>` operator so the result is simply `(b>x)>(a>x)`.
> 1 votes

# Answer
# Python 3, 83 bytes

```
lambda a:len({*chain(*[product(*map(range,*x))for x in a])})
from itertools import*

```

Try it online!

-3 thanks to pxeger.
> 0 votes

# Answer
# Scala, 72 bytes

```
_.map{(?,<,c,d)=>Set(?to c-1*)flatMap(d+1 to<map _.->)}.reduce(_|_).size

```

Try it in Scastie!

Does it the simple, stupid way: by making sets of all the points each rectangle contains and then finding the size of their union. Input is a list of flattened 4-tuples, with the top left corner first and the bottom right corner second.
> 0 votes

# Answer
# Gaia, 11 bytes

```
N†⊢×⊢
↑¦|⊢l

```

Try it online!

```
N†⊢×⊢  -- helper function to convert rectangle corners to coordinate list
N†⊢    -- reduce rows by vectorized half-inclusive range
   ×⊢  -- reduce the two ranges by cartesian product

↑¦     -- map the helper function over each rectangle
  |⊢   -- reduce by set union
    l  -- take the length

```
> 0 votes

# Answer
# JavaScript (Node.js), 77 bytes

```
x=>x.map(([i,b,c,d])=>{for(;i++<c;)for(j=b;j++<d;)x[y=[i,j]]=s+=!x[y]},s=0)|s

```

Try it online!
> 0 votes

---
Tags: code-golf, math, geometry, grid
---


# Question
Title: Sums of sum of divisors in sublinear time
Given a number \\$n\\$, we have its sum of divisors, \\$\sigma(n)\ = \sum\_{d | n} {d}\\$, that is, the sum of all numbers which divide \\$n\\$ (including \\$1\\$ and \\$n\\$). For example, \\$\sigma(28) = 1 + 2 + 4 + 7 + 14 + 28 = 56\\$. This is OEIS A000203.

We can now define the sum of sum of divisors as \\$S(n) = \sum\_{i=1}^{n}{\sigma(i)}\\$, the sum of \\$\sigma(i)\\$ for all numbers from \\$1\\$ to \\$n\\$. This is OEIS A024916.

Your task is to calculate \\$S(n)\\$, **in time sublinear in \\$n\\$, \\$o(n)\\$**.

# Test cases

```
10 -> 87
100 -> 8299
123 -> 12460
625 -> 321560
1000 -> 823081
1000000 (10^6) -> 822468118437
1000000000 (10^9) -> 822467034112360628

```

# Rules

* **Your complexity must be \\$o(n)\\$**. That is, if your code takes time \\$T(n)\\$ for input \\$n\\$, you must have \\$\lim\_{n\to\infty}\frac{T(n)}n = 0\\$. Examples of valid time complexities are \\$O(\frac n{\log(n)})\\$, \\$O(\sqrt n)\\$, \\$O(n^\frac57 \log^4(n))\\$, etc.
* You can use any reasonable I/O format.
* Note that due to the limited complexity you can't take the input in unary nor output in it (because then the I/O takes \\$\Omega(n)\\$ time), and the challenge might be impossible in some languages.
* Your algorithm should in theory be correct for all inputs, but it's fine if it fails for some of the big test cases (due to overflow or floating-point inaccuracies, for example).
* Standard loopholes are disallowed.

This is code golf, so the shortest answer in each language wins.

# Answer
> 10 votes
# Ruby, ~~55~~ 52 bytes

Formula is adapted from this math.SE question. Runs in \\$\mathcal{O}(\sqrt{n})\\$.

-3 bytes thanks to @dingledooper.

```
->x{(1..$.=x**0.5).sum{(v=x/_1)*_1-(v*~v-$.*~$.)/2}}

```

Attempt This Online!

# Answer
> 9 votes
# Python 2, 58 bytes

Runs in \\$ \mathcal{O}(\sqrt{n}) \\$ time.

```
f=lambda n,i=1:~i*i*(n/-~i-n/i)/2+(i<n and f(n,n/(n/-~i)))

```

Try it online!

## Explanation

Note: @Neil's answer seems to use a similar approach to mine.

We first take the \\$ O(n) \\$-time formula \\$ \sum\_{i=1}^n{i \cdot \lfloor\frac{n}{i}\rfloor} \\$, noticing that there can only be \\$ O(\sqrt{n}) \\$ unique values of \\$ \lfloor\frac{n}{i}\rfloor \\$. For example, if \\$ n = 50 \\$, the possible values of \\$ i \\$ for each \\$ \lfloor\frac{n}{i}\rfloor \\$ are:

```
 n//i |   i
------+-------
   1  | 26-50
   2  | 17-25
   3  | 13-16
   4  | 11-12
   5  | 9-10
   6  | 8-8
   7  | 7-7
   8  | 6-6
  10  | 5-5
  12  | 4-4
  16  | 3-3
  25  | 2-2
  50  | 1-1

```

Let \\$ a \\$ be a sorted list of all unique values of \\$ \lfloor\frac{n}{i}\rfloor \\$. For this example, \\$ a = \[ 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 16, 25, 50 \] \\$. We can then construct a new summation that solves the problem in \\$ O(\sqrt{n}) \\$:

$$ \sum\_{i=1}^{|a|}{\left\lfloor \frac{n}{a\_{i}} \right\rfloor \times (T(a\_{i}) - T(a\_{i-1}))} $$

where \\$ T(n) \\$ is the sum of the first \\$ n \\$ positive integers, and assuming that \\$ a\_0 = 0 \\$. Next, a bit of insight allows us to rearrange the summation like so:

$$ \sum\_{i=1}^{|a|}{T(a\_i) \times \left(\left\lfloor\frac{n}{a\_i}\right\rfloor - \left\lfloor\frac{n}{a\_i+1}\right\rfloor\right)} $$

To compute \\$ a \\$, we can apply the following recurrence:

$$ a\_i = \left\lfloor\frac{n}{\lfloor n / (1+a\_{i-1}) \rfloor}\right\rfloor $$

The proof is left as an exercise to the reader. Finally, we can compute \\$ T(n) \\$ using the formula \\$ \frac{n(n+1)}{2} \\$.

# Answer
> 4 votes
# , ~~61~~ ~~51~~ 49 bytes

*Edit: saved ~~10~~ 12 bytes by re-arrangement, goaded (and inspired) by Giuseppe golfing-down my original version in his answer*

```
\(x,y=1:x^.5,z=x%/%y)min((2*y+z+1)%*%z-y^3-y^2)/2

```

Attempt This Online!

Golfed calculation based on the same Math.SE question used in ovs' Ruby answer.

**Ungolfed**

```
triangle=function(x)x*(x+1)/2
D=
function(x){
    y=sqrt(x)%/%1
    k=1:y
    sum(k*x%/%k+triangle(x%/%k))-triangle(y)*y
}

```

# Answer
> 4 votes
# Nibbles, 17 bytes (34 nibbles)

```
+:.;.,;^$-2/_$-;~$/*+$~$~$;$!$,_*

```

Attempt This Online!

Direct port of my R answer.

This feels very clunky, with half the tokens used for control-flow (`,;,;;~`) or explicit variable names (`$_$$$$$;$$_`); I suspect that one of the stack-based languages will be able to better this...

**Bit-by-bit** (in conjunction with the Nibbles quick reference and tutorial):
y (=floor(sqrt(x)): `^$-2`
z (=floor(x/(1..y))), saving y: `.,;^$-2/_$` (y saved as `$`)
triangle(z), saving z, y & triangle function: `.;.,;^$-2/_$;~$/*+$~$~`
triangle(z)-triangle(y): `.;.,;^$-2/_$-;~$/*+$~$~$;$`
(leaves z saved as `$`, y saved as `@`, x is `_`)

So now we can easily use the saved variables to calculate D: D = (1..y)\*z + triangle(z)-triangle(y): `+: .;.,;^$-2/_$-;~$/*+$~$~$;$ !$,_*`

# Answer
> 4 votes
# , 52 bytes

```
\(x,y=1:x^.5,z=x%/%y)y%*%z+(z+1)%*%z/2-max(y)*sum(y)

```

Attempt This Online!

Golfed down version of Dominic's answer which in turn uses the same observation as ovs. Nothing crazy here; should run in \\$\mathcal{O}\left(\sqrt n\right)\\$ time, but saves bytes by using `1:sqrt(x)` to truncate, and `%*%` to calculate the sumproduct.

# Answer
> 3 votes
# Python, 74 bytes

```
lambda n,i=0,k=1:(k>=i)*i*k+(i<k and f(n,j:=i+1,l:=n//j)+i*(l*~l-k*~k)//2)

```

Attempt This Online!

### Old Python, 88 bytes

```
lambda n,k=0:sum(i*k*(k>i)+i*(k-~(j:=n//-~i))*(k-(k:=j))//2for i in range(int(n**.5)+1))

```

Attempt This Online!

Probably similar to @ovs's although found independently.

The basic idea is to regroup the given double sum by divisors and then count how many numbers in the range are a multiple of the divisor.

To achieve O(n^0.5) divisors with the same multiplicity are lumped together.

# Answer
> 3 votes
# Charcoal, ~~41~~ 38 bytes

```
 Ｎθ≔θη≔⁰ζＷη«≔÷θιε≔÷θ⊕εη≧⁺×⁻ιη÷×ε⊕ε²ζ»Ｉζ

```

Try it online! Link is to verbose version of code. Explanation: Uses the formula \\$ A024916(n) = \sum\_{i=1}^n i \lfloor n/i \rfloor \\$ with the linked observation that it can be calculated more efficiently by grouping terms with the same value of \\$ \lfloor n/i \rfloor \\$, and then applying @dingledooper's rearrangement that \\$ \sum\_{j=1} \lfloor n/a\_j \rfloor (T(a\_j) - T(a\_{j-1})) = \sum\_{j=1} T(a\_j) ( \lfloor n/a\_j \rfloor - \lfloor n/a\_{j+1} \rfloor ) \\$ where \\$ T(n) \\$ are the triangular numbers to save 3 bytes.

```
 Ｎθ

```

Input \\$ n \\$.

```
≔θη

```

Start counting \\$ \lfloor n / a\_j \rfloor \\$ down from \\$ n \\$.

```
≔⁰ζ

```

Start with no total.

```
Ｗη«

```

Repeat until \\$ \lfloor n / a\_j \rfloor \\$ is zero. This also conveniently makes a copy of the value, so I can update the original variable in the loop while still being able to access its former value.

```
≔÷θιε

```

Calculate \\$ a\_j \\$.

```
≔÷θ⊕εη

```

Calculate \\$ \lfloor n / a\_{j+1} \rfloor = \lfloor n / ( 1 + a\_j ) \rfloor \\$.

```
≧⁺×⁻ιη÷×ε⊕ε²ζ

```

Calculate \\$ T(a\_j) ( \lfloor n/a\_j \rfloor - \lfloor n/a\_{j+1} \rfloor ) \\$, and accumulate it to the total.

```
»Ｉζ

```

Output the final total.

On TIO, \\$ 10^{11} \\$ takes about \\$ 10 \\$ times as long as \\$ 10^9 \\$, so the time complexity appears to be \\$ O(\sqrt n) \\$.

# Answer
> 3 votes
# Scala 3, 75 bytes

Port of @ovs's Ruby answer in Scala.

---

```
x=>{val d=sqrt(x);(BigInt(1) to d).map(k=>x-x%k-(x/k* ~(x/k)-d* ~d)/2).sum}

```

Attempt This Online!

# Answer
> 2 votes
# JavaScript (ES6), 54 bytes

Based on the formula found by ovs.

```
x=>(g=k=>++k*k>x?--k*k*~k/2:k*(q=x/k|0)-q*~q/2+g(k))``

```

Try it online!

---

# JavaScript (ES11), 45 bytes

*-3 bytes thanks to @tsh*

A port of dingledooper's answer.

Expects a BigInt.

```
f=(n,q=n)=>q&&(i=n/q)*(q-n/++i)*i/2n+f(n,n/i)

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), ~~44~~ 42 bytes

```
{+/-[q*k;x@s]+x@q:_y%k:1+!s:_%y}{-2!x*1+x}

```

-2 thanks to @coltim

Same formula as @ovs' answer.

Try it online!

# Answer
> 1 votes
# C#, ~~82~~ 80 bytes

-2 thanks to ceilingcat

With 2 dummy parameters (`y` and `z`).

```
(x,y,z)=>Enumerable.Range(1,y=(int)Math.Sqrt(x)).Sum(i=>2*i*(z=x/i)-z*~z+y*~y)/2

```

Try it online!

# C#, ~~89~~ 87 bytes

Single parameter.

```
x=>{int i=0,s=0,y=(int)Math.Sqrt(x),z;for(;i++<y;)s+=i*(z=x/i)+(y*~y-z*~z)/2;return s;}

```

Try it online!

Both use the same formula:

$$ \begin{eqnarray\*} D(x) &=& \Big(\sum\_{i=1}^{\lfloor\sqrt x\rfloor}i \cdot \Big\lfloor\frac x i\Big\rfloor + T(\Big\lfloor\frac x i\Big\rfloor) \ \Big) - \lfloor \sqrt x\rfloor \cdot T\big(\lfloor \sqrt x\rfloor \big)\\ &=& \Big(\sum\_{i=1}^{y}i \cdot z + T(z) \ \Big) - y \cdot T(y)\\ &=& \sum\_{i=1}^{y}i \cdot z + T(z) - T(y)\ \\ &=& \sum\_{i=1}^{y}i \cdot z + \frac{z \cdot (z-1) - y \cdot (y-1) }{2} \\ \end{eqnarray\*} $$ where $$ T(x) = \frac{x(x+1)}{2} \\ y = \lfloor\sqrt x\rfloor \\ z = \Big\lfloor\frac x i\Big\rfloor $$

---
Tags: code-golf, math, number-theory, restricted-complexity
---