title: Superstitious hotel elevator

text:
# Question
Title: Superstitious hotel elevator
# Description

Here's a very superstitious hotel elevator in Shanghai:

It avoids the number 13, because thirteen is unlucky in the Western world, and it avoids the digit 4, because four is unlucky in parts of Asia. What if this hotel was taller?

Read a positive even integer `n` from STDIN, representing the number of floors, and print what the button layout would look like to STDOUT: `-1`, followed by the next `n-1` positive integers that aren't equal to 13 and don't contain digit 4. Arrange these numbers in two columns such as in the above image: print two floor numbers per line, separated by a horizontal tab, so that reading the lines in reverse order from left-to-right yields the sequence in ascending order. (You may optionally print a trailing newline character, too.)

# Test cases

For the input `14`, output should be as in the above image:

```
15  16
11  12
9   10
7   8
5   6
2   3
-1  1

```

where the whitespace in each line is a single horizontal tab character.

For the input `2`, you should print `-1 1`.

For the input `100`, you should print:

```
120 121
118 119
116 117
113 115
111 112
109 110
107 108
105 106
102 103
100 101
98  99
96  97
93  95
91  92
89  90
87  88
85  86
82  83
80  81
78  79
76  77
73  75
71  72
69  70
67  68
65  66
62  63
60  61
58  59
56  57
53  55
51  52
39  50
37  38
35  36
32  33
30  31
28  29
26  27
23  25
21  22
19  20
17  18
15  16
11  12
9   10
7   8
5   6
2   3
-1  1

```

# Goal

This is . Shortest answer in bytes wins.

# Answer
> 8 votes
# Pyth, 27 bytes

```
jjLC9_c+_1.f&!@\4`ZnZ13tQ)2

```

Try it online here.

Gets `.f`irst `Q-1` numbers that match the filter `!=13` and `4` isn't in the string representation of the number. Then it prepends `-1` , chops in half, joins each by tabs(`C9`) and joins by newlines.

# Answer
> 19 votes
# Bash + common utils, 51

```
seq 9$1|sed 13d\;/4/d\;1i-1|rs 0 2|sed $[$1/2]q|tac

```
* `seq` generates ascending integers from 1 to N with an extra 9 digit in front - more than enough for 64bit integer input
* `sed` filters out the unlucky floors and inserts `-1` before line 1
* `rs` reshapes into two tab-separated columns
* `sed` stops after N/2 lines
* `tac` reverses output line order

# Answer
> 10 votes
# JavaScript ES6, ~~236~~ ~~234~~ ~~233~~ ~~210~~ ~~195~~ 188 bytes

Saved a whole bunch 'a bytes thanks to usandfriends!

Uses the `function*` for generators. Probably a shorter way to do this, but it was fun. *Way* fun. I'll bet some golfing can be done. Those weird whitespace things are tabs.

```
z=prompt(i=x=0,l=[]);y=(function*(){while(i<z-x)yield(i?(/4/.test(i)||i==13?--x&&".":i):-1)+(0*++i)})();while(a=y.next().value)+a&&l.push(a);l.join`    `.match(/-?\d+  \d+/g).reverse().join`
`

```

# Answer
> 7 votes
# C, 282 Bytes

```
int main(int r,char*v[]){int c=atoi(v[1]),a[c],b,E=1E9,g,i,t,o=t=g=(E)-2;while(i++<c){while(t>0){r=t%10;t=t/10;if(r==4||g==(E)+13||g<=o||g==E)t=++g;}a[i-1]=o=t=g;}for(c-=3;c>=0;c-=2){printf("%d\t",a[c+1]-E);printf("%d\n",a[c+2]-E);}printf("%d\t",a[0]-E);if(i%2)printf("%d",a[1]-E);}

```

### Formatted :

```
int main ( int r , char * v[] ) {
    int c = atoi ( v[ 1 ] ) , a[c] , b , E = 1E9 , g , i , t , o = t = g = ( E ) - 2;
    while ( i ++ < c ) {
        while ( t > 0 ) {
            r = t % 10;
            t = t / 10;
            if ( r == 4 || g == ( E ) + 13 || g <= o || g == E )t = ++ g;
        }
        a[ i - 1 ] = o = t = g;
    }
    for ( c -= 3 ; c >= 0 ; c -= 2 ) {
        printf ( "%d\t" , a[ c + 1 ] - E );
        printf ( "%d\n" , a[ c + 2 ] - E );
    }
    printf ( "%d\t" , a[ 0 ] - E );
    if ( i % 2 )printf ( "%d" , a[ 1 ] - E );
}

```

**Features :**

It can compute up to 2095984 floors, if each floor is `19.5m` high (incl. ceiling) then this building is long enough to be wrapped around the equator! `2095984*19.5=40871688m=~40000km=one 'lap' around the planet`.

# Answer
> 6 votes
# Julia, ~~134~~ 132 bytes

```
x=[-1;filter(i->i!=13&&'4'∉"$i",1:2(n=parse(readline())))][1:n]
for i=2:2:endof(x) println(join((r=reverse)(r(x)[i-1:i]),"  "))end

```

That funny whitespace in there is a literal tab. As Conor O'Brien noted, this is a byte shorter than doing `\t`.

Ungolfed:

```
# Read an integer from STDIN
n = parse(readline())

# Generate all numbers from 1 to 2n, exclude 0, 13, and all numbers containing 4,
# prepend -1, then take the first n
x = [-1; filter(i -> i != 13 && '4' ∉ "$i", 1:2n)][1:n]

# Loop over pairs, print tab-separated
for i = 2:2:endof(x)
    println(join(reverse(reverse(x)[i-1:i]), "  "))
end

```

# Answer
> 6 votes
# JavaScript, 116 ~~122~~

**Edit** Saved 6 bytes thx @Neil

Simple array solution - not even using ES6

Try with any browser

```
/* test */ console.log=function(x){ O.innerHTML+=x+'\n'; }

n=prompt();for(r=[-1],v=1;n;v++)v!=13&!/4/.test(v)&&--n&&r.push(v);for(;r[0];)console.log(a=r.pop(b=r.pop())+'\t'+b)
```

```
<pre id=O></pre>
```

# Answer
> 6 votes
## Python 2, ~~120~~ 110 bytes

```
N=input()
n=['-1']+[`i`for i in range(N*2)if i!=13and'4'not in`i`][1:N]
while n:x=n.pop();print n.pop()+'\t'+x

```

# Answer
> 6 votes
# Python 2, 94 bytes

```
n=input();c=-1;s=''
while n:
 if('4'in`c`)==0!=c!=13:n-=1;s=(n%2*'%d	%%d\n'+s)%c
 c+=1
print s

```

Try it online!

There's a tab character in the string that SE doesn't render (thanks to Sp3000 for suggested to use it, saving a byte).

Tests floors `c` starting from floor `-1` until the quota `n` of floors is reached. For each floor, tests that it doesn't contain a `4` nor equals `0` or `13`. If so, prepends it to the elevator string `s` and decrements the quota `n`.

A trick with string formatting is used to get the two floors per column to appear in the proper order when prepended. Each new line is prepared as `'%d\t%%d\n'`, so that when two floors are substituted in order, the first is on the left and the second is on the right. For example,

```
('%d\t%%d\n'%2)%3 == ('2\t%d\n')%3 == '2\t3\n'

```

# Answer
> 5 votes
# Ruby 2.3, ~~84~~ 83 characters

(82 characters code + 1 characters command line option)

```
puts (["-1",*?1..?1+$_].grep_v(/^13$|4/)[0..$_.to_i]*?\t).scan(/\S+\t\d+/).reverse

```

Sample run:

```
bash-4.3$ ruby -ne 'puts (["-1",*?1..?1+$_].grep_v(/^13$|4/)[0..$_.to_i]*?\t).scan(/\S+\t\d+/).reverse' <<< '14'
15      16
11      12
9       10
7       8
5       6
2       3
-1      1

```

## Ruby, ~~93~~ 92 characters

(91 characters code + 1 character command line option)

```
puts ([-1,*1..2*n=$_.to_i].reject{|i|i==13||i.to_s[?4]}[0..n]*?\t).scan(/\S+\t\d+/).reverse

```

Sample run:

```
bash-4.3$ ruby -ne 'puts ([-1,*1..2*n=$_.to_i].reject{|i|i==13||i.to_s[?4]}[0..n]*?\t).scan(/\S+\t\d+/).reverse' <<< '14'
15      16
11      12
9       10
7       8
5       6
2       3
-1      1

```

# Answer
> 5 votes
# C#, 296 bytes

```
namespace System.Collections.Generic{using Linq;class X{static void Main(){var a=new List<int>();var b=new List<int>();for(int i=int.Parse(Console.ReadLine()),j=-2;i>0;)if(++j!=13&&j!=0&&!(j+"").Contains("4"))(i--%2<1?a:b).Insert(0,j);Console.Write(string.Join("\n",a.Zip(b,(x,y)=>x+"\t"+y)));}}}

```

Ungolfed:

```
namespace System.Collections.Generic
{
    using Linq;
    class X
    {
        static void Main()
        {
            var a = new List<int>();
            var b = new List<int>();
            for (int i = int.Parse(Console.ReadLine()), j = -2; i > 0;)
                if (++j != 13 && j != 0 && !(j + "").Contains("4"))
                    (i-- % 2 < 1 ? a : b).Insert(0, j);
            Console.Write(string.Join("\n", a.Zip(b, (x, y) => x + "\t" + y)));
        }
    }
}

```

Golfing tricks used:

* *i* (the running counter) and *j* (the current number under consideration) are decremented/incremented, respectively, inside the expression in the loop body instead of the for statement as is normal
* `j+""` instead of `j.ToString()`
* Place everything inside `namespace System.Collections.Generic` not only so that we can access `List<T>`, but also implicitly use the namespace `System` without further qualification
* Place the `using` inside the namespace so that we can write `using Linq;` instead of `using System.Linq;`
* `.Insert(0,j)` is shorter than using `.Add(j)` and later applying `.Reverse()`

It is unfortunate that the `using Linq;` is necessary, since it is needed only for `.Zip`, but writing it as `Linq.Enumerable.Zip()` is longer.

# Answer
> 4 votes
# Lua, 169 Bytes

```
t={-1}i=1 repeat if(i..""):find("4")or i==13 then else table.insert(t,i)end i=i+1 until #t==arg[1] for i=#t%2==0 and#t-1 or#t,1,-2 do print(t[i],t[i+1]and t[i+1]or"")end

```

Fairly straight forward, we first assemble a table filled with all the button values. Then we iterate through it backwards, printing two values at a time, or nothing if the second value does not exist.

# Answer
> 4 votes
# Mathematica, 105 bytes

```
StringRiffle[Reverse[Select[Range[2#]-2,#!=13&&#!=0&&DigitCount[#,10,4]<1&][[;;#]]~Partition~2],"
","\t"]&

```

Replace the `\t` with an actual tab character.

# Answer
> 4 votes
# Brachylog, 105 bytes

```
,Ll?,Lbb:1{h_.|[L:I]hhH,I+1=J((13;J:Zm4),L:J:1&.;Lb:J:1&:[J]c.)}:[1:-1]c{_|hJ,?bhw,[9:J]:"~c~w
"w,?bb:2&}

```

Would have been a lot shorter with CLPFD support, here I have to iteratively try integers in the first sub-predicate.

The new line before `"w,?bb:2&}` is mandatory, this is the new line that is printed between every row.

# Answer
> 3 votes
## C#, 277 343

```
using System;using System.Collections.Generic;static void f(int v){List<int>a=new List<int>();List<int>b=new List<int>();int s=1;for(int i=-1;i<v-1;i++){if(i==13||i.ToString().Contains("4")||i==0){ v++;continue;}if(s==1){s=2;a.Add(i);}else{s=1;b.Add(i);}}a.Reverse();b.Reverse();int l=0;foreach(int y in a){Console.WriteLine(y+" "+b[l]);l++;}}

```

This is as a function only. I'm new to C#. Increase was to make valid for 40-49, and for including `using`s

Ungolfed, as a complete running program:

```
using System;
using System.Collections.Generic;

class P {
    static void Main()
    {
        List<int> a = new List<int>();
        List<int> b = new List<int>();
        int v = Int32.Parse(Console.ReadLine());
        int s = 1;
        for (int i = -1; i < v - 1; i++)
        {
            if (i == 13 || i.ToString().Contains("4") || i == 0)
            {
                v++;
                continue;
            }
            if (s == 1)
            {
                s = 2;
                a.Add(i);
            }
            else {
                s = 1;
                b.Add(i);
            }
        }
        a.Reverse();
        b.Reverse();
        int l = 0;
        foreach (int y in a)
        {
            Console.WriteLine(y + " " + b[l]);
            l++;
        }
        Console.ReadLine();
    }
}

```

Explained

I create two lists, and alternate between pushing to them, reverse them, loop through one, and grab the other by index.

# Answer
> 3 votes
## C++11, 259 258 203 202 195 194 bytes

Slashed off 1 byte, thanks to Conor O'Brien's idea to use literal tab instead of `\t`.

UPD 2: slashed off 55 bytes with improved logic and comma abuse.

UPD 3: another byte off thanks to ceilingcat.

UPD 4: 7 bytes off courtesy of ceilingcat.

UPD 5: and another byte off by ceilingcat.

Happy to have all includes in place AND still beat the C and C# solutions.

```
#include<iostream>
#include<string>
int main(){std::string o="-1    1",c,b;int n,i=2,s=2;for(std::cin>>n;s<n;o=i==14|~c.find(52)?o:(++s&1?b=c,"":b+'    '+c+'\n')+o)c=std::to_string(i++);std::cout<<o;}

```

Ungolfed:

```
#include <iostream>
#include <string>

int main()
{
    std::string o = "-1 1", c, b;
    int n, i = 2, s = 2;
    for (std::cin >> n;
         s < n;
         o = i == 14 | ~c.find(52) ? o : (++s & 1 ? b = c, "" : b + '   ' + c + '\n') + o
    )
        c = std::to_string(i++);
    std::cout << o;
}

```

# Answer
> 3 votes
## Python 3, 155 bytes

I think listifying, reversing, and self-zipping the floor-number generator `s()` may have been too clever for its own good, but others have already done the alternative (popping two items at a time), not to mention using Python 2 which saves bytes on some key points.

```
def s(m,n=-1):
 while m:
  if not(n in(0,13)or'4'in str(n)):yield n;m-=1
  n+=1
*f,=s(int(input()))
g=iter(f[::-1])
h=zip(g,g)
for a,b in h:print(b,'\t',a)

```

The shorter, but already-done-better alternative takes 140 bytes.

```
def s(m,n=-1):
 while m:
  if not(n in(0,13)or'4'in str(n)):yield n;m-=1
  n+=1
*f,=s(int(input()))
while f:a=f.pop();print(f.pop(),'\t',a)

```

# Answer
> 3 votes
# Japt, 42 bytes

```
JoU*2 k0 kD f@!Xs f4} ¯U ã f@Yv} w ®q'    } ·

```

The four spaces should be an actual tab char. Try it online!

### How it works

```
          // Implicit: U = input integer, D = 13
JoU*2     // Create the range of integers [-1,U*2).
k0 kD     // Remove 0 and 13.
f@!Xs f4} // Filter out the items X where X.toString().match(/4/g) is not null, i.e. the numbers that contain a 4.
¯U ã      // Slice to the first U items, and generate all adjacent pairs of items.
f@Yv}     // Filter out the items where the index Y is odd. This discards every other pair.
w         // Reverse.
®q'\t}    // Join each item with tabs.
·         // Join the whole list with newlines.
          // Implicit: output last expression

```

# Answer
> 3 votes
# Lua, 141 bytes

```
n,s=1,'-1 1'function g()repeat n=n+1 until s.find(n,4)==z and n~=13 return n end for i=4,io.read(),2 do s=g()..' '..g().."\n"..s end print(s)

```

# Ungolfed

```
n,s = 1,'-1'1' --n is the current floor number, S is the string to be printed
function g() --This function raises n to the next valid floor
    repeat --Same as while loop except it runs the following block before checking the expression
        n = n + 1 --Self-explanatory, increases n by one
    until --Checks the expression, if it is true, it breaks out of the loop
        s.find(n,4) == z --[[Strings have a member :find(X) where it finds the position of
                             X in the string (X can also be a pattern). However, calling it
                             by .find(S,X) executes find on S with argument X. I can't
                             directly do n:find(4) because n is a number. This is a "hack"
                             (sort of) to cut down some bytes. Also, if X is not a string,
                             lua tries to (in this case, succeeds) cast X to a
                             string and then look for it. I check if this is equal to z
                             because z is nil (because it is undefined), and find returns
                             nil if X is not found in S.
                             TL;DR: Checks if 4 is not the last digit.]]
        and n ~= 13 --Self-explanatory, checks if n is not 13
        return n --Self-explanatory, returns n
end
for i = 4, io.read(), 2 do --[[Start at floor 3 (shows 4 because we're going by target
                               floor, not by starting floor), continue until we reach
                               floor io.read() (io.read returns user input), increment by
                               2 floors per iteration)]]
    s = g() .. ' ' .. g() .. "\n" .. s --[[Prepend the next floor, a space, the next floor,
                               and a newline to s]]
end
print(s) --Self-explanatory, output the string

```

Try it online (you need to click 'execute' on the top and then click the terminal on the bottom before typing input; I'm looking for a better way to test lua online with stdin and stdout)

# Answer
> 3 votes
# 05AB1E, ~~25~~ ~~23~~ 22 bytes

-1 byte thanks to @ASCII-only

```
·Ý<0K13Kʒ4å_}s£2ôR9çý»

```

Try it online!

## Explanation

```
                           # Implicit input: integer n
·Ý<                        # Push list [-1,0,1,...,2n-1]
   0K                      # Remove 0 from [-1,0,1,...,2n-1]
     13K                   # Remove 13 from [-1,1,...,2n-1]
        ʒ4å_}              # Filter out every number containing a 4 from the list
             s£            # Pick out the n first element in the list
               2ôR         # Splice list into parts of length 2
                  9çý      # Join with tab character (ascii value 9)
                     »     # Join with newlines

```

# Answer
> 2 votes
# Java, 333 Bytes

```
import java.util.*;interface E{static void main(String[]a){byte i=-1;Stack<Byte>s=new Stack<>();while(s.size()<Byte.valueOf(a[0])){if(i==13|i==0|String.valueOf(i).contains("4")){i++;continue;}s.add(i);i++;}if(s.size()%2!=0){System.out.println(s.pop());}while(!s.isEmpty()){int r=s.pop();int l=s.pop();System.out.println(l+"\t"+r);}}}

```

Adds allowed floor numbers to a stack then pops them back off to print them.

I played around using an IntStream, but with all the imports this one ended up being smaller.

# Answer
> 2 votes
**Scala 147**

```
val n=io.StdIn.readInt;(-1 to 4*n).filter(i=>i!=0&&i!=13&&(!(i+"").contains(52))).take(n).reverse.grouped(2).toList.map{i=>println(i(1)+"\t"+i(0))}

```

# Answer
> 2 votes
# PowerShell, 106 ~~107~~ bytes

```
$c=,-1+$(while($i+1-lt"$args"){if(++$c-notmatch'^13$|4'){$c;++$i}})
while($c){$a,$b,$c=$c;$s="$a    $b
$s"}$s

```

# Ungolfed

```
# Calculate floors:
$c=,-1 # Array with one element
  +
  $( # Result of subexpression
    while($i+1-lt"$args"){ # Uninitialized $i is 0, +1 ensures loop start from 1
      if(
        ++$c-match'^13$|4' # Expression increments uninitialized $c (i.e. start from 1)
                           # and matches resulting number to regex.
      ){
        $c;++$i # Return $c and increment $i counter
      }
    }
  )

# Print floors:
while($c){ # Loop until no more elements in $c
  $a,$b,$c=$c # Use PS's multiple assignment feature
              # $a - first element of $c array
              # $b - second element of $c array
              # $c - the rest of elements of $c array
  $s="$a    $b
$s" # Create string with tabs and newlines,
    # literal characters are used
}
$s # Output resulting string

```

# Example

```
PS > .\Elevator.ps1 14
15  16
11  12
9   10
7   8
5   6
2   3
-1  1

```

# Answer
> 2 votes
# Python 3, 117 Bytes

```
n=int(input())
l=[-1]+[i for i in range(n*2)if(i!=13)*(not'4'in str(i))][1:n]
while l:x=l.pop();print(l.pop(),'\t',x)

```

Modified version of the python 2 post to fit the python 3 specification.

# Answer
> 2 votes
## Haskell 202 bytes

```
t=(-1):[x|x<-[1..],x/=13,all (/='4')(show x)]
by2 []=[[]]
by2 [a]=[[a]]
by2 [a,b]=[[a,b]]
by2 (a:b:xs)=[a,b]:(by2 xs)
main=do
 n<-getLine
 putStr$unlines$map unwords$by2$map show$reverse$take(read n) t

```

I’am haskell beginner…

* first create the infinite list of values. (t list)
* function by2 group a list into sublists of 2 elements.
* main take the value.
    + take value elements of *t* list
    + reverse the list to have greaters elements first
    + map show function to convert int list to string list
    + group element 2 by 2 with by2 function
    + We have a list like \[ \["4", "5"\], \["6", "7"\] \] transformed like \[ "4 5", "6 7"\] with *unwords* function mapped on list
    + unlines the list (each element of the list separate by '\n')
    + finish with putStrLn to write string on terminal.

# Answer
> 2 votes
# Javascript ES6 114 bytes

```
n=>[...Array(n)].map(_=>{while(/^13$|4|^0/.test(++i));return i;},i=-2).join`    `.match(/-?\d+  \d+/g).reverse().join`\n`

```

Usage

```
f=n=>[...Array(n)].map(_=>{while(/^13$|4|^0/.test(++i));return i;},i=-2).join`  `.match(/-?\d+  \d+/g).reverse().join`\n`

```

f(100);

# Answer
> 2 votes
# Perl 6, 73 bytes

```
{.join("    ").say for (-1,|grep {$_-13&!/4/},1..Inf)[^$_].rotor(2).reverse}

```

Assumes an even number of floors, since the problem statement seems to assume it as well and at least one other provided solution breaks for odd numbers of floors. Just add `,:partial` as a second argument to `rotor`, for nine more bytes, to support odd numbers of floors.

# Answer
> 2 votes
# Jelly, 20 bytes

```
ḟ13D_4Ȧµ#o-s2Ṛj€9Ọ¤Y

```

**Try it online!**

### How?

```
ḟ13D_4Ȧµ#o-s2Ṛj€9Ọ¤Y - Main Link: no arguments
        #            - start at n=0 and collect the first INPUT values which are truthy under:
       µ             -   the monad (i.e. f(n)):        e.g.:    0      3      4      13     42        813
ḟ13                  -     filter out thirteens                 [0]    [3]    [4]    []     [42]      [813]
   D                 -     convert to decimal lists             [[0]]  [[3]]  [[4]]  []     [[4,2]]   [[8,1,3]]
    _4               -     subtract four (vectorises)           [[-4]] [[-1]] [[0]]  []     [[0,-2]]  [[4,-3,-1]
      Ȧ              -     any & all?                           1      1      0      0      0         1
         o-          - logical OR with -1 (replace floor 0 with floor -1)
           s2        - split into twos
             Ṛ       - reverse
                  ¤  - nilad followed by link(s) as a nilad:
                9    -   literal nine
                 Ọ   -   to character (a tab)
              j€     - join €ach
                   Y - join with newlines
                     - implicit print

```

# Answer
> 1 votes
# JavaScript (ES6), ~~151~~ 146

```
alert([for(a of Array((n=+prompt(i=0))*2).keys())if((i+=t=/4/.test(a)||a==13,!t&&a<n+i))a].reduce((a,b,j,r)=>j%2-1?(b||-1)+`  ${r[j+1]}
`+a:a,''))

```

Did this before I realized edc65 had already made a shorter one. Oh well!

# Answer
> 1 votes
# , 106 bytes

```
n=scan();x=-1:n^2;x=x[-grep(4,x)][-14][-2][n:1];cat(paste0(matrix(x,2,n/2)[2:1,],c("	","\n"),collapse=""))

```

Try it online!

Explanation: it starts with the vector of floors from \\$-1\\$ to \\$n^2\\$, which is more than enough in all my tests. Should that ever be insufficient, we could switch to \\$n^3\\$ or \\$n^9\\$. It then removes the unlucky floor numbers (as well as floor 0), converts to a 2-row matrix form and inverts the rows to get the numbers in correct order, then outputs in the desired format, recycling the vector `c("\t","\n")`. As suggested by Conor O'Brien, use a literal tab instead of `\t` for -1 byte.

```
n=scan();                                        # read number of floors n
x=-1:n^2;                                        # initial vector of numbers
x=x[-grep(4,x)]                                  # remove floors with a 4
               [-14]                             # remove floor 13
                    [-2]                         # remove floor 0
                        [n:1];                   # keep lowest n remaining floors, highest to lowest
cat(paste0(
  matrix(x,2,n/2)                                # split vector of floors into 2 rows
                 [2:1,],                         # take row 2 then row 1
                        c("   ","\n"),           # separate integers with alternating tabs and newlines (uses recycling)
                                    collapse=""))

```

# Answer
> 0 votes
# APL (Dyalog), 34 bytes

```
{⊖(⍵÷2)2⍴o/⍨~'4'∊¨⍕¨o←13~⍨¯1,⍳⍵×⍵}

```

Try it online!

# Answer
> 0 votes
# Perl 5 `-MList::Util=pairmap -n`, 62 bytes

```
pairmap{say"$b	$a"}reverse((-1,grep!/^13$|4/,1..121)[0..$_-1])

```

Try it online!

# Answer
> 0 votes
# Japt `-R`, ~~23~~ ~~22~~ 21 bytes

```
È©DÀX«ìø4}jUJ ò Ômq9d

```

Try it

```
È©DÀX«ìø4}jUJ ò Ômq9d     :Implicit input of integer U
È                         :Function taking an integer X as argument
 ©                        :  Logical AND with
  D                       :    13
   ÀX                     :    Is not equal to X
     «                    :  Logical AND with logical NOT of
      ì                   :    Convert X to digit array
       ø4                 :    Contains 4?
         }                :End function
          jU              :Get the first U integers that return truthy
            J             :Starting with -1
              ò           :Partitions of length 2
                Ô         :Reverse
                 m        :Map
                  q       :  Join with
                   9d     :  Character at codepoint 9 (TAB)
                          :Implicit output joined with newlines

```

# Answer
> 0 votes
# Husk, 25 bytes

```
↔mJc9†sC2↑¹fȯ¬€4d-0-13…_1

```

Try it online!

# Answer
> 0 votes
# Thunno `N`, \\$36\log\_{256}(96)\approx\\$ 29.63 bytes

```
1ns2*:gzt13Q&s4Aq!&kDLz0-Zy2Apre9Csj

```

Attempt This Online!

Port of Wisław's 05AB1E answer.

#### Explanation

```
1n        # Push -1
  s2*     # Swap and double the input
     :    # Push the range between -1 and 2*n
      g   # Filter this list by:
       zt #  Triplicate the integer       STACK:  i, i, i
13Q       #  Is it not equal to 13?       STACK:  i, i, i != 13
   &      #  Logical AND                  STACK:  i, (i and i != 13)
    s4Aq  #  Swap and check if it         STACK:  (i and i != 13), (4 in i)
          #  contains the digit 4
        ! #  Logical NOT                  STACK:  (i and i != 13), (4 not in i)
&         #  Logical AND                  STACK:  i and (i != 13) and (4 not in i)
 k        # End filter
  DL      # Duplicate and push the length
    z0-   # Subtract the input
       Zy # Remove this many elements from the back
2Ap       # Split into chunks of length 2
   r      # Reverse
    e     # Map over this list:
     9C   #  Push chr(9), a tab
       sj #  Join the list by a tab
          # N flag joins by newlines
          # Implicit output

```

# Answer
> 0 votes
# Thunno 2 `N`, 21 bytes

```
ḌĖ⁻0o13oæṘ4Ƈ}ɱ2ẇr9Cȷj

```

Try it online!

#### Explanation

```
ḌĖ⁻0o13oæṘ4Ƈ}ɱ2ẇr9Cȷj  # Implicit input
ḌĖ⁻                    # Push the range [-1 .. 2*input)
   0o13o               # Remove the 0 and the 13
        æṘ4Ƈ}          # Remove anything containing 4
             ɱ         # Take the first (input) items
              2ẇ       # Split into pairs
                9Cȷj   # Join each by ASCII 9 (tab)
                       # Join on newlines
                       # Implicit output

```

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


title: Special String reformatting

text:
# Question
Title: Special String reformatting
This challenge is to take an alphabetical string as input and to apply the following conversion:

The first of each type of character of the string must stay, and must be immediately followed by an integer representing how many of these characters were in the original string. Any repeating characters must be omitted.

All inputs will be entirely lower-case letters (no spaces). Outputs must be ordered in the same way as the inputs (input `hi` must give output of `h1i1`, not `i1h1`)

# Examples

Input: `potato` Output: `p1o2t2a1`

Input: `pqwertyuiop` Output: `p2q1w1e1r1t1y1u1i1o1`

Input: `thisisanexample` Output: `t1h1i2s2a2n1e2x1m1p1l1`

Input: `oreganoesque` Output: `o2r1e3g1a1n1s1q1u1`

Input: `aaaaaaabaaaaaa` Output: `a13b1`

# Scoring

This is . Shortest answer wins!

# Answer
> 10 votes
# APL (Dyalog Unicode), 7 bytes (SBCS)

Anonymous tacit prefix function.

```
,,∘⍕∘≢⌸

```

Try it online!

apply the following function between each unique character and the indices where it occurs:

`,` concatenate the character

to

the stringification

of

the indices' count

`,` flatten

# Answer
> 5 votes
# Python 3, ~~58~~ \\$\cdots\\$ ~~50~~ 57 bytes

Added 3 bytes and switched to Python 3 to fix bugs.
Added 7 bytes to make output a string.

```
lambda s:''.join(c+f'{s.count(c)}'for c in{}.fromkeys(s))

```

Try it online!

Outputs a string.

Outputting a list of strings is 50 bytes.

# Answer
> 5 votes
# PHP, 63 bytes

```
foreach(array_count_values(str_split($argn))as$a=>$b)echo$a.$b;

```

Try it online!

Built-ins and a whole lot of glue. Input via `STDIN`, output to `STDOUT`.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 34 bytes

This is the dreaded *obvious chain-the-built-ins*. `Print` can accept multiple arguments and will print them without any separators.

```
Print@@Flatten@Tally@Characters@#&

```

More scary version, for the same number of bytes:

```
Print@@(##&)@@@Tally@Characters@#&

```

I suspect that a better hack consisting entirely of the characters `#&/()` can be used to get rid of Flatten, but I couldn't come up with one.

Of course, Mathematica has both `LetterCounts` *and* `CharacterCounts`, and there's also `Counts` instead of `Tally`, but all of these seem to return association objects that seem excessively complicated to work with.

Try it online!

# Answer
> 4 votes
# , ~~15~~ 17 bytes

Thanks to Jonah for finding and fixing a bug!

```
[:;~.<@,&":"0#/.~

```

Try it online!

# Answer
> 4 votes
# Python 3, 49 bytes

```
lambda s:''.join({c+str(s.count(c)):1for c in s})

```

Try it online!

Outputs a string.

Based on Noodle9's solution, which uses a nice idea of a dictionary to deduplicate while preserving order, which they do in Python 3 but not Python 2. Note that `set` doesn't preserve order.

The idea is to make the character-with-count strings be keys of a dictionary so that only the first instance is used. The values in the dictionary don't matter, since dictionaries iterate over keys by default.

I had thought at first that the deduplication must be applied to the characters of the input string, but realized that it also works on the strings to be joined in the output, since a given character is always attached to the same count.

Outputting a list of strings without joining takes 43 bytes.

# Answer
> 4 votes
# K (oK), ~~23~~ 18 bytes

```
{,/t,'$+/x=\:t:?x}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
Ùε¢yì?

```

Try it online or verify all test cases.

**Explanation:**

```
Ù       # Uniquify the (implicit) input-string
 ε      # For-each over each character in this string:
  ¢     #  Count the amount of times the current character occurs in the (implicit) input
   yì   #  Prepend the current character before this count
     ?  #  Print it without newline

```

# Answer
> 3 votes
# Jelly, 5 bytes

```
Lƙż@Q

```

A full program printing the result (or a monadic Link yielding a list of pairs of characters and integers).

**Try it online!**

There are loads of ways to achieve this in 6 bytes (e.g. `Qżċ@€¥`).

### How?

```
Lƙż@Q - Main Link: list of characters, S          e.g. "cabbage"
 ƙ    - for groups of identical elements (of S):       (c aa bb g e)
L     -   length                                       [1,2,2,1,1]
    Q - de-duplicate S                                 "cabge"
   @  - with swapped arguments:
  ż   -   zip                                          [['c',1],['a',2],['b',2],['g',1],['e',1]]
      - implicit, smashing, print                      c1a2b2g1e1

```

# Answer
> 2 votes
# Python 3, 62 bytes

```
f=lambda s:s and s[0]+str(s.count(s[0]))+f(s.replace(s[0],''))

```

Try it online!

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

```
s=>[...new Set(s)].map(c=>c+~-s.split(c).length).join``

```

Try it online!

### Commented

```
s =>                    // s = input string
  [...new Set(s)]       // create a set from the input string and split it,
                        // resulting in an array of characters arranged in
                        // order of first appearance
  .map(c =>             // for each character c in this array:
    c +                 //   append c
    ~-s.split(c).length //   followed by the number of occurrences in the
                        //   original string
  )                     // end of map()
  .join``               // join everything

```

# Answer
> 2 votes
# perl -p, 52 50 bytes

```
s/./$&1/g;1while s/(\D)\K(\d+)(.*)\1\d/($2+1).$3/e

```

Try it online!

Starts off by adding 1 to each character. Then, as often as possible, find a letter followed by a number, with the same letter elsewhere in the string followed by a digit (which has to be 1). Increment the count, and remove the same letters followed by its 1.

Initial solution, following a very different technique:

# perl -nF//, 52 bytes

```
$F{$_}++for@F;$F{$_}&&print$_,$F{$_}xor$F{$_}=0for@F

```

Try it online!

Reads a line from `STDIN`, assuming it's **not** newline terminated.

Splits the input into characters, available (in order), in `@F` (due to the `-F//`). Counts the occurrence of each character in the hash `%F`. Then loops over `@F`: if present in `%F` with a true value, print the character and its count, then set the corresponding entry in `%F` to 0. This ensures each character is only outputted once.

The TIO code has some header and footer code so we can handle multiple test inputs. They're not needed if we just have one line of input.

# Answer
> 2 votes
# C (gcc), ~~105~~ \\$\cdots\\$~~93~~ 90 bytes

Saved ~~2~~ 5 bytes from the man himself Arnauld!!!

```
d;c;f(char*s){for(;d=1,c=*s;c-1&&printf("%c%d",c,d))for(char*q=s++;*++q;d+=*q==c?*q=1:0);}

```

Try it online!

# Answer
> 2 votes
# Brachylog, 5 bytes

```
ọ∋∋w⊥

```

Try it online!

Full program, or alternatively a predicate which prints the output then fails. Could be one byte shorter if it could generate the characters as a mix of strings and integers, but that seems like a bit too far out there of an output format.

```
   w     Print (without a newline)
  ∋      an element of
 ∋       an element of
ọ        a list of pairs [element, # of occurrences] in order of first appearance,
    ⊥    then try it again some other way.

```

# Answer
> 2 votes
# AWK \+ `-F ''`, 65 + 4 = 69 bytes

```
{while(i++<NF)if(!a[$i]++)b[i]=$i;while(j++<i)printf b[j]a[b[j]]}

```

Try it at awk.js.org

A shorter ~~64~~ 59+4 byte program, which runs on GNU awk with `-F ''`, is this:

```
{while(i++<NF)if(!a[$i]++)b[i]=1;for(i in b)printf$i a[$i]}

```

Annoyingly, though, while 'Try it online' links to the GNU awk manual page, it doesn't seem to use GNU awk, and refuses the `-F ''` command-line option.

The alternative link above (to awk .js.org) accepts the command-line option, but then outputs in a different order, which costs a frustrating additional ~~one~~ six bytes to correct (which I have included above as the price of verifiability).

# Answer
> 2 votes
# CJam, 12 bytes

Port of the Pyth answer.

```
q:A_&{_Ae=}%

```

Try it online!

## Explanation

```
q            Take the whole input
 :A          Assign to a variable
   _&        Set union w/ itself
     {    }% Map:
      _          Join the uniquified character
       Ae=       With the count of the character in the input string.

```

# CJam, 16 bytes

CJam has the built-in, so I guess it simplifies the question. Unfortunately the built-in does it in the wrong order...

```
q:A{A#}$e`{-1%}%

```

Try it online!

# Answer
> 2 votes
# Perl 5 `-p`, 28 bytes

```
s|.|($b=s/$&//g)?$&.$b:''|ge

```

Try it online!

# Answer
> 2 votes
# Ruby 2.7 -paF|, 17 bytes

```
$_=[*$F.tally]*''

```

Try it online!

This is more or less built in to the recent Ruby release as the `tally` method.

# Answer
> 2 votes
# K4 ~~17~~ 16 bytes

**Solution:**

```
{,/(?x),'$#:'=x}

```

**Examples:**

```
q)k){,/(?x),'$#:'=x}"potato"
"p1o2t2a1"
q)k){,/(?x),'$#:'=x}"pqwertyuiop"
"p2q1w1e1r1t1y1u1i1o1"
q)k){,/(?x),'$#:'=x}"thisisanexample"
"t1h1i2s2a2n1e2x1m1p1l1"
q)k){,/(?x),'$#:'=x}"oreganoesque"
"o2r1e3g1a1n1s1q1u1"
q)k){,/(?x),'$#:'=x}"aaaaaaabaaaaaa"
"a13b1"

```

**Explanation:**

```
{,/(?x),'$#:'=x} / the solution
{              } / lambda function taking implicit 'x' argument
             =x  / group x (dict of unique chars => indices)
          #:'    / count length of each group
         $       / cast to string
       ,'        / join each-both
   (  )          / do this together
    ?x           / distinct x
 ,/              / flatten

```

# Answer
> 2 votes
# , ~~72~~ 71 bytes

```
cat(rbind(z<-unique(y<-el(strsplit(scan(,""),""))),table(y)[z]),sep="")

```

Try it online!

# Answer
> 1 votes
# JavaScript (V8), ~~106~~ 102 bytes

```
e=>{for(o="",i=0;i<e.length;i++)o.includes(e[i])||(o+=e[i]+e.match(RegExp(e[i],"g")).length);return o}

```

Try it online!

# Answer
> 1 votes
# Gaia, 9 bytes

```
u$:@$C¦Z$

```

Try it online!

There's a bug or a mis-description of  in the documentation:

> Push an extra copy of the arguments in swapped order, then run the operator. This only alters the behaviour of dyads.

While the description for  reads:

> Push an extra copy of the arguments before executing the operator.

Unfortunately,  only swaps the order of the arguments rather than pushing a swapped copy, otherwise `$:uC¦ₔZ$` would be 8 bytes.

# Answer
> 1 votes
# T-SQL, 111 bytes

Added a line change to make it readable

```
WHILE @+@ like'_[a-z]%'
SELECT @=concat(s,left(@,1),len(@)-len(s))FROM(SELECT
replace(@,left(@,1),'')s)s
PRINT @

```

**Try it online**

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 96 bytes

```
	I =INPUT
N	I LEN(1) . X	:F(O)
	N =
S	I X =	:F(B)
	N =N + 1	:(S)
B	O =O X N	:(N)
O	OUTPUT =O
END

```

Try it online!

```
	I =INPUT		;* Read input, set to I
N	I LEN(1) . X	:F(O)	;* Get the first character of I as X; if I is empty then goto O
	N =			;* set N to empty string (evaled as 0 in arithmetic)
S	I X =	:F(B)		;* remove the first occurrence of X from I. If none exist, goto B
	N =N + 1	:(S)	;* increment N and goto S
B	O =O X N	:(N)	;* Add to the output string and goto N to get the Next character
O	OUTPUT =O		;* print the result
END

```

# Answer
> 1 votes
# Pyth, ~~8~~ 7 bytes

*-1 byte thanks to @isaacg*

```
s+R/Qd{

```

Try it online!

```
s+R/Qd{
      {  Deduplicate: keep the first occurrence of each unique character
  R      For each of these unique characters:
 +        - append the character
   /Qd    - to its count in the original input
s        Join the resulting strings

```

# Answer
> 1 votes
# Stax, 7 bytes

```
ô!Ω;òá☺

```

Run and debug it

# Answer
> 1 votes
# Retina 0.8.2, 31 bytes

```
+`(.)(.+)\1
$1$1$2
(.)\1*
$1$.&

```

Try it online! Link includes test cases, unusually without even needing a header. Explanation:

```
+`(.)(.+)\1
$1$1$2

```

Collect all repeated characters into a single run at the first appearance.

```
(.)\1*
$1$.&

```

Replace each run with its first character and its length.

# Answer
> 1 votes
# Charcoal, 14 bytes

```
⭆Φθ¬№…θκι⁺ι№θι

```

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

```
  θ             Input string
 Φ              Filter over characters
    №           Count of
        ι       Current character in
      θ         Input string
     …          Truncated to length
       κ        Current index
   ¬            Is zero
⭆               Map over unique characters and join
          ι     Current character
         ⁺      Concatenated with
           №    Count of
             ι  Current character in
            θ   Input string
                Implicitly print

```

# Answer
> 1 votes
## Kotlin, ~~69~~ 67 bytes

```
fun String.f()=groupBy{it}.map{(a,b)->"$a"+b.size"}.joinToString("")

```

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 57 bytes

```
s=>s.GroupBy(c=>c).Aggregate("",(r,g)=>r+g.Key+g.Count())

```

Try it online!

# Answer
> 1 votes
# SimpleTemplate, ~~54~~ 47 bytes

This was a very easy, but incredibly fun challenge!

The code simply loops through every character and counts how many times it shows, and presents it all again.
Nothing fancy at all...

```
{@eachargv.0}{@incR.[_]}{@/}{@eachR}{@echo__,_}

```

Hey, I didn't say the code was readable!

---

Here's an ungolfed and readable version:

```
{@each argv.0 as char}
    {@inc by 1 result.[char]}
{@/}
{@each result as times key char}
    {@echo char, times}
{@/}

```

Should be easy to understand ...
`{@inc}` increments the value or creates a new one, if it doesn't exist. (this keeps key ordering).

---

You can try this on http://sandbox.onlinephpfunctions.com/code/a180782e659c29674fbb0d77dc82d90d238c6e08
Older version: http://sandbox.onlinephpfunctions.com/code/6ee5077eaf38ec445d84086cc07966026ca7c565

(There, you have an example on how to use this in a function, with multiple tests.)

# Answer
> 1 votes
# Husk, 8 bytes

```
ṁS:os#¹u

```

Try it online!

# Husk, 9 bytes

```
ṁ§:←osLk=

```

Try it online!

# Answer
> 1 votes
# Thunno 2 `J`, 1 byte

```
ƈ

```

Try it online!

LOL! Let me explain...

The `ƈ` built-in gets the count of each unique element in a list or string:

* For `"potato"` it gives `[["p",1], ["o",2], ["t",2], ["a",1]]`
* For `"aaaaaaabaaaaaa"` it gives `[["a",13], ["b",1]]`

Now this happens to be almost *exactly* what we need. The only thing left is just to join everything into a string, which is what the `J` flag does.

# Answer
> 1 votes
# Arturo, 24 bytes

```
$=>[tally&|map=>as|join]

```

Try it!

```
$=>[           ; a function where input is assigned to &
    tally&     ; create dictionary of occurrences in input
    |          ; then
    map=>as    ; convert to a block
    |          ; then
    join       ; join to a string
]              ; end function

```

# Answer
> 0 votes
# Perl 5 \+ `-pF -MList::Util+uniq`, 29 bytes

```
for$s(uniq@F){$\.=$s.s/$s//g}

```

Try it online!

# Answer
> 0 votes
# Japt `-P`, ~~10~~ 8 bytes

Would be 7 in Japt v2 but for a bug that costs 2 bytes to workaround.

```
¬â Ë+UèD

```

Try it

# Answer
> 0 votes
# Arn, 9 bytes

```
yŽ▬ö░Ú^`"

```

Try it!

# Explained

Unpacked: `|{:{|#}\:@`

```
     _         Variable initialized to STDIN; implied
  :@           Grouped by frequency
|{      }\     Folded with concatenation after mapping (key of _)
     :{        First entry
   |           Concatenated with
     #         Length

```

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


title: lwap She tirst fetters!

text:
# Question
Title: lwap She tirst fetters!
Given a list or delimited string, output a list or delimited string with the first character of each word one word later.

For this challenge, a "word" consists of only all printable ASCII characters, except the space, newline, and tab character.

For example, take the string "Good afternoon, World!" (space-delimited):

```
1. String
"Good afternoon, World!"

2. Get the first characters:
"[G]ood [a]fternoon, [W]orld!"

3. Move the characters over. The character at the end gets moved to the beginning.
"[W]ood [G]fternoon, [a]orld!"

4. Final string
"Wood Gfternoon, aorld!"

```

This is , so shortest code wins!

**Test cases:**

```
Input -> output (space-delimited)

"Good afternoon, World!" -> "Wood Gfternoon, aorld!"
"This is a long sentence." -> "shis Ts i aong lentence."
"Programming Puzzles and Code Golf" -> Grogramming Puzzles Pnd aode Colf"
"Input -> output" -> "onput I> -utput"
"The quick brown fox jumped over the lazy dog." -> "dhe Tuick qrown box fumped jver ohe tazy log."
"good green grass grows." -> "good green grass grows."

```

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
€ćÁ2ôJ

```

Explanation:

```
€ć      Extract head of each
  Á     Rotate to the right
    2ô  Split into pieces of length two
      J Join

```

Try it online!
> 10 votes

# Answer
# Japt, ~~11~~ ~~10~~ ~~9~~ 8 bytes

Takes advantage of Japt's index wrapping and negative indexing.

```
ËhUgEÉ g

```

Try it online

---

## Explanation

```
        :Implicit input of array U (each element is an individual word).
Ë       :Map over the array.
h       :Replace the first character of the current element (word) ...
Ug      :  with the word in the array at index ...
EÉ      :    current index (E) -1's ...
g       :  first character.
        :Implicit output of array of modified words

```
> 9 votes

# Answer
# Haskell, 43 bytes

```
p%((a:b):r)=(p:b):a%r
_%e=e
(%)=<<head.last

```

Try it online! Uses a list of strings for input and output.

Remembers the first letter of the previous word `p`, and recursively makes it the first letter of the current word while sending the new first letter down the chain. The previous first letter is initialized as the first letter of the last word.
> 6 votes

# Answer
# Ruby, ~~85~~ ~~77~~ 63 bytes

Pretty sure this could be much shorter.

Edit: Thanks for @manatwork for collect -\> map

```
a=gets.split;$><<a.zip(a.rotate -1).map{|x,y|y[0]+x[1..-1]}*' '

```
> 4 votes

# Answer
# CJam, ~~12~~ ~~10~~ 9 bytes

Saved 1 byte thanks to jimmy23013

```
q~Sf+:()o

```

Takes input as a list of words.

Try it online!

### Explanation

```
     e# Example input: ["Good" "afternoon," "World!"]
q~   e# Read and eval the input.
     e# STACK: [["Good" "afternoon," "World!"]]
Sf+  e# Append a space to each word.
     e# STACK: [["Good " "afternoon, " "World! "]]
:(   e# Remove the first character from each substring.
     e# STACK: [["ood " 'G "fternoon, " 'a "orld! " 'W]]
)o   e# Remove and print the last element of the array.
     e# STACK: [["ood " 'G "fternoon, " 'a "orld! "]]
     e# Implicitly join the remaining array with no separator and output.

```
> 4 votes

# Answer
# Jelly, 6 bytes

```
Ḣ€ṙ-;"

```

Try it online!

Thanks to Dennis for reading the rules better than me, this returns a list of the words. It doesn't work as a full program.
> 4 votes

# Answer
## JavaScript (ES6), 46 bytes

```
s=>s.map((k,i)=>s.slice(i-1)[0][0]+k.slice(1))

```

Takes advantage of the fact that `slice(-1)` returns the last element of an array.

**Snippet**

```
f =

s=>s.map((k,i)=>s.slice(i-1)[0][0]+k.slice(1))

console.log(f(['Good', 'afternoon,', 'World!']));
console.log(f(['This', 'is', 'a', 'long', 'sentence.']));
console.log(f(['Programming', 'Puzzles', 'and', 'Code', 'Golf']));
console.log(f(['Input', '->', 'output']));
console.log(f(['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog.']));
console.log(f(['good', 'green', 'grass', 'grows.']));
```
> 4 votes

# Answer
# Vim, ~~16~~, 9 bytes

```
<C-v>GdjPGD{P

```

*7 bytes saved thanks to @Wossname!*

Takes input one word per line, e.g.

```
Hello
world
and
good
day
to
you

```

I believe this should be fine since taking the input as a list is allowed.

Try it online!
> 3 votes

# Answer
# , 7 bytes

```
Îxjp
{P

```

Try it online!

Explanation:

```
Î       " On every line:
 x      "   Delete the first character
  j     "   Move down a line
   p    "   And paste a character (into column 2)
{       " Move to the beginning of the input
 P      " And paste the last thing we deleted (into column 1)

```
> 3 votes

# Answer
# \>\<\>, ~~44~~ 45 bytes

```
90.f3+0.>&i&01.>~r&l0=?;o20.
 i:" "=?^:1+ ?!^

```

Assumes space-separated words.

Correction by Aaron added 1 byte
> 3 votes

# Answer
# APL (Dyalog), 6 bytes

Takes matrix with one word per column.

```
¯1∘⌽@1

```

Try it online!

`¯1∘⌽` rotate one step right

`@` at

`1` row 1
> 3 votes

# Answer
## Python 2, 74 bytes

Try it online

```
S=input().split()
print' '.join(b[0]+a[1:]for a,b in zip(S,S[-1:]+S[:-1]))

```

-5 bytes, thanks to @Rod
> 2 votes

# Answer
# Haskell, 50 bytes

```
f=zipWith(:).((:).last<*>init).map head<*>map tail

```

Input and output are as lists of words.
> 2 votes

# Answer
# R, ~~72~~ 70 bytes

`function(x)paste0(substr(x,1,1)[c(y<-length(x),2:y-1)],substring(x,2))`

Try it online

2 bytes saved thanks to Giuseppe.

Input and output are lists. Takes a substring consisting of the first letters, cycles the last one to the front, and pastes it together with a substring of the rest of each word. The cycling step is a killer, but I can't figure out a way to cut it down any further.
> 2 votes

# Answer
## Python 2 + Numpy, 104 bytes

```
from numpy import *
s=fromstring(input(),"b")
m=roll(s==32,1)
m[0]=1
s[m]=roll(s[m],1)
print s.tobytes()

```
> 2 votes

# Answer
# PHP, 62 bytes

```
$c=end($_GET);foreach($_GET as$g)echo$g|$g[0]=$c^$g^$c=$g,' ';

```
> 2 votes

# Answer
# C#, ~~78~~ 77 bytes

```
using System.Linq;a=>a.Select((s,i)=>a[i-->0?i:a.Count-1][0]+s.Substring(1));

```

Compiles to a `Func<List<string>, IEnumerable<string>>`, Full/Formatted version:

```
using System;
using System.Collections.Generic;
using System.Linq;

class P
{
    static void Main()
    {
        Func<List<string>, IEnumerable<string>> f = a =>
                a.Select((s, i) => a[i-- > 0 ? i : a.Count - 1][0] + s.Substring(1));

        Console.WriteLine(string.Join(" ", f(new List<string>() { "Good", "afternoon,", "World!" })));
        Console.WriteLine(string.Join(" ", f(new List<string>() { "This", "is", "a", "long", "sentence." })));

        Console.ReadLine();
    }
}

```
> 2 votes

# Answer
# Brachylog, 12 bytes

```
{hᵐ↻|bᵐ}ᶠzcᵐ

```

Try it online!

### Explanation

```
Example input: ["Good","afternoon,","World!"]

{      }ᶠ       Find: [["W","G","a"],["ood","fternoon,","orld!"]]
 hᵐ↻              Take the head of each string, cyclically permute them
    |             (and)
     bᵐ           Get the strings without their heads
         z      Zip: [["W","ood"],["G","fternoon,"],["a","orld!"]]
          cᵐ    Map concatenate on each list: ["Wood","Gfternoon,","aorld!"]

```
> 2 votes

# Answer
# Fig, \\$13\log\_{256}(96)\approx\\$ 10.701 bytes

```
j/ +e[qJ]xxep

```

*-2.469 bytes thanks to one of the @Sʨɠɠans*

Try it online!

Explanation:

```
       J       # Append
          x    # the input
        ]x     # to the first item from the input,
      q        # then remove the first item from that.
    e[         # Get the first character from each item.
           ep  # Get the input with the first char of each word removed.
   +           # Add,
j              # join by
 /             # space

```
> 2 votes

# Answer
# Retina, ~~46~~ ~~37~~ 31 bytes

*Several bytes saved thanks to @Neil and @PunPun1000*

```
(\S)(\S* +)
$2$1
(.* .)(.)
$2$1

```

Try it online!
> 1 votes

# Answer
# kdb+, ~~25~~ 22 bytes

**Solution:**

```
rotate[-1;1#'a],'1_'a:

```

**Example:**

```
q)rotate[-1;1#'a],'1_'a:("The";"quick";"brown";"fox";"jumped";"over";"the";"lazy";"dog.")
"dhe"
"Tuick"
"qrown"
"box"
"fumped"
"jver"
"ohe"
"tazy"
"log."

```

**Explanation:**

```
1_'a:             // (y) drop first character of each element of a
,'                // join each left with each right
rotate[-1;1#'a]   // (x) take first character of each element of a, rotate backwards 1 char

```

**Extra:**

A version that takes a regular string (37 bytes):

```
q){" "sv rotate[-1;1#'a],'1_'a:" "vs x}"The quick brown fox jumped over the lazy dog."
"dhe Tuick qrown box fumped jver ohe tazy log."

```
> 1 votes

# Answer
## Mathematica, 59 bytes

```
""<>#&/@Thread@{RotateRight@#~StringTake~1,#~StringDrop~1}&

```

Try it online!

Takes and returns a list of words.

If you prefer to take and return strings, this works for 87 bytes:

```
StringRiffle[Thread@{RotateRight@#~StringTake~1,#~StringDrop~1}&@StringSplit@#," ",""]&

```
> 1 votes

# Answer
# Perl 5, 40 bytes

39 bytes of code + 1 for `-a`

```
$F[-1]=~/./;$a=$&,s/./$a/ for@F;say"@F"

```

Try it online!
> 1 votes

# Answer
# , 34 bytes

```
;@(,.~_1|.])~/@|:@(split;.2)@,&' '

```

Try it online!
> 1 votes

# Answer
# Husk, 11 bytes

```
Foz:ṙ_1TmΓ,

```

Input and output as a list of strings, try it online!

<sub>(The header just transforms the input to a list of words and joins the output list with spaces.)</sub>

### Explanation

```
F(z:ṙ_1)TmΓ,  -- example input: ["Good" "afternoon,","World!"]
         m    -- map the following (example on "Good")
          Γ   -- | pattern match head & tail: 'G' "ood"
           ,  -- | construct tuple: ('G',"ood")
              -- : [('G',"ood"),('a',"fternoon,"),('W',"orld!")]
        T     -- unzip: ("GaW",["ood","fternoon,","orld!"])
F(     )      -- apply the function to the pair
    ṙ_1       -- | rotate first argument by 1 (to right): "WGa"
  z:          -- | zip the two by (example with 'W' and "ood")
              -- | | cons/(re)construct string: "Wood"
              -- :-: ["Wood","Gfternoon,","aorld!"]

```

### Alternative, 11 bytes

```
§oz:ṙ_1m←mt

```

Try it online!
> 1 votes

# Answer
# Vyxal `S`, 7 bytes

```
vhǔ?vḢ+

```

Try it online!

```
vh       # Get the first item of each
  ǔ      # Rotate to the right
   ?     # Push the input
    vḢ   # Get the all but the first char of each
      +  # Add

```
> 1 votes

# Answer
## Retina, ~~25~~ 20 bytes

Byte count assumes ISO 8859-1 encoding.

```
Om$`^.((?=.*¶))?
$#1

```

Try it online!

Input and output are linefeed-separated. The test suite performs the necessary I/O conversion from space-separation.
> 0 votes

# Answer
## Mathematica, 134 bytes

```
(w=Characters@StringSplit@#;d=Drop[w,0,1];StringRiffle[StringJoin/@Table[PrependTo[d[[i]],RotateRight[First/@w][[i]]],{i,Length@w}]])&

```
> 0 votes

# Answer
# C, ~~106~~ 77 bytes

```
i,a,b;f(char*o){a=*o;for(i=0;o[i++];)if(o[i]==32){b=o[++i];o[i]=a;a=b;}*o=a;}

```

-29 bytes from scottinet

Modifies the string in-place.

Ungolfed:

```
char *f(char *o){
    char a=*o,b; // start with a as the first character of the first word
    for(int i=0;++i<strlen(o);){
        // iterate through the string with i as the index
        if(o[i]==32){ // if the current character is a space,
                      // i.e. if a word begins after this character
            b=o[++i]; // store the beginning of the next word in b
            o[i]=a; // set the beginning of the next word to a
            a=b; // set a to what the beginning of the next work used to be
        }
    }
    *o=a;
    // set the beginning of the first word to the old beginning of the last word
}
```
> 0 votes

# Answer
# Pyth, 12 bytes

```
.b+hNtY.>Q1Q

```

Takes a list of words and returns a list of words.

Try it!
> 0 votes

# Answer
# Java (OpenJDK 8), 97 bytes

```
for(int n=s.length,i=0,j=n-1;i<n;j%=n)System.out.print(s[j++].charAt(0)+s[i++].substring(1)+" ");

```

Try it online!
> 0 votes

# Answer
# AWK, 63 bytes

```
{for(R=substr($NF,1,1);++j<=NF;R=r)sub(r=substr($j,1,1),R,$j)}1

```

Try it online!

It seems like there should be a way to reduce the redundancy, but I'm not seeing it.

Note: the TIO link has 4 extra bytes to allow for multiline input.
> 0 votes

# Answer
# Python 3, 73 bytes

```
lambda s:' '.join(s.split()[i-1][0]+w[1:]for i,w in enumerate(s.split()))

```

Try it online!
> 0 votes

# Answer
# Rust, 129 bytes

```
|k:&str|k.split(' ').zip(k.split(' ').cycle().skip(k.matches(' ').count())).map(|(a,b)|[&b[0..1],&a[1..]," "].concat()).collect()

```

Attempt This Online!

Shifting the other direction would be a *lot* shorter.
> 0 votes

# Answer
# Thunno 2 , 5 bytes

```
€ḢṾ2ẇ

```

Try it online!

Port of Okx's 05AB1E answer.

#### Explanation

```
€ḢṾ2ẇ  # Implicit input
€Ḣ     # Head extract from each
  Ṿ    # Rotate right once
   2ẇ  # Split into pairs
       # Join on spaces
       # Implicit output

```
> 0 votes

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


title: Strange Addition

text:
# Question
Title: Strange Addition
## Challenge

Calculate the strange sum of two natural numbers (also known as lunar addition):

Given \\$A=...a\_2 a\_1 a\_0\\$ and \\$B=... b\_2 b\_1 b\_0\\$ two natural numbers written in the decimal base, the **strange sum** is defined, based on the **maximum** operation, as: \\$A+B=... \max(a\_2,b\_2) \max(a\_1,b\_1) \max(a\_0,b\_0)\\$

```
   ...         a2         a1         a0
 + ...         b2         b1         b0
 ----------------------------------------
   ...  max(a2,b2) max(a1,b1) max(a0,b0)

```

## Input

Two natural numbers

All the following is allowed:

* Zero-padded strings (same length)
* Left-space-padded strings
* Right-space-padded strings
* Array of two padded strings
* 2D space-padded char array

## Output

A natural numbers

## Example

```
1999 + 2018 -> 2999
17210 + 701 -> 17711
32 + 17     -> 37
308 + 250   -> 358
308 + 25    -> 328

```

## Rules

* The input and output can be given in any convenient format (choose the most appropriate format for your language/solution).
* No need to handle **negative** values or **invalid input**
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 17 votes
# Python 2, 20 bytes

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

```

Try it online!

I/O as 0-pre-padded lists of digits.

# Answer
> 14 votes
# Jelly, 1 byte

```
»

```

Try it online!

I/O as 0-pre-padded lists of digits.

# Answer
> 7 votes
# , ~~68~~ 65 bytes

```
function(x)apply(outer(x,10^(max(nchar(x)):1-1),`%/%`)%%10,2,max)

```

Try it online!

Input as integers, output as list of digits.

If zero-padding lists of digits was allowed, then simply `pmax` would suffice.

# Answer
> 6 votes
# MATL, 2 bytes

```
X>

```

> Choose the most appropriate format for your language/solution

The input format is: 2D char array of two rows, each corresponding to a line, with the shorter number left-padded with spaces. For example

```
17210
  701

```

which in MATL is defined as

```
['17210'; '  701']

```

Try it online!

### Explanation

```
      % Implicit input: 2D char array with two rows
X>    % Take maximum of (code points of) each column
      % Implicit display

```

# Answer
> 5 votes
# Python 2, ~~73~~ ~~60~~ 56 bytes

```
lambda a,b:map(max,zip(a.rjust(len(b)),b.rjust(len(a))))

```

Try it online!

Takes input as two strings, and returns a list of digits

---

Alternative:

Takes input as two integers; same output

# Python 2, ~~60~~ 59 bytes

```
lambda*i:map(max,zip(*['%*d'%(len(`max(i)`),v)for v in i]))

```

Try it online!

# Answer
> 5 votes
# Java 10, ~~78~~ 57 bytes

```
a->b->{for(int i=a.length;i-->0;)if(a[i]<b[i])a[i]=b[i];}

```

Input as two space-padded character arrays.

Modifies the first input-array instead of returning a new one to save 21 bytes (thanks to *@OlivierGrégoire*).

Try it online.

**Explanation:**

```
a->b->{            // Method with two char-array parameters and String return-type
  for(int i=a.length;i-->0;)
                   //  Loop `i` in the range (length, 0]:
    if(a[i]<b[i])  //   If the `i`'th character in input `a` is smaller than in input `b`:
      a[i]=b[i];}  //    Change the `i`'th character in `a` to the `i`'th character of `b`

```

# Answer
> 4 votes
# , 14  12 bytes

-2 bytes thanks to Jonah

```
(>./@,:)&.|.

```

Try it online!

Input and output as list(s) of digits

# Answer
> 4 votes
# 05AB1E, ~~9 6~~ 5 bytes

-3 thanks to Emigna
-1 thanks to Shaggy

```
íζ€àR

```

Takes input as a list of lists of digits

```
í      # Reverse both inputs
 ζ     # Zip
  €à   # Keep the bigger digits
    R  # Reverse

```

Try it online! or Try all test cases

# Answer
> 4 votes
# Japt, ~~9~~ ~~8~~ 7 bytes

Takes input as an array of digit arrays.

```
mÔÕÔËrw

```

Try it

```
m            :Map
 Ô           :  Reverse
  Õ          :Transpose
   Ô         :Reverse
    Ë        :Map
     r       :  Reduce by
      w      :  Maximum

```

---

If taking zero-padded arrays as input is permitted (it would currently fall under a "convenient format" but I suspect that's not the challenger's intent) then this can be 3 bytes.

```
íwV

```

Try it

```
í       :Interleave the first input
  V     :With the second
 w      :Reduce each pair by maximum

```

# Answer
> 4 votes
# Haskell, 40 bytes

```
a#b=zipWith max(p b++a)$p a++b
p=(' '<$)

```

Input/output as strings, try it online!

### Explanation

The function `p` replaces each character by a space, using `p b++a` and `p a++b` are thus the same length. This way we can use `zipWith` without losing any elements, using `max` with it works because a  (space) has lower codepoint than any of the characters `['0'..'9']`.

# Answer
> 4 votes
# Perl 6, 37 bytes

```
{[R~] roundrobin($_».reverse)».max}

```

Try it online!

Takes input as a list of lists of digits.

# Answer
> 4 votes
# Perl 6, 15 bytes

```
{[~] [Zmax] $_}

```

Try it online!

Takes input as a list of space padded arrays of characters, though for this challenge the lax input format makes it rather boring. Alternatively, here's the program that takes a list of two integers instead:

# Perl 6, 41 bytes

```
{+[~] [Zmax] $_>>.fmt("%{.max}d")>>.comb}

```

Try it online!

If you don't mind a huge amount of whitespace, you can also remove the `+` from the front.

### Explanation:

```
{                                       }  # Anonymous code block
             $_>>    # Map each integer to
                 .fmt("%{.max}d") # The number padded by the max of the list spaces
                                 >>.comb   # And split each to list of characters
      [Zmax]  # Get the max of each digit at each index
              # This works because space is coerced to 0
              # Otherwise we would have to add a 0 to the formatting string
  [~]   # Join the list of digits and spaces
 +      # And coerce the string to a number to get rid of leading whitespace

```

# Answer
> 3 votes
# JavaScript (ES6), ~~51~~ 49 bytes

*NB: This answer was posted before the loose I/O formats were explicitly allowed. With zero-padded arrays of digits, this can be done in 33 bytes, (but is much less interesting, IMHO).*

Takes input as two integers. Returns an integer.

```
f=(a,b,t=10)=>a|b&&(a%t<b%t?b:a)%t+t*f(a/t,b/t)|0

```

Try it online!

### Commented

```
f = (                     // f = recursive function taking:
  a,                      //   a = first integer
  b,                      //   b = second integer
  t = 10                  //   t = 10 (which is used 6 times below)
) =>                      //
  a | b                   // bitwise OR between a and b to test whether at least one of
                          // them still has an integer part
  &&                      // if not, stop recursion; otherwise:
  (                       //
    a % t < b % t ? b : a // if a % 10 is less than b % 10: use b; otherwise: use a
  ) % t +                 // isolate the last decimal digit of the selected number
  t *                     // add 10 times the result of
  f(a / t, b / t)         // a recursive call with a / 10 and b / 10
  | 0                     // bitwise OR with 0 to isolate the integer part

```

### Alternate version

Same I/O format.

```
f=(a,b)=>a|b&&[f(a/10,b/10)]+(a%10<b%10?b:a)%10|0

```

Try it online!

# Answer
> 3 votes
# Python 3, 53 bytes

```
s=lambda p,q:p+q and 10*s(p//10,q//10)+max(p%10,q%10)

```

# Answer
> 2 votes
# Tcl, 156 bytes

```
proc S a\ b {join [lmap x [split [format %0[set l [expr max([string le $a],[string le $b])]]d $a] ""] y [split [format %0$l\d $b] ""] {expr max($x,$y)}] ""}

```

Try it online!

Not very golfy, but I had to give a try on it. Will golf it later!

# Answer
> 2 votes
## Batch, 120 bytes

```
@set/aw=1,x=%1,y=%2,z=0
@for /l %%i in (0,1,9)do @set/a"z+=w*((v=y%%10)+(v-=x%%10)*(v>>4)),y/=10,x/=10,w*=10
@echo %z%

```

Takes input as command-line parameters. 188-byte version works on arbitrary length integers:

```
@set/px=
@set/py=
@set z=
:l
@if %x:~-1% gtr %y:~-1% (set z=%x:~-1%%z%)else set z=%y:~-1%%z%
@set x=%x:~,-1%
@set y=%y:~,-1%
@if "%x%" neq "" if "%y%" neq "" goto l
@echo %x%%y%%z%

```

Takes input on STDIN.

# Answer
> 2 votes
# Twig, 125 bytes

When I saw this challenge, I though: "let me use a template language! sure is a good fit"

I was wrong ... so wrong .... ... But was fun!

```
{%macro a(a,b,s='')%}{%for k,x in a|reverse|split('')%}{%set s=max(x,(b|reverse|split('')[k]))~s%}{%endfor%}{{s}}{%endmacro%}

```

This requires that "strict\_variables" is set to `false` (default value).

To use this macro, you can do like this:

```
{% import 'file.twig' as my_macro %}

{{ my_macro.a(195,67) }}

```

Should display 167.

You can try this in https://twigfiddle.com/rg0biy
("strict\_variables" set to off, it is on by default on the website)

# Answer
> 1 votes
# Husk, 5 bytes

```
↔¤żY↔

```

Conveniently takes input/output as list of digits, try it online or verify all!

## Explanation

```
↔¤żY↔  -- example inputs [1,4] [3,2]
 ¤  ↔  -- reverse the arguments of: [4,1] [2,3]
  żY   -- | zipWith (keeping elements of longer) max: [4,3]
↔      -- reverse: [3,4]

```

# Answer
> 1 votes
# Stax, 5 bytes

```
|>E:o

```

Run and debug it

This program takes input as an array of strings.

```
|>  Right align inputs (filling with \0)
E   "Explode" array onto stack separately
:o  "Overlay" Keep the maximum element respective element from two arrays.

```

Run this one

This is the first time I've seen a use for the overlay instruction "in the wild".

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 153 bytes

```
	X =INPUT
	Y =INPUT
	Y =DUPL(0,SIZE(X) - SIZE(Y)) Y
S	X LEN(1) . A REM . X	:F(O)
	Y LEN(1) . B REM . Y
	O =O GT(A,B) A	:S(S)
	O =O B	:(S)
O	OUTPUT =O
END

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 39 bytes

```
+`^(.*)(.)¶(.*)(.)
$1¶$3¶$2$4
%O`.
¶.?

```

Try it online! Link includes test suite. Previous 45-byte Retina 1 version accepts unpadded strings:

```
P^`.+
+`^(.*)(.)¶(.*)(.)
$1¶$3¶$2$4
%O`.
¶.?

```

Try it online! Link includes test suite. Explanation:

```
P^`.+

```

Pad both values to the same length. (Retina 1 only. There are ways of emulating this in Retina 0.8.2 but they are not very golfy.)

```
+`^(.*)(.)¶(.*)(.)
$1¶$3¶$2$4

```

Transpose the values.

```
%O`.

```

Sort each pair into order.

```
¶.?

```

Delete all the low digits and surplus newlines.

# Answer
> 1 votes
# Charcoal, 8 bytes

```
⭆θ⌈⟦ι§ηκ

```

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

```
 θ          First input
⭆           Map over characters and join
  ⌈         Maximum of
   ⟦        List of
    ι       Current character of first input and
      η     Second input
     §      Indexed by
       κ    Current index
            Implicitly print

```

10-byte version "adds" any number of padded strings:

```
⭆§θ⁰⌈Ｅθ§λκ

```

Try it online! Link is to verbose version of code. Previous 14-byte version accepts unpadded strings:

```
⭆◧θＬη⌈⟦ι§◧ηＬθκ

```

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

```
  θ             First input
 ◧              Padded to
   Ｌ            Length of
    η           Second input
⭆               Map over characters and join
     ⌈          Maximum of
      ⟦         List of
       ι        Current character of first input and
          η     Second input
         ◧      Padded to
           Ｌ    Length of
            θ   First input
        §       Indexed by
             κ  Current index
                Implicitly print

```

17-byte version "adds" any number of strings:

```
≔⌈ＥθＬιη⭆η⌈Ｅθ§◧ληκ

```

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

# Answer
> 1 votes
# Pyth, 5 bytes

```
meSdC

```

Takes input as array of two space-padded strings.

```
meSd       map greatest
    C      on the transpose of input

```

Try it here.

# Answer
> 1 votes
# C# (.NET Core), 57 bytes

```
a=>b=>a.Select((x,i)=>a[i]>b[i]?x:b[i])

```

*-1 bytes by adding currying*

Try It Online

# Answer
> 1 votes
# Japt, 4 bytes

Input is taken as a an array of two 0-padded number arrays.

```
y_rw

```

Try it online!

# Answer
> 1 votes
# Ceylon, 55 / 99

With 0- or space-padded strings of same length (returning an iterable of characters):

```
function t(String a,String b)=>zipPairs(a,b).map(max);

```

With 0- or space-padded strings (returning a String):

```
String t(String a,String b)=>String(zipPairs(a,b).map(max));

```

With strings of possibly different length (returning a String):

```
String u(String a,String b)=>String(zipPairs(a.padLeading(b.size),b.padLeading(a.size)).map(max));

```

# Answer
> 1 votes
# Ruby, 25 bytes

```
->a,b{a.zip(b).map &:max}

```

Try it online!

Pre-padded list blah blah. (Although it feels a little like cheating.)

# Answer
> 1 votes
# Wren, 74 bytes

```
Fn.new{|i|(0...i.count/2).map{|j|i[j]>i[j+i.count/2]?i[j]:i[j+i.count/2]}}

```

Try it online!

Input is a single list of the two operands, e.g.

```
[1, 7, 2, 1, 0,
 0, 0, 7, 0, 1]

```

## Explanation

Now I need to figure out a formula for maximum.

```
Fn.new{|i|                                                               } // New anonymous function with the operand i
          (0...i.count/2)                                                  // Define an exclusive range from 0 to half the input
                         .map{|j|                                       }  // Turn every item of the list into ...
                                 i[j]>i[j+i.count/2]?i[j]:i[j+i.count/2]   // ... The maximum between i[j] and i[j+i.count/2]
                                                                           // (which is simply the other list's index at the same position)

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=max -F`, 22 bytes

```
say map{max $_,getc}@F

```

Try it online!

Input must be 0 or space padded so that the entries are the same length.

# Answer
> 1 votes
# APL(NARS), 51 chars, 102 bytes

```
{k←⌈/≢¨(a b)←⍎¨∘⍕¨⍺⍵⋄f←{((k-≢⍵)⍴0),⍵}⋄10⊥(f a)⌈f b}

```

test:

```
  h←{k←⌈/≢¨(a b)←⍎¨∘⍕¨⍺⍵⋄f←{((k-≢⍵)⍴0),⍵}⋄10⊥(f a)⌈f b}
  1999 h 2018
2999
  17210 h 701
17711
  32 h 17
37
  308 h 250
358
  308 h 25
328

```

# Answer
> 1 votes
# Pip, 13 bytes

```
{aGTb?ab}MZab

```

Maps zipped pairs of the two inputs and then returns the greater one.

Inputs must be padded with spaces.

Try it online!

# Answer
> 1 votes
# Knight, 45 bytes

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

```

Try it online!

Takes two zero-padded numbers (it works with spaces as well).

# Answer
> 0 votes
# Factor, 4 bytes

```
vmax

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 1 byte

```
§

```

Try it online!

I/O as pre-padded lists of digits. Built-in for "dyadic maximum".

---
Tags: code-golf, math, arithmetic
---


title: Manage Trash So

text:
# Question
Title: Manage Trash So
It's become somewhat of a tradition in PPCG that some users temporarily change their names by an anagram (a new name formed by reordering the letters of the old).

Sometimes it gets difficult to find out who is who. I could use a program or function to tell if two phrases are anagrams of each other.

### The challenge

The program or function should take two strings and produce a truthy result if they are anagrams of each other, and falsy otherwise.

### Rules

* Input will only contain letters (ASCII 65 to 90 and 97 to 122), digits (ASCII 48 to 57) or space (ASCII 32).
* The anagram relation is independendent of case. So "Arm" and "RAM" are anagrams.
* Spaces don't count either. So "keyboard" and "Barked Yo" are anagrams
* All builtins allowed
* Input format is flexible (two strings, an array of two strings, a string containing both phrases with a suitable separator ...)

Code golf. Fewest bytes wins.

### Test cases

Truthy:

```
Lynn, Nyl N
Digital Trauma, Tau Digital Arm
Sp3000, P S 3000
Manage Trash So, Those anagrams

```

Falsy

```
Calvins Hobbies, Helka Homba
Android, rains odd
In between days, bayed entwine
Code golf, cod elf got

```

# Answer
> 14 votes
# 05AB1E, ~~9~~ 8 bytes

Code:

```
lvyð-{}Q

```

Explanation:

```
l         # Lowercase the strings
 vy   }   # Map over the list, for each...
   ð-     #   remove spaces
     {    #   and sort
       Q  # Check equality

```

Try it online!

# Answer
> 15 votes
# Retina, 25

```
i+`(\w)(.*,.*)\1
$2
^\W*$

```

Try it Online! Additionally, you can run a modified multi-line version.

Delete letters from before the comma along with their matches after the comma. If we have no letters left then it was an anagram.

# Answer
> 11 votes
# Pyth, ~~11~~ 10 bytes

Thanks to @FryAmTheEggman for teaching me the power of `;`!

```
qFmSr-d;0Q

```

Try it here!

Takes a list of two strings as input.

## Explanation

```
qFmSr-d;0Q    # Q = input

  m      Q    # map Q with d as lambda variable
     -d;      # filter spaces out of the string
    r   0     # convert to lowercase
   S          # sort all characters in string
qF            # Unfold resulting list and check for equality

```

# Answer
> 10 votes
# Python 2, ~~63~~ 61 bytes

```
lambda*l:len({`sorted(s.lower())`[2::5].strip()for s in l})<2

```

An anonymous function that, in fact, takes *n* arguments and determines if all *n* of them are mutual palindromes! `f("Lynn", "Nyl N")` returns `True`.

This set comprehension trick is by xnor. It saved two bytes, but the old approach looked very neat:

```
exec"a=`sorted(input().lower())`[2::5].strip();a"*2;print a==aa

```

# Answer
> 7 votes
# Jelly, 12 bytes

```
ḟ€⁶O&95Ṣ€QLḂ

```

Try it online!

### How it works

```
ḟ€⁶O&95Ṣ€QLḂ  Main link. Input: A (list of strings)

  ⁶           Yield ' '.
ḟ€            Filter it from each string.
   O          Apply ordinal to all characters.
    &95       Take bitwise AND with 95 to make the ordinals case-insensitive.
       Ṣ€     Sort each list of ordinals.
         Q    Deduplicate the list.
          L   Get the length.
           Ḃ  Compute the length's parity (1 -> 1, 2 -> 0).

```

## Alternate version (9 bytes)

Jelly's uppercase atom had a bug, and Jelly still had no built-in to test lists for equality...

```
ḟ⁶ŒuṢµ€⁼/

```

Try it online!

### How it works

```
ḟ⁶ŒuṢµ€⁼/     Main link. Input: A (list of strings)

     µ€       Map the chain to the left over A.
 ⁶            Yield ' '.
ḟ             Filter it from the string.
  Œu          Cast to uppercase.
    Ṣ         Sort.
       ⁼/     Reduce by equality.

```

# Answer
> 6 votes
# MATL, 11 bytes

```
2:"jkXvS]X=

```

*EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.*

**Try it online!**

```
2:"     ]       % do this twice
   j            % read input line as a string
    k           % convert to lowercase
     Xv         % remove spaces
       S        % sort
         X=     % are they equal?

```

# Answer
> 6 votes
# Javascript, ~~69~~ ~~61~~ ~~60~~ 59 bytes

1 byte off thanks @ӍѲꝆΛҐӍΛПҒЦꝆ. 1 byte off with currying (pointed out by @apsillers)

```
n=>m=>(G=s=>[]+s.toLowerCase().split(/ */).sort())(n)==G(m)

```

```
f=n=>m=>
    (G=s=>[]+s.toLowerCase()
        .split(/ */)
        .sort()
    )(n)==G(m)

F=(n,m)=>document.body.innerHTML+=`<pre>f('${n}')('${m}') -> ${f(n)(m)}</pre>`

F('Luis Mendo','Don Muesli')
F('Calvins Hobbies','Helka Homba')
F('Android','rains odd')
F('In between days','bayed entwine')
F('Code golf','cod elf got')
F('Lynn','Nyl N')
F('Digital Trauma','Tau Digital Arm')
F('Sp3000','P S 3000')
F('Manage Trash So','Those anagrams')
```

# Answer
> 6 votes
# CJam, 11 ~~12~~ ~~14~~ bytes

*3 ~~2~~ bytes removed thanks to @FryAmTheEggman*

```
{lelS-$}2*=

```

**Try it online!**

```
{      }2*       e# do this twice
 l               e# read line as a string
  el             e# make lowercase
    S-           e# remove spaces from string
      $          e# sort
          =      e# compare strings

```

# Answer
> 4 votes
## Seriously, ~~11~~ 9 bytes

```
2`,ùSô`n=

```

Try It Online!

Everyone seems to be using the same algorithm. Here it is yet again.

```
2`    `n          Do it twice
  ,               Read a string
   ù              Make it lowercase
    S             Sort
     ô            Strip spaces.
        =         Check equality.

```

Edit: realized sorting does work correctly on strings, and sorts spaces to the front so strip() will work.

# Answer
> 4 votes
# C, 165 bytes

```
#define d(x) int x(char*a,char*b){
d(q)return*a&224-*b&224;}
#define n(x) for(qsort(x,strlen(x),1,(__compar_fn_t)q);*x<33;x++);
d(s)n(a)n(b)return strcasecmp(a,b);}

```

Readable and in working context,

```
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// start of comparison
int q(char *a, char *b){
     return ((*a)&0xdf)-((*b)&0xdf); // case-insensitive
}
int s(char *a, char *b){
    for(qsort(a,strlen(a),1,(__compar_fn_t)q); *a<33; a++) /**/;
    for(qsort(b,strlen(b),1,(__compar_fn_t)q); *b<33; b++) /**/;
    return strcasecmp(a,b);
}
// end of comparison

int main(int i, char **v){
    printf("'%s' '%s'", v[1], v[2]);
    printf("=> %d\n", s(v[1], v[2])); // 0 if equalish
    return 0;
}

```

# Answer
> 3 votes
## zsh, 85 bytes

```
[ $(for x in $@;{tr -d \ <<<$x|tr A-Z a-z|fold -1|sort|paste -sd x}|uniq|wc -l) = 1 ]

```

Input as command line arguments, output as return code.

The `for` syntax makes this Bash-incompatible.

```
[               # test...
$(for x in $@;  # map over arguments
{tr -d \ <<<$x  # remove spaces
|tr A-Z a-z     # lowercase
|fold -1        # put each character on its own line
|sort           # sort lines
|paste -sd x    # remove all newlines except last
}|uniq          # take only unique lines
|wc -l          # how many lines remain?
) = 1 ]         # if only 1 line left, it must have been an anagram

```

# Answer
> 3 votes
# Japt, 12 bytes

```
N®v ¬n ¬xÃä¥

```

Test it online!

### How it works

```
        // Implicit: N = array of input strings
N®    Ã // Take N, and map each item Z to:
v ¬n    //  Take Z.toLowerCase(), split into chars, and sort.
¬x      //  Join and trim off whitespace.
ä¥      // Reduce each pair of items (that's exactly one pair) X and Y to X == Y.

```

# Answer
> 3 votes
# Bash + GNU utilities, 51

```
f()(fold -1<<<${@^^}|sort)
f $1|diff -qBw - <(f $2)

```
* Define a function `f()` which:
    + `${@^^}` converts all parameters to upper case
    + `fold -1` splits chars - one per line
    + `sort`s lines
* call `diff` with `-q` to suppress full diff output and `-Bw` to ignore whitespace changes

# Answer
> 3 votes
# GNU Sed, 33

Score includes +2 for `-rn` options to sed.

This is almost a direct port of @FryAmTheEggman's Retina answer:

```
:
s/(\w)(.*,.*)\1/\2/i
t
/\w/Q1

```

Ideone.

# Answer
> 3 votes
## Perl, ~~34~~ 33 + 1 = 34 bytes

```
s/(.)(.*,.*)\1/$2/i?redo:say!/\w/

```

Requires the `-n` flag and the free `-M5.010`|`-E`:

```
$ perl -M5.010 -ne's/(.)(.*,.*)\1/$2/i?redo:say!/\w/' <<< 'hello, lloeh'
1

```

How it works:

```
                                   # '-n' make a implicit while loop around the code
 s/(.)(.*,.*)\1/$2/i               # Remove a letter that occurs on both sides of the comma.
                    ?
                     redo:         # Redo is a glorified goto statement that goes to the top of the while loop
                          say!/\w/ # Check to see if any letter is left

```

Thanks to msh210 for suggesting using ternary operators to save one byte

# Answer
> 3 votes
# Cyborg Hal, ~~9~~ 8 bytes

```
{ṇ₁cḷo}ᵛ

```

Try it online!

Truthy/falsy output is achieved through predicate success/failure, this being Brachylog.

Previously saved a byte using `cṇ₁cḷḍ` instead of `{ṇ₁cḷ}ᵐ` under the assumption that the two input strings would be the same length minus whitespace, but I realized that it would succeed where it should fail on `Ah Hass, haha`.

```
{     }ᵛ    For both strings in the input,
 ṇ₁         split on spaces,
   c        concatenate,
    ḷ       lowercase,
     o      and sort.
       ᵛ    Are the results the same?

```

# Answer
> 3 votes
# Zsh, 51 bytes

Try it Online!

```
g()<<<${(j::)${(os::)1:l}// }
<<<${$(g $1)/$(g $2)}

```

Similar to my other anagram solution, again using Zsh's gnarly parameter expansion. Added a few bits to lowercase everything and parse out spaces.

# Answer
> 3 votes
# Arturo, 33 bytes

```
$=>[=do map&=>[tally--lower&` `]]

```

Try it!

Takes input as a list of two strings.

```
$=>[               ; a function where input is assigned to &
    map&=>[        ; map over input, assign current elt to &
        lower&     ; lowercase current elt
        -- _ ` `   ; remove spaces
        tally      ; create dictionary of occurrences
    ]              ; end map
    do             ; put the pair on the stack
    =              ; are they equal?
]                  ; end function

```

# Answer
> 2 votes
# PHP, ~~109~~ 94 bytes

```
function f($x){return str_split((trim($x));}function g($x,$y){return array_diff(f($x),f($y));}

```

Blech, the two `function/return`s are killing me here.

Returns the difference between two `string` inputs as an `array` of characters. PHP considers `[]` falsy, satisfying the `return` requirements.

# Answer
> 2 votes
## Pyke (commit 30, noncompetitive), 9 bytes

```
Fl1dk:S)q

```

Explanation:

```
F      )  -  for _ in eval_or_not(input())
 l1       -     ^.lower()
   dk:    -    ^.replace(" ", "")
      S   -   sorted(^)
        q - ^==^

```

# Answer
> 2 votes
# Mathematica, ~~77~~ 76 bytes

```
StringMatchQ[##,IgnoreCase->1>0]&@@(""<>Sort[Characters@#/." "->""]&/@{##})&

```

The first part is actually one of my answers to another question!

# Answer
> 2 votes
# Pike, ~~54~~ ~~112~~ ~~109~~ ~~109~~ 96 bytes

```
#define a(x) sort((array)replace(lower_case(x)," ",""))
int s(mixed i){return a(i[0])==a(i[1]);}

```

`mixed` happens to be shorter than `array(string)`.

`s` returns `1` if its arguments are anagrams.

# Answer
> 2 votes
## APL, 31 chars

```
{≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}

```

To be used so:

```
    {≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}'Sp3000' 'P S 3000'
1

```

In English:

* `{ ... }¨⍵`: for each of the two elements of the argument
* `x←('.'⎕R'\u0')⍵~' '`: transform to uppercase (using a regex...) the string without the spaces and assign the temporary result to `x`
* `x[⍋x]`: sort x
* `≡/`: compare the two results of the sorting: if they match, return 1.

# Answer
> 2 votes
# Java, 218 Bytes

*First time I've ever written Java...*

Golfed:

```
import java.util.Arrays;boolean M(String a,String b){char[]A=a.toUpperCase().replace(" ","").toCharArray();char[]B=b.toUpperCase().replace(" ","").toCharArray();Arrays.sort(A);Arrays.sort(B);return Arrays.equals(A,B);}

```

Ungolfed:

```
import java.util.Arrays;
public class ManageTrashSo {
    public boolean M(String a, String b) {
    char[] A = a.toUpperCase().replace(" ", "").toCharArray();
    char[] B = b.toUpperCase().replace(" ", "").toCharArray();
    Arrays.sort(A);
    Arrays.sort(B);
    return Arrays.equals(A, B);
   }
}

```

Testing:

```
    ManageTrashSo manageTrashSo = new ManageTrashSo();

    //True
    System.out.println(manageTrashSo.M("Lynn", "Nyl N"));
    System.out.println(manageTrashSo.M("Digital Trauma", "Tau Digital Arm"));

    //False
    System.out.println(manageTrashSo.M("Android", "rains odd"));
    System.out.println(manageTrashSo.M("In between days", "bayed entwine"));

```

# Answer
> 2 votes
# Japt, 10 bytes

```
v á øVrS v

```

Try it

# Answer
> 2 votes
# lyxaV, 5 bytes

```
ɽȧvs≈

```

Try it Online!

Or try a testsuite to verify the test cases.

Takes inputs as a list of strings.

## Explained

```
ɽȧvs≈
ɽ     # Convert each string to lowercase
 ȧ    # Remove whitespace from each string
  vs  # Sort each string
    ≈ # Are they equal?

```

# Answer
> 2 votes
# Thunno 2, 5 bytes

```
Rw€Ṡạ

```

Try it online!

Input as a list of both strings.

#### Explanation

```
Rw€Ṡạ  # Implicit input
R      # Uppercase the input
 w     # Remove all whitespace
  €Ṡ   # Sort each string
    ạ  # All equal?
       # Implicit output

```

# Answer
> 1 votes
# Ruby, 50 bytes

```
def f;gets.upcase.chars.sort.join.strip;end
p f==f

```

Writing `f=->{...}` and `f[]==f[]` is just as long. :(

# Answer
> 1 votes
## PowerShell, 81 bytes

```
param([char[]]$a,[char[]]$b)-join($a-replace' '|sort)-eq-join($b-replace' '|sort)

```

A slight rewrite of my answer on the linked Anagram challenge.

Takes input as char-arrays, performs a `-replace` operation to remove spaces, `sort`s them (which sorts alphabetically, not by ASCII value), then `-join`s them back into a string. The `-eq` in PowerShell is by default case-insensitive, but here it must be performed on strings, as `[char]'a'` is not equal to `[char]'A'`, hence the reason for `-join`.

# Answer
> 1 votes
# Perl, 35 bytes

Include +1 for `-p`

Somewhat abusive since it depends on the program being given on the commandline.

```
perl -pe'<>=~s%\S%*_=s/$&//i?_:0%reg;$_=!//'

```

Then give the strings as 2 consecutive lines on STDIN

A very abusive solution is 30 bytes:

```
perl -ne'<>=~s%\w%1/!s/$&//i%reg;1/!//'

```

This crashes if the strings are not anagrams and therefore gives a false exit code from the point of view of the shell. It also gives garbage on STDERR for that case. If the strings are anagrams the program is silent and gives a "true" exit code

# Answer
> 1 votes
# Factor, 68 bytes

```
[ [ 32 swap remove >lower natural-sort ] map duplicates length 1 = ]

```

An anyonymous function. Call it like `{ "array" "of" "strings" } ~quotation~ call`.

# Answer
> 1 votes
## Q, 25 Bytes

```
f:{~/{x@<x:x@&~^x:_x}'x}

```

*NOTE.- counting include function name f: to facilitate tests* (as lambda we can decrement 2 Bytes)

**Readable version**

match over {ascending not null lower x} each x

```
{.. x ..} is an anonymous function with arg x
_x        lowers string x
&~^x      where not null x (space is considered null)
x@..      selects elements of x according to indexes ..
<x        ascending indexes of x (not values). Ex <"cab" is 1 2 0
x@<x      ascending values of x (x at ascending indexes of x)
~         match (diad function). Ex "one"~"one" is true
f'..      applies function f for each argument ..
f/..      applies function f over elements of sequence (fold)

```

**Test**

```
f("Lynn";"Nyl N")
f("Digital Trauma";"Tau Digital Arm")
f("Sp3000";"P S 3000")
f("Manage Trash So";"Those anagrams")
f("Calvins Hobbies";"Helka Homba")
f("Android";"rains odd")
f("In between days";"bayed entwine")
f("Code golf";"cod elf got")

```

generates (1b = true, 0b = false)

```
1b
1b
1b
1b
0b
0b
0b
0b

```

**About Q**

General-purpose language (APL derivative, specialized in data processing) developed by kx.com. Free full functional evaluation version for Windows/Linux/MacOS.

# Answer
> 1 votes
# PHP, 89 bytes

```
for(;$i++<2;)$r[]=count_chars(join(explode(" ",strtolower($argv[$i]))));echo$r[0]==$r[1];

```

Try it online!

# PHP, 94 bytes

```
for(;$i++<2;sort($x),$r[]=trim(join($x)))$x=str_split(strtolower($argv[$i]));echo$r[0]==$r[1];

```

Try it online!

# Answer
> 1 votes
# Excel VBA, 122 Bytes

Anonymous VBE immediate window Function that takes input from range `[A1:B1]` and outputs to the VBE immediate window

```
a=Replace([A1]," ",""):b=Replace([B1]," ",""):For i=1To Len(a):b=Replace(b,Mid(a,i,1),"|",,1,1):Next:?b=String(len(a),"|")

```

# Answer
> 0 votes
# D, ~~99~~ ~~107~~ ~~103~~ ~~102~~ ~~99~~ ~~131~~ ~~116~~ 117 bytes

Edit: forgot about ~~Dre~~ ~~case insensitivity~~ ~~imports~~ lambdas

I ~~don't~~ like this language :D

```
import std.string,std.algorithm;(string[]a)=>sort(split(strip(a[0].toLower),""))==sort(split(strip(a[1].toLower),""))

```

To use it, assign it:

```
import std.string,std.algorithm;

void main () {
    auto x = (string[]a) => sort(split(strip(a[0].toLower),"")) == sort(split(strip(a[1].toLower),""))
}

```

# Answer
> 0 votes
## C#, 378 bytes

I need a handicap!!

https://dotnetfiddle.net/FNDt0E

```
using System;
using System.Linq;
using System.Text;

public class Program
{

    public static void Main()
    {
        var l = "Hello World";

        var r = "Red Who Loll";

        var y = new Func<string,string>(s => new String(s.ToLower().Replace(" ","").OrderBy(v => v).ToArray()));
        var z = new Func<string,string,Func<string,string>,bool>((w,x,f) => f(w) == f(x));
        var o = z(l, r, y);

        Console.WriteLine("{0} & {1} are anagram: {2}",l, r, o);

                Console.WriteLine("C#, {0} bytes", Encoding.Unicode.GetByteCount(@"var y = new Func<string,string>(s => new String(s.ToLower().Replace("" "","""").OrderBy(v => v).ToArray()));
    var z = new Func<string,string,Func<string,string>,bool>((w,x,f) => f(w) == f(x));"));

    }

}

```

---
Tags: code-golf, string, decision-problem, permutations
---