title: Evaluation order of an APL n-train

text:
# Question
Title: Evaluation order of an APL n-train
*From Codidact with permission.*

## Description

APL trains are a series of functions, that get applied to an argument in this way:

`(f g) x = f g x` here `f` and `g` are prefix functions

`(f g h) x = (f x) g (h x)` here `f` and `h` are prefix functions, while `g` is an infix function

`(a b c d e f) x = (a (b c (d e f))) x = a (b x) c (d x) e (f x)` here `f`, `d`, `b`, and `a` are prefix functions, while `e` and `c` are infix functions

Trains evaluate from the right to the left, so in the last example, `(f x)` is evaluated, then `(d x)`, then `(d x) e (f x)`, then `(b x)`, etc.

For the purposes of this challenge, when counting from the right, the the first, third, fifth, etc. functions are monads, and the second, fourth, sixth, etc. functions are dyads, except that if the leftmost function would be a dyad, it is instead a monad because there is nothing to its left that can provide it with a left argument.

The final evaluation order there is `fdebca`, or using numbers instead, `6 4 5 2 3 1`.

## Challenge

Given a number n, output the evaluation order of a train with n functions. Your result can be 0 indexed or 1 indexed.

## Examples

Here are the first 10 outputs starting from n=1 (1 indexed)

```
1 (0 if 0 indexed)
2 1 (1 0 if 0 indexed)
3 1 2
4 2 3 1
5 3 4 1 2
6 4 5 2 3 1
7 5 6 3 4 1 2
8 6 7 4 5 2 3 1
9 7 8 5 6 3 4 1 2
10 8 9 6 7 4 5 2 3 1

```

# Answer
> 8 votes
# , 14 bytes

```
[:\:0 _2#:i.@-

```

Try it online!

Alternative solution that makes use of divmod with negative divisor.

### How it works

Example using `n = 5`:

* `i.@-` Generate descending range `4 3 2 1 0`
* `0 _2#:` Divmod each number by negative 2:
```
_2  0
_2 _1
_1  0
_1 _1
 0  0

```
* `[:\:` Grade down; sort indices in the descending order of above `4 2 3 0 1`

Alternatively, ranking (grade up twice) on the forward range also works:

# , 15 bytes

```
[:/:@/:0 _2#:i.

```

Try it online!

# Answer
> 4 votes
# Japt, 10 bytes

Trying out insomniac golfing.

```
o ÅÔò cÔiU

```

Try it

```
o ÅÔò cÔiU     :Implicit input of integer U
o              :Range [0,U)
  Å            :Slice off the first element
   Ô           :Reverse
    ò          :Partitions of length 2
      c        :Map then flatten
       Ô       :  Reverse
        iU     :Prepend U

```

# Answer
> 3 votes
# JavaScript (ES6), 35 bytes

Returns a 0-indexed, comma-separated string.

```
n=>(g=k=>--n?n-k+[,g(-k|1)]:+!~k)``

```

Try it online!

---

# JavaScript (ES6),  ~~39~~  38 bytes

Returns a 1-indexed array.

```
n=>(g=k=>n?[n---k||1,...g(-k|1)]:[])``

```

Try it online!

### How?

We start with `k = 0`. At each iteration, we output `n - k || 1`, decrement `n` afterwards and update `k` to `-k | 1`, which means that we alternate between `1` and `-1`.

The `|| 1` in `n - k || 1` is required for the last iteration if there's an even number of terms in the sequence:

```
 n          | 10  9  8  7  6  5  4  3  2  1
 k          |  0  1 -1  1 -1  1 -1  1 -1  1
 n - k      | 10  8  9  6  7  4  5  2  3  0
 n - k || 1 | 10  8  9  6  7  4  5  2  3  1

```

# Answer
> 3 votes
# , 16 14 bytes

```
[:/:>.@-:@i.@-

```

Try it online!

For 5:

```
[:/:>.@-:@i.@-
          i.@- 4 3 2 1 0 count down
    >.@-:@     2 2 1 1 0 halve and round up
[:/:           4 2 3 0 1 grade up
                         (indices of lowest to highest values:
                          4 for 0,
                          2 for the first 1,
                          3 for the second 1, …)

```

# Answer
> 3 votes
# K (oK), 8 bytes

```
<-2!-!-:

```

Try it online!

A port of xash's J solution.

### How it works

```
<-2!-!-:  Monadic train; input = n
    -!-:  Generate n..1; colon attached to force a monadic train
 -2!      Truncating division by 2
<         Grade up

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
ṖUs2U;ƒ

```

Try it online!

-2 bytes thanks to caird coinheringaahing

# Jelly, 5 bytes

```
ḶHĊUỤ

```

Try it online!

By porting xash's J answer.

# Answer
> 2 votes
# Python 3, ~~47~~ ~~46~~ 45 bytes

Saved a byte thanks to Arnauld!!!
Saved another byte thanks to ovs!!!

```
f=lambda n,k=0:n*[0]and[n-k or 1]+f(n-1,-k|1)

```

Try it online!

Uses idea from Arnauld's JavaScript answer.

# Answer
> 2 votes
# Haskell, ~~52~~ ~~48~~ ~~45~~ 42 bytes

Caught mistake thanks to rak1507

Saved 3 bytes thanks to Hakerh400 on Codidact

```
f n=n:g[n-1,n-2..1]
g(b:c:t)=c:b:g t
g t=t

```

Try it online!

`g` takes the rest of the trains.

```
-- This is a fork, so append c (monad) and b (dyad)
-- and continue with the rest of the train
g(b:c:t)#=[c,b]++g t
-- t is either empty or a single monad, so finish it off
g t=t

```

`f` simply starts it off with the last function `n` and the other trains `1..n-1` (in reverse).

```
f n=n:g[n-1,n-2..1]

```

# Answer
> 2 votes
# Python 3, 44 bytes

```
lambda n:sorted(range(n),key=lambda i:n-i^1)

```

Try it online!

Thanks xnor for -3 bytes by change the key function for sorting.

# Answer
> 1 votes
# posix SH + GNU sed, 43 bytes

```
seq $1|tac|sed -zE 's/(\n.+)(\n.+)/\2\1/mg'

```

```
seq $1                 # 1..the argument (inclusive)
      |tac|            # reverse
           sed         # replace
               -z      # null terminated. basically this means that \n is
                       # treated as a normal character, needed because
                       # seq and tr operate on lines
                 E     # extended regex so we can use () instead of \(\)
                   ' do this replacement  '

s/(\n.+)(\n.+)/\2\1/mg
s/            /    /mg  # replace all occurences of
   \n.+                 # a newline followed by non-newlines
                        # the (GNU extension) m modifier makes
                        # . not match a newline
  (    )(....)          # twice
              /         # with
               \2\1     # swap their places

```

# posix SH, 50 bytes

```
seq $1|tac|sed -zE 's/(\n[^\n]+)(\n[^\n]+)/\2\1/g'

```

From codidact with permission

# Answer
> 1 votes
# Python 3, ~~48~~ 44 bytes

```
f=lambda n,x=2:-~n*[n]and[n][:n]+f(n-x,-x|3)

```

Try it online!

The forward differences are always `-2, +1, -3, +1, -3, ...`, except for the last one for even cases. `[:n]` removes a `0` that would occur if we always use the same sequence of forward differences.

`-x|3` maps 2 and 3 to -1 and -1 to 3.

# Answer
> 1 votes
# , 42 bytes

```
function(n)pmax(n:1-c(0,(-1)^(1:n)[-1]),1)

```

Try it online!

Implementing @Arnauld's algoritm

# Answer
> 0 votes
# Retina 0.8.2, 28 bytes

```
.+
$*
1
$.'¶
(¶.+)(¶.+)
$2$1

```

Try it online! Link includes test cases. 0-indexed. Explanation:

```
.+
$*

```

Convert to decimal.

```
1
$.'¶

```

Create the range in reverse.

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

```

Swap pairs of values after the first.

# Answer
> 0 votes
# Charcoal, 13 bytes

```
⟦θ⟧Ｆ⪪⮌…¹Ｎ²Ｉ⮌ι

```

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

```
⟦θ⟧

```

Print the input on its own line.

```
Ｆ⪪⮌…¹Ｎ²

```

Reverse the range from 1 to the input, split into pairs, and loop over each pair.

```
Ｉ⮌ι

```

Print the reversed pair.

---
Tags: code-golf, parsing, permutations, apl
---


title: 418: I'm a teapot

text:
# Question
Title: 418: I'm a teapot
As we all should know, there's a HTTP status code **418: I'm a teapot**.

Your mission, should you choose to accept it, is to use your creativitea and write the smallest possible server that responds with the above status code to any and every HTTP request made to it.

Standard loopholes apply, including

> ### Fetching the desired output from an external source
>
> This includes doing an HTTP request to fetch the page with the question and extracting a solution from that page. This was mildly amusing back in 2011, but now is derivative and uninteresting.

Meaning you cannot simply redirect the request to another server to have it return the response.

Your server can do anything (or nothing) while no HTTP request is made to it as long as it replies with the correct response once a HTTP request is made.

# Answer
# GNU Awk: 69 characters

A server itself (endlessly serves one request at a time), no library used.

Send 418 to everybody who connects (~~82~~ 69 characters):

```
BEGIN{while(s="/inet/tcp/80/0/0"){print"HTTP/1.1 418\n"|&s
close(s)}}

```

Send 418 to everybody who sends something (~~93~~ 80 characters):

```
BEGIN{while(s="/inet/tcp/80/0/0"){s|&getline
print"HTTP/1.1 418\n"|&s
close(s)}}

```

Send 418 to everybody who sends a valid HTTP GET request (~~122~~ 109 characters):

```
BEGIN{while(s="/inet/tcp/80/0/0"){s|&getline
if(/^GET \S+ HTTP\/1\.[01]$/)print"HTTP/1.1 418\n"|&s
close(s)}}

```
> 43 votes

# Answer
## Bash (33)

```
nc -lp80 -q1<<<"HTTP/1.1 418
";$0

```
> 33 votes

# Answer
## PHP - 85 bytes

```
<?for($s=socket_create_listen(80);socket_write(socket_accept($s),"HTTP/1.1 418
"););

```

Saved with Windows-Style (CR-LF) line endings, requires `php_sockets` enabled.

I actually used this as my error code for the Hard Code Golf: Create a Chatroom challenge, but no one noticed.

---

**Browser-Friendly version**

```
<?for(socket_getsockname($s=socket_create_listen(80),$n);$t="I'm a teapot";socket_write($c=socket_accept($s),"HTTP/1.0 418 $t
Content-Length: $l

<title>418 $t</title><h1>$t</h1>The requested resource is not suitable for brewing coffee.<hr><i>$n:80</i>"))$l=124+strlen($n);

```

Start the script in the CLI, and point your browser at `http://localhost`.
> 32 votes

# Answer
# Node.js (LiveScript)

## `http` module - 66

```
require(\http)createServer (->&1.writeHead 418;&1.end!) .listen 80

```

Inspired by Qwertiy's answer.

## `net` module - 76

```
require(\net)createServer (->it.write 'HTTP/1.1 418\r\n';it.end!) .listen 80

```
> 22 votes

# Answer
# Ruby + Rack, 19 bytes

```
run->e{[418,{},[]]}

```

Must be saved as `config.ru`, and run with the `rackup` command.

Or if you prefer "pure" Ruby:

```
Rack::Handler::WEBrick.run->e{[418,{},[]]}

```

42 bytes + `-rrack` flag = **48 bytes**
> 21 votes

# Answer
# Bash+BSD general commands, 29

Borrowing back a little bit from other answers:

```
nc -lp80<<<"HTTP/1.1 418
";$0

```

Works for me with `wget`.

### First answer to use `nc`, 38

```
for((;;)){
nc -l 80 <<<HTTP/1.1\ 418
}

```

I'm assuming root privileges - run as follows:

```
sudo bash ./418.sh

```
> 15 votes

# Answer
# Ruby (nc system command) - 35

```
loop{`nc -l 80 <<<"HTTP/1.1 418"`}

```

DigitalTrauma should get the credit for the idea of using `nc`, however Ruby can make an infinite loop with fewer characters than Bash :)

# Ruby (TCPServer) - 75

```
require'socket'
s=TCPServer.new 80
loop{(s.accept<<'HTTP/1.1 418
').close}

```

That newline is intentional -- the actual newline character is one character shorter than "\n".

# Ruby (WEBrick HTTPServer) - 87

```
require'webrick'
(s=WEBrick::HTTPServer.new).mount_proc(?/){|_,r|r.status=418}
s.start

```
> 10 votes

# Answer
## Node.js, 72

```
require('http').createServer((q,s)=>s.writeHead(418)+s.end()).listen(80)

```

Response:

```
HTTP/1.1 418 I'm a Teapot
Date: Thu, 01 Apr 2021 16:12:59 GMT
Connection: keep-alive
Transfer-Encoding: chunked

0

```

---

## Node.js, 80 with ES5 syntax only

```
require('http').createServer(function(q,s){s.writeHead(418);s.end()}).listen(80)

```

The response is

```
HTTP/1.1 418 I'm a teapot
Date: Wed, 19 Nov 2014 21:08:27 GMT
Connection: keep-alive
Transfer-Encoding: chunked

0

```
> 10 votes

# Answer
# Python 3 106

```
s=__import__('socket').socket(2,1)
s.bind(('',80))
s.listen(9)
while 1:s.accept()[0].send('HTTP/1.1 418\n')

```
> 9 votes

# Answer
# Haskell - 142 bytes

```
import Network
import System.IO
main=listenOn(PortNumber 8888)>>=f
f s=do{(h,_,_)<-accept s;hPutStr h"HTTP/1.1 418\r\n";hFlush h;hClose h;f s}

```
> 8 votes

# Answer
# R, 80 characters

Never did socket programming with R before, but I'll give it a try:

```
repeat{s=socketConnection(,80,T,open="r+");cat("HTTP/1.1 418\n",file=s);close(s)}

```

Here `socketConnection` opens a socket: first argument should be the host, the default being `localhost` we can skip it here; the second argument is the port which has no default, then argument `server` when specified `TRUE` creates the socket, if `FALSE` it just connects to an existing one. `T` is, by default, equals to `TRUE`, in R.

**Edit:** As suggested in a suggested edit by @AlexBrown, this could be shorten into **69 characters**:

```
repeat cat("HTTP/1.1 418\n",file=s<-socketConnection(,80,T))+close(s)

```
> 7 votes

# Answer
# Tcl (\>= 8.5), 78 bytes

Edit - added in an extra newline (total of 2 newlines) for the sake of compliance.

```
socket -server {apply {{c - -} {puts $c "HTTP/1.1 418
";close $c}}} 80
vwait f

```
> 6 votes

# Answer
# Powershell, 398

```
$Listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse("10.10.10.10"), 80)
$Listener.Start()
while($true)
{
    $RemoteClient = $Listener.AcceptTcpClient()
    $Stream = $RemoteClient.GetStream()
    $Writer = New-Object System.IO.StreamWriter $Stream
    $Writer.Write("HTTP/1.1 418 I'm a Teapot`nConnection: Close`n`n")
    $Writer.Flush()
    $RemoteClient.Close()
}

```

# 258

```
$l=New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse("10.10.10.10"),80);$l.Start();while($true){$r = $l.AcceptTcpClient();$s = $r.GetStream();$w = New-Object System.IO.StreamWriter $s;$w.Write("HTTP/1.1 418`n`n");$w.Flush();$r.Close()}

```
> 6 votes

# Answer
## Shell + socat, 60

```
socat tcp-l:80,fork exec:'printf HTTP/1.1\\ 418\\ T\r\n\r\n'

```
> 6 votes

# Answer
# Julia 0.6, ~~86~~ 73 bytes

```
s=listen(80)
while 1<2
c=accept(s)
write(c,"HTTP/1.1 418

")
close(c)
end

```
> 6 votes

# Answer
# Node.js **koa**, 61 Bytes

```
require('koa')().use(function*(){this.status=418}).listen(80)

```

Response:

```
HTTP/1.1 418 I'm a teapot
X-Powered-By: koa
Content-Type: text/plain; charset=utf-8
Content-Length: 12
Date: Thu, 20 Nov 2014 07:20:36 GMT
Connection: close

I'm a teapot

```

Requires node v0.11.12 +

Run as:

```
node --harmony app.js

```
> 5 votes

# Answer
# MATLAB, ~~97~~ 86 bytes

Not really a serious contender in terms of absolute byte-count, but I'd like to post it because I didn't think it would be possible to write a fully functional webserver using a mathematical tool. Note the use of property shortening: `'Ne','s'` internally expands to `'NetworkRole', 'server'`.

```
t=tcpip('0.0.0.0','Ne','s');while 1
fopen(t)
fprintf(t,'HTTP/1.1 418\n')
fclose(t)
end

```
> 5 votes

# Answer
## Perl, 78

```
use Web::Simple;sub dispatch_request{sub{[418,[],[]]}}__PACKAGE__->to_psgi_app

```

run as `plackup whatever.pl`.
> 4 votes

# Answer
# Go, 162 bytes

```
package main
import "net/http"
func main(){http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request){w.WriteHeader(418)})
http.ListenAndServe(":80", nil)
}

```
> 4 votes

# Answer
# Python 2.7/Django, 94 bytes

(added from default boilerplate from `django-admin.py startproject`) In urls.py:

```
import django.http.HttpResponse as r;urlpatterns=patterns(url(r'^*$',lambda q:r(status=418)))

```
> 4 votes

# Answer
## node.js with CoffeeScript (76)

```
require("connect")().use((q,s,n)->s.writeHead 418;s.end();return;).listen 80

```

Just compile it to JavaScript, then you need to run `npm install connect`. After that start it with `node server.js`
> 3 votes

# Answer
# Factor, ~~101~~ 141 bytes

```
[ utf8 <threaded-server> readln 10 base> >>insecure [ "HTTP/1.1 418\r" print flush ] >>handler [ start-server ] in-thread start-server drop ]

```

Return 418 to everyone who connects.
> 3 votes

# Answer
# C# + OWIN ~~251~~ 240

I was really hoping it'd be shorter, but the long namespaces ruined that plan. Requires the `Microsoft.Owin.SelfHost` package available on NuGet.

```
using Owin;class P{static void Main(){Microsoft.Owin.Hosting.WebApp.Start<P>("http://localhost");while(0<1);}public void Configuration(IAppBuilder a){a.Run(c=>{c.Response.StatusCode=418;return System.Threading.Tasks.Task.FromResult(0);});}}

```
> 2 votes

# Answer
## node.js with connect (78)

```
require('connect')().use(function(q,s,n){s.writeHead(418);s.end()}).listen(80)

```

You need to run `npm install connect` first. Then start it with `node server.js`
> 2 votes

# Answer
You can do this with minimal effort using a `.htaccess` file and php.

All the accesses to your server will return the status 418.

Below is the code:

# .htaccess (28 bytes)

```
RewriteRule .* index.php [L]

```

# PHP (~~38~~ 19 bytes)

```
<<?header(TE,1,418);

```

---

Thanks to @primo for saving me a bunch of bytes!

---

I have tested this and confirm it returns the desired result!

By the way, "Pedido" means "Request" and "Resposta" means "Answer".
> 2 votes

# Answer
# Java 7, 208 bytes

```
import java.net.*;class R{public static void main(String[]a)throws Exception{for(ServerSocket s=new ServerSocket(80);;){Socket p=s.accept();p.getOutputStream().write("HTTP/1.0 418\n".getBytes());p.close();}}}

```

This question needed a java answer.

```
poke@server ~
$ curl -i localhost:80
HTTP/1.0 418

```
> 2 votes

# Answer
# 05AB1E \+ `ncat`, ~~75~~ ~~74~~ ~~69~~ ~~62~~ ~~44~~ 42 bytes

*-12 thanks to ovs*.

```
'‚«™’ÿ.¬•"n—Ä -k¯à80<<<'HTTP/1.1 418
'"’.E

```

Your ISP must be AT&T for this to work, as it abuses AT&T's automatic conversion of `\n` to `\r\n` in HTTP requests.

```
'‚«™’...’.E  # trimmed program
         .E  # evaluate...
    ’...’    # "ÿ.shell\"ncat -klp80<<<'HTTP/1.1 418\n'\""...
             # (implicit) with ÿ replaced by...
'‚«          # "system"...
   ™         # in title case...
         .E  # as Elixir code

====================

System.shell"..."  # trimmed program
System.shell       # execute shell command...
            "..."  # literal

====================

ncat -klp80<<<'...'  # trimmed program
ncat                 # host web server...
     - l             # that listens to requests...
     -k              # forever...
     -  p            # on port...
         80          # literal...
ncat                 # that returns response input...
           <<<       # with...
              '...'  # literal...
           <<<       # as input

```

Side note: I do not know Elixir at all so if there are ways to improve the Elixir code please let me know.

# 05AB1E (legacy) \+ `ncat`, ~~64~~ ~~54~~ 52 bytes

```
’__£Ø__('ï´').‚«("n—Ä -k¯à80<<<'HTTP/1.1 418\n'")’.E

```

---

```
’...’.E  # trimmed program
     .E  # evaluate...
’...’    # "__import__('os').system(\"ncat -klp80<<<'HTTP/1.1 418\n'\")"...
     .E  # as Python code

====================

__import__('os').system("...")  # trimmed program
__import__('os').system(     )  # execute shell command...
                        "..."   # literal

====================

ncat -klp80<<<'...'  # trimmed program
ncat                 # host web server...
     - l             # that listens to requests...
     -k              # forever...
     -  p            # on port...
         80          # literal...
ncat                 # that returns response input...
           <<<       # with...
              '...'  # literal...
           <<<       # as input

```
> 2 votes

# Answer
# nginx - 35

```
events{}http{server{return 418;}}

```

Throw that in nginx.conf, start nginx.

*Not sure if this uses standard loopholes "Using built-in functions to do the work" or "Interpreting the challenge too literally." Oops, looks like OP won't like this answer.*
> 1 votes

# Answer
# Python 3 \+ Flask, 64 80 76 75 bytes

```
from flask import*
a=Flask("");a.route("/")(lambda:abort(418));a.run("",80)

```

I don't know much Flask, so I'm not entirely sure if this works. Please let me know in the comments if there's some problem with this. Ungolfed version:

```
from flask import Flask, abort

app = Flask(__name__)

@app.route("/")
def index():
    abort(418)

app.run("127.0.0.1", 80)

```

Simply binds the path "/" to a function that aborts with error code 418.

*Thanks to Makonede for pointing out that I didn't start the server and giving a modification to make the solution 80 76 75 bytes. The 80 was from using `app` instead of `a`. Oops! The 76 was from `(a:=Flask(""))` instead of `a=Flask("");a`.*
> 1 votes

# Answer
# Python 3 \+ `ncat`, ~~55~~ 53 bytes

```
import os;os.system("ncat -klp80<<<'HTTP/1.1 418\n'")

```

Your ISP must be AT&T for this to work.

```
import os;os.system("...")  # trimmed program
import                      # import module named...
       os                   # variable
          os.system(     )  # run shell command...
                    "..."   # literal

====================

ncat -klp80<<<'...'  # trimmed program
ncat                 # host web server...
     - l             # that listens to requests...
     -k              # forever...
     -  p            # on port...
         80          # literal...
ncat                 # that returns response input...
           <<<       # with...
              '...'  # literal...
           <<<       # as input

```
> 1 votes

---
Tags: code-golf, internet
---


title: Ambiguous Chemical Formula

text:
# Question
Title: Ambiguous Chemical Formula
If you convert a chemical formula to lower case, it may become ambiguous: `co` can be both `CO` or `Co`.

Given an input consisting of `a-z0-9`, where `0` can only stand behind `0-9`. Check whether it's ambiguous, unambiguous, or impossible. Return 3 different values for them. Shortest code wins.

Examples:

```
co     - ambiguous
2h83o6 - unambiguous
li     - unambiguous
l      - impossible
cli    - ambiguous
c10h7o - unambiguous

```

One-sentence meaning: Is there zero, one or multiple ways to split input into concatenation of the following strings, case insensitive:

```
0,1,2,3,4,5,6,7,8,9,H,He,Li,Be,B,C,N,O,F,Ne,Na,Mg,Al,Si,P,S,Cl,Ar,K,Ca,Sc,Ti,V,Cr,Mn,Fe,Co,Ni,Cu,Zn,Ga,Ge,As,Se,Br,Kr,Rb,Sr,Y,Zr,Nb,Mo,Tc,Ru,Rh,Pd,Ag,Cd,In,Sn,Sb,Te,I,Xe,Cs,Ba,La,Ce,Pr,Nd,Pm,Sm,Eu,Gd,Tb,Dy,Ho,Er,Tm,Yb,Lu,Hf,Ta,W,Re,Os,Ir,Pt,Au,Hg,Tl,Pb,Bi,Po,At,Rn,Fr,Ra,Ac,Th,Pa,U,Np,Pu,Am,Cm,Bk,Cf,Es,Fm,Md,No,Lr,Rf,Db,Sg,Bh,Hs,Mt,Ds,Rg,Cn,Nh,Fl,Mc,Lv,Ts,Og

```

# Notes

* You need to code the table into your program, since as I searched there was no question requiring an unordered chemical element table.

# Answer
# JavaScript (ES6), 265 bytes

*Saved 6 bytes thanks to @tsh*

Expects an array of characters. Returns **0** for *unambiguous*, **1** for *ambiguous*, or **-1** for *impossible*.

```
s=>s.reduce((p,c,i)=>p|=1/c||b?b=0:/[bcfhiknopsuvwy]/.test(c)+(b=/([ace][rsu]|[cgn][ade]|[iz][nr]|a[cglmt]|b[aehikr]|c[fl-o]|d[bsy]|f[elmr]|h[efgos]|kr|l[airuv]|m[cdgnot]|n[bhiop]|o[gs]|p[abdmortu]|r[abe-hnu]|s[bcegimnr]|t[abcehilms]|xe|yb)$/.test(c+s[i+1]))-1,b=0)

```

Try it online!

## How?

The variable \\$p\\$ holds the final result. The flag \\$b\\$ is set whenever a 2-character chemical symbol is matched.

For each character \\$c\\$ at position \\$i\\$ in the input array:

* If \\$c\\$ is a digit or the flag \\$b\\$ is set, we clear \\$b\\$ and leave \\$p\\$ unchanged.
* Otherwise, we compute:

```
p |= /E1/.test(c) + (b = /E2/.test(c + s[i + 1])) - 1

```

where `/E1/` and `/E2/` are regular expressions matching 1-character and 2-character chemical symbols respectively.

Which leads to:

```
 /E1/ matching | /E2/ matching | sum - 1 | meaning
---------------+---------------+---------+------------
 no            | no            |   -1    | impossible
 no            | yes           |    0    | unchanged
 yes           | no            |    0    | unchanged
 yes           | yes           |    1    | ambiguous

```
> 5 votes

# Answer
# Jelly, 194 bytes

```
“×ĿcṚ¦mßṛy|3¹,GƊ§ḋCƤṂỴƇƈÇ¡ɱɓkȷ¶ʂạ⁺ịọ9ėżḣ÷8ÆC⁼³°0|KṪƈŀ@:ḤvƥÄƭsɲẸpI0⁷tÞO§ƒ;ḷ8ḟhıA€ḊṪḷ`ɦḊa¥IƭịƤñ¡÷?²ạ©œ5EẏṢɲ⁺ȷɗL4Q¤F⁹~Ṿ⁸ṪṄ|eėgṖ€ṂɠƲ2ʂ⁺ɱḌḳWƘɠṛ;⁵2nȦƝ]ṇUṆ84¥ẸṪḲdþ¹Ẋd©’ṃØẠØD;µe€ØD;ØA¤œṗ
¢Œl⁸ŒṖ¤e€€ȦƇL«2

```

Try it online!

-2 bytes thanks to caird coinheringaahing via better usage of chaining

Output 2 for ambiguous, 1 for unambiguous, 0 for impossible.

The logic behind this is pretty trivial, I just need to figure out a better way of encoding this periodic table...

```
“...’ṃØẠØD;µe€ØD;ØA¤œṗ  Helper Link; produce the list of components
“...’                   Compressed Integer
     ṃØẠ                Base-decoded into the upper and lower-case alphabet
        ØD;             Prepend the digits (as strings) as well
           µ            With the list of components (joined on nothing) as the left argument
            e€          Check if each element is in
              ØD;ØA¤    The digits + uppercase alphabet
                    œṗ  And partition the components before those indices

¢Œl⁸ŒṖ¤e€€ȦƇL«2         Main Link
¢Œl                     The components above, lowercased
   ⁸ŒṖ¤                 All ways of partitioning the input
         €              For each partition
        €               For each component
       e                Is it in the list of valid components?
          ȦƇ            Filter to keep partitions where every component was valid
            L           Length; 0 if impossible, 1 if unambiguous, 2+ if ambiguous
             «2         Minimum of the above and 2 (sets ambiguous case to 2 no matter how many occurrences existed)

```
> 3 votes

# Answer
# 05AB1E, 117 bytes

Prints `-1` for impossible, `0` for unambiguous and `1` for ambiguous.

```
.œε.•B‚Δ—₅H^ƶƵXJ∍æ“ºl¦¯í-āмIõVÑK:Λ‘(·÷ΓKå<70'V∍∞±ζÚšË›¿ĆÅRÙΔu”ípā<À¿ýÌQмÛì‰Óǝ“§KhúγIÑËM`Êιš•#€SASõšøε`ì}˜žhS«såP}O<.±

```

Try it online!

```
.œ              # push all partitions of the input
  ε      }      # map over the partitions:
   ...          #   push the table of valid parts (see below)
      s         #   swap to the current partition
       åP       #   test if every part is in the table
          O     # take the sum over all results
           <    # decrease by 1
            .±  # print the sign of this

```

#### Compressing the table

```
.•B...š•                  # alphabet compressed string (contains 26 spaces)
        #                 # split on spaces
         €S               # split each string into a list of chars
           ASõš           # the characters of the alphabet with the empty string prepended
               øε`ì}      # zip alphabet with previous list and prepend matching characters
                    ˜     # flatten the list
                     žhS« # append the digits

```

Try this part with step-by-step output!
> 1 votes

# Answer
# Jelly, 124 bytes

```
“€ṡƥvẏÄhʠ!ịẈ?iḥẋỌ¹'ṅɦçç⁹.Sð$ṚṠȥṢK}/>œ;ỵZƤẓ}:;tÆṾḶj⁶ḄỵḋİʠUḊẈ½^ɲṆßṇµ⁶æḟɦ1¥©ḟþjHṀṪỤƑgạȥḂṾḞƓƑ@Ð⁾æƭVẈṣ’ḃ90Äḃ26ịØaØDW€¤;
ŒṖfƑƇ¢L«2

```

Try it online!

A set of links that takes a string argument and returns 0 for impossible, 1 for a single valid interpretation and 2 for ambiguous.

Loosely based on @hyper-neutrino’s answer, but mostly rewritten.
> 1 votes

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


title: Swap contents of two files

text:
# Question
Title: Swap contents of two files
This is a code-golf question. You need to take the contents of two separate files (i.txt and o.txt) and swap them. You can create a third file to help you with the process, but have your program delete it after the file contents are swapped. Renaming the files is now allowed again.

Programs must work for any file content.

Shortest code wins, all eligible submissions will be up-voted.

# Answer
> 10 votes
## zsh, 20 + 4 = 24

The script needs to be named `.txt`.

```
(mv [io]$0;>i$0)<o$0

```

or **14** with parameters:

```
(mv $@;>$1)<$2

```

# Answer
> 3 votes
# Python, 77

```
import os;t='.txt';r,i,o,x=[os.rename,'i'+t,'o'+t,'1'+t];r(i,x);r(o,i);r(x,o)

```

# Python, 65

```
import os;t='.txt'
for a,b in zip('iox','xio'):os.rename(a+t,b+t)

```

# Python, 63

```
import os;t='.txt'
for a,b in 'ix','oi','xo':os.rename(a+t,b+t)

```

# PHP, 68

```
<?$r=rename;$t='.txt';$r("i$t","x");$r("o$t","i$t");$r("x","o$t");?>

```

# Windows Batch File, 42

```
move i.txt x&move o.txt i.txt&move x o.txt

```

# Windows Batch File (args), 30

```
move %1 x&move %2 %1&move x %2

```

# Answer
> 2 votes
# Two based answers; 52 and 62 chars

## shell: diff + patch (+ tee + sed...) 52

Maybe not the shorter, but I find this fun (and there is no use of *temporary* file):

```
diff -u [io]*|tee >(patch -r -)|sed 1s/i/o/|patch -R

```

Where content is swapped and files are modified **in place**:

### Sample run

```
swapContent() { diff -u $1 $2|tee >(patch -r -)|sed 1s/$1/$2/|patch -R ;}

while read page file ;do man -Pcol\ -b $page >$file.txt;done <<<$'man i\nbash o'
printf "%s %8d  %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))
swapContent [io]*
printf "%s %8d  %s\n" $(join -j 2 <(stat -c '%s %n' [io]*) <(md5sum [io]*))

```

Could produce something like:

```
i.txt    46007  1da1f7533e0eab1e97cce97bb7ca1d3b
o.txt   321071  7dcd230890faf4ef848d4745eda14407
patching file o.txt
i.txt   321071  7dcd230890faf4ef848d4745eda14407
o.txt    46007  1da1f7533e0eab1e97cce97bb7ca1d3b

```

## use of xargs to *simplify* `mv` requests

Not as funny, but nice anyway.

```
set -- {i,o}.txt t&&eval 'xargs -n2 mv<<<"' \${1,3,2,1,3,2} \"

```

# Answer
> 2 votes
## PHP, 89

I thought I'd give it a shot.

```
<?php $f1='f1.txt';$f2='f2.txt';$ft='ft.txt';copy($f1,$ft);copy($f2,$f1);rename($ft,$f2);

```

Ungolfed version:

```
<?php
$f1 = 'f1.txt';
$f2 = 'f2.txt';
$ft = 'ft.txt';

copy($f1, $ft);
copy($f2, $f1);
rename($ft, $f2);

```

Apparently I took 2 answers of here and combined them.. oh well.

# Answer
> 2 votes
# VBA (148...132) and (126...110)

Renaming with a temp file t in the c:\ drive. Also first attempt at golf :S

```
Sub s():Set f=CreateObject("Scripting.FileSystemObject"):i="c:\i.txt":t="c:\t":f.MoveFile i,t:f.MoveFile "c:\o.txt",i:Kill t:End Sub

```

If scrrun.dll is referenced already, could cut it down a bit to 126...110.

```
Sub s():Set f=new FileSystemObject:i="c:\i.txt":t="c:\t":f.MoveFile i,t:f.MoveFile "c:\o.txt",i:Kill t:End Sub

```

# Answer
> 2 votes
## Ruby, 72 bytes

Wow! A Ruby code golf! I don't think that's ever been attempted before!

In all reality though, this required some nice Ruby shortcuts and a couple patterns which I found. It was my first golf ever and it was very fun to do. Without further ado, here's the golfed code:

```
3.times{|x|x*=2;t=".txt";a=([?i,?a,?o]*2);File.rename(a[x]+t,a[x+1]+t)}

```

And the ungolfed version

```
3.times do |x|
    x = x * 2
    t=".txt"
    a=([?i,?a,?o]*2)
    File.rename(a[x]+t, a[x+1]+t)}
end

```

The key factor in this is that the parameters passed to the `File.rename` are this, exactly:

```
File.rename "i.txt", "a.txt"
File.rename "o.txt", "i.txt"
File.rename "a.txt", "o.txt"

```

Hope this (doesn't) make sense!

# Answer
> 2 votes
# Powershell, ~~44~~ 49 bytes

```
$t='.txt'
ren i$t a$t -fo
ren o$t i$t
ren a$t o$t

```

where `ren` is alias for Rename-Item. The script uses and delete a third file `a.txt`.

# Answer
> 2 votes
# 05AB1E `--no-lazy`, ~~39~~ ~~37~~ 35 bytes

*-2 thanks to Kevin Cruijssen.*

```
'°ŽDÀøεS’.í¼t"’«`’File.‚™‚ˆ"ÿ,"ÿ’.E

```

Try it online! Link includes a header and footer to create the files and prove that it worked.

```
'°ŽDÀøεS’...’«`’...’.E  # trimmed program
      ε                 # for each in...
     ø                  # all characters of...
'°Ž                     # "bio"...
     ø                  # paired with corresponding characters of...
'°ŽD                    # "bio"...
    À                   # rotated left one character...
                    .E  # evaluate...
               ’...’    # "File.rename\"ÿ\",\"ÿ\""...
                        # (implicit) with the first ÿ replaced by...
              `         # second element of...
       S                # list of characters of...
                        # (implicit) current element...
                        # (implicit) with each element...
             «          # concatenated with...
        ’...’           # ".txt"...
                        # (implicit) with the second ÿ replaced by...
              `         # first element of...
        S               # list of characters of...
                        # (implicit) current element...
                        # (implicit) with each element...
              «         # concatenated with...
         ’...’          # ".txt"...
                    .E  # as Elixir code

====================

File.rename  # full program
File.rename  # rename file with name argument 1 to argument 2

```

# Answer
> 1 votes
# Ruby

```
i1="i.txt"
i2="o.txt"
c1=IO.readlines(i2)
c2=IO.readlines(i1)
File.open(i1){|x|x.puts(c1)}
File.open(i2){|x|x.puts(c2)}

```

Shortened version:

```
a=["i.txt","o.txt"]
(0..1).each{|x|b[x]=IO.readlines(a[x])*"\n"}
a.reverse!
(0..1).each{|x|IO.write(a[x],b[x])}

```

Not the shortest, but very simple and easy to read. Also, no intermediate files, only RAM.

# Answer
> 1 votes
## Shell script, 24

Works in Bash and probably most shells. Pass with your two filenames as parameters.

```
mv $1 ੴ;mv $2 $1;mv ੴ $2

```

If you want fixed filenames then this will do it, for a 12 char penalty:

```
mv i.txt ੴ;mv o.txt i.txt;mv ੴ o.txt

```

# Answer
> 1 votes
**Python:**

```
import os
l,e='i_o'*2,'.txt'
for x,y in zip(l,l[1:])[::2]:
 os.rename(x+e,y+e)

```

# Answer
> 1 votes
# Windows Batch File (48)

```
type i.txt>a&type o.txt>i.txt&type a>o.txt&del a

```

I forgot about the move command when I wrote this...

# Answer
> 1 votes
## C 162

Golfed: uses t.txt as tmp file and swaps names then removes t.txt.

```
#include <stdio.h>
#define R(x,y) rename(x,y)
#define X(x) remove(x)
int main(){char *i="i.txt",*o="o.txt",*t="t.txt";R(i,t);X(i);R(o,i);R(t,o);X(t);return 0;}

```

Edit: removed 2 spaces

# Answer
> 1 votes
**PHP** \- 172

Golfed version of @EisaAdil's answer

```
$f1='file1.txt';$f2='file2.txt';$f1contents=file_get_contents($f1);$f2contents=file_get_contents($f2);file_put_contents($f1,$f2contents);file_put_contents($f2,$f1contents);

```

# Answer
> 1 votes
# PHP, 45

```
<?php
copy('i','t');copy('o','i');rename('t','o');

```

Not very golfy but shortest PHP so far.

# Answer
> 1 votes
# Rebol - 46 (rename file) or 55 (r/w contents)

Rename file (using `t` as temporary file):

```
r: :rename
r i: %i.txt %t
r o: %o.txt i
r %t o

```

Read in then write out file contents:

```
a: read i: %i.txt
b: read o: %o.txt
write o a
write i b

```

# Answer
> 1 votes
## Groovy - 99 chars

This is my attempt, with Groovy 2.2.1. I tried to do it without renaming:

```
f={new File(it+".txt")}
w={x,y->x.withWriter{it.write y}}
i=f "i"
o=f "o"
t=i.text
w i,o.text
w o,t

```

Ungolfed:

```
file = { new File(it+".txt") }
writeTextToFile = { x,y -> x.withWriter{it.write y} }

iFile = file("i")
oFile = file("o")

iText = iFile.text
writeTextToFile (iFile,oFile.text)
writeTextToFile (oFile,iText)

```

# Answer
> 1 votes
# C: 65 characters

```
#define r(a,b)rename(#a".txt",#b".txt");
main(){r(i,)r(o,i)r(,o)}

```

A quite simple solution in C that does the job. It uses a temporary name (`.txt`) for one of the files before giving it its proper new name.

Ungolfed (note how the syntax highlighting fails in the define, a bug has been uncovered!):

```
#include <stdio.h>

#define r(a, b) rename(#a ".txt", #b ".txt");

int main()
{
    r(i,  ) // rename("i.txt",  ".txt");
    r(o, i) // rename("o.txt", "i.txt");
    r( , o) // rename( ".txt", "o.txt");

    return 0;
}

```

# Answer
> 1 votes
# Perl, 120 bytes (Contents swapping without file renaming)

```
use open IO,':bytes';undef$/;open I,"<i.txt";$I=<I>;open I,"<o.txt";open O,">i.txt";print O<I>;open O,">o.txt";print O$I

```

The file contents is put into memory and written back to the other file. Thus `i.txt` and `o.txt` must fit into memory.

Since the file contents are actually exchanged, hard links are updated automatically, see AJManfield's comment.

**Ungolfed:**

```
use open IO => ':bytes'; # binmode, not needed for Unix, but needed for Windows
undef $/;                # read whole file instead of lines
open I, "<i.txt";        # open i.txt for reading
$I = <I>;                # read i.txt
open I, "<o.txt";        # open o.txt for reading
open O, ">i.txt";        # open i.txt for writing
print O <I>;             # read o.txt and put the contents in i.txt
open O, ">o.txt";        # open o.txt for writing
print O $I;              # write o.txt with contents of old i.txt

```

# Answer
> 1 votes
## Windows Batch, 39 bytes

```
ren i.txt x&ren o.txt i.txt&ren x o.txt
```

# Answer
> 1 votes
# Tcl, 122 bytes

```
set A [read [open i.txt]]
puts [set i [open i.txt w]] [read [open o.txt]]
puts [set o [open o.txt w]] $A
close $i
close $o

```

Try it online!

---

~~Tcl, 169 bytes
```
set A [read [set i [open i.txt r]]]
set B [read [set o [open o.txt r]]]
close $i
close $o
puts [set i [open i.txt w]] $B
puts [set o [open o.txt w]] $A
close $i
close $o

```
Try it online!<br>~~

# Answer
> 1 votes
# Lua, ~~71~~ 70 bytes

```
_ENV=os t='.txt'i,o,r='i'..t,'o'..t,rename r(i,t)r(o,i)r(t,o)remove(t)

```

Try it online!

Define `os`, the operating system library, as the global table so we can write `rename` and `remove` instead of `os.rename` and `os.remove`. (Incidentally this also means the one-letter variables are actually fields in the `os` table.) Make short alias for `os.rename` to save some space. Set up filename variables, using `'.txt'` as temporary file. Do the renaming and deleting.

# Answer
> 1 votes
# PHP, 52 bytes

AsksAnyway´s php modernized & golfed:

```
($r=rename)(i.$e=".txt",x);$r(o.$e,i.$e);$r(x,o.$e);

```

Run with `php -nr '<code>'`.

# Answer
> 1 votes
# AWK, 66 bytes

```
a=FILENAME,b=!b?a:b{c[a]=c[a]$0RS}END{printf c[a]>b;printf c[b]>a}

```

Try it online!

Note: I provided a TIO line, but I have no idea how to make it work when the code needs to read from input files?

The rename approaches seem to be much shorter, but here's one in AWK that copies the data instead. At a high level, it takes a commandline like,

```
gawk '...code...' i.txt o.txt

```

which feeds both files into the program on STDIN. It uses the magic variable `FILENAME` to cache the contents of each one into a separate entry in an associative array. Then the `END` clause just overwrites each file with the content from the other one.

The "test" per line, which is always truthy, sets `a` to the current filename over and over. And it also ensures `b` is to the first filename seen.

```
a=FILENAME,b=!b?a:b

```

The code block executed per line, just appends the current line to the accumulated data for the current filename.

```
c[a]=c[a]$0RS

```

Then once all the lines from both files have been read, the `END` code block writes out the files with the content swapped.

```
printf c[a]>b;printf c[b]>a

```

# Answer
> 0 votes
# SmileBASIC, ~~36~~ 35 bytes

```
@L
RENAME@OI[2-I],@IO[I]I=I+1GOTO@L

```

---
Tags: code-golf
---


title: A scene of Jimmy diversity

text:
# Question
Title: A scene of Jimmy diversity
As you probably know, there have been multiple lovely Jimmy challenges recently popping up. In these challenges, you were challenged with our beloved friend's acrobatics skills. Now we've got a different challenge for you. Today you will be identifying different types of Jimmys!

---

# Explanation

There are three varieties of Jimmys: dwarf, acrobat, and bodybuilder.

```
This is dwarf Jimmy:               o

This is acrobat Jimmy:            /o\

This is bodybuilder Jimmy:       /-o-\

```

These Jimmys are all great friends and they like to stand on the same line as each other. Your task is, given a Jimmy scene like so:

```
  o  /o\       o   /-o-\/-o-\  o          /o\

```

Output the amount of dwarves, acrobats, and bodybuilders on the line, respectively.

# The challenge

* Take input in any reasonable form as a Jimmy scene, as shown in an example above.

1. The input string should be one line and optionally contains the three varieties of Jimmys and optional whitespace.
2. The string will not necessarily contain all of the Jimmy varieties or whitespace.
3. The string will not contain any characters not in `o/\ -` .
4. Any combination of Jimmy varieties is possible. This means that the same or different type of Jimmy can be next to each other. You must account for that.
5. Leading and trailing whitespace is optional and by no means required - your program should account for a string with or without leading and/or trailing whitespace.
6. The string should contain only valid Jimmys and whitespace. For instance, `---///---` is not allowed because it is not a valid Jimmy sequence.

* Output three numbers: The count of dwarves, acrobats, and bodybuilders in the scene (in respective order).

1. This may be an output to the console as space-separated integers, or it may be a return value from a function as some sort of container (i.e an array type).
2. The output, in whatever format, must be ordered as mentioned in the top bullet above this rule.

* Standard rules and loopholes apply.

# Test cases

```
     /-o-\           /-o-\     o/o\  /-o-\       /-o-\                /-o-\
OUTPUT: 1 1 5

      o o               /o\    o o      o                    /o\             /o\
OUTPUT: 5 3 0

 /-o-\     /-o-\            /-o-\/-o-\   o /o\/o\    /-o-\o /-o-\       /o\/-o-\
OUTPUT: 2 3 7

  /-o-\  o                 /-o-\               o/o\
OUTPUT: 2 1 2

```

If you'd like more test cases, use this tool to generate more random test cases.

# Scoring

This is , so lowest score in bytes wins.

# Answer
# Jelly, (12?) 13 bytes

```
ċⱮ“-/o”H1¦ŻIṚ

```

A monadic Link accepting a list of characters which yields a list of integers, `[ dwarves, acrobats, and body-builders]` (save the  byte if we may specify our output)

**Try it online!**

### How?

All Jimmys show a `o`; all non-dwarves show a `/`; all body-builders show two `-`. Count these up, halve the count of `-`, and perform subtraction to find the Jimmy counts:

```
ċⱮ“-/o”H1¦ŻIṚ - Link: list of characters
  “-/o”       - list of characters ['-', '/', 'o']
 Ɱ            - map across right with:
ċ             -   count occurrences   = [n('-'), n('/'), n('o')]
         ¦    - sparse application...
        1     - ...to indices: [1] -- i.e. n('-')
       H      - ...action: halve    = [n('-')/2, n('/'), n('o')]
          Ż   - prepend a zero =   [0, n('-')/2, n('/'), n('o')]
           I  - incremental differences
              -     = [n('-')/2, n('/')-n('-')/2, n('o')-n('/')]
            Ṛ - reverse
              -     = [n('o')-n('/'), n('/')-n('-')/2, n('-')/2]

```
> 8 votes

# Answer
# Python 3.8 (pre-release), 51 bytes

```
lambda s:((c:=s.count)('o')-c('/'),c('/o'),c('/-'))

```

Try it online!
> 21 votes

# Answer
# Python 2, 50 bytes

```
x,y,z=map(input().count,'o/-')
print x-y,y-z/2,z/2

```

Try it online!

-10 bytes by converting lambda expression to a full program thanks to @xnor (removes the double-lambda nested thing and uses assignment instead)
> 12 votes

# Answer
# PowerShell, ~~59~~ 55 bytes

```
$c=,0*3
$args|sls '/?-?o'-a|% m*|% le*|%{++$c[$_-1]}
$c

```

Try it online!

Unrolled:

```
$counters=,0*3
$args|select-string '/?-?o'-AllMatches|% Matches|% Length|%{++$counters[$_-1]}
$counters

```
> 8 votes

# Answer
# , ~~36~~ 25 bytes

-11 bytes thanks to cole!

```
2-/\0,~1 1 2%~1#.'o/-'=/]

```

Try it online!

## Original solution

# , 36 bytes

```
[:(-/@}:,-/@}.,{:)1 1 2%~1#.'o/-'=/]

```

Try it online!

## Explanation:

```
                            'o/-'=/] compare the input with each one of "o/-" characters
                                     / the result is a 3-row matrix /
                         1#.         add up each row to find the number of occurences
                                     of each character, the result is a vector of 3 items
                  1 1 2%~            divide the last item by 2 to find the number of
                                     bodybuilder Jimmys
[:(              )                   use the result to construct the following vector:
               {:                    the last item
              ,                      appended to
         -/@}.                       the difference of the second and the third items
        ,                            appended to
   -/@}:                             the difference of the first and the second items

```

A sample  session:

```
a=:'  /-o-\  o                 /-o-\               o/o\'
   'o/-'=/a
0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
   1#.'o/-'=/a
5 3 4
   1 1 2%~1#.'o/-'=/a
5 3 2
   (-/@}:,-/@}.,{:)1 1 2%~1#.'o/-'=/a
2 1 2

```
> 5 votes

# Answer
# Excel as CSV, 130 bytes

```
,=LEN(A3)-LEN(A4)
=SUBSTITUTE(A1,"-o",""),=(LEN(A2)-LEN(A3))/2
=SUBSTITUTE(A2,"/o",""),=(LEN(A1)-LEN(A2))/2
=SUBSTITUTE(A3,"o","")

```

Insert input in space before first `,`, save as .csv, open in Excel. Outputs Dwarfs, Acrobats and Bodybuilders in `B1`, `B2` and `B3` respectively.

---

**Excel, 244 bytes**

```
=LEN(SUBSTITUTE(SUBSTITUTE(A1,"-o",""),"/o",""))-LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"-o",""),"/o",""),"o",""))&" "&(LEN(SUBSTITUTE(A1,"-o",""))-LEN(SUBSTITUTE(SUBSTITUTE(A1,"-o",""),"/o","")))/2&" "&(LEN(A1)-LEN(SUBSTITUTE(A1,"-o","")))/2

```
> 5 votes

# Answer
# Kotlin ~~131~~ ~~130~~ ~~129~~ ~~121~~ ~~117~~ ~~97~~ ~~96~~ 88 bytes

```
fun String.j(b:Int=count{'-'==it}/2,a:Int=count{'/'==it})=listOf(count{'o'==it}-a,a-b,b)

```

Try it online!

Edit - Wew, got it under 100! I doubt I can shrink it more, but only time will tell...

Edit - Spoke too soon, dropped one more byte by using a list instead of a string

Edit - minus 8 bytes thanks to AsoLeo suggesting using a extension function
> 4 votes

# Answer
# APL (Dyalog Unicode), 20 bytesSBCS

```
2-/2÷⍨@2+/'o/-x'∘.=⎕

```

Try it online!
> 4 votes

# Answer
# Retina, ~~39~~ 35 bytes

*Edit:* -4 bytes thanks to @FryAmTheEggMan

```
^((o)|(/o.)|(/-o-.)| )*
$#2 $#3 $#4

```

Try it online!

**Explanation:**

A simple replace stage. It finds all matches of the regex `^((o)|(/o.)|(/-o-.)| )*` (which should result in one match - the whole string) and replaces it by the number of captures of groups 2, 3, and 4. Here is the regex broken down:

```
^((o)|(/o.)|(/-o-.)| )*
^                               start at the beginning of the string
 (                       )*     have any amount of Jimmy / spaces
     |       |         |        select one of:
  (o)                           capturing group 2 - dwarf
      (/o.)                   capturing group 3 - acrobat
              (/-o-.)         capturing group 4 - bodybuilder

```

We have to start with `^` or the end of the input counts as a match too. In the substitution syntax of Retina, `$n` references the nth capturing group, and the modifier `#` counts how many matches it made.
> 3 votes

# Answer
# JavaScript, 55 bytes

Searches the string using a regex pattern matching `o`, `o-`, or `o-\`; increments the corresponding count in an array, using the length of each match to determine the index.

```
s=>s.replace(/o-?\\?/g,m=>a[m.length-1]++,a=[0,0,0])&&a

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~69~~ ~~66~~ ~~60~~ 56 bytes

-4 bytes thanks to @Maarten Fabré

```
g=input().count
b,c=g('/'),g('/-')
print(g('o')-b,b-c,c)

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 63 bytes

```
Reverse@{a=(m=CharacterCounts@#)["-"]/2,b=m["/"]-a,m["o"]-a-b}&

```

Try it online!

55 bytes if the pointless order requirement is dropped...
> 2 votes

# Answer
# Clojure, 78 bytes

```
(defn ?[s](def c #(count(re-seq % s)))[(-(c #"o")(c #"/"))(c #"/o")(c #"/-")])

```

Try it online!
> 2 votes

# Answer
# , 63 bytes

Uses Regex matching to find and count the Jimmys.

```
library(stringr)
str_count(scan(,''),c('(?<![/-])o','/o','/-'))

```

Try it online!
> 2 votes

# Answer
# K (oK), 25 bytes

```
{|-':|1 1 .5*+/x=\:"o/-"}

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-p`, 41 bytes

```
$_=1*s/o(?!\\|-)//g.$".1*s|/o||g.$".y/o//

```

Try it online!

Counts the number of times `o` appears without being followed by `\` or `-` to find the dwarves and removes them from the string. Then counts the number of times `/o` appears to find the acrobats and removes them from the string. Then counts the number of `o` remaining to determine the body builders. Inserts spaces between the numbers and implicitly outputs the result.
> 1 votes

# Answer
# Ruby, 50 bytes

```
->s{%w(o /o -o).map{|x|s.scan(/[\/-]?o/).count x}}

```

Try it online!
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 135 bytes

```
	I =INPUT
B	I '-o' =	:F(A)
	B =B + 1	:(B)
A	I '/o' =	:F(D)
	A =A + 1	:(A)
D	I 'o' =	:F(O)
	D =D + 1	:(D)
O	OUTPUT =+D ' ' +A ' ' +B
END

```

Try it online!

Removes `-o`, `/o`, and `o` from the string and increments the appropriate counters each time. Leaves behind a lot of arms and legs (`/-\`, `\`, and nothing).
> 1 votes

# Answer
# Forth (gforth), 118 bytes

```
: c -rot 0 tuck do over i + c@ 3 pick = - loop nip nip ;
: f 2dup '/ c >r 2dup '- c 2/ -rot 'o c i - . r> over - . . ;

```

Try it online!

### Explanation

* Get Count of `/`, `-`, and `o` characters
* Bodybuilder is number of `-` characters divided by 2
* Acrobat is number of `/` characters minus the number of body builders
* Dwarf is number of `o` characters minus the number of Acrobat and Bodybuilders

### Code Explanation

```
\ c counts the number of occurrences of the given character in a string
\ stack usage is ( c-addr u1 w1 - u )
: c                 \ start a new word definition
  -rot 0 tuck       \ sets up parameters for a counted loop
  do                \ loop from 0 to string-length - 1 (inclusive)
    over i +        \ get the address of the current character in the string
    c@              \ get the ascii value of the current character
    3 pick =        \ compare it to the character we're counting
    -               \ subtract result from the accumulator (subtract because -1 = true in forth)
  loop              \ end the loop
  nip nip           \ remove extra values from the stack
;                   \ end the word definition

\ Main function
: f                 \ start a new word definition
  2dup              \ duplicate the string address and length
  '/ c >r           \ count the number of '/' characters and stick the result on the return stack
  2dup '- c 2/      \ count the number of '-' characters and divide by 2
  -rot 'o c         \ move the string to the top of the stack and count the number of 'o characters
  i - .             \ calculate number of dwarf jimmy's and print
  r> over - .       \ calculate number of acrobat jimmy's and print (drop '/' count from return stack)
  .                 \ print number of body-builder jimmy's
;                   \ end word definition

```
> 0 votes

# Answer
# 05AB1E, 13 bytes

```
…-/oS¢ć;š0š¥R

```

This one could be **12 bytes** by removing the `R` if an output-order of `[bodybuilder, acrobat, dwarf]` would have been allowed.

Try it online or verify all test cases.

Minor equal-bytes alternative:

```
…-/oS¢R`;0)üα

```

Try it online or verify all test cases.

**Explanation:**

```
…-/o           # Push string "-/o"
    S          # Split to a list of characters: ["-","/","o"]
     ¢         # Count the occurrence of each character in the (implicit) input-string
      ć        # Extract the head; pop and push head and remainder-list
       ;       # Halve this head
        š      # And prepend it back in front of the remainder-list
         0š    # Then also prepend a 0
           ¥   # Get the deltas (forward differences)
            R  # And reverse the list to get the required order of output-counts
               # (after which the result is output implicitly)

…-/oS¢         # Same as above
      R        # Reverse this list
       `       # Pop the list and push its values separately to the stack
        ;      # Halve the top value on the stack
         0     # Push a 0
          )    # Wrap all values on the stack into a list
           ü   # For each overlapping pair of values:
            α  #  Get the absolute difference between the two values
               # (after which the result is output implicitly)

```
> 0 votes

# Answer
# C (gcc), ~~99~~ ~~98~~ 96 bytes

-1 byte thanks to ceilingcat

```
o,S,d,c;f(char*s){for(o=S=d=0;c=*s++;o+=c>93)d+=c==45,S+=c==47;printf("%d %d %d",o-S,S-d,d/=2);}

```

Try it online!
> 0 votes

# Answer
# Vyxal, 17 bytes

```
`-/o`f$vOḣ$½p0pṘ¯

```

Try it Online!
> 0 votes

# Answer
# Ly, 87 bytes

```
0>0>0>i['-=[pl'o=[p<1+>0]pp0]p'/=[p<<1+>>0]p'o=[p<<<1+>>>0]psp]<s<l-:l+sp<l-u>' ou>' ou

```

Try it online!

I think this could be shorter, but I've hit a brick wall at this point.

At a high level, it counts the number of `-` (matched), `/` and `o` characters, then subtracts to remove duplicate counts before printing the results.

First is initializes counters to `0` on three different stacks.

```
0>0>0>

```

Then it reads the input onto the stack a codepoints, and loops over each character. The code also saved the current character to the backup cell with `s` so we can only count matched `-` characters.

```
i[ ...                                                sp]

```

The first check increments the counter on the first stack if it's `-` and the previous character was `o`. That works since the characters are processes in reverse order.

```
  '-=[pl'o=[p<1+>0]pp0]p

```

The second check increments the counter on the second stack anytime the code hits a `/` character.

```
                        '/=[p<<1+>>0]p

```

And the last check increments the counter on the third stack when the code finds a `o` character.

```
                                      'o=[p<<<1+>>>0]p

```

Once all the input has been scanned and counted, to code subtracts the number of matched `-` characters (bodybuilders) from the number of `/` characters to find the number of acrobats.

```
<s<l-

```

Then it remember the number of acrobats plus the number of bodybuilders by stashing the sum of the two in the backup cell.

```
     :l+sp

```

Then is subtracts that from the number of `o` characters to get the final counter and prints it.

```
          <l-u

```

The last bits just shift to the next counter and prints with a space appended. \>' ou

And does the same shift/print to output the last counter.

```
                   >' ou

```
> 0 votes

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


title: Sums of square roots

text:
# Question
Title: Sums of square roots
Program the sequence \\$R\_k\\$: all numbers that are sum of square roots of some(maybe one) natural numbers \\$\left\\{\sum\_{i\in A}\sqrt i\middle|A\subset \mathbb{N}\right\\}\\$, in ascending order without duplication. Outputting zero is optional.

You should do one of:

* Take an index k and output \\$R\_k\\$, either 0 or 1 indexing
* Take a positive integer k and output the first \\$k\\$ elements of \\$R\\$
* Output the whole sequence

Shortest code in each language wins. Beware of floating error, which returns \\$\sqrt 2+\sqrt 8=\sqrt {18}\\$ twice using my raw code, which is disallowed.

---

First few elements:

```
(0,)1,1.4142135623730951,1.7320508075688772,2,2.23606797749979,2.414213562373095,2.449489742783178,2.6457513110645907,2.732050807568877,2.8284271247461903,3,3.1462643699419726,3.1622776601683795,3.23606797749979,3.3166247903554,3.414213562373095,3.449489742783178,3.4641016151377544,3.605551275463989,3.6457513110645907,3.6502815398728847,3.732050807568877,3.7416573867739413,3.8284271247461903,3.863703305156273,3.872983346207417,3.968118785068667,4,4.059964873437686,4.123105625617661,4.146264369941973,4.16227766016838,4.1815405503520555,4.23606797749979,4.242640687119286,4.3166247903554,4.358898943540674,4.377802118633468,4.414213562373095,4.449489742783178,4.464101615137754,4.47213595499958,4.5604779323150675,4.576491222541475,4.58257569495584,4.60555127546399,4.645751311064591,4.650281539872885,4.685557720282968,4.69041575982343,4.730838352728495,4.732050807568877,4.741657386773941,4.795831523312719,4.82842712474619,4.863703305156273,4.872983346207417,4.878315177510849,4.8818192885643805,4.894328467737257,4.898979485566356,4.9681187850686666,5,5.0197648378370845,5.048675597924277,5.059964873437686,5.06449510224598,5.095241053847769,5.0990195135927845,5.123105625617661,5.146264369941973,5.155870949147037,5.16227766016838,5.1815405503520555,5.196152422706632,5.23606797749979,5.242640687119286,5.277916867529369,5.287196908580512,5.291502622129181,5.3166247903554,5.337602083032866,5.358898943540674,5.377802118633468,5.382332347441762,5.385164807134504,5.39834563766817,5.414213562373095,5.449489742783178,5.464101615137754,5.47213595499958,5.4737081943428185,5.4741784358107815,5.477225575051661,5.5373191879907555,5.55269276785519,5.5604779323150675,5.5677643628300215,5.576491222541474

```

# Answer
# , ~~9~~ 8 bytes

```
ŒP½ḅ1QṢḣ

```

Try it online!

Outputs the exact values (in the form `sqrt(n)`, and by composing these with products and sums). Very similar to hyper-neutrino's answer, but doesn't fail due to floating point errors.

Outputs the first \\$k\\$ elements of \\$R\_k\\$.

This times out on TIO for \\$k \ge 10\\$.

-1 byte (indirectly) thanks to DLosc's SageMath answer, so be sure to give that an upvote

## How it works

```
ŒP½ḅ1QṢḣ - Main link. Takes k on the left
ŒP       - Powerset of [1, 2, ..., k]
  ½      - Square root of each; [[], [1], [sqrt(2)], ..., [1, sqrt(2), ..., sqrt(k)]]
   ḅ1    - Convert each from base 1, summing them
     QṢ  - Remove duplicates and sort
       ḣ - Take the first k elements

```
> 7 votes

# Answer
# SageMath, 62 bytes

```
lambda k:sorted({*map(sum,powerset(map(sqrt,range(k+1))))})[k]

```

SageMath is a computer algebra system built on top of Python--the right choice if you want Python syntax without Python floating-point errors. Outputs exact values, written like `sqrt(2) + 1`, 0-indexed starting with `0`. Try it here!

### Explanation

Uses the "powerset of the first several square roots" approach:

```
lambda k:                       Anonymous function that takes an index k
                         [k]    and returns the kth element
         sorted(        )       of the following list sorted ascending:

                    range(k+1)  List of integers from 0 through k inclusive
               map(sqrt,     )  Square root of each
       powerset(             )  All possible subsets of the list of square roots
  map(sum,                   )  Sum of each subset
 {*                          }  Splat that list into a set, removing duplicates

```

(Passing a set to `sorted` automatically casts it to a list in Python--TIL.)
> 4 votes

# Answer
# Wolfram Language (Mathematica), ~~44~~ 42 bytes

1-indexed, output includes `0`. First duplicates are removed, then numbers are converted to a numerical value to make the sorting shorter.

```
Sort[N[{}⋃Tr/@√Subsets@Range@#]][[#]]&

```

Try it online!
> 2 votes

# Answer
# , ~~261~~ ~~169~~ 157 bytes

*Edit: substantial code golfing at the expense of now running painfully slowly for any input higher than 6 (although the underlying algorithm should still be valid if given sufficient time & resources)*

```
function(x)sort(rowSums(unique(t(apply(expand.grid(rep(list(unlist(sapply(-1:x+1,n))),x+1)),1,sort)))^.5))[x]
n=function(x,y=2)`if`(y<x,if(x%%y^2)n(x,y+1),x)

```

Try it online!

Base  *is* subject to floating-point inaccuracies, so this rather long code attempts to avoid these by first constructing a list of lists of integers from which to sum the square-roots, in such a way that 'clashes' are avoided.

**How?**
We first note that 'clashes' - when a number can be expressed as the sum of square-roots of integers in two different ways - happen for composite numbers with repeated prime factors.
For instance: `sqrt(4) = sqrt(2x2) = 2*sqrt(1) = sqrt(1)+sqrt(1)`
Or: `sqrt(18) = sqrt(2x3x3) = 3*sqrt(2) = sqrt(2)+2*sqrt(2) = sqrt(2)+sqrt(8)`

So, we first remove integers with repeated prime factors:

```
no_repeated_factors=
n=function(x,y=2)`if`(y<x,if(x%%y^2)n(x,y+1),x)

```

We then generate a list of all lists of combinations of non-negative integers that sum any integer value up to `x` (so, all combinations of `x` elements of `0...x`), excluding those with repeated prime factors (this step is pretty slow & greedy):

```
combinations_of_integers_without_repeated_factors_that_sum_to_up_to_x=
b=unique(t(apply(expand.grid(rep(list(unlist(sapply(-1:x+1,n))),x+1)),1,sort)))

```

The sums of square-roots from this list shouldn't give any 'clashes', so now we can just use all these lists of lists of integers that sum to `1...x`, calculate the sums of square roots, sort, and output the `x`-th one:

```
sums_of_sqrts=
function(x)sort(rowSums(b(x)^.5))[x]

```

Omitting the final `[x]` allows us to inspect the list of sums of square-roots - click here \- to check that the 'clashes' have been correctly removed, although at high indexes there will obviously be some missing values that will only get added when higher values of `x` are used.

There's probably a slicker way to do this... (particularly in languages with built-ins for finding prime factors or generating integer partitions).
> 2 votes

# Answer
# Ruby, 70 bytes

```
->n{r=(0..n).map{|x|x**0.5};r.product(*[r]*n).map(&:sum).uniq.sort[n]}

```

Try it online!

0-based, returns n-th number, very slow for n\>6.
> 1 votes

# Answer
# GNU-APL, 56 bytes

```
k←15◊a←{⍉(⍵⍴2)⊤⍳2⋆⍵}k◊b←{+/a[⍵;⍳k]/(1↓⍳k+1)*0.5}¨⍳2⋆k◊k↑b[⍋b]

```

```
a←{⍉(⍵⍴2)⊤⍳2⋆⍵}k                  ⍝ Power Set Matrix - every row is a selector
b←{+/a[⍵;⍳k]/(1↓⍳k+1)*0.5} ¨ ⍳2⋆k ⍝ for every row find the sum of sqrt of selected elements
k↑b[⍋b]                           ⍝ sort and take k elements from b

```
> 1 votes

# Answer
# Japt, 12 bytes

Returns the `n`th term, 0-indexed and including `0`

```
gUô¬à mx â ñ

```

Try it

```
gUô¬à mx â ñ     :Implicit input of integer U
g                :Index into
 Uô              :  Range [0,U]
   ¬             :  Square roots
    à            :  Powerset
      m          :  Map
       x         :    Reduce by addition
         â       :  Deduplicate
           ñ     :  Sort

```
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
∞ætOê

```

Outputs the entire sequence. Takes an infinite amount of time to generate the sequence, but works in theory.

```
∞ætOê  # full program
   O   # push list of sums of...
       # (implicit) each element in...
  t    # square root of...
       # (implicit) each element in...
       # (implicit) each element in...
 æ     # powerset of...
∞      # [1, 2, 3, ...]...
    ê  # sorted without duplicates
       # implicit output

```
> 0 votes

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


title: Staircase Program

text:
# Question
Title: Staircase Program
The challenge is simple: given two parameters, *x* and *y*, output *y* staircases with *x* steps. For example:

f(3,1) - 1 staircase with 3 steps.

```
    _
  _|
_|

```

f(5,2) - 2 staircases with 5 steps.

```
        _         _
      _|        _|
    _|        _|
  _|        _|
_|        _|

```

Make sure you output the staircases just like, this and that there is no extra space between staircases. Note that there is **one empty line** at the top.

**But there's a twist.** We are going to use a special kind of scoring called **staircase scoring**. In staircase scoring, as long as the character code (in the encoding your language uses) of each character is higher than the previous character you don't accumulate any points. You get a 1 point penalty for using a character with a code that is less than or equal to that of the previous character. Lowest score wins.

**E.g.** (Assume we are using Unicode).

* "abcd" - 0 points (every character is higher than the previous)
* "bbbb" - 3 points (the three last b's are not higher than the first)
* "aBcD" - 2 points (remember that in ASCII lowercase letters have higher values than uppercase letters).
* "™©" - 1 point (in Unicode the TM symbol has a value of 8482, where as the copyright symbol has value of 169.)

You can use the following snippet to check your score, as well as get the Unicode values of different characters, using the "Show Codes" toggle. (**Note**: This snippet scores using the Javascript UTF-16 encoding. It will break up some complex characters into multiple surrogate characters. If you do not want this, you must score yourself.) :

```
function showCodes() {
  if(!check.checked) return;
  var val = program.value;
  var c = "";
  for(var i = 0;i<val.length;i++) {
    c+= val.charCodeAt(i) + " ";
  }
  codes.textContent = c;
}

function toggle() {
  if(!check.checked) codes.textContent = "";
  else showCodes();
}

function getScore() {
  var val = program.value;
  var score = 0;
  for(var i = 0;i<val.length-1;i++) {
    score += val[i+1] <= val[i];
  }
  alert(score);
}
```

```
<textarea rows=10 cols=40 id="program" oninput="showCodes()"></textarea>
<input type="submit" value="Get Score" onclick="getScore()" /> Show Codes<input type="checkbox" id="check" onchange="toggle()" />
<div id="codes"></div>
```

## Notes:

* The input values *x* and *y* will always be \> 0

# Answer
> 4 votes
# Headsecks - 0 points

I took up @Mauris' idea. I didn't want to actually do this in brainfuck, so I used bfbasic.

Here is the Basic program:

```
INPUT A
INPUT B

A=A-2
B=B-2

J=0
DO
    I=0
    DO
        IF I=0 THEN
            IF A-J>1 THEN
                K=0
                DO
                    PRINT "  ";
                    K=K+1
                LOOP WHILE K<A-J-1
            END IF

        ELSE
            K=0
            DO
                PRINT "  ";
                K=K+1
            LOOP WHILE K<A-1

            IF J=0 THEN
                PRINT " ";
            END IF
        END IF

        IF J=0 THEN
            PRINT "_";
        ELSE
            PRINT "_|";
        END IF

        I=I+1
    LOOP WHILE I<B
    PRINT

    J=J+1
LOOP WHILE J<A

PRINT

```

bfbasic was incrementing all my inputs by two for some reason.

I then got this brainfuck code:

```
>+<+[>[>[-]+<-]>[<+>>>>>>>>>>>[-]<<<<<<<<<+[->,.----------[<+>>++++++[<------>-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>++++++++++<<<<<<<-]<[>>>>>>>>+<<<<<<<<-]]<]>>>>>>>>>>>>[-]<<<<<<<<<<<<+[->,.----------[<+>>++++++[<------>-]>>>>>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<[>>[-]+<<-]>>-]<[>>>>>>>-<<<<<<<[-]]>>>[-]>>>>[>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]<[>[-]+<-]>[<+>>++++++++++.[-]<<<->>-]<<]

```

I finished it by using this Python script in conjunction with Multilang's headsecks implementation:

```
import headsecks

m=0
with open(input()) as p:
 p=p.read().strip()
c="+-<>.,[]"
h=""

for i in p:
 h+=chr(c.index(i)+8*m)
 m+=1

with open('h.hs', 'w') as x:
 x.write(h)

headsecks.execute(h)

```

And ended up with this headsecks program (It works in the snippet):

https://gist.github.com/anonymous/d956240df995f3cd7d86

xxd dump:

https://gist.github.com/anonymous/67e1fed9e53a770bb770

# Answer
> 5 votes
# CJam, 2 points

```
"qžɟ̬вխتܯࡗथ੻୾భ൓๟༫ဢቼጢᐿᕽᙦᜥᠺᥳᩗ᭦᰼ᵓṦἫK≎〉"127f&~

```

Try it here.

It takes a long ascending UTF-8 string, gets all character values modulo 128, then evaluates it as CJam code. Removing the final `~` reveals the "real" program hiding underneath:

```
q~_,2m*/W%{~-S_+"_|"?}f%:sWf<Sf+f*N*

```

Which might not even be a very good golf, but luckily it doesn't matter. ^^

Saved a point thanks to Dennis!

# Answer
> 1 votes
# Python 2, 25 points

Following Mauris' approach of unicode character conversion:

```
exec ''.join([chr(ord(unicode(c))%256) for c in u'dťɦ̠ѨԨٳܬ࡮ऩ਺ଊఠ൰๲ཀྵၮᅴሠ፮ᐪᔨᘧᜠᠧᤪᨲᬪᱳᴫḧὟ‧℩∊⌠⑦╯♲✠⡫⤠⩩⭮Ⱐ⵲⹡⽮でㅥ㈨㍳㐩㔺㘊㜠㠠㥰㩲㭩㱮㵴㸠㽮䀪䄨䈧䌠䐧䔪䘨䜲䠪䥳䨭䬲䰪䵫中伲倩儫刧卟呼唧嘫圧堠大娪嬨尲崪幫弫怱愩戩'])

```

Example input and output:

```
h(5,2)

          _          _
        _|         _|
      _|         _|
    _|         _|
  _|         _|
_|         _|

h(3,1)

      _
    _|
  _|
_|

```

# Answer
> 1 votes
# Vyxal `j`, Score 5

```
ƛd‛_|↳¹d↲Ṫ⁰*;Ṙ

```

Try it Online!

Using the Vyxal codepage, score is 5.

# Answer
> 0 votes
# TeaScript, 33 points

```
r(x)vm#pR(l*2)+"_"+(g=l==a.n-1?p:"|")+(pR(x*2-2)+"_"+g)R(y-1))j(n

```

This is unusually long because TeaScript 3 is fairly new and contains many bugs, especially with unicode shortcuts which kills the score.

Try it online

---
Tags: code-challenge, ascii-art
---


title: Format a Swedish phone number

text:
# Question
Title: Format a Swedish phone number
In some parts of the world, phone numbers are fixed-length, apparently. That sounds boring, though.

For this challenge, your task is to take the digits of a what is presumed to be a valid phone number, and format it based on some simplified rules around what a phone number looks like.

### Input format

Your input will consist of nothing except the digits `0` through `9`, and the input will contain between five and ten of them (both inclusive). Every input *will* be a valid phone number, according to the following simplified rules:

* A full phone number consists of eight to ten digits and can be divided into an optional area code of two to four digits (the first of which is `0`), and a mandatory subscriber number of five to eight digits (the first of which is *not* `0`)
* When calling someone from a landline phone who has the same area code as you, you do not need to dial the area code. Thus, your program must be able to handle inputs consisting only of a subscriber number with no area code.
* The subscriber number consists of 5 to 8 digits, and the first one isn't `0`.
* The area code, if present, begins with `0`, and has 2 to 4 digits. For this challenge's purposes, the length depends on the second digit:
    + The second digit of the area code will never be `0`.
    + If the second digit is `8`, the entire area code will be 2 digits long (so the entire area code will be `08`)
    + If the second digit is `1`, `2`, `3`, `4`, or `7`, the area code will be 3 digits long.
    + If the second digit is `5`, `6`, or `9`, the area code will be 4 digits long.
* *However*, for some inputs, the above cutoff point would cause the subscriber number to be too short or begin with a `0`. Since we know the input is a valid phone number (because I say so) we have to conclude that the length of the area code is different from the above. If the length listed above does not work, you should pick a length which works, preferring 3-digit codes over 4-digit codes, and preferring either of those to 2-digit codes. You will not need to handle inputs like `0801234`, which are invalid for all those cutoff points.

### Output format

Your output should be the area code, followed by a dash (only if an area code is present), followed by the subscriber number which should be grouped in one of the following manners (with the groups separated by a single space):

```
xxx xxx xx
xxx xx xx
xx xx xx
xxx xx

```

That means numbers *with* area codes specified will have one of the following formats:

```
0x-xxx xxx xx
0x-xxx xx xx
0x-xx xx xx
0xx-xxx xx xx
0xx-xx xx xx
0xx-xxx xx
0xxx-xx xx xx
0xxx-xxx xx

```

## Test cases

All numbers were randomly generated, and some of them could potentially be in use, so while I don't expect any of them to belong to anyone in particular, please don't try to call them.

```
27983516    ->  279 835 16     # No area code, 8 digits
6278304     ->  627 83 04      # No area code, 7 digits
627830      ->  62 78 30       # No area code, 6 digits
11865       ->  118 65         # No area code, 5 digits
067934821   ->  0679-348 21    # Simple 4+5
0927586130  ->  0927-58 61 30  # Simple 4+6
0374821096  ->  037-482 10 96  # Simple 3+7
042807961   ->  042-80 79 61   # Simple 3+6
04629873    ->  046-298 73     # Simple 3+5
0897106384  ->  08-971 063 84  # Simple 2+8
081859302   ->  08-185 93 02   # Simple 2+7
08379451    ->  08-37 94 51    # Simple 2+6
0480936572  ->  0480-93 65 72  # Area code couldn't be 048 to prevent subscriber number starting with 0
0957024168  ->  095-702 41 68  # Area code couldn't be 0957 for the same reason
06057291    ->  060-572 91     # Area code couldn't be 0605 because of subscriber number's length
04809714    ->  04-80 97 14    # Area code could neither be 048 nor 0480 didn't help
080062517   ->  0800-625 17    # Area code could neither be 08 nor 080
09106574    ->  09-10 65 74    # Area code had to be shortened twice from 0910 because shortening it to 091 didn't work

```

This is , shortest code in each language wins.

# Answer
> 10 votes
# Retina, ~~78~~ 73 bytes

```
(0(8|[569].?.?|..?0?)(?=[^0]....))?(...?)?(...?)(..)$
$1$#1*-$3$#3* $4 $5

```

Inspired by both *@mazzy*'s PowerShell answer and *@NahuelFouilleul*'s Perl 5 answer, so make sure to upvote them both as well!
-5 bytes thanks to *@Neil*.

Try it online.

**Explanation:**

Match the digit groups like this:

```
(                                )? # An optional group 1, which consists of:
 0                                  #  A leading 0
  ( |         |     )               #  followed by either (ignored inner group 2):
   8                                #   A single 8
    |[569]                          #   or one of 569,
          .?.?                      #      with one or two optional chars
              |.                    #   or any character,
                .?                  #      with one optional character,
                  0?                #      and an optional trailing 0
                     (?=        )   #  followed by an uncaptured inner group with:
                        [^0]        #   A character which is NOT a 0
                            ....    #   followed by any four characters
(    )?                             # An optional group 3, which consists of:
 ..                                 #  Two characters,
   .?                               #  followed by an optional character
(    )                              # A mandatory group 4,
 ...?                               #  which is similar as group 3
(  )                                # Followed by a mandatory group 5
    $                               # (at the end of the string), which consists of:
 ..                                 #  Any two characters

```

Then replace it with:

```
$1                                  # The content of group 1 (possibly empty)
  $#1*                              # If group 1 isn't empty:
      -                             #  A "-"
       $3                           # The content of group 3 (possibly empty)
         $#3*                       # If group 3 isn't empty:
             <sp>                   #  A " "
                 $4                 # The content of group 4
                   <sp>             # A " "
                       $5           # The content of group 5

```

# Answer
> 8 votes
# Perl 5 (`-p`), ~~92~~, 84 bytes

```
s/(0(8|[569].?.?|..?0?)(?=.{5})(?!0))?(...?)?(...?)(..)$/$1-$3 $4 $5/;s/^\D*|-\K //g

```

Try it online!

# Answer
> 7 votes
# PowerShell, ~~135~~ ~~127~~ ~~118~~ ~~107~~ 105 bytes

*-1 byte thanks @Kevin Cruijssen*

```
$args-replace'(0(8|[569].?.?|..?0?)(?=[^0].{4}))?(...?)?(...?)(..)$','$1-$3 $4 $5'-replace'^\D+|(?<=\D) '

```

Try it online!

# Answer
> 3 votes
# Python 3.8, 554 bytes

```
#it's the source patterns
s=r'''xxx xxx xx
xxx xx xx
xx xx xx
xxx xx
0x-xxx xxx xx
0x-xxx xx xx
0x-xx xx xx
0xx-xxx xx xx
0xx-xx xx xx
0xx-xxx xx
0xxx-xx xx xx
0xxx-xxx xx'''.split('\n')
import re
#now we make pattern matchers for each of them,
#assuming 0 does not start a short number (^) or the first group after '-'
m=[re.compile('^'+
              re.sub(r'(^)?(\-)?(x+)',
                         lambda m:
                         (lambda x:
                          [r'(\d{%d})'%x,r'([1-9]\d{%d})'%(x-1)]
                          [(m.group(2)!=None)or(m.group(1)!=None)])
                         (len(m.group(3))),i)
              .replace(' ','')
              +'$')
   for i in s]
f=lambda i:(lambda k,v:re.sub('x+','%s',k)%v)(*(
    #then we sort matching patterns by
    #first character in ['','8','12347','569'][len(first_group)]
    #and by len(first_group)
    #and take the last elem. It will be with key (True,n) or
    #(False,max(n)) if n is the first group's length
    sorted(
    [(k,v.groups()) for j,k in zip(m,s) if (v:=j.match(i))],
    key=lambda x:((g:=x[1][0])[0] in ['','8','12347','569'][len(g)],
                                len(g)) )[-1]))

```

Try it online!
I see it can be shortened by `sum(len(j)-1 for i in s for j in re.findall('x+',i))==50` bytes by replacing 'x' repeating n times by n, but I just wanted to demonstrate the approach.

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 246 bytes

```
s=>{int a=s[1]-'0',b=0,c=s.Length,d,e;bool f=s[4]==48,g=s[2]==48;var h="";if(s[0]==48){b=a==8?2:a<5|a==7?3:f?3:4;b=s[3]==48?!g&c-b<6?2:f?3:4:g?3:b;h+=s.Substring(0,b)+"-";}for(d=b;d<c-1;d+=e)h+=$"{s.Substring(d,e=c-b==6?2:c-d<5?2:3)} ";return h;}

```

Try it online!

```
int a = s[1]-'0'   //int value of second char
    b = 0,         //area code length
    c = s.Length,  //length of the input
    d,             //for loop iterator
    e;             //length of the current number group

bool f = s[4]==48, //5th digit is 0
     g = s[2]==48; //3rd digit is 0

var h="";          //output string

if(s[0]==48)       //starts with 0 / is area code
{
    b=a==8?2:a<5|a==7?3:f?3:4;          //set area code length from subscriber number
    b=s[3]==48?g&c-b<6?2:f?3:4:!g?3:b;  //modify area code length according to special 0's
    h+=s.Substring(0,b)+"-";            //append area code to output
}

for(d=b;d<c-1;d+=e) //iterate the non area code numbers
{
    h+=$"{s.Substring(d,e=c-b==6?2:c-d<5?2:3)} "; //append number group of 'e' length
}

return h;

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~284~~ 267 bytes

```
(n,B=I=>+n[I]&&n.length-I>4,A=a=>a.includes(n[1]),b=B(0),L=A('8')?2:A('569')?4:3)=>(b?'':n.slice(0,B(L)?L:L=L>3?B(3)?3:2:L>2?B(4)?4:2:B(4)?4:3))+(b?'':'-')+n.slice(b?0:L).replace(/./g,(e,i,T,U=e+' ')=>T[5]?T[6]?T[7]?i==2|i==5?U:e:i==2|i==4?U:e:i==1|i==3?U:e:i==2?U:e)

```

Try it online!

**No regex** except for the basic `/./g`, and that's the way I want it to be.

# Answer
> 1 votes
# Python 3, 128 bytes

```
lambda x:re.sub(r'^\D+|(?<=\D) ','',re.sub(r'(0(8|[569].?.?|..?0?)(?=[^0].{4}))?(...?)?(...?)(..)$',r'\1-\3 \4 \5',x))
import re

```

Try it online!

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


title: N Slab Slanted Slash Cake

text:
# Question
Title: N Slab Slanted Slash Cake
Write a program or function that takes in a positive integer N.

When N is 1, output

```
/\
\/

```

When N is 2, output

```
/\/\
\/ /
/ /
\/

```

When N is 3, output

```
/\/\/\
\/ / /
/ / /
\/ /
/ /
\/

```

When N is 4, output

```
/\/\/\/\
\/ / / /
/ / / /
\/ / /
/ / /
\/ /
/ /
\/

```

For larger N the pattern continues, a new layer is added every time N is incremented.

* "Output" means print the slash pattern or return it as a string.
* A single trailing newline in the output is allowed.
* Trailing spaces in the output are allowed but leading spaces are not.

**The shortest code in bytes wins.**

# Answer
# Pyth, 25 bytes

```
j_+t.iJ*R"/ "SQ+L\\J*Q"/\

```

Try it online: Demonstration or Test Suite

### Explanation:

```
j_+t.iJ*R"/ "SQ+L\\J*Q"/\   implicit: Q = input number
             SQ             create the list [1, 2, ..., Q]
       *R"/ "               repeat "/ " accordingly to this numbers
      J                     assign this list of strings to J
               +L\\J        create a 2nd list, which contains the same strings
                            as in J, just with a "\" prepended
    .i                      interleave these two lists
   t                        remove the first element
                    *Q"/\   repeat the string "/\" Q times
  +                         append it to the list
 _                          reverse it
j                           print each string on a separate line

```
> 10 votes

# Answer
## CJam, ~~32~~ ~~30~~ ~~29~~ 28 bytes

```
ri_"/\ /"2/f*)@,\f>+_z..e>N*

```

Test it here.

I was trying to help Reto golf his CJam answer but ended up with a solution that had nothing to do with his, so I figured I might as well post it myself.

### Explanation

This makes use of the symmetry of the output. In particular, the fact that the output is the same as its transpose.

First, we generate the first `N+1` lines, but without the left edge:

```
ri       e# Read input and convert to integer N.
_        e# Duplicate.
"/\ /"2/ e# Push an array with two strings: ["/\" " /"]
f*       e# Repeat each of the two strings N times. That gives the first two rows.
)        e# Detach the second row.
@,       e# Pull up the other copy of N and turn into range [0 1 ... N-1].
\f>      e# For each element i in that range, discard the first i characters of
         e# the second row.
+        e# Add all those lines back to the first row.

```

Now we've got an array of strings representing the following grid:

```
/\/\/\/\
 / / / /
/ / / /
 / / /
/ / /

```

The transpose of that looks like this:

```
/ / /
\/ /
/ / /
\/ /
/ / /
\/ /
/ /
\/

```

Together, these have all the non-space characters that we need. We can now make use of Dennis's rad tip to combine two ASCII grids into one, by taking the maximum of each corresponding pair of characters. In all positions where the two grids differ, one will have a space (or nothing at all) and the other will have the character we're looking for. When one list in a vectorised operation is longer than the other, the additional elements of the longer list will simply be kept, which is just what we're looking for. In the other cases, the non-space character will always be the maximum of the two characters:

```
_z   e# Duplicate the grid and transpose it.
..e> e# For each pair of characters in corresponding positions, pick the maximum.
N*   e# Join the lines by linefeed characters.

```
> 10 votes

# Answer
# Japt, ~~46~~ ~~44~~ ~~41~~ 40 bytes

```
Uo-U £Y?"\\/"sYv)+" /"pU-Y/2 :"/\\"pU} ·

```

Try it online!

### Ungolfed and explanation

```
Uo-U mXYZ{Y?"\\/"sYv)+" /"pU-Y/2 :"/\\"pU} qR

```

The core of the program makes a list of `U * 2` items, maps each to one row of the pattern, then joins them with newlines:

```
Uo-U    // Build an array of all integers in the range [-U, U).
mXYZ{   // Map each item X and index Y in this array with the following function.
 ...
} qR    // Join the resulting array with newlines.

```

As for the pattern itself, here's how I have broken it up:

```
/\/\/\/\

\/   / / /
/    / / /
\/   / /
/    / /
\/   /
/    /
\/

```

As you can see here, this now devolves into three simple patterns. The first one is the easiest, generated with this code:

```
Y? ... :  // If Y, the current index, is 0,
"/\\"pU   // return the pattern "/\" repeated U*2 times.

```

Now for the left half. Odd indices should map to `\/`, and even to `/`, so we use this code:

```
"\\/"s  // Otherwise, slice the pattern "\/" at
Yv)     //  if Y is even, 1; otherwise, 0.

```

This makes the right half way easier; all we need to do is repeat `/` a few times:

```
" /"p  // Repeat the pattern " /"
U-Y/2  //  floor(U - (Y/2)) times.

```

Suggestions welcome!
> 7 votes

# Answer
# GNU Sed, 59

Score includes +2 for '-nr' options to `sed`.

```
s|1|/\\|gp
y|/\\| /|
s| |\\|p
:
s|\\(..)|\1|p
s|/ |\\|p
t

```

Input in unary as per this meta answer.

### Test output:

```
$ sed -nrf slantcake.sed <<< 111
/\/\/\
\/ / /
/ / /
\/ /
/ /
\/
$

```
> 5 votes

# Answer
## Python 2, 80 bytes

```
n=input()
print"/\\"*n
for i in range(n*2,1,-1):print"\\"*(1-i%2)+"/ "*(i/2+i%2)

```
> 3 votes

# Answer
# CJam, ~~36~~ ~~35~~ 34 bytes

```
ri_"/\\"*N@,W%{'\'/@" /"*+_N\N}/;;

```

Try it online

Thanks to @NinjaBearMonkey for pointing out the extra `;`.

While this looks relatively inelegant, I tried a couple of other options, and they did not end up any shorter.

Explanation:

```
ri_     Get input, convert to integer, and copy.
"/\\"   Pattern for first line.
*N      Repeat N times, and add a newline.
@,      Rotate N to top, and create [0 .. N-1] sequence.
W%      Invert sequence to [N-1 .. 0].
{       Loop over counts, creating two lines for each.
  '\      Leading character for first in pair of lines. Rest will be the same
          for both lines.
  '/      First character for repeated part.
  @       Rotate count to top.
  " /"    Repetitive pattern.
  *       Replicate it by count.
  +       Concatenate with '/.
  _       Copy whole thing for use as second in pair of lines.
  N\      Put a newline between the pair of lines.
  N       Add a newline after second line.
}/      End of loop over counts.
;;      Created an extra line, get rid of it.

```
> 3 votes

# Answer
## Mathematica, ~~123~~ ~~122~~ 121 bytes

```
""<>(#<>"
"&/@Normal@SparseArray[{{i_,j_}/;2∣(i+j)&&i+j<2#+3->"/",{i_,j_}/;i~Min~j<2&&2∣i~Max~j->"\\"},{2#,2#}," "])&

```

Could probably be golfed further.
> 2 votes

# Answer
## Java - 141 bytes

Not the shortest of course, but nice to have a Java solution :

```
String a(int a){String s="";int b=-1,c,e;for(a*=2;++b<a;){for(c=-1;++c<a;)s+=(e=b+c)>a?" ":e%2==0?"/":b==0||c==0?"\\":" ";s+="\n";}return s;}

```

---

## Ungolfed

```
String a(int a){
    String s ="";
    int b=-1,c,e;
    for (a*=2;++b < a;){
        for (c = -1 ; ++c < a ;)
            s+= (e=b+c)>a?" ": e%2==0? "/" : b==0||c==0? "\\" : " ";
        s+="\n";
    }
    return s;
}

```

---

## Input

```
System.out.println(a(5));

```

## Output

```
/\/\/\/\/\
\/ / / / /
/ / / / /
\/ / / /
/ / / /
\/ / /
/ / /
\/ /
/ /
\/

```
> 2 votes

# Answer
# JavaScript, ~~128~~ ~~125~~ ~~123~~ 114 bytes

```
n=>{r='';for(i=0;i<n;i++)r+='/\\';for(j=0;j<2*n-1;j++){r+='\n'+(j%2?'':'\\');for(i=n-j/2;i>0;i--)r+='/ '}return r}

```

De-golf (also converted to ES5) + demo:

```
function c(n) {
    r = '';
    for (i = 0; i < n; i++) r += '/\\';
    for (j = 0; j < 2 * n - 1; j++) {
        r += '\n' + (j % 2 ? '' : '\\');
        for (i = n - j / 2; i > 0; i--) r += '/ '
    }
    return r
}

alert(c(prompt()));
```
> 1 votes

# Answer
## Pyth, 30 Bytes

```
*"/\\"QVr*2Q1+*\\!%N2*s.DN2"/

```

Try it here.
> 1 votes

# Answer
# Javascript (ES6), ~~107~~ ~~104~~ ~~100~~ ~~98~~ ~~97~~ ~~91~~ 90 bytes

```
p=>{s=`/\\`.repeat(p++)+`
`;for(i=p;i>2;s+='\\'+o+o)o=`/ `.repeat(--i)+`
`;return s+'\\/'}

```

*First post here!*

Used to use `Array(len)``.``join(str)` but now uses `String.repeat(len)`, similar to Ruby's `operator*(str,len)`.

Ungolfed:

```
len => {
    var str = `/\\`.repeat(len++) + '\n';

    for (var i = len, mid; i > 2; str += '\\' + mid + mid) {
        mid = `/ `.repeat(--i) + '\n';
    }

    return str + '\\/';
}

```

*Thanks to:*
*107 =\> 104 bytes: @insertusernamehere*
*97 =\> 90 bytes: @user81655*
> 1 votes

# Answer
# Ruby, 50 bytes

```
->n{s='/\\'*n
n.times{|i|puts s,?\\+s='/ '*(n-i)}}

```

In test program:

```
f=->n{s='/\\'*n
n.times{|i|puts s,?\\+s='/ '*(n-i)}}
f[gets.to_i]

```

The loop prints 2 rows for every iteration from i=0 to i=n-1.

The second row is always `'\'` followed by n-i incidences of `'/ '`.

The first row is the same as the second row of the previous iteration, but with the `'\'` missing (so we store this value in `s` when we print the second row of the previous iteration.)

The only exception is iteration zero, which is handled by initializing `s` to `'/\'*n`.
> 1 votes

# Answer
## Python 2, 66 bytes

```
n=input();b=1
print'/\\'*n
while~-n+b:print'\\'*b+'/ '*n;b^=1;n-=b

```

Pretty straightforward. The value `n` is the number of `/` on the line, and `b` says whether the line starts with `\`. The value of `b` alternates between 0 and 1, and `n` decreases every second step. The ugly termination condition stops when `n=1, b=0`. The alternative of an `exec` loop would have the issue of needing lots of escapes for `"'\\\\'"`.

I was surprised to find this approach shorter than using a single number `k=2*n+b`. This is 68 bytes:

```
k=2*input()+1
print k/2*"/\\"
while k>2:print k%2*'\\'+k/2*'/ ';k-=1

```

An alternative strategy would avoid a separate `print` for the top line, but I didn't see a concise way.
> 1 votes

# Answer
## Batch, 121 bytes

```
@echo off
set/an=%1-1
if %1==1 (echo /\%2) else call %0 %n% /\%2
set a=/\%2
echo \%a:\= %
if not \%2==\ echo %a:\= %

```

Or if unary is acceptable, 107 bytes:

```
@echo off
set a=%1
echo %a:1=/\%
:a
echo \%a:1=/ %
set a=%a:~1%
if not %a%1==1 echo / %a:1=/ %&goto a

```

Invoke with the appropriate number of 1s.
> 1 votes

# Answer
## Minkolang 0.14, 46 bytes

I'm sure this could be golfed, but it's 4 am here and I need to go to bed.

```
n$z"/\"z$D$OlOz[" /"zi-$Dlr$d"\"zi1+-3&5$X$O].

```

Try it here.

### Explanation

```
n$z               Take number from input (n) and store it in the register (z)
   "/\"           Push these characters (in reverse)
       z$D        Push register value and duplicate the whole stack that many times
          $O      Output whole stack as characters
            lO    Output newline

z                                   Push n from register
 [                                  Open for loop that repeats n times
  " /"                              Push these characters (in reverse)
      zi-                           n - loop counter
         $D                         Pop k and duplicate whole stack k times
           l                        Push 10 (for newline)
            r                       Reverse stack
             $d                     Duplicate whole stack
               "\"                  Push this character
                  zi1+-             0 if n = loop counter + 1, truthy otherwise
                       3&           Do the next three characters if top of stack is 0
                         5$X        Dump the bottom-most five items of the stack
                            $O      Output whole stack as characters
                              ].    Close for loop and stop

```
> 1 votes

# Answer
# Vyxal, 27 bytes

```
`/\\`*,ɾṘƛ\/*fṄ;:ƛ\\p;$YṪ⁋,

```

Try it Online!

```
`/\\`                       # '/\'
     *,                     # Input times
       ɾṘ                   # n...1
         ƛ     ;            # Map...
          \/*               # That many slashes
             fṄ             # Joined by spaces
                :           # Duplicate
                 ƛ\\p;      # Prepend a backslash to each
                      $Y    # Swap and interleave
                        Ṫ   # Cut off last
                         ⁋, # Joined by newlines

```
> 1 votes

# Answer
# Matlab, 122 bytes

```
M=2*input('');
z=zeros(M);[y,x]=ndgrid(1:M);
z(~mod(x+y,2)&x+y<M+3)=1;v=2-mod(1:M,2);
z(1,:)=v;z(:,1)=v;disp([15*z.^2+32,''])

```
> 0 votes

# Answer
## Ceylon, 100

```
String s(Integer n)=>"\n".join{"/\\".repeat(n),for(i in 2*n+1..3)"\\".repeat(i%2)+"/ ".repeat(i/2)};

```

This features an "named argument list" for `join` (without any named arguments, but an iterable comprehension instead), and several uses `String.repeat` (one of which actually means "include only for odd `i`").

Formatted:

```
String s(Integer n) =>
        "\n".join{
            "/\\".repeat(n),
            for (i in 2*n + 1 .. 3)
                "\\".repeat(i % 2)
                        + "/ ".repeat(i / 2)
        };

```
> 0 votes

# Answer
# Haskell, 99 bytes

Two solutions of equal length.

Call `f`.

```
f n=mapM_ putStrLn$[[x?y|x<-[0..2*n-y-0^y]]|y<-[0..2*n-1]]
x?y|mod(x+y)2==0='/'|x*y==0='\\'|0<1=' '

```

and

```
f n=mapM_ putStrLn$[[x?y|x<-[y..2*n-0^y]]|y<-[0..2*n-1]]
x?y|mod x 2==0='/'|mod y x==0='\\'|0<1=' '

```
> 0 votes

# Answer
## Haskell, 96

```
f=g.(*2)
g m=unlines$t m(c"/\\"):[t n l|(n,l)<-zip[m,m-1..2]$c['\\':p,p]]
p=c"/ "
c=cycle
t=take

```

This is not actually competitive against the existing Haskell solution because it saves 5 characters by returning instead of printing a string. I am posting it only to show how the infinite pattern approach compares to the coordinate-based approach. Notes:

* `p` can be inlined for no change in length.
* `[t n l|(n,l)<-...]` saves 2 over `(map(uncurry t)$...)`.
> 0 votes

# Answer
## PHP, 117 bytes

```
<?$n=$argv[1];$r=str_repeat;echo$r("/\\",$n);for(;$i++<$n*2-1;)echo"\n".($i%2?"\\":'').$r("/ ",$n-floor(($i-1)/2));?>

```

Assumes notices are turned off and input is taken from command line.

Ungolfed:

```
<?php
error_reporting(E_ALL & ~E_NOTICE);

$n = $argv[1];
$r='str_repeat';
echo $r("/\\",$n);
for(;$i++<$n*2-1;){
    echo"\n".(($i%2)?"\\":'') . $r("/ ",$n-floor(($i-1)/2));
}
?>

```

Comments are welcome :)
> 0 votes

# Answer
# Japt `-R`, 24 bytes

```
õç'/ú2)cÈ·p'\+XÃÅÔiUç"/\

```

Try it
> 0 votes

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