title: Unfurling-Safe Quine

text:
# Question
Title: Unfurling-Safe Quine
Write a proper quine **containing at least one newline/linefeed** whose every unfurling is either itself a proper quine or outputs the original quine. Your answer can mix and match outputting itself and outputting the original quine.

# Unfurlings

Unfurlings consist of:

1. Appending spaces to make the input a rectangle.
2. Taking all lines above the bottom one and rotating them a quarter-turn clockwise about the lower-right corner so that the right edge is on the same level as the bottom edge.
3. Repeat step (2) until the string is a single line to find all unfurlings.

For example, the first unfurling of

```
GFE
HID
ABC

```

is

```
   HG
   IF
ABCDE

```

and the rest are

```
   HG
   IF
ABCDE

     IH
ABCDEFG

       I
ABCDEFGH

ABCDEFGHI

```

This process is automated with this program adapted from Emigna's answer here,where each step of unfurling in the output is delimited by a dashed line.

# Example

For example, if you have a program

```
K
AB

```

(no trailing spaces)

then it must be a proper quine and print itself(`'K\nAB'`, where `\n` represents a linefeed/newline). According to the output of the unfurling program, we see that the next step in unfurling is

```
  K
AB

```

(note trailing space)

This must either print itself(`' K\nAB '`) or the original program (`'K\nAB'`). The next step in the unfurling is

```
AB K

```

This must either print itself (`'AB K'`), or the original program(`'K\nAB'`).

The byte-count of this program is `4` (`K`, `\n`, `A`, `B`).

# Score

This is , so the shortest answer in bytes wins. Standard loopholes apply, as usual.

# Answer
> 10 votes
# Python 3, 48 bytes

```

_='\n_=%r;print(_%%_,end="")';print(_%_,end="")

```

Try it online!

I mean, it works :p

# Answer
> 6 votes
# Python 3, 42 bytes

```

_='\n_=%r;print(end=_%%_)';print(end=_%_)

```

Try it online!

# Answer
> 4 votes
# Ruby, 32 bytes

```

_="\n_=%p;print _%%_";print _%_

```

Try it online!

# Answer
> 1 votes
# CJam, 11 bytes

OK, let's go with the obvious trivial solution. At least it's shorter than the Python and Ruby solutions that use the same trick.

```

{N\"_~"}_~

```

This code begins with a newline, which is ignored by the CJam interpreter. All the actual code is on the last line, which is not changed by the unfurling process. The extra spaces and newlines introduced by unfurling the empty first line are also ignored by the interpreter.

Otherwise this is just a trivial tweak of a (or perhaps *the*) standard CJam quine. `{N\"_~"}` defines a code block, `_~` makes a copy of it and executes it. Inside the code block, `N\` pushes a newline before the copy of the block on the stack and `"_~"` pushes the string `_~` after it. When the program ends, the CJam interpreter automatically prints everything on the stack, i.e. the newline, the code block and the `_~`.

Try it online!

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


title: Application screen shot

text:
# Question
Title: Application screen shot
Write the minimal code you need to take a screenshot of your application window. I am not asking for a function or program; just only a code segment.

It has obviously to be a GUI application; console applications not allowed.

**Input:**

None.

**Output:**

The valid outputs are:

* Clipboard. Then post a screenshot of the Paste contents on a drawing program.
* A file. Upload it somewhere and post a link to it here.
* Inside any other window different from the window that was shoot. Post screenshot of the new window here.

As it is minimum number of characters wins!

# Answer
> 1 votes
# Java 8, ~~82~~ ~~80~~ 77 bytes

Class that extends `Frame`:

```
ImageIO.write(new Robot().createScreenCapture(bounds()),"png",new File("a"));

```

Regular Class **98 Bytes**:

```
ImageIO.write(new Robot().createScreenCapture(Frame.getFrames()[0].bounds()),"png",new File("a"));

```

Uses deprecated `bounds()` method.

---
Tags: code-golf, graphical-output
---


title: Skip like a frog!

text:
# Question
Title: Skip like a frog!
Given an array of non-negative integers, your task is to only keep certain elements of it, as described below.

* Let's say the array is `[1, 3, 2, 4, 11, 5, 2, 0, 13, 10, 1]`.
* First get the first element of the array, `n`. Keep the first `n` elements and discard the next one (discard the `n+1`th). The new array is `[1, 2, 4, 11, 5, 2, 0, 13, 10, 1]`.
* Then, you grab the element following the one removed and do the exact same thing. Reapplying the process, we get `[1, 2, 11, 5, 2, 0, 13, 10, 1]`
* You repeat the process until you arrive outside the array's bounds / there are no elements left in the array. We stop because `11` is higher than the length of the array.
* Now you should output the result.

Input / output may be taken / provided in any standard form. The array will never be empty, and will only contain non-negative integers. All standard loopholes are forbidden.

This is so the shortest code in bytes wins!

---

# Test Cases

```
Input --> Output

[1, 2, 3, 4, 5] --> [1, 3, 4]

[6, 1, 0, 5, 6] --> [6, 1, 0, 5, 6]

[1, 3, 2, 4, 11, 5, 2, 0, 13, 10, 1] --> [1, 2, 11, 5, 2, 0, 13, 10, 1]

[2, 2, 2, 2, 2, 2] --> [2, 2]

[1, 2, 3, 1, 2, 3, 1, 2, 3] -> [1, 2]

[3, 1, 2, 4, 0] --> []*

```

* The last test case involves `0`, so I decided to post the process such that it is clearer:

```
[3, 1, 2, 4, 0] --> [3, 1, 2, 0] --> [1, 2, 0] --> [1, 0] --> [0] --> [] )

```

<sup>(Inspired by this challenge by Erik the Outgolfer)</sup>

# Answer
# Pyth, 18 bytes

```
#IgZlQB .(Q=Z@QZ)Q

```

Try it here.
> 1 votes

# Answer
# JavaScript (ES6), 45 bytes

```
f=(a,k=0,x=a[k])=>1/x?f(a.splice(x,1)&&a,x):a

```

### Test cases

```
f=(a,k=0,x=a[k])=>1/x?f(a.splice(x,1)&&a,x):a

console.log(JSON.stringify(f([1, 2, 3, 4, 5]))) // --> [1, 3, 4]
console.log(JSON.stringify(f([6, 1, 0, 5, 6]))) // --> [6, 1, 0, 5, 6]
console.log(JSON.stringify(f([1, 3, 2, 4, 11, 5, 2, 0, 13, 10, 1]))) // --> [1, 2, 11, 5, 2, 0, 13, 10, 1]
console.log(JSON.stringify(f([2, 2, 2, 2, 2, 2]))) // --> [2, 2]
console.log(JSON.stringify(f([1, 2, 3, 1, 2, 3, 1, 2, 3]))) // -> [1, 2]
console.log(JSON.stringify(f([3, 1, 2, 4, 0]))) // --> []
```
> 5 votes

# Answer
# Haskell, 50 bytes

`g.pure.(0:)` is an anonymous function taking and returning a list of `Int`s, use as `(g.pure.(0:))[1,2,3,4,5]`.

```
g.pure.(0:)
g(a,_:b:c)=g$splitAt b$a++b:c
g(a,_)=a

```

Try it online!

# How it works

* The function `g` takes a tuple argument representing a split list. `a` is the list of initial elements kept at the previous step, `_` is the element to be discarded, `b` is the next element to be used as a length, and `c` is the remaining elements.
    + If there are enough elements in the second part of the tuple to select a `b`, then a new split is performed and `g` recurses. Otherwise, it halts with `a` as the result.
* The anonymous function `g.pure.(0:)` starts it all by calling `g` with the tuple `([],0:l)`, where `l` is the input and `0` gets immediately discarded by `g`.
    + `pure` here uses the `Applicative` instance for (binary) tuples, and with the result type `([Int],[Int])` conveniently puts its argument as the second element in a tuple with `[]` as first element.
> 4 votes

# Answer
# Python 3, 59 bytes

```
f=lambda a,i=0:f(a[:a[i]]+a[a[i]+1:],a[i])if i<len(a)else a

```

Try it online!
> 3 votes

# Answer
# Haskell, 51 bytes

```
f s=s%s
s%(n:_)|(x,_:z)<-splitAt n s=(x++z)%z
s%_=s

```

Try it online! Example usage: `f [1,2,3,4,5]`.
> 3 votes

# Answer
# APL (Dyalog Classic), 32 bytes

```
1∘{n∇⍣(n≤≢w)⊢w←⍵/⍨(n←1+⍺⊃⍵)≠⍳≢⍵}

```

## Explanation

```
1∘{                             } bind 1 as starting left argument (⍺)
                             ⍳≢⍵  generate indexes for right argument (⍵)
                   (n←1+⍺⊃⍵)      n is 1+item at position ⍺
              w←⍵/⍨         ≠     w is ⍵ with item at n removed
   n∇⍣(n≤≢w)⊢                     recurse with n as left and w as right arg if n <= length of w

```

Try it online!
> 2 votes

# Answer
# Java 8, 68 bytes

This lambda accepts a mutable `List<Integer>` (supports `remove(int)`, e.g. `ArrayList`). Output is mutated input. Assign to `Consumer<List<Integer>>`.

```
l->{for(int i=0,f=0;i<l.size();f^=1)i=f>0?l.remove(i)*0+i:l.get(i);}

```

Try It Online

The control flow for this problem is very annoying. Each iteration we have to remove an element and get the element at the next position, and both of these operations require a range check (and either may trigger program completion). One strategy is to carry out both operations in a single loop iteration, with the index update guarded by its own range check. Another strategy, which turned out to be shorter, is to alternate between the operations each loop iteration, which is what this solution does.
> 2 votes

# Answer
# Perl 5, 38 + 1 (-a) = 39 bytes

```
splice@F,$p=$F[$p],1while$p<@F;say"@F"

```

Try it online!
> 1 votes

# Answer
**Haskell, 99 bytes (88 without indentation)**

```
f x y
 |y>=l=f x$l-1
 |e>=l=x
 |True=f (take e x ++ drop (1+e) x) e
 where e=x!!y
       l=length x

```
> 1 votes

# Answer
# VI, 31 25 bytes

```
O@0kdd<C-v><C-a>Y<C-v><C-x>gg@a<Esc>"add<C-a>Y<C-x>@a

```

`<C-?>` corresponds to `Control + ?`, and `<Esc>` to `Escape` obviously. Each of these count for 1 byte (see meta).

## Input

The input file should contain 1 integer per line + 1 blank line at the end, example :

```
1
2
3
4
5

```

We can see each line of the input file as an array element, such as `1 :: 2 :: 3 :: 4 :: 5 :: []`, like in some languages (caml for example).

## Launch

You can start vi with the following command, and type the solution stroke by stroke :

```
vi -u NONE input

```

You can also use this one-liner :

```
vi -u NONE -c ':exec "norm O@0kdd\<C-v>\<C-a>Y\<C-v>\<C-x>gg@a\<Esc>\"add\<C-a>Y\<C-x>@a"' -c ":w output" -c ':q' input

```

This should produce a file `output` with the correct result from an input file `input`.

## Explanations

To introduce the solution, I will first present a 19-bytes solution working only for arrays without 0. This solution uses a recursive macro, used with little modification in the final solution :

```
Yqa@0ddYgg@aquggY@a

```

### Explanation of a partial solution

```
Y                       # yank first line (first integer + line break) to "0 register
 qa                     # start recording a macro ("a register)
   @0                   # jump n lines, where n is the content of the "0 register
     dd                 # delete the current line (n+1th line)
       Y                # yank current line (integer after the previously deleted line)
        gg              # go back to the first line
          @a            # recurse on macro "a"
            q           # finish recording the macro
             u          # cancel modifications done by the execution of the macro
              gg        # go back to the first line
                Y@a     # apply the recorded macro with first parameter equal to the first integer

```

The trick here is to use the `"0` register to store the current integer (and the line break, very important). Therefore, the command `@0` allows to jump `n` lines (call `n` the value of `"0`). If the jump exceeds the number of lines in the file, the macro will fail, so the program will stop (outside of the array bounds, as required).

But this solution does not work if the input contains `0`. Indeed, if `"0` register value equals `0`, then `@0` will jump one line (due to the line break), not `0` as we liked. So the next command (`dd`) won't delete the 0th integer, but the 1st (not correct).

A valid solution to handle the `0` is to always increment the integer before yanking it, and decrement it just after. Thus, the `@0` command will jump `n+1` lines (`n` is the current integer that have been incremented). A `k` command is then necessary to go to line `n` (previous line). Using this trick, a blank line is needed at the end of the input file, to avoid jumping outside of the array (thus, terminating the program), since we now always jump `n+1` lines, before jumping to the previous line.

### Explanation of the final solution

```
O                                                       # insert a new line at the beginning of the file, enter insert mode to write the macro content
 @0                                                     # jump n lines
   k                                                    # go to the previous line
    dd                                                  # delete this line
      <C-v><C-a>                                        # type Control+A (C-v is needed because we are in insert mode) to increment the current integer
                Y                                       # yank the incremented integer
                 <C-v><C-x>                             # decrement the current integer
                           gg                           # go to the first line
                             @a                         # recurse on macro "a"
                               <Esc>                    # exit insert mode : at this step, the first line of the file contains the macro content @0kdd^AY^Xgg@a
                                    "add                # copy @0kdd^AY^Xgg@a line to the register "a and delete the line
                                        <C-a>           # increment the first integer
                                             Y          # yank it (into "0)
                                              <C-x>     # decrement the first integer
                                                   @a   # apply macro in a" (initial @0 will jump n+1 lines, since we incremented the first integer before calling the macro)

```

Writing the macro content inside the file before registering it allows to save a few bytes :

* avoids to write `qa...q` and undo all changes after registering
* avoids `:let @a="..."`)

## Edits

**#1**

* write the macro content on the first line (instead of last line)
* change input (1 blank line at the end)
* add one-liner to test in command-line
> 1 votes

# Answer
# Pyth, 32 bytes

```
VlQIgNlQBK@QNI!K=QYBIgKlQB.(QK;Q

```

Try it online
> 0 votes

# Answer
# C# (.NET Core), 74 bytes

```
n=>{for(int i=n[0];i<n.Count;){n.RemoveAt(i);i=i<n.Count?n[i]:n.Count+1;}}

```

Try it online!

This takes in a list of ints and modifies it. I have seen some Java answers that skirt around imports by using the fully qualified name in the Lambda argument definition. If this is not allowed, I can remove this answer.
> 0 votes

# Answer
# , ~~64~~ 53 bytes

```
f=function(a,i=1,d=a[i]+1)"if"(is.na(d),a,f(a[-d],d))

```

Recursive function. Has one mandatory input, `a`, the list to skip over. `i` is the index of the number of things to jump over (defaults to `1`), and `d` is the index of the next item after the required value has been removed, which is also the index of the item to be removed. Returns `numeric(0)`, an empty vector, for empty output.

Try it online!

Ungolfed:

```
f <- function(a, i = 1, d = a[i] + 1) {
  if(is.na(d)) {   # d is NA if and only if a[i] is out of bounds
    a
  } else {
    f( a[-d], d, a[d] + 1 )   # a[-d] is a with the item at index d removed
  }
}

```
> 0 votes

---
Tags: code-golf, array, integer
---


title: House of cards (version 1)

text:
# Question
Title: House of cards (version 1)
> Version 2 here.

Simple challenge: given an integer, draw a house of cards with the given number of stories. If the number is negative, draw the house upside-down. Examples:

```
Input: 2
Output:

 /\
 --
/\/\

Input: 5
Output:

    /\
    --
   /\/\
   ----
  /\/\/\
  ------
 /\/\/\/\
 --------
/\/\/\/\/\

Input: 0
Output: <empty, whitespace or newline>

Input: -3
Output:

\/\/\/
 ----
 \/\/
  --
  \/

```

Input can be numeric or a string. Output must be exactly as shown, with leading and/or trailing spaces and newlines allowed.

This is , so may the shortest program/function for each language win!

# Answer
> 14 votes
# Python 2, ~~97~~ ~~95~~ ~~94~~ 92 bytes

-2 bytes thanks to Luka
This version produces an exception on `n=0`,but without printing anything

```
n=input()*2
m=abs(n)
for i in range(2,m+1)[::n/m]:print(i/2*'/-\-'[i%2::2][::n/m]).center(m)

```

Try it online!

### Non-error version, Python 2, 94 bytes

```
n=input()*2
x=n>0 or-1
for i in range(2,x*n+1)[::x]:print(i/2*'/-\-'[i%2::2][::x]).center(n*x)

```

Try it online!

# Answer
> 9 votes
# 05AB1E, ~~30~~ ~~29~~ 24 bytes

```
ÄF„--N×„/\N>×}).C∊2ä¹0‹è

```

Try it online!

**Explanation**

```
ÄF                         # for N in [0 ... abs(input-1)] do:
  „--N×                    # push the string "--" repeated N times
       „/\N>×              # push the string "/\" repeated N+1 times
             }             # end loop
              )            # wrap stack in a list
               .C          # pad strings on both sides to equal length
                 ∊         # vertically mirror the resulting string
                  2ä       # split in 2 parts
                    ¹0‹    # push input < 0
                       è   # index into the the list with the result of the comparison

```

# Answer
> 7 votes
# PHP, 125 bytes

input negative leading newline

input positive trailing newline

```
for($s=str_pad;++$i<$b=2*abs($argn);)$t.=$s($s("",2*ceil($i/2),["-","/\\"][1&$i]),$b," ",2)."
";echo$argn>0?$t:$t=strrev($t);

```

Try it online!

# PHP, 130 bytes

```
for(;++$i<$b=2*abs($a=$argn);)echo($s=str_pad)($s("",2*abs(($a<0?$a:$i&1)+($i/2^0)),["-",["/\\","\/"][0>$a]][1&$i]),$b," ",2)."
";

```

Try it online!

# Answer
> 5 votes
# MATL, 39 bytes

```
|:"G|@-:~'/\'G0<?P]@E:)htg45*c]xXhG0<?P

```

**Try it online!**

### Explanation

```
|         % Implicitly input, N. Absolute value
:"        % For k from 1 to that
  G|      %   Push absolute value of N again
  @-      %   Subtract k
  :       %   Range [1 2 ... N-k]
  ~       %   Convert to vector of N-k zeros
  '/\'    %   Push this string
  G0<     %   Is input negative?
  ?       %   If so
    P     %     Reverse that string (gives '\/')
  ]       %   End
  @E      %   Push 2*k
  :       %   Range [1 2 ... 2*k]
  )       %   Index (modularly) into the string: gives '/\/\...' or '\/\/...'
  h       %   Horizontally concatenate the vector of zeros and the string. Zeros
          %   are implicitly converted to char, and will be shown as spaces
  t       %   Duplicate
  g       %   Convert to logical: zeros remain as 0, nonzeros become 1
  45*c    %   Multiply by 45 (ASCII for '=') and convert to char
]         % End
x         % Delete (unwanted last string containing '=')
Xh        % Concatenate into a cell array
G0<       % Is input negative?
?         % If so
  P       %   Reverse that cell array
          % Implicit end. Implicit display

```

# Answer
> 4 votes
## Charcoal, ~~31~~ ~~28~~ 27 bytes

```
ＦＩ⊟⪪θ-«←ι↓→/…\/ι↙»‖Ｍ¿‹Ｎ⁰‖Ｔ↓

```

Try it online! Link is to verbose version of code. I had about 4 different 32 byte answers then found this. Edit: Saved ~~3~~ 4 bytes by performing the `abs` using string manipulation. Explanation:

```
   ⪪θ-                          Split the input (θ = first input) on -
  ⊟                             Take the (last) element
 Ｉ                              Convert it to a number i.e. abs(θ)
Ｆ     «                         Repeat that many times
       ←ι                       Print half of the -s
         ↓                      Position for the /\s
          →/                    Print the first /
            …\/ι                Print half of any remaining \/s
                ↙               Position for the next row of -s
                 »              End of the loop
                  ‖Ｍ            Mirror everything horizontally
                    ¿‹Ｎ⁰        If the input was negative
                        ‖Ｔ↓     Reflect everything vertically

```

# Answer
> 4 votes
# C (gcc), 169 ~~171~~ ~~173~~ ~~160~~ ~~164~~ bytes

```
#define F(A,B,C)for(i=A;B--;)printf(C);
#define P puts("");F(y,i," ")F(abs(n)-y
s,i,x,y;f(n){x=n<0;for(s=x?1-n:n;s--;){y=x?-n-s:s;P,i,x?"\\/":"/\\")y+=x;P,s>x&&i,"--")}}

```

+13 bytes for negative case bug.

Try it online!

Ungolfed (207 bytes after removing all spaces and newline):

```
s, i, x, y;
f(n) {
  x = n < 0;
  for (s = x ? 1 - n : n; s--;) {
    y = x ? - n - s : s;
    puts("");
    for (i = y; i--;) printf(" ");
    for (i = abs(n) - y; i--;) printf(x ? "\\/" : "/\\");;
    y += x;
    puts("");
    for (i = y; i--;) printf(" ");
    for (i = abs(n) - y; s > x && i--;) printf("--");;
  }
}

```

# Answer
> 2 votes
# Gaia, 21 bytes

```
:┅“/\\“--”×¦¦_€|ḣ¤ọ×ṣ

```

### Explanation

```
:                      Push 2 copies of the input
 ┅                     Get the range to the input. If positive: [1 .. n]. If negative:
                       [-1 .. n]. If zero: [0].
  “/\\“--”             Push ["/\", "--"]
          ×¦¦          Repeat both of those strings by each number in the range. Strings go
                       in reverse order when repeated a negative number of times.
             _         Flatten the list
              €|       Centre-align the rows of the list
                ḣ      Remove the last row (the "--"s on the bottom)
                 ¤     Swap (bring input back to the top)
                  ọ    Sign: -1 for negative, 0 for 0, 1 for positive
                   ×   Repeat the list that many times; (-1 × list) reverses it
                    ṣ  Join with newlines and implicitly output

```

# Answer
> 2 votes
# Japt, ~~40~~ 38 bytes

*-2 bytes thanks to @Shaggy*

```
o½½@aXc)ç +"--/\\\\/"ò gYv *Ug)pXc aÃ·

```

Try it online!

## Explanation

```
o½½@aXc)ç +"--/\\\\/"ò gYv *Ug)pXc aÃ·              // implicit: U = input integer
o.5,.5,XYZ{UaXc)ç +"--/\\\\/"ò gYv *Ug)pXc a} qR    // ungolfed
o.5,.5,                                             // array [.5,U] with step size .5
       XYZ{                                 }       // mapped by the function: (X = value, Y = index)
           UaXc)                                    //   absolute diff between U and ceil(X)
                ç                                   //   " " times that value
                  +"--/\\\\/"ò g      )             //   plus ["--","/\","\/"].get(...
                                Yv                  //     if Y is even, 1, else 0
                                   *Ug              //     times sign(U)
                                       pXc a        //   repeated abs(ceil(X)) times
                                              qR    // all that joined with newlines

```

# Answer
> 1 votes
# Mathematica, 140 bytes

```
(T=Table;z=Column;B[a_]:=""<>"/\\"~T~a;If[#>0,m=0,m=Pi];z[Join[z/@T[{B@i,""<>"--"~T~i},{i,Abs@#-1}],{B@Abs@#}],Alignment->Center]~Rotate~m)&

```

# Answer
> 1 votes
# Retina, ~~116~~ ~~111~~ 105 bytes

*this got way too long :/*

```
\d+
$*
+`^~?( *1*)1
 $1¶$&¶_$&
.*$

+`(_.*)1
$1--
1
/\
Ts`/\\`\\/`.*~.*
+`(.*)¶((.*¶)*)(~.*)
$2$4¶$1
~|_

```

Try it online!

negative input is denoted as `~n`

# Answer
> 1 votes
# Perl 5, 100 + 1 (-n) = 101 bytes

```
$/=$_>0?'/\\':'\\/';push@r,$_=$"x--$q.$/x$_,y|/\\|-|r for 1..($q=abs);pop@r;say for$_<0?reverse@r:@r

```

Try it online!

---
Tags: code-golf, ascii-art
---


title: House of cards (version 2)

text:
# Question
Title: House of cards (version 2)
> Thanks to FryAmTheEggman for the idea for this second version.
> Version 1 here.

Not-so-simple challenge: given a number of cards, build the biggest house of cards you can with that number of cards, according to the following building order:

```
                          /\       /\         /\         /\/\
                 --       --       --         ----       ----
/\  →  /\/\  →  /\/\  →  /\/\  →  /\/\/\  →  /\/\/\  →  /\/\/\  →

                /\         /\
     --         --         --
    /\/\       /\/\       /\/\
    ----       ----       ----
→  /\/\/\  →  /\/\/\  →  /\/\/\/\  →  ...

```

So you start with a single-storey house, then build the adjacent group, then put the bridge card, then build the group in the second floor, then start building groups and bridges from the first floor diagonally to reach the third floor, and so on.

A single card will be represented with a `/`, a `\` or a `--`. If after using as many cards as possible you have one card left, just output what you have accomplished so far (see example for 3 cards, the result is the same as for 2 cards). The only exception is the case of 1 card, that must output a flat card.

Examples:

```
Input: 1
Output:

--   <a card lying on the floor>

Input: 2
Output:

/\

Input: 3
Output:

/\

Input: 5
Output:

 --
/\/\

Input: 10
Output:

 /\
 ----
/\/\/\

Input: 20
Output:

  /\
  --
 /\/\/\
 ------
/\/\/\/\

Input: 39
Output:

    --
   /\/\
   ----
  /\/\/\
  ------
 /\/\/\/\
 --------
/\/\/\/\/\

Input: 40
Output:

    /\
    --
   /\/\
   ----
  /\/\/\
  ------
 /\/\/\/\
 --------
/\/\/\/\/\

```

Input can be numeric or a string, and will always be a positive integer. Output must be exactly as shown, with leading and trailing spaces and newlines allowed.

This is , so may the shortest program/function for each language win!

# Answer
> 4 votes
# Charcoal, 67 bytes

```
Ｎθ⁼θ¹Ａ²ηＷ¬‹θη«←÷η³↓→/…\/÷η³↙Ａ⁻θηθＡ⁺³ηη»‖ＭＭ÷η³→Ｆθ≡﹪ι³¦¹«↗←\/»²«↑Ｐ²»«

```

Try it online! Note: The latest version of Charcoal doesn't need the `»«` for -2 bytes. Explanation:

```
Ｎθ

```

Read the input as an integer into `θ`.

```
⁼θ¹

```

Special case: if the input is 1, print a `-`.

```
Ａ²ηＷ¬‹θη«

```

`η` represents the number of cards needed to build the next layer, initially 2. A while loop repeats as long as there are enough cards for the layer.

```
←÷η³↓→/…\/÷η³↙

```

Print the left half of the next layer. (I wanted to print the right half, but I couldn't get it to reflect properly for some reason.) The number of `-`s is one third of the number of cards in the layer, rounded down. (See also my answer to part 1.)

```
Ａ⁻θηθＡ⁺³ηη»

```

Subtract the number of cards from the input number, and add three cards to the number required for the next layer.

```
‖Ｍ

```

Mirror the house so far. (This also turns the `-` into `--` for the case of 1 card.)

```
Ｍ÷η³→

```

Move the cursor to the right of the house.

```
Ｆθ

```

Repeat for each remaining card (if any).

```
≡﹪ι³¦

```

If the card modulo 3 is:

```
¹«↗←\/»

```

1, then print a pair of cards;

```
²«↑Ｐ²»

```

2, then print a horizontal card;

```
«

```

Otherwise skip the card (because a pair is needed at this point).

# Answer
> 2 votes
# Python 2, 167 182 bytes

**167 bytes**

```
f=lambda x,y=0:y<x<2and"--"or~-x>y*3and f(x-2-y*3,y+1)or d(y,x)
d=lambda h,r,v=0:h and d(~-h,max(r-3,1),-~v)+" "*-~v+"--"*(h-(r<3))+"\n"+" "*v+"/\\"*(h+(r>1))+"\n"or""

```

**182 bytes**

```
f=lambda x,y=0:[x>1+y*3and f(x-2-y*3,y+1)or d(y,x),"--"][2>x>y]
d=lambda h,r,v=0:d(h-1,r-3*(r>2)-2*(r==2),v+1)+" "*(v+1)+"--"*(h-1+(r>2))+"\n"+" "*v+"/\\"*(h+(r>1))+"\n"if h+r else""

```

**Explanation (167-byte version)**

```
f=lambda x,y=0:
    "--" if y<x<2         # handle case where x is 1 on step 0 (only one card)
    else f(x-2-y*3,y+1)   # recursive call with one full triangular level accounted for
    if x>= 2+y*3          # one full level requires 2+3y cards (2, 7, 15...)
    else d(y,x)           # if no more full levels can be constructed, draw
d=lambda h,r,v=0:         # (h)eight to draw, (r)emaining cards, (v)ertical height already drawn (to determine leading white space)
    d(h-1,          ,v+1) # recursive call to draw upper lines
          max(r-3,1)      # subtract remainder cards used in this iteration
    +" "*(v+1)            # leading whitespace for -- row
    +"--"*(       )+"\n"  # -- line.
           h-(r<3)        # horizontal card count is equal to the remaining count of levels to draw, minus 1,
                          # ...plus 1 if there are at least three remaining cards to add to the right
    +" "*v                # leading whitespace for /\ row
    +"/\\"*(       )+"\n" # /\ line
            h+(r>1)       # vertical card pair count equals remaining level count
                          # ...plus 1 if there are at least two extra cards
    if h                  # return above is there are levels to draw (h)
    else ""               # else return nothing (ends recursion)

```

Try it online!

* This feels unnecessarily long, but I can't see anything to remove at the moment...feel free to comment any suggestions

# Answer
> 1 votes
# Perl 5, 129 bytes

```
@r=($_=<>-2)<0?'--':'/\\';while($_>1){$#r+=2;$i=0;$r[$i].=$i++%2?'--':'/\\'while$i<@r&&($_-=2-$i%2)>=0}say$"x(@r/2).pop@r while@r

```

Try it online!

---
Tags: code-golf, ascii-art
---


title: Fizz Buzz for Turtles

text:
# Question
Title: Fizz Buzz for Turtles
## Problem Description

Imagine you're a turtle on a grid. You're given two numbers ***f*** and ***b***, and you're facing east. You perform a march across the grid, counting each of the cells you encounter, according to the following rules:

* By default, you write the count to the cell you're in, then walk forward.
* If the count is divisible by ***f***, you write `F` to the cell you're in, then turn right, then walk forward.
* If the count is divisible by ***b***, you write `B` to the cell you're in, then turn left, then walk forward.
* If the count is divisible by both ***f*** and ***b***, you write `FB` to the cell you're in, then walk forward.
* If you reach a square you've already been to, you stop.

For example, following these rules using ***f*** = 3 and ***b*** = 5 will generate a pattern like this:

```
    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

```

## The challenge

Write a program or function that accepts two numbers as input, corresponding to ***f*** and ***b***, and produces as output the pattern for these numbers given by the rules above.

Formatting requirements:

* Each cell is two characters wide
* Cell contents are right aligned within these two characters
* Cells on the same row are delimited by a space
* The first column of cells must contain a non-empty cell
* All rows must contain non-empty cells
* Trailing whitespace is not required, but allowed
* However, the total width of each row must not exceed 3 times the number of non-empty columns

Your code must work for provided test cases.

Standard loopholes are disallowed.

This is code golf; shortest answer in bytes wins.

## Test cases

*(f=3, b=5 case repeated here as a courtesy convenience).*

```
f=3, b=5 ->
    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

f=4, b=10 ->
 F 25 26 27  F
23          29
22        1  2  3  F
21                 5
FB                 6
19                 7
18           B  9  F
17          11
 F 15 14 13  F

f=3, b=11 ->
 F 16 17  F
14       19
13     1  2  F
 F  B        4
   10        5
    F  8  7  F

f=5, b=9 ->
    F 41 42 43 44  1  2  3  4  F
   39                          6
   38                          7
   37                          8
 F  B                          B  F
34                               11
33                               12
32                               13
31                               14
 F 29 28  B              B 17 16  F
         26             19
          F 24 23 22 21  F

f=5, b=13 ->
    F 31 32 33 34  F
   29             36
   28        1  2  3  4  F
   27                    6
 F  B                    7
24                       8
23                       9
22              B 12 11  F
21             14
 F 19 18 17 16  F

```

# Answer
> 1 votes
# JavaScript (ES6), 230 ~~240~~

```
(f,b)=>(d=>{for(g=[s=x=y=d];!(r=g[y]=g[y]||[])[x];d&1?d&2?y?--y:g=[,...g]:++y:d&2?x?--x:g=g.map(r=>[,...r]):++x)o=++s%f?'':(++d,'F'),s%b||(--d,o+='B'),r[x]=o||s})(0)||g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `).join`
`

```

*Less golfed*

```
(f,b)=>{
  for(g=[s=x=y=d=0]; !(r = g[y]= g[y]||[])[x]; )
  {
    o=++s%f?'':(++d,'F')
    s%b||(--d,o+='B')
    r[x]=o||s,
    d&1
      ? d&2 ? y ? --y : g=[,...g] : ++y
      : d&2 ? x ? --x : g=g.map(r=>[,...r]) : ++x
  }
  return g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `)
          .join`\n`
}

```

**Test**

```
F=
(f,b)=>(d=>{for(g=[s=x=y=d];!(r=g[y]=g[y]||[])[x];d&1?d&2?y?--y:g=[,...g]:++y:d&2?x?--x:g=g.map(r=>[,...r]):++x)o=++s%f?'':(++d,'F'),s%b||(--d,o+='B'),r[x]=o||s})(0)||g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `).join`
`

function update()
{
  var i = I.value.match(/\d+/g)||[],f=+i[0],b=+i[1]
  O.textContent = (f>0 & b>0) ? F(f,b) : ''
}

update()
```

```
<input id=I value="3 5" oninput="update()">
<pre id=O></pre>
```

# Answer
> 5 votes
## Python 2, ~~379~~ ~~338~~ 326 bytes

Takes input as two numbers, separated by a comma. Eg. `4,5` or `(4,5)`

```
d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
 i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
 if d%2:x+=(d==1)*2-1
 else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*['  ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))

```

### Version that works if path is longer than 99, ~~384~~ ~~343~~ 330 bytes

Shows 2 significant digits.

```
d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
 i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i%100`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
 if d%2:x+=(d==1)*2-1
 else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*['  ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))

```

### Examples:

`input=(4,16)`

```
 F 21 22 23  F
19          25
18          26
17          27
FB  1  2  3  F
15           5
14           6
13           7
 F 11 10  9  F

```

`input=(6,7)` (truncating version)

```
                                              F 63 64 65 66 67 FB  1  2  3  4  5  F
                               F 57 58 59 60  B                                   B  8  9 10 11  F
                              55                                                                13
                   F 51 52 53  B                                                                 B 15 16 17  F
                  49                                                                                19
                  48                                                                                20
          F 45 46  B                                                                                B 22 23  F
         43                                                                                25
         42                                                                                26
         41                                                                                27
    F 39  B                                                                                B 29  F
   37                                                                                31
   36                                                                                32
   35                                                                                33
   34                                                                                34
 F  B                                                                                B  F
31                                                                                37
30                                                                                38
29                                                                                39
28                                                                                40
27                                                                                41
FB                                                                                FB
25                                                                                43
24                                                                                44
23                                                                                45
22                                                                                46
21                                                                                47
 F  B                                                                                B  F
   18                                                                                50
   17                                                                                51
   16                                                                                52
   15                                                                                53
    F 13  B                                                                                B 55  F
         11                                                                                57
         10                                                                                58
         09                                                                                59
          F 07 06  B                                                                                B 62 61  F
                  04                                                                                64
                  03                                                                                65
                   F 01 00 99  B                                                                 B 69 68 67  F
                              97                                                                71
                               F 95 94 93 92  B                                   B 76 75 74 73  F
                                              F 89 88 87 86 85 FB 83 82 81 80 79  F

```

@Edit: Thanks to Jonathan Allan, Copper, and shooqie for savings me a bunch of bytes.

# Answer
> 4 votes
# Excel VBA, ~~347~~ 421 bytes

New version, to deal with the whitespace-requirements. Not having this in my first version was an oversight n my part, but this takes its toll in the bytecount... It now cuts and pastes the used range to cell `A1`.

```
Sub t(f, b)
x=70:y=70:Do:s=s+ 1
If Cells(y,x).Value<>"" Then
ActiveSheet.UsedRange.Select:Selection.Cut:Range("A1").Select:ActiveSheet.Paste:Exit Sub
End If
If s Mod f=0 Then Cells(y,x).Value="F":q=q+1
If s Mod b=0 Then Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q Mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub

```

---

Here's the old version that did not move the end result to `A1`

```
Sub t(f,b)
x=70:y=70:Do:s=s+1:if Cells(y,x).Value<>"" then exit sub
If s Mod f=0 Then
Cells(y,x).Value="F":q=q+1
End If
If s Mod b=0 Then
Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
End If
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub

```

Starts at 70, 70 (or BR70 in Excel) and walks around it. Function is called with the `f` and `b` as parameters: `Call t(4, 16)`

@Neil just saved me a bunch of bytes, thanks!

# Answer
> 3 votes
# Excel VBA, <sub>~~284~~ ~~278~~ ~~277~~ ~~261~~ ~~259~~  ~~255~~ ~~254~~ ~~253~~</sub> 251 Bytes

`Sub`routine that takes input as values, `F`, `B` and outputs to cells on the `Sheets(1)` Object (which is restricted to the `Sheets(1)` object to save 2 Bytes)

```
Sub G(F,B)
Set A=Sheet1
R=99:C=R
Do
I=I+1
Y=Cells(R,C)
If Y<>""Then A.UsedRange.Cut:[A1].Select:A.Paste:End
If I Mod F=0Then Y="F":J=J+1
If I Mod B=0Then Y=Y+"B":J=J+3
Cells(R,C)=IIf(Y="",i,Y)
K=J Mod 4
If K Mod 2Then R=R-K+2 Else C=C+1-K
Loop
End Sub

```

### Usage:

```
Call G(3, 4)

```

# Answer
> 2 votes
# C, 305 Bytes

**Thanks to @ceilingcat for finding a much better (and shorter) version**

```
#define z strcpy(G[x]+y,
F(f,b){int G[99][99]={},d=3,x=49,y=x,i=1,q=0,s=99,t=0,u=s,v=0;for(;!G[x][y];i++)q=!(i%f)*2|i%b<1,q-3?q?d=q-1?z"F"),d+3&3:!z"B")-~d%4:sprintf(z""),"%d",i):z"FB"),d%2?x+=d-2:(y+=d-1),s=s>x?x:s,t=t<x?x:t,u=u>y?y:u,v=v<y?y:v;for(;v/u;u+=puts(""))for(x=s;t/x;)printf("%2s ",G[x++]+u);}

```

Try it online!

A slightly more indented version:

```
#define z strcpy(G[x][y],
char G[99][99][3];
d=3,x=49,y=49,i=1,q,s=99,t,u=99,v;

F(f,b)
{
    for(;!*G[x][y];i++)
    {
        q=(!(i%f))<<1|!(i%b);
        q==3&&z"FB");
        if(q==2)z"F"),d=(d+3)%4;
        if(q==1)z"B"),d=(d+1)%4;
        !q&&sprintf(G[x][y],"%d",i);
        if(d%2)x+=d-2;else y+=d-1;
        s=s>x?x:s;t=t<x?x:t;u=u>y?y:u;v=v<y?y:v;
    }
    for(y=u;y<=v;puts(""),y++)for(x=s;x<=t;x++)printf("%2s ",G[x][y]);
}

```

Here is a 364 byte version that handles numbers bigger than 100

```
#define g G[x][y]
#define z strcpy(g,
char G[99][99][9];d=3,x=49,y=49,i=1,q,s=99,t,u=99,v;F(f,b){for(;!*g;i++){q=(!(i%f))<<1|!(i%b);q==3&&z"FB");if(q==2)z" F"),d=(d+3)%4;if(q==1)z" B"),d=(d+1)%4;!q&&sprintf(G[x][y],"%2d",i);if(d%2)x+=d-2;else y+=d-1;s=s>x?x:s;t=t<x?x:t;u=u>y?y:u;v=v<y?y:v;}for(y=u;y<=v;puts(""),y++)for(x=s;x<=t;x++)printf("%2s ",g+strlen(g)-2);}

```

# Answer
> 1 votes
# Perl, 275 bytes

Indentation is provided for readability and is not part of the code.

```
($f,$e)=@ARGV;
for($i=$x=1,$y=0;!$m{"$x,$y"};$i++){
    ($g,$m{"$x,$y"})=$i%$e&&$i%$f?($g,$i):$i%$f?($g+1,B):$i%$e?($g-1,F):($g,FB);
    ($g%=4)%2?($y+=$g-2):($x+=1-$g);
    ($a>$x?$a:$b<$x?$b:$x)=$x;
    ($c>$y?$c:$d<$y?$d:$y)=$y
}
for$k($c..$d){
    printf("%*s",1+length$i,$m{"$_,$k"})for$a..$b;
    say
}

```

Explanation:

The code works by keeping track of a hash of all places the turtle has been, and the appropriate value, stored in `%m`. For example: in `3 5`, `$m{0,2}` contains `2`, and `$m{1,-3}` = `26`. It continues in this fashion until it reaches a place that has already been defined. Additionally, it keeps track of the current boundaries of the turtle's path, using `$a,$b,$c,$d` as maximums and minimums.

Once it reaches a place it has already been, it prints the path using the boundaries, everything padded with spaces.

There is no limit to the size of the path, nor the size of the numbers.

# Answer
> 1 votes
# PHP, 292 bytes

```
for($x=$y=$u=$l=0;!$q[$x][$y];$s="") {
    ++$i%$argv[1]?:$a-=1+$s="F";
    $i%$argv[2]?:$a+=1+$s.="B";
    $q[$x][$y]=$s?:$i;
    $z=[1,-2,-1,2][$a=($a+4)%4];
    $y+=$z%2;
    $x+=~-$z%2;
    $u>$y?$u=$y:$d>$y?:$d=$y;
    $l>$x?$l=$x:$r>$x?:$r=$x;
}
for(;$l++<=$r;print"\n")for($j=$u-1;$j++<=$d;)echo str_pad($q[$l-1][$j],3," ",0);

```

Try it online!

Indents are for clarity, not counted.

Follows much the same algorithm as the Perl answer. Track where the turtle has been in a 2D array, `$a` tracks where the turtle is facing, and `$u, $d, $l, $r` track the boundaries for printing. `str_pad` allows us to ensure that each entry is exactly 3 spaces wide for the print formatting.

For some reason I can't fathom, PHP doesn't mind me not initializing half the variables to 0, but screws up the formatting if I don't initialize others, even though it usually treats uninitialized variables as 0 when they're first used. Hence the `$x=$y=$u=$l=0` bit.

# Answer
> 0 votes
# Python 2, ~~267~~ ~~262~~ ~~258~~ ~~249~~ ~~245~~ 243 bytes

```
f,b=input()
X=x=Y=y=i=p=0
g={}
S=sorted
while(p in g)<1:i+=1;g[p]='F'[i%f:]+'B'[i%b:]or`i`;p+=1j**(i/f-i/b);X,_,x=S([X,x,int(p.real)]);Y,_,y=S([Y,y,int(p.imag)])
j=Y
while j<=y:print' '.join(g.get(i+j*1j,'').rjust(2)for i in range(X,x+1));j+=1

```

Try it online!

---
Tags: code-golf, grid
---


title: Mathematical Expression Showdown!

text:
# Question
Title: Mathematical Expression Showdown!
You are given 6 numbers: 5 digits \[0-9\] and a target number. Your goal is to intersperse operators between the digits to get as close as you can to the target. You have to use each digit **exactly** once, and can use the following operators **as many** times as you want: `+ - * / () ^ sqrt sin cos tan`. For example, if I'm given `8 2 4 7 2 65` I can output `82-(2*7)-4`. This evaluates to 64, thus giving me a score of 1 since I was 1 away from the target. **Note:** You can not put a decimal point between digits.

I am using the code from this StackOverflow answer to evaluate the mathematical expressions. At the bottom of this question there are programs you can use to test it out.

## Chaining Functions (Update!)

@mdahmoune has revealed a new level of complexity to this challenge. As such, I'm adding a new feature: chaining unary functions. This works on sin, cos, tan, and sqrt. Now instead of writing `sin(sin(sin(sin(10))))`, you can write `sin_4(10)`. Try it out in the evaluator!

## Input

200 line-separated test cases of 5 digits and a target number that are space-separated. You can use the program at the bottom of the question to make sample test cases, but I will have my own test cases for official scoring. The test cases are broken up into 5 sections of 40 tests with the following ranges for the target number:

* Section 1: \[0,1\] (to 5 decimal points)
* Section 2: \[0,10\] (to 4 decimal points)
* Section 3: \[0,1000\] (to 3 decimal points)
* Section 4: \[0,106\] (to 1 decimal point)
* Section 5: \[0,109\] (to 0 decimal points)

## Output

200 line separated mathematical expressions. For example, if the test case is `5 6 7 8 9 25.807`, a possible output could be `78-59+6`

## Scoring

The goal each round is to get closer to the target number than the other competing programs. I'm going to use Mario Kart 8 scoring, which is: `1st: **15** 2nd: **12** 3rd: **10** 4th: **9** 5th: **8** 6th: **7** 7th: **6** 8th: **5** 9th: **4** 10th: **3** 11th: **2** 12th: **1** 13th+: **0**`. If multiple answers get the same exact score, the points are split evenly, rounded to the nearest int. For example, if the programs in 5th-8th place are tied, they each get (8+7+6+5)/4 = 6.5 =\> **7** points that round. At the end of 200 rounds, the program that got the most points wins. If two programs have the same number of points at the end, the tie-breaker is the program that finished running faster.

## Rules

1. You can only use one of the languages commonly pre-installed on Mac like C, C++, Java, PhP, Perl, Python (2 or 3), Ruby, and Swift. If you have a language you want to use with a compiler/interpreter that is a relatively small download I may add it. You can also use a language with an online interpreter, but that will not run as fast.
2. Specify in your answer if you want trig functions to be calculated in **degrees** or **radians**.
3. Your program must output its solutions to all 200 test cases (to a file or STDOUT) within **60 seconds** on my Mac.
4. Randomness must be seeded.
5. Your total output for all test cases can't be more than **1 MB**.
6. If you have improved your solution and would like to be re-scored, add **Re-Score** at the top of your answer in bold.

## Programs

(change the "deg" argument to "rad" if you want radians)

1. **Test out evaluator**
2. **Score your program's output for test cases**
3. Generate test cases:

```
document.getElementById("but").onclick = gen;
var checks = document.getElementById("checks");
for(var i = 1;i<=6;i++) {
var val = i<6 ? i : "All";
var l = document.createElement("label");
l.for = "check" + val;
l.innerText = " "+val+" ";
checks.appendChild(l);
  var check = document.createElement("input");
  check.type = "checkBox";
  check.id = "check"+val;
  if(val == "All") {
  check.onchange = function() {
  if(this.checked == true)  {
  for(var i = 0;i<5;i++) {
    this.parentNode.elements[i].checked = true;
  }
  }
};
  }
  else {
  check.onchange = function() {
    document.getElementById("checkAll").checked = false;
  }
  }
  checks.appendChild(check);

}

function gen() {
var tests = [];
var boxes = checks.elements;
if(boxes[0].checked)genTests(tests,1,5,40);
if(boxes[1].checked)genTests(tests,10,4,40);
if(boxes[2].checked)genTests(tests,1000,3,40);
if(boxes[3].checked)genTests(tests,1e6,1,40);
if(boxes[4].checked)genTests(tests,1e9,0,40);
document.getElementById("box").value =  tests.join("\n");
}

function genTests(testArray,tMax,tDec,n) {
for(var i = 0;i<n;i++) {
  testArray.push(genNums(tMax,tDec).join(" "));
}
}

function genNums(tMax,tDec) {
var nums = genDigits();
nums.push(genTarget(tMax,tDec));
return nums;
}

function genTarget(tMax,tDec) {
  return genRand(tMax,tDec);
}

function genRand(limit,decimals) {
  var r = Math.random()*limit;
  return r.toFixed(decimals);
}

function genDigits() {
  var digits = [];
   for(var i = 0;i<5;i++) {
    digits.push(Math.floor(Math.random()*10));
   }
   return digits;
}
```

```
textarea {
  font-size: 14pt;
  font-family: "Courier New", "Lucida Console", monospace;
}

div {
text-align: center;
}
```

```
<div>
<label for="checks">Sections: </label><form id="checks"></form>
<input type="button" id="but" value="Generate Test Cases" /><br/><textarea id="box" cols=20 rows=15></textarea>
</div>
```

## Leaderboard

1. user202729 (C++): 2856, *152 wins*
2. mdahmoune (Python 2) \[v2\]: 2544, *48 wins*

### Section scores (# of wins):

1. \[0-1\] **user202729**: 40, mdahmoune: 0
2. \[0-10\] **user202729**: 40, mdahmoune: 0
3. \[0-1000\] **user202729**: 39, mdahmoune: 1
4. \[0-106\] **user202729**: 33, mdahmoune: 7
5. \[0-109\] user202729:0, **mdahmoune**: 40

Related: Generate a valid equation using user-specified numbers

# Answer
> 3 votes
# C++

```
// This program use radian mode

//#define DEBUG

#ifdef DEBUG
#define _GLIBCXX_DEBUG
#include <cassert>
#else
#define assert(x) void(0)
#endif

namespace std {
    /// Used for un-debug.
    struct not_cerr_t {
    } not_cerr;
}

template <typename T>
std::not_cerr_t& operator<<(std::not_cerr_t& not_cerr, T) {return not_cerr;}

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
#include <array>
#include <bitset>
#include <string>
#include <sstream>

#ifndef DEBUG
#define cerr not_cerr
#endif // DEBUG

// String conversion functions, because of some issues with MinGW
template <typename T>
T from_string(std::string st) {
    std::stringstream sst (st);
    T result;
    sst >> result;
    return result;
}

template <typename T>
std::string to_string(T x) {
    std::stringstream sst;
    sst << x;
    return sst.str();
}

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

const int N_ITER = 1000, N_DIGIT = 5, NSOL = 4;
std::array<int, N_DIGIT> digits;
double target;

typedef std::bitset<N_ITER> stfunc; // sin-tan expression
// where sin = 0, tan = 1

double eval(const stfunc& fn, int length, double value) {
    while (length --> 0) {
        value = fn[length] ? std::tan(value) : std::sin(value);
    }
    return value;
}

struct stexpr { // just a stfunc with some information
    double x = 0, val = 0; // fn<length>(x) == val
    int length = 0;
    stfunc fn {};
//    bool operator[] (const int x) {return fn[x];}
    double eval() {return val = ::eval(fn, length, x);}
};

struct expr { // general form of stexpr
    // note that expr must be *always* atomic.
    double val = 0;
    std::string expr {};

    void clear() {
        val = 0;
        expr.clear();
    }

    // cos(cos(x)) is in approx 0.5 - 1,
    // so we can expect that sin(x) and tan(x) behaves reasonably nice
    private: void wrapcos2() {
        expr = "(cos_2 " + expr + ")"; // we assume that all expr is atomic
        val = std::cos(std::cos(val));
    }

    public: void wrap1() {
        if (val == 0) {
            expr = "(cos " + expr + ")"; // we assume that all expr is atomic
            val = std::cos(val);
        }
        if (val == 1) return;
        wrapcos2(); // range 0.54 - 1
        int cnt_sqrt = 0;
        for (int i = 0; i < 100; ++i) {
            ++cnt_sqrt;
            val = std::sqrt(val);
            if (val == 1) break;
        }
        expr = "(sqrt_" + to_string(cnt_sqrt) + " " + expr + ")"; // expr must be atomic
    }
};

stexpr nearest(double initial, double target) {
    stexpr result; // built on the fn of that
    result.x = initial;
    double value [N_ITER + 1];
    value[0] = initial;
    for (result.length = 1; result.length <= N_ITER; ++result.length) {
        double x = value[result.length-1];
        if (x < target) {
            result.fn[result.length-1] = 1;
        } else if (x > target) {
            result.fn[result.length-1] = 0;
        } else { // unlikely
            --result.length;
//            result.val = x;
            result.eval();
            assert(result.val == x);
            return result;
        }
        value[result.length] = result.eval(); // this line takes most of the time
        if (value[result.length] == value[result.length-1])
            break;
    }

//    for (int i = 0; i < N_ITER; ++i) {
//        std::cerr << i << '\t' << value[i] << '\t' << (value[i] - target) << '\n';
//    }

    double mindiff = std::numeric_limits<double>::max();
    int resultlength = -1;
    result.length = std::min(N_ITER, result.length);
    for (int l = 0; l <= result.length; ++l) {
        if (std::abs(value[l] - target) < mindiff) {
            mindiff = std::abs(value[l] - target);
            resultlength = l;
        }
    }

    result.length = resultlength;
    double val = value[resultlength];
    assert(std::abs(val - target) == mindiff);
    if (val != target) { // second-order optimization
        for (int i = 1; i < result.length; ++i) {
            // consider pair (i-1, i)
            if (result.fn[i-1] == result.fn[i]) continue; // look for (sin tan) or (tan sin)
            if (val < target && result.fn[i-1] == 0) { // we need to increase val : sin tan -> tan sin
                result.fn[i-1] = 1;
                result.fn[i] = 0;
                double newvalue = result.eval();
//                if (!(newvalue >= val)) std::cerr << "Floating point sin-tan error 1\n";
                if (std::abs(newvalue - target) < std::abs(val - target)) {
//                    std::cerr << "diff improved from " << std::abs(val - target) << " to " << std::abs(newvalue - target) << '\n';
                    val = newvalue;
                } else {
                    result.fn[i-1] = 0;
                    result.fn[i] = 1; // restore
                    #ifdef DEBUG
                    result.eval();
                    assert(val == result.val);
                    #endif // DEBUG
                }
            } else if (val > target && result.fn[i-1] == 1) {
                result.fn[i-1] = 0;
                result.fn[i] = 1;
                double newvalue = result.eval();
//                if (!(newvalue <= val)) std::cerr << "Floating point sin-tan error 2\n";
                if (std::abs(newvalue - target) < std::abs(val - target)) {
//                    std::cerr << "diff improved from " << std::abs(val - target) << " to " << std::abs(newvalue - target) << '\n';
                    val = newvalue;
                } else {
                    result.fn[i-1] = 1;
                    result.fn[i] = 0; // restore
                    #ifdef DEBUG
                    result.eval();
                    assert(val == result.val);
                    #endif // DEBUG
                }
            }
        }
    }
    double newdiff = std::abs(val - target);
    if (newdiff < mindiff) {
        mindiff = std::abs(val - target);
        std::cerr << "ok\n";
    } else if (newdiff > mindiff) {
        std::cerr << "Program error : error value = " << (newdiff - mindiff) << " (should be <= 0 if correct) \n";
        std::cerr << "mindiff = " << mindiff << ", newdiff = " << newdiff << '\n';
    }
    result.eval(); // set result.result
    assert(val == result.val);

    return result;
}

expr nearest(const expr& in, double target) {
    stexpr tmp = nearest(in.val, target);
    expr result;
    for (int i = 0; i < tmp.length; ++i)
        result.expr.append(tmp.fn[i] ? "tan " : "sin ");

    result.expr = "(" + result.expr + in.expr + ")";
    result.val = tmp.val;
    return result;
}

int main() {
    double totalscore = 0;

    assert (std::numeric_limits<double>::is_iec559);
    std::cerr << std::setprecision(23);

//    double initial = 0.61575952241185627;
//    target = 0.6157595200093855;
//    stexpr a = nearest(initial, target);
//    std::cerr << a.val << ' ' << a.length << '\n';
//    return 0;

    while (std::cin >> digits[0]) {
        for (unsigned i = 1; i < digits.size(); ++i) std::cin >> digits[i];
        std::cin >> target;

/*        std::string e;
//        int sum = 0;
//        for (int i : digits) {
//            sum += i;
//            e.append(to_string(i)).push_back('+');
//        }
//        e.pop_back(); // remove the last '+'
//        e = "cos cos (" + e + ")";
//        double val = std::cos(std::cos((double)sum));
//
//        stexpr result = nearest(val, target); // cos(cos(x)) is in approx 0.5 - 1,
//        // so we can expect that sin(x) and tan(x) behaves reasonably nice
//        std::string fns;
//        for (int i = 0; i < result.length; ++i) fns.append(result.fn[i] ? "tan" : "sin").push_back(' ');
//
//        std::cout << (fns + e) << '\n';
//        continue;*/

        std::array<expr, NSOL> sols;
        expr a, b, c, d; // temporary for solutions

        /* ----------------------------------------
           solution 1 : nearest cos cos sum(digits) */

        a.clear();
        for (int i : digits) {
            a.val += i; // no floating-point error here
            a.expr.append(to_string(i)).push_back('+');
        }
        a.expr.pop_back(); // remove the last '+'
        a.expr = "(" + a.expr + ")";
        a.wrap1();

        sols[0] = nearest(a, target);

        /* -----------------------------------------
              solution 2 : a * tan(b) + c (also important) */

        // find b first, then a, then finally c
        a.clear(); b.clear(); c.clear(); // e = a, b = e1, c = e2

        a.expr = to_string(digits[0]);
        a.val = digits[0];
        a.wrap1();

        b.expr = "(" + to_string(digits[1]) + "+" + to_string(digits[2]) + ")";
        b.val = digits[1] + digits[2];
        b.wrap1();

        c.expr = to_string(digits[3]);
        c.val = digits[3];
        c.wrap1();

        d.expr = to_string(digits[4]);
        d.val = digits[4];
        d.wrap1();

        b = nearest(b, std::atan(target));

        double targetA = target / std::tan(b.val);
        int cnt = 0;
        while (targetA < 1 && targetA > 0.9) {
            ++cnt;
            targetA = targetA * targetA;
        }
        a = nearest(a, targetA);
        while (cnt --> 0) {
            a.val = std::sqrt(a.val);
            a.expr = "sqrt " + a.expr;
        }
        a.expr = "(" + a.expr + ")"; // handle number of the form 0.9999999999

        /// partition of any number to easy-to-calculate sum of 2 numbers
        {{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}

        double targetC, targetD; // near 1, not in [0.9, 1), >= 0.1
        // that is, [0.1, 0.9), [1, inf)

        double target1 = target - (a.val * std::tan(b.val));

        double ac = std::abs(target1), sc = sgn(target1);
        if (ac < .1) targetC = 1 + ac, targetD = -1;
        else if (ac < 1) targetC = 1 + ac/2, targetD = ac/2 - 1;
        else if (ac < 1.8 || ac > 2) targetC = targetD = ac/2;
        else targetC = .8, targetD = ac - .8;

        targetC *= sc; targetD *= sc;

        c = nearest(c, std::abs(targetC)); if (targetC < 0) c.val = -c.val, c.expr = "(-" + c.expr + ")";
        d = nearest(d, std::abs(targetD)); if (targetD < 0) d.val = -d.val, d.expr = "(-" + d.expr + ")";

        sols[1].expr = a.expr + "*tan " + b.expr + "+" + c.expr + "+" + d.expr;
        sols[1].val = a.val * std::tan(b.val) + c.val + d.val;

        std::cerr
        << "\n---Method 2---"
        << "\na = " << a.val
        << "\ntarget a = " << targetA
        << "\nb = " << b.val
        << "\ntan b = " << std::tan(b.val)
        << "\nc = " << c.val
        << "\ntarget c = " << targetC
        << "\nd = " << d.val
        << "\ntarget d = " << targetD
        << "\n";

        /* -----------------------------------------
              solution 3 : (b + c) */

        target1 = target / 2;
        b.clear(); c.clear();

        for (int i = 0; i < N_DIGIT; ++i) {
            expr &ex = (i < 2 ? b : c);
            ex.val += digits[i];
            ex.expr.append(to_string(digits[i])).push_back('+');
        }
        b.expr.pop_back();
        b.expr = "(" + b.expr + ")";
        b.wrap1();

        c.expr.pop_back();
        c.expr = "(" + c.expr + ")";
        c.wrap1();

        b = nearest(b, target1);
        c = nearest(c, target - target1); // approx. target / 2

        sols[2].expr = "(" + b.expr + "+" + c.expr + ")";
        sols[2].val = b.val + c.val;

        /* -----------------------------------------
              solution 4 : a (*|/) (b - c)  (important) */

        a.clear(); b.clear(); c.clear(); // a = a, b = e1, c = e2

        a.expr = to_string(digits[0]);
        a.val = digits[0];
        a.wrap1();

        b.expr = "(" + to_string(digits[1]) + "+" + to_string(digits[2]) + ")";
        b.val = digits[1] + digits[2];
        b.wrap1();

        c.expr = "(" + to_string(digits[3]) + "+" + to_string(digits[4]) + ")";
        c.val = digits[3] + digits[4];
        c.wrap1();

        // (b-c) should be minimized
        bool multiply = target < a.val;
        double factor = multiply ? target / a.val : a.val / target;

        target1 = 1 + 2 * factor; // 1 + 2 * factor and 1 + factor

        std::cerr << "* Method 4 :\n";
        std::cerr << "b initial = " << b.val << ", target = " << target1 << ", ";
        b = nearest(b, target1);
        std::cerr << " get " << b.val << '\n';

        std::cerr << "c initial = " << c.val << ", target = " << b.val - factor << ", ";
        c = nearest(c, b.val - factor); // factor ~= e1.val - e2.val
        std::cerr << " get " << c.val << '\n';

        sols[3].expr = "(" + a.expr + (multiply ? "*(" : "/(") +
        ( b.expr + "-" + c.expr )
        + "))";
        factor = b.val - c.val;
        sols[3].val = multiply ? a.val * factor : a.val / factor;

        std::cerr << "a.val = " << a.val << '\n';

        /* ----------------------------------
                    Final result */

        int minindex = 0;
        assert(NSOL != 0);
        for (int i = 0; i < NSOL; ++i) {
            if (std::abs(target - sols[i].val) < std::abs(target - sols[minindex].val)) minindex = i;
            std::cerr << "Sol " << i << ", diff = " << std::abs(target - sols[i].val) << "\n";
        }
        std::cerr << "Choose " << minindex << "; target = " << target << '\n';
        totalscore += std::abs(target - sols[minindex].val);

        std::cout << sols[minindex].expr << '\n';
    }

    // #undef cerr // in case no-debug
    std::cerr << "total score = " << totalscore << '\n';
}

```

Input from standard input, output to standard output.

# Answer
> 2 votes
# Python 2, radians, score 0.0032 on official test

This is the second draft solution gives an average score of 0.0032 points. As it uses a composition of a lot of `sin` I used the following compact notation for the output formula:

* `sin_1 x=sin(x)`
* `sin_2 x=sin(sin(x))`
* `...`
* `sin_7 x=sin(sin(sin(sin(sin(sin(sin(x)))))))`
* `...`

```
import math
import bisect
s1=[[float(t) for t in e.split()] for e in s0.split('\n')]
maxi=int(1e7)
A=[]
B=[]
C=[]
D=[]
a=1
for i in range(maxi):
	A.append(a)
	C.append(1/a)
	b=math.sin(a)
	c=a-b
	B.append(1/c)
	D.append(c)
	a=b
B.sort()
C.sort()
A.sort()
D.sort()
d15={0:'sqrt_100 tan_4 cos_2 sin 0',1:'sqrt_100 tan_4 cos_2 sin 1',2:'sqrt_100 tan_2 cos_2 sin 2',3:'sqrt_100 tan_4 cos_2 sin 3',4:'sqrt_100 tan_4 cos_2 sin 4',5:'sqrt_100 tan_4 cos_2 sin 5',6:'sqrt_100 tan_4 cos_2 sin 6',7:'sqrt_100 tan_2 cos_2 sin 7',8:'sqrt_100 tan_2 cos_2 sin 8',9:'sqrt_100 tan_4 cos_2 sin 9'}
def d16(d):return '('+d15[d]+')'

def S0(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(B, r)-1
	w1=abs(r-B[i1])
	i2=bisect.bisect(C, w1)-1
	w2=abs(w1-C[i2])
	s='('+d16(a1)+'/(sin_'+str(i1)+' '+d16(a2)+'-'+'sin_'+str(i1+1)+' '+d16(a3)+')'+'+'+d16(a4)+'/sin_'+str(i2)+' '+d16(a5)+')'
	return (w2,s)

def S1(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(C, r)-1
	w1=abs(r-C[i1])
	i2=bisect.bisect(A, w1)-1
	w2=abs(w1-A[i2])
	s='('+d16(a1)+'/sin_'+str(i1)+' '+d16(a2)+'+sin_'+str(maxi-i2-1)+' ('+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')'
	return (w2,s)

def S2(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(A, r)-1
	w1=abs(r-A[i1])
	i2=bisect.bisect(D, w1)-1
	w2=abs(w1-D[i2])
	s='('+'(sin_'+str(maxi-i2-1)+' '+d16(a1)+'-'+'sin_'+str(maxi-i2)+' '+d16(a2)+')'+'+sin_'+str(maxi-i1-1)+' ('+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+'))'
	return (w2,s)

def S3(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(A, r)-1
	w2=abs(r-A[i1])
	s='('+'sin_'+str(maxi-i1-1)+' ('+d16(a1)+'*'+d16(a2)+'*'+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+'))'
	return (w2,s)

def S4(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(B, r)-1
	w2=abs(r-B[i1])
	s='('+d16(a1)+'/(sin_'+str(i1)+' '+d16(a2)+'-'+'sin_'+str(i1+1)+' '+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')'+')'
	return (w2,s)

def S5(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(C, r)-1
	w2=abs(r-C[i1])
	s='('+d16(a1)+'/sin_'+str(i1)+' '+d16(a2)+'*'+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')'
	return (w2,s)

def S6(l):
	cpt=0
	d=l[:-1]
	r=l[-1]
	a1,a2,a3,a4,a5=[int(t) for t in d]
	i1=bisect.bisect(D, r)-1
	w2=abs(r-D[i1])
	s='(sin_'+str(maxi-i1-1)+' '+d16(a1)+'-'+'sin_'+str(maxi-i1)+' '+d16(a2)+'*'+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')'
	return (w2,s)

def all4(s1):
	s=0
	for l in s1:
		f=min(S0(l),S1(l),S2(l),S3(l),S4(l),S5(l),S6(l))
		print f[1]
		s+=f[0]
	s/=len(s1)
	print 'average unofficial score:',s
all4(s1)

```

Try it online!

---
Tags: code-challenge, test-battery, expression-building
---


title: Format a US address

text:
# Question
Title: Format a US address
Your task is to format an address given in all lowercase to a friendlier format. Here's the catch, **no regexes**.

Addresses will be given in the following format:

`123 serpentine pl ne shoreline wa 98199`

The expected output is the following: (notice the period and commas)

`123 Serpentine Pl. NE, Shoreline WA, 98199`

**Formatting Rules**

* Cardinal directions should be capitalized, e.g. "e" --\> "E", "nw" --\> "NW".
* Abbreviations for streets, avenues, etc. should have the first letter capitalized with the abbr. followed by a period (".") e.g "st" --\> "St.", "ave" --\> "Ave.".
* State abbreviation should be in all caps
* A comma is placed after each section. i.e. after the street address and state and city.
* Capitalize the city and street/avenue/place.

**EDIT**: Addresses will always be given in the above format *except* with or without a cardinal direction.

Your code should also be able to handle "st" and "ave". The input is given through `stdin`. This is code-golf so the shortest code in bytes wins.

# Answer
# Perl 6: ??? characters

The simplest Perl 6 solution is probably: (*61 characters*)

```
$/=get.wordcase.words;"$0 $1 $2. $3.uc(), $4 $5.uc(), $6".say

```

Unfortunately, I don't feel comfortable using this, since `.wordcase` and `.words` are both implemented internally using regexes. Thus: (also, oddly, *61 characters*)

```
$/=get.split(' ')».tc;"$0 $1 $2. $3.uc(), $4 $5.uc(), $6".say

```

BUT this only handles the specific address given in the problem. Consider:

```
42 awesome ln dogeland hi 96899

```

I see this as valid under to be formatted given the rules above, and this should be formatted as `42 Awesome Ln., Dogeland HI, 96899` rather than `42 Awesome Ln. DOGELAND, Hi 96899,`. So let's fix the case that a cardinal direction isn't included: (*136 characters*)

```
my@a=get.split(" ")».tc;@a[3].=uc if @a[3] eq tc any "n","s","" X~ "e","w","";@a[2]~=".";say "@a[0..*-4], @a[*-3] @a[*-2].uc(), @a[*-1]"

```
> 6 votes

# Answer
# Lua - 462

```
_=_G d={n=_,nw=_,sw=_,s=_,se=_,e=_,ne=_,al=_,ak=_,az=_,ar=_,ca=_,co=_,ct=_,de=_,dc=_,fl=_,ga=_,hi=_,id=_,il=_,["in"]=_,ia=_,ks=_,ky=_,la=_,me=_,md=_,ma=_,mi=_,mn=_,ms=_,mo=_,mt=_,nv=_,nh=_,nj=_,nm=_,ny=_,nd=_,oh=_,ok=_,["or"]=_,pa=_,ri=_,sc=_,sd=_,tn=_,tx=_,ut=_,vt=_,va=_,wa=_,wv=_,wi=_,wy=_}l={pl=_,st=_,ave=_,hw=_}print((io.read"*a":gsub("%w+",function(x)if d[x]then return x:upper()..","end return x:sub(1,1):upper()..x:sub(2):lower()..(l[x]and"."or"")end)))

```

The first is a list of states and directions, the second is a list of places.
One might argue that gsub is using regular expressions, but lua uses *patterns*, that are close, but not exactly are regexes. They cannot match regular languages and don't even have a proper Klenee star.

Example:

```
 $ lua % <<< '123 serpentine pl ne shoreline wa 98199'
 123 Serpentine Pl. NE, Shoreline WA, 98199

```
> 1 votes

# Answer
# Javascript

```
b="123 serpentine pl ne shoreline wa 98199".split(" ");
c=[];
cap = function(l){var code=parseInt(l.charCodeAt(0));if(code>=97&&code<=122){l=String.fromCharCode(code-32);}return l;}
c[0]=b[0];
c[6]=b[6];
b.forEach(function(txt,index){
 tx=txt.split("");
 switch(index){
     case 1:case 4:tx[0]=cap(tx[0]);c[index]=tx.join("");break;
     case 2:case 3:case 5:tx.forEach(function(t,idx){
            tx[idx]=cap(t);
        });
        c[index]=tx.join("");
        break;
      }
});

//now
output=c[0]+" "+c[1]+" "+c[2]+". "+c[3]+", "+c[4]+" "+c[5]+", "+c[6];

```
> 1 votes

# Answer
# Python3 ~~137~~ 122

```
i=input().split()
c=lambda x:x.capitalize()
print(i[0],c(i[1]),c(i[2])+".",i[3].upper()+",",c(i[4]),i[5].upper()+",",i[6])

```

```
>python main.py
123 serpentine pl ne shoreline wa 98199  #Pasted
123 Serpentine Pl. NE, Shoreline WA, 98199  #Output
>

```
> 1 votes

# Answer
# Python2

(based on other python3 answer)

```
i=raw_input().split()
i=map(lambda x:x.capitalize(),i)
print " ".join((i[0],i[1],i[2]+".",i[3].upper()+",",i[4] ,i[5].upper()+",",i[6]))

```

running in Windows cmd

```
C:\Python27>python main.py
123 serpentine pl ne shoreline wa 98199 #Pasted
123 Serpentine Pl. NE, Shoreline WA, 98199 #Output

```
> 0 votes

# Answer
# Powershell v4

```
$h=Read-Host
$i=(Get-Culture).TextInfo.ToTitleCase($h).Split()
($i[0..2 ] -join " ")+". "+$i[-4].ToUpper()+", "+$i[-3]+" "+$i[-2].ToUpper()+",",$i[-1]

```

running

```
C:\>powershell .\address.ps1
123 serpentine pl ne shoreline wa 98199 #Pasted
123 Serpentine Pl. NE, Shoreline WA, 98199 #Output

```
> 0 votes

---
Tags: code-golf, restricted-source
---


title: How to pluralize ellipsis?

text:
# Question
Title: How to pluralize ellipsis?
It's obviously ellipsisessieses.

Inspired by a chat message.

# Your challenge

Given a list or space or comma-separated string of words, ellipsisessiesesify them.

To ellipsisessieses-ify a word:

1. Start with the word.
2. Add the first letter of the original word to the end.
3. Add 2 of the last letter of the original word to the end.
4. Add the second-to-last letter of the original word to the end.
5. Add the first letter of the original word to the end.
6. Add the last letter of the original word to the end.
7. Repeat steps 5 & 6 once.
8. You're done!

# You can assume:

* The input words will only be alphanumeric
* Input & output can be a space-separated string or list
* The input will contain only words
* The words will be at least 2 letters long
* The input will match the regex `/^[a-z0-9]{2,}( [a-z0-9]{2,})*$/i`
* You can have a different input and output format
* *More to come...*

# Test cases:

```
ellipsis -> ellipsisessieses
goat -> goatgttagtgt
covfefe -> covfefeceefcece
programmer5000 -> programmer5000p000p0p0
up vote down goat -> upuppuupup voteveetveve downdnnwdndn goatgttagtgt
it is golf yo -> itittiitit isissiisis golfgfflgfgf yoyooyyoyo
crossed out 44 is still 44 -> crossedcddecdcd outottuotot 4444444444 isissiisis stillslllslsl 4444444444

```

Shorteststtsstst answerarrearar ininniinin bytesbssebsbs winswssnwsws!

# Answer
> 15 votes
# JavaScript (ES6), ~~58~~ 57 bytes

*NB: This turns out to use the same trick as Jonathan Allan in this Jelly answer (though I noticed after posting).*

*Saved 1 byte thanks to Jonathan Allan*

Works on arrays of strings.

```
s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1)))

```

### Test cases

```
let f =

s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1)))

console.log(f(['ellipsis']))
console.log(f(['goat']))
console.log(f(['covfefe']))
console.log(f(['programmer5000']))
console.log(f(['up', 'vote', 'down', 'goat']))
console.log(f(['it', 'is', 'golf', 'yo']))
console.log(f(['crossed', 'out', '44', 'is', 'still', '44']))
```

# Answer
> 11 votes
# Jelly,  ~~13 12~~  11 bytes

```
⁽×ʠb3’ịṭµ€K

```

A full program that takes a list of lists of characters and prints the space separated output.

**Try it online!**

### How?

```
⁽×ʠb3’ịṭµ€K - Main link: list of lists of characters e.g. ["this","is","it"]
        µ€  - for each word in the input:            e.g. "this"
⁽×ʠ         -   base 250 literal 5416                     5416
   b3       -   converted to base 3                       [2,1,1,0,2,1,2,1]
     ’      -   decrement                                 [1,0,0,-1,1,0,1,0]
      ị     -   index into the word                       "tssitsts"
       ṭ    -   tack to the word                          ["this",["tssitsts"]]
          K - join the results with spaces                ["this",["tssitsts"]," is",["issiisis"]," it",["ittiitit"]]
            - implicit print                              thistssitsts isissiisis itittiitit

```

---

Alternatively a list of words to list of words is also possible in **11 bytes**:

```
⁽×ʠb3’ị;@µ€

```

`⁽×ʠb3’` may also be replaced by `4,⁵Bj-` for the same byte count
(`[4,10]` in binary is `[[1,0,0],[1,0,1,0]]` joined by `-1` is `[1,0,0,-1,1,0,1,0]`).

# Answer
> 6 votes
# 05AB1E, 12 bytes

```
εD•Lz•3вÍèJ«

```

Try it online!

**Explanation**

```
ε              # apply on each word in input
 D             # duplicate the word
  •Lz•         # push the base-255 compressed number 5416
      3в       # convert to a list of base-3 digits (yields [2, 1, 1, 0, 2, 1, 2, 1])
        Í      # subtract 2 from each (yields [0, -1, -1, -2, 0, -1, 0, -1])
         è     # index into the word with these numbers
          J    # join to string
           «   # append to the original word

```

# Answer
> 5 votes
# Retina, ~~52~~ 49 bytes

3 bytes thanks to Arnauld.

```
(\w)(\w+)
$1$2$1
(.)(.)(.)\b
$1$2$3$2$2$1$3$2$3$2

```

Try it online!

# Answer
> 4 votes
# Python 2, 56 bytes

```
lambda s:[i+i[0]+i[-1]*2+i[-2]+(i[0]+i[-1])*2for i in s]

```

Try it online!

I think this is my fastest FGITW and it's not even that impressive. :P

# Answer
> 3 votes
# Python 3, 60 bytes

```
lambda k:[x+''.join(x[-int(i)]for i in"01120101")for x in k]

```

Try it online!

# Answer
> 3 votes
# Charcoal, 20 bytes

```
Ｆ⪪Ｓ «ι↑Ｅ”o∨↙8”§ι±Ｉκ→

```

Try it online! Link is to verbose version of code. Only happened to read @Arnauld's answer after coding this but this is basically a port of it. Explanation:

```
Ｆ   «                   Loop over
  Ｓ                     Input string
 ⪪                       Split at spaces
     ι                  Print the word
        ”o∨↙8”          Compressed string 01120101
       Ｅ                Map over each character
                 Ｉκ     Cast character to integer
                ±       Negate
              §ι        Circularly index into word
      ↑                 Print array upwards, prints each element rightwards
                    →    Move right

```

# Answer
> 3 votes
# sed, 46 bytes

```
s/^\(\(.\).*\(.\)\(.\)\)$/\1\2\4\4\3\2\4\2\4/g

```

Try it online!

# Answer
> 2 votes
# Dyalog APL, ~~51~~ 49 bytes

Requires `⎕ML←3`

```
∊{⍺,' ',⍵}/{S←1,L←≢⍵⋄⍵,⍵[∊S(L-0 1)S S]}¨' '(≠⊂⊢)⍞

```

-9 bytes thanks to @Adám in chat!

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), ~~74~~ 60 bytes

```
s=>s.map(s=>s+(a=s[l=s.length-1],b=s[0])+a+a+s[l-1]+b+a+b+a)

```

Takes input as an array, and outputs an array.

-9 bytes thanks to Programmer5000

**Test cases:**

```
let f=

s=>s.map(s=>s+(a=s[l=s.length-1],b=s[0])+a+a+s[l-1]+b+a+b+a)

console.log(JSON.stringify(f(['ellipsis']))) // ellipsisessieses
console.log(JSON.stringify(f(['goat']))) // goatgttagtgt
console.log(JSON.stringify(f(['covfefe']))) // covfefeceefcece
console.log(JSON.stringify(f(['programmer5000']))) // programmer5000p000p0p0
console.log(JSON.stringify(f(['up', 'vote', 'down', 'goat']))) // upuppuupup,voteveetveve,downdnnwdndn,goatgttagtgt
console.log(JSON.stringify(f(['it', 'is', 'golf', 'yo']))) // itittiitit,isissiisis,golfgfflgfgf,yoyooyyoyo
console.log(JSON.stringify(f(['crossed', 'out', '44', 'is', 'still', '44']))) // crossedcddecdcd,outottuotot,4444444444,isissiisis,stillslllslsl,4444444444
```

# Answer
> 2 votes
# Mathematica, 89 bytes

```
((f[a_]:=#~StringTake~a;k=#<>(q=f@1)<>(w=f[-1])<>w<>f@{-2}<>q<>w<>q<>w)&/@StringSplit@#)&

```

# Answer
> 2 votes
# Pyth, 17 bytes

Uses the same trick as in @Jonathan's answer.

```
m+dsm@dttkj5416 3

```

**Try it here!** or **Check out the test Suite** (Give it some time).

Port of my Python solution, ~~**19 bytes**~~ **18 bytes**:

```
m+dsm@d_k+0j1144 3

```

# Answer
> 2 votes
# Paradoc (v0.2.10), 13? bytes (CP-1252)

```
µ96Qó3BÌDX=v+

```

Try it online!

Takes a list of words, and results in a list of words on the stack.

A small variation on the base-3 trick. Maybe it's time to work on my base 250-whatever compressor.

Explanation:

```
μ             .. Map the following block over each word (the block is
              .. terminated by }, but that doesn't exist, so until EOF)
              .. (The word is on the stack now.)
 96Qó         .. 96 * 26 (Q in base 26) = 2496, a hack to prevent us from
              .. needing a space to separate this from the following number.
     3B       .. Convert 2496 to base 3 to get [1,0,1,0,2,1,1,0]
       ÌD     .. Negate and reverse to get [0,-1,-1,-2,0,-1,0,-1]
         X    .. Push the loop variable: the word being mapped over
          =v  .. Index, vectorize; map over the indices by indexing them
              .. into the word
            + .. Concatenate with the original word

```

(Byte-counting question: Now that I'm actually demonstrating this in TIO, it take a list of words on the stack and results in a list of words on the stack, but you can't really do much with that list of words unless you close the block started by µ. Should I count that closing brace?)

# Answer
> 2 votes
# Wolfram Language/Mathematica, 66 bytes

```
StringJoin[StringSplit[#,""]/.{a_,___,b_,c_}:>{#,a,c,c,b,a,c,a,c}]&

```

Just whipped it up real quick, might have a minor improvement here or there.

# Answer
> 1 votes
# Charcoal, ~~38~~ 30 bytes

*-8 bytes thanks to ASCII-only.*

```
Ｆ⪪Ｓ «ι§ι⁰×²§ι±¹§ι±²×²⁺§ι⁰§ι±¹

```

Try it online! Link is to verbose version.

Note the trailing space.

# Answer
> 1 votes
# Perl 5, ~~55~~ 49 + 1 (-a) = ~~56~~ 50 bytes

*used a trick from @Arrnauld's post to save a couple bytes*

```
say map$_.'01120101 '=~s/\d/substr$_,-$&,1/egr,@F

```

Try it online!

# Answer
> 1 votes
# Java 8, 117 bytes

```
a->{int i=0,l;for(String s:a){char c=s.charAt(0),d=s.charAt(l=s.length()-1);a[i++]+=""+c+d+d+s.charAt(l-1)+c+d+c+d;}}

```

Takes the input as a String-array, and modified this original array instead of returning a new one to save bytes.

Can most likely be golfed some more..

**Explanation:**

Try it here.

```
a->{                          // Method with String-array as parameter and no return-type
  int i=0,                    //  Index-integer (starting at 0)
      l;                      //  Length-integer which we use multiple times
  for(String s:a){            //  Loop over the input array
    char c=s.charAt(0),       //   The first character of the word
         d=s.charAt(          //   The last character of the word
            l=s.length()-1);  //    and set `l` at the same time to `length()-1`
    a[i++]+=                  //   Append to the current value in the array:
      ""                      //    String so the characters aren't appended as integers
      +c                      //    + the first character
      +d+d                    //    + two times the last character
      +s.charAt(l-1)          //    + the single-last character
      +c+d+c+d;               //    + the first + last character two times
  }                           //  End of loop
}                             // End of method

```

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

```
n=>{for(int i=0,x;i<n.Length;){var h=n[i];x=h.Length-1;char y=h[0],j=h[x];n[i++]=h+y+j+j+h[x-1]+y+j+y+j;}}

```

Try it online!

Lambda function that takes input as array of strings, and modifies original array for output

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


# Question
Title: Crazy Librarian's Amazing Sorting System
It's back to school season! So for a part-time job, you're helping out at the school's library. The problem is, the head librarian has never even heard the words "Dewey Decimal," let alone implemented that system. Instead, the sorting system in use has grown "organically" as the library has expanded...

In an effort to keep your sanity, you've elected to write a program to help you sort books as they're returned, because woe unto you if you sort the books wrong. (The head librarian is VERY strict.)

## Input / Output

* The input will be a list of (hypothetical) book titles, one per line, from STDIN / language equivalent.
* You can assume no more than 100 books input at a time (you can only carry so many around the library at once).
* Books can have multiple words in their titles, and these words may be separated by spaces or other punctuation (e.g., a colon`:`, a dash`-`, etc.).
* For ease of calculation, assume all titles are UTF-8.

Output is the same titles, sorted according to the below rules, again one per line, to STDOUT / language equivalent.

## The Sorting Rules

Books are sorted numerically based on their average character value (i.e., cumulative character value divided the number of characters in the book title), counted by the following rules:

* All characters count for determining the number of characters in a title.
* Lowercase letters are counted by their position in the alphabet. (a=1,b=2,...z=26)
* If the title contains capital letters, those count for 1.5 their lowercase value (A=1.5,B=3,...Z=39). *("Capital letters are important!" says the librarian.)*
* Each punctuation mark / symbol in this list `!@#$%^&*()-=_+[]\{}|;':",./<>?~` counts -1 from the cumulative value before averaging. *("Grandiose titles are not!")*
* If the title contains a number, written in Arabic numerals, that number is subtracted from the average value before sorting. Multiple consecutive digits are treated as one number (e.g., `42` would subtract 42, not subtract 4 and then subtract 2). Individual digits don't count for the cumulative value (i.e., each digit contributes 0), but DO count for number of characters. Note that this may result in a negative value and should be treated appropriately. *(Rumor has it, the librarian has had a crush on a math instructor for several years, now.)*
* If the title contains two separate words that start with an `R`, the book gets a score of "infinity" and is dumped into a pile in the corner (i.e., randomly arranged at the end of the list). *(The librarian was once dumped by a person with those initials, or so you've heard.)*
* Spaces don't count for the cumulative character value (i.e., they contribute 0), but DO contribute to the number of characters in a title.
* Characters that don't fit the above rules (e.g, a `ÿ`) don't count for the cumulative character value (i.e., they contribute 0), but DO contribute to the number of characters in a title.
* For example, a hypothetical book `ÿÿÿÿÿ` would have a "score" of `(0+0+0+0+0) / 5 = 0`, but a hypothetical book `ÿÿyÿÿ` would have a "score" of `(0+0+25+0+0) / 5 = 5`.
* Two books that happen to "score" the same can be Output in your choice of order. *(They're on the same shelf, anyway)*

### Example Input 1

```
War and Peace
Reading Rainbow: The Best Unicorn Ever
Maus
Home for a Bunny

```

### Example Output 1 (with "scores" in parentheses to show reasoning - you don't need to print them)

```
War and Peace (8.5)
Home for a Bunny (10.125)
Maus (15.125)
Reading Rainbow: The Best Unicorn Ever (infinity)

```

### Example Input 2

```
Matthew
Mark
Luke
John
Revelations

```

### Example Output 2 (with "scores" in parentheses to show reasoning - you don't need to print them)

```
Mark (12.375)
John (13)
Revelations (13.545454...)
Luke (13.75)
Matthew (~13.786)

```

### Example Input 3

```
42
9 Kings
1:8
7th

```

### Example Output 3 (with "scores" in parentheses to show reasoning - you don't need to print them)

```
42 (-42)
1:8 (-9.3333...)
9 Kings (~0.36)
7th (2.3333...)

```

## Other restrictions

* This is Code-Golf, because you need to keep the program secret from the ever-watching eyes of the librarian, and the smaller the program, the easier it is to hide.
* Standard loophole restrictions apply
* Don't let the librarian catch you slacking off by spending all your time on PPCG.

# Answer
> 5 votes
# APL (132)

```
{⎕ML←3⋄⍵[⍋{2='R'+.=↑¨⍵⊂⍨⍵≠' ':!99⋄↑(+/⍎¨'0',⍵⊂⍨⍵∊⎕D)-⍨((+/∊1.5 1×(⍳×∊⍨)∘⍵¨G)-+/⍵∊(⎕UCS 32+⍳94)~'`',⎕D,∊G←(⊂⎕A),⊂⎕UCS 96+⍳26)÷⍴⍵}¨⍵]}

```

Since everyone else is doing the same thing, this too is a function that takes an array of titles and returns it sorted, e.g.:

```
      titles
┌─────────────┬──────────────────────────────────────┬────┬────────────────┬───────┬────┬────┬────┬───────────┬──┬───────┬───┬───┐
│War and Peace│Reading Rainbow: The Best Unicorn Ever│Maus│Home for a Bunny│Matthew│Mark│Luke│John│Revelations│42│9 Kings│1:8│7th│
└─────────────┴──────────────────────────────────────┴────┴────────────────┴───────┴────┴────┴────┴───────────┴──┴───────┴───┴───┘

      {⎕ML←3⋄⍵[⍋{2='R'+.=↑¨⍵⊂⍨⍵≠' ':!99⋄↑(+/⍎¨'0',⍵⊂⍨⍵∊⎕D)-⍨((+/∊1.5 1×(⍳×∊⍨)∘⍵¨G)-+/⍵∊(⎕UCS 32+⍳94)~'`',⎕D,∊G←(⊂⎕A),⊂⎕UCS 96+⍳26)÷⍴⍵}¨⍵]}titles
┌──┬───┬───────┬───┬─────────────┬────────────────┬────┬────┬───────────┬────┬───────┬────┬──────────────────────────────────────┐
│42│1:8│9 Kings│7th│War and Peace│Home for a Bunny│Mark│John│Revelations│Luke│Matthew│Maus│Reading Rainbow: The Best Unicorn Ever│
└──┴───┴───────┴───┴─────────────┴────────────────┴────┴────┴───────────┴────┴───────┴────┴──────────────────────────────────────┘

```

Explanation:

* `⎕ML←3`: set `⎕ML` to `3` (for )
* `⍵[⍋{`...`}¨⍵]`: sort the input by the values returned from the inner function
    + `↑¨⍵⊂⍨⍵≠' '`: get the first character of each word
    + `2='R'+.=`: see if two of these are `'R'`.
    + `:!99`: if so, return 99! (≈ 9.3×10155). This is not quite infinity, but it'll do: a title can never have a score more than 38 times its length (ZZZZ...), so as long as no single title is bigger than about 2×10130 yottabytes, it is guaranteed that these will be at the end.
    + : otherwise:
    + `(`...`)÷⍴⍵`: divide the score by the length of  after calculating it:
        - `G←(⊂⎕A),(⎕UCS 96+⍳26)`: store in `G` the uppercase and lowercase letters
        - `(⎕UCS 32+⍳94)~'`',⎕D,∊G`: the printable ASCII characters, except letters, digits, spaces and `'`'`, which are the characters for which a point is subtracted. (This is shorter than writing them all out, because `G` is used later on.)
        - `+/⍵∊`: count the amount of these characters in
        - `-`: subtract this from:
        - `+/∊1.5 1×(⍳×∊⍨)∘⍵¨G`: the sum of 1.5 × the scores for the capitals, and 1 × the scores for the lowercase letters.
    + `-⍨`: afterwards, subtract the total of the numbers in :
        - `⍵⊂⍨⍵∊⎕D`: find the groups of digits in
        - `'0',`: add `'0'`, to prevent the list being empty
        - `⍎¨`: evaluate each string
        - `+/`: find the sum

# Answer
> 2 votes
# Lua 5.3, ~~366~~ 364 Bytes

```
r={}for i,s in ipairs(arg)do n=0 s:gsub("%l",function(a)n=n+(a:byte()-96)end):gsub("%u",function(a)n=n+(a:byte()-64)*1.5 end):gsub("%p",function(a)n=n-1 end):gsub("^R?.- R.- ?R?",function()n=math.huge end)m=n/utf8.len(s)s:gsub("%d+",function(a)m=m-a end)table.insert(r,{s=s,n=m})end table.sort(r,function(a,b)return a.n<b.n end)for i,v in ipairs(r)do print(v.s)end

```

This code only works in Lua 5.3 because it needs to deal with Unicode characters. If you don't care about Unicode, then replace "utf8" with "string" and it will work fine with Lua 5.2 or 5.1.

It takes its inputs from command-line arguments, so either run it from the command line or put this code above my answer:

```
arg = {"Title 1", "Title 2", "Title 3"}

```

# Answer
> 2 votes
# JavaScript (ES6), 210 ~~218 251~~

As a function with an array argument, returned sorted.

```
f=L=>(S=s=>([...s].map(c=>t-=(a=s.charCodeAt(l++))>32&a<48|a>57&a<65|a>90&a<96|a>122&a<127?1:a>64&a<123?96-(a<96?a*1.5:a):0,l=t=0),s.split(/\D/).map(n=>t-=n,t/=l),t/!s.split(/\bR/)[2]),L.sort((a,b)=>S(a)-S(b)))

//TEST

test1=['War and Peace','Reading Rainbow: The Best Unicorn Ever','Maus','Home for a Bunny']
test2=['Matthew','Mark','Luke','John','Revelations']
test3=['42','9 Kings','1:8','7th']

;O.innerHTML=f(test1)+'\n\n'+f(test2)+'\n\n'+f(test3);

// The comparing function used to sort, more readable

Sort=s=>(
  t = 0, // running total
  l = 0, // to calc the string length avoiding the '.length' property
  [...s].map(c=>{
    a=s.charCodeAt(l++);
    t-=a>32&a<48|a>57&a<65|a>90&a<96|a>122&a<127
      ? 1 // symbols (ASCII char except space, alphanumeric and backtick)
      : a>64&a<123
        ? 96-(a<96?a*1.5:a) // alphabetic both upcase and lowcase, and backtick
        // lowcase: 96-a, upcase (64-a)*1.5=>96-a*1.5, backtick is 96 and 96-96 == 0
        : 0 // else space, non ASCII, and numeric : 0
  }),
  t = t/l, // average
  s.split(/\D/).map(n=>t-=n), // sub number values
  f = s.split(/\bR/)[2], // split at words starting with R, if less then 2 f is undefined
  t/!f // dividing by not f I can get the infinity I need
)
```

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

# Answer
> 2 votes
# Mathematica, ~~253~~ 216 bytes (214 chars)

```
r=RegularExpression;c=ToCharacterCode;f=SortBy[Tr@Flatten@Reap[StringCases[#,
{r@"(\\bR.*)+"->∞,r@"\\d+":>0Sow@-FromDigits@"$0",r@"[a-z]":>c@"$0"-96,
r@"[A-Z]":>1.5c@"$0"-96,r@"[!-/:-@[-_{-~]"->-1}]/StringLength@#]&]

```

Call the function like `f[{"42", "9 Kings", "1:8", "7th"}]`; it will return a sorted list of the inputs.

Just barely made it! *Mathematica*'s pattern matching is not as concise when strings are involved, and I just get killed by those long names. The extra two bytes are for the `Infinity` unicode character.

(Let me know if I've fallen afoul of any Standard Loopholes.)

## Update

Looking a little closer at edc65's answer, it looks like the OP will accept a function that sorts a list of strings. With that in mind we can use the curried form of `SortBy` (which *Mathematica* calls the "operator form"); with one argument (the function applied to the list elements to determine their order) it behaves like a function that takes one argument, returning the sorted form of the input; that is, `SortBy[list, f]` is equivalent to `(SortBy[f])[list]`.

# Ungolfed

```
Function[{titles},
  SortBy[titles, Function[{str}, (* sort by function value *)
    Total[Flatten[Reap[ (* total up all the parts *)
      StringCases[str, {
        RegularExpression["(\\bR.*){2}"] -> Infinity
          (* matches R at the start of a word twice, adds infinity to the total *),
        RegularExpression["\\d+"] :> 0 * Sow[-FromDigits["$0"]]
          (* matches a number, Sows it for Reap to collect, then multiplies by zero
                                                          to not affect the average *),
        RegularExpression["[a-z]"] :> ToCharacterCode["$0"] - 96
          (* matches a lowercase letter and returns its value *),
        RegularExpression["[A-Z]"] :> 1.5 ToCharacterCode["$0"] - 96
          (* matches an uppercase letter and returns 1.5 its value *),
        RegularExpression["[!-/:-@[-_{-~]"] -> -1
          (* matches a 'grandiose' symbol and returns -1 *)
      }] / StringLength[#] (* averages character values *)
    ]]]
  ]]
]

```

# Answer
> 1 votes
# C#, 352 349 Bytes

Due to the magic of linq:

```
class A{static void Main(string[]a){foreach(var x in a.OrderBy(b=>{var s="0";int j=0;return Regex.Split(b,@"[^\w]+").Count(l=>l[0]=='R')==2?(1/0d):b.Aggregate(0d,(d,e)=>{if(e>47&e<58){s+=e;return d;}d+=(e>64&e<91)?(e-64)*1.5:(e>96&e<123)?e-96:e>32&e<127&e!=96?-1:0;j+=int.Parse(s);s="0";return d;})/b.Length-j-int.Parse(s);}))Console.WriteLine(x);}}

```

Could have saved another 6 bytes if backtick would be included in the punctuation list!

```
class A
{
    static void Main(string[] a)
    {
        foreach (var x in a.OrderBy(b =>
            {
                var s = "0";
                int j = 0;
                return Regex.Split(b, @"[^\w]+").Count(l => l[0] == 'R') == 2
                    ? (1 / 0d)
                        : b.Aggregate(0d, (d, e) =>
                        {
                            if (e > 47 & e < 58) { s += e; return d; }
                            d += (e > 64 & e < 91) ? (e - 64) * 1.5 : (e > 96 & e < 123) ? e - 96 : e > 32 & e < 127 & e != 96 ? -1 : 0;
                            j += int.Parse(s);
                            s = "0";
                            return d;
                        }) / b.Length - j - int.Parse(s);
            }))
            Console.WriteLine(x);
    }

}

```

# Answer
> 1 votes
# Go, 755 Bytes

```
package main
import("os"
"fmt"
"math"
"bufio"
"regexp"
"sort"
"strconv")
type F float64
type T []F
func(t T)Swap(i,j int){t[i],t[j],S[i],S[j]=t[j],t[i],S[j],S[i]}
func(t T)Len()int{return len(t)}
func(t T)Less(i,j int)bool{return t[i]<t[j]}
var S []string
func main(){var t T
for{b:=bufio.NewReader(os.Stdin)
w,_,_:=b.ReadLine()
if len(w)==0{break}
u:=string(w)
var v F
for _,c:=range u{if 96<c&&c<123{v+=F(c)-F(96)}else
if 64<c&&c<91{v+=(F(c)-64)*1.5}else
if (48>c&&c>32)||(c>57&&c<127){v-=1}}
a:=v/F(len(w))
r,_:=regexp.Compile("[0-9]+")
n:=r.FindAllString(string(w),-1)
for _,x:=range n{y,_:=strconv.Atoi(x);a-=F(y)}
if m,_:=regexp.Match("((^| )R.*){2}",w);m{a=F(math.Inf(1))}
S=append(S,u)
t=append(t,a)}
sort.Sort(t)
for _,o:=range S{fmt.Println(o)}}

```

The formatted version:

```
package main

import (
    "bufio"
    "fmt"
    "math"
    "os"
    "regexp"
    "sort"
    "strconv"
)

type F float64
type T []F

func (t T) Swap(i, j int)      { t[i], t[j], S[i], S[j] = t[j], t[i], S[j], S[i] }
func (t T) Len() int           { return len(t) }
func (t T) Less(i, j int) bool { return t[i] < t[j] }

var S []string

func main() {
    var t T
    for {
        b := bufio.NewReader(os.Stdin)
        w, _, _ := b.ReadLine()
        if len(w) == 0 {
            break
        }
        u := string(w)
        var v F
        for _, c := range u {
            if 96 < c && c < 123 {
                v += F(c) - F(96)
            } else if 64 < c && c < 91 {
                v += (F(c) - 64) * 1.5
            } else if (48 > c && c > 32) || (c > 57 && c < 127) {
                v -= 1
            }
        }
        a := v / F(len(w))
        r, _ := regexp.Compile("[0-9]+")
        n := r.FindAllString(string(w), -1)
        for _, x := range n {
            y, _ := strconv.Atoi(x)
            a -= F(y)
        }
        if m, _ := regexp.Match("((^| )R.*){2}", w); m {
            a = F(math.Inf(1))
        }
        S = append(S, u)
        t = append(t, a)
    }
    sort.Sort(t)
    for _, o := range S {
        fmt.Println(o)
    }
}

```

Implementing a custom sort interface made it longer than expected. The program reads from STDIN until end of input o a blank line is entered.

# Answer
> 1 votes
# PHP, 362 ~~367~~ Bytes

```
<?for(;$w=fgets(STDIN);$S[]=$w){for($l=$i=mb_strlen($w);$i--;){$c=array_sum(unpack("C*",mb_substr($w,$i,1)));96<$c&&$c<123 and $v+=$c-96 or 64<$c&&$c<91 and $v+=1.5*$c-96 or 48<$c&&$c>32||$c>57&&$c<127 and $v-=1;}$v/=$l;preg_match_all("/\d+/",$w,$m);$v-=array_sum($m[0]);preg_match("/((^| )R.*){2}/",$w)&&$v=INF;$t[]=$v;}array_multisort($t,$S);echo join("
",$S);

```

### Formatted version:

```
<?php
for (; $w = fgets(STDIN); $S[] = $w) {
    for ($l = $i = mb_strlen($w); $i--;) {
        $c = array_sum(unpack("C*", mb_substr($w, $i, 1)));
        96 < $c && $c < 123 and $v += $c - 96
        or 64 < $c && $c < 91 and $v += 1.5 * $c - 96
        or 48 < $c && $c > 32 || $c > 57 && $c < 127 and $v -= 1;
    }
    $v /= $l;
    preg_match_all("/\d+/", $w, $m);
    $v -= array_sum($m[0]);
    preg_match("/((^| )R.*){2}/", $w) && $v = INF;
    $t[] = $v;
}
array_multisort($t, $S);
echo join("
", $S);

```

### Interesting lines:

```
$c = array_sum(unpack("C*", mb_substr($w, $i, 1)));

```

Converts a single UTF-8 character to its byte values and sums them, so that we get the real value for ASCII characters and a value higher than 127 for multibyte characters.

```
96 < $c && $c < 123 and $v += $c - 96
or 64 < $c && $c < 91 and $v += 1.5 * $c - 96
or 48 < $c && $c > 32 || $c > 57 && $c < 127 and $v -= 1;

```

Makes use of low operator precedence of `and` and `or` to assign the character value in a single statement without `if`.

# Answer
> 1 votes
# Perl 5, 190 bytes

```
sub p{$_=pop;chomp;$c=-y/A-Za-z0-9 \\`//c;map$c+=(32&ord$_?1:1.5)*(31&ord),/[a-z]/gi;$c/=length;map$c-=$_,/\d+/g;$c}say(sort{$y=$b=~/\bR.*\bR/;($x=$a=~/\bR.*\bR/)||$y?$x-$y:(p($a)<=>p$b)}<>)

```

Try it online!

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