title: Count the bytes of a program

text:
# Question
Title: Count the bytes of a program
**Note 2: I accepted `@DigitalTrauma`'s 6-byte long answer. If anyone can beat that I will change the accepted answer. Thanks for playing!**

**Note: I will be accepting an answer at 6:00pm MST on 10/14/15. Thanks to all that participated!**

I am very surprised that this has not been asked yet (or I didn't search hard enough). Either way, this challenge is very simple:

**Input:** A program in the form of a string. Additionally, the input may or may not contain:

* Leading and trailing spaces
* Trailing newlines
* Non-ASCII characters

**Output:** Two integers, one representing *UTF-8* character count and one representing byte count, you may choose which order. Trailing newlines are allowed. Output can be to STDOUT or returned from a function. IT can be in any format as long as the two numbers are distinguishable from each other (2327 is not valid output).

**Notes:**

* You may consider newline as `\n` or `\r\n`.
* Here is a nice byte & character counter for your tests. Also, here is a meta post with the same thing (Thanks to @Zereges).

**Sample I/O:** (All outputs are in the form `{characters} {bytes}`)

Input: `void p(int n){System.out.print(n+5);}`

Output: `37 37`

Input: `(~R∊R∘.×R)/R←1↓ιR`

Output: `17 27`

Input:

```

friends = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(friends):
    print "iteration {iteration} is {name}".format(iteration=i, name=name)

```

Output: `156 156`

**This is code golf - shortest code in *bytes* wins!**

## Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=60733,OVERRIDE_USER=36670;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 34 votes
# Shell + coreutils, 6

This answer becomes invalid if an encoding other than UTF-8 is used.

```
wc -mc

```

### Test output:

```
$ printf '%s' "(~R∊R∘.×R)/R←1↓ιR" | ./count.sh
     17      27
$

```

---

In case the output format is strictly enforced (just one space separating the the two integers), then we can do this:

# Shell + coreutils, 12

```
echo`wc -mc`

```

Thanks to @immibis for suggesting to remove the space after the `echo`. It took me a while to figure that out - the shell will expand this to `echo<tab>n<tab>m`, and tabs by default are in `$IFS`, so are perfectly legal token separators in the resulting command.

# Answer
> 22 votes
# GolfScript, ~~14~~ 12 bytes

```
.,p{64/2^},,

```

Try it online on Web GolfScript.

### Idea

GolfScript doesn't have a clue what Unicode is; all strings (input, output, internal) are composed of bytes. While that can be pretty annoying, it's perfect for this challenge.

UTF-8 encodes ASCII and non-ASCII characters differently:

* All code points below 128 are encoded as `0xxxxxxx`.
* All other code points are encoded as `11xxxxxx 10xxxxxx ... 10xxxxxx`.

This means that the encoding of each Unicode character contains either a single `0xxxxxxx` byte or a single `11xxxxxx` byte (and 0 to 5 `10xxxxxx` bytes).

By dividing all bytes of the input by **64**, we turn `0xxxxxxx` into **0** or **1**, `11xxxxxx` into **3**, and `10xxxxxx` into **2**. All that's left is to count the bytes whose quotient is not **2**.

### Code

```
                (implicit) Read all input and push it on the stack.
.               Push a copy of the input.
 ,              Compute its length (in bytes).
  p             Print the length.
   {     },     Filter; for each byte in the original input:
    64/           Divide the byte by 64.
       2^         XOR the quotient with 2.
                If the return is non-zero, keep the byte.
           ,    Count the kept bytes.
                (implicit) Print the integer on the stack.

```

# Answer
> 8 votes
# Python, ~~42~~ 40 bytes

```
lambda i:[len(i),len(i.encode('utf-8'))]

```

Thanks to Alex A. for the two bytes off.

Straightforward, does what it says. With argument `i`, prints the length of `i`, then the length of `i` in UTF-8. Note that in order to accept multiline input, the function argument should be surrounded by triple quotes: `'''`.

EDIT: It didn't work for multiline input, so I just made it a function instead.

Some test cases (separated by blank newlines):

```
f("Hello, World!")
13 13

f('''
friends = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(friends):
    print "iteration {iteration} is {name}".format(iteration=i, name=name)
''')
156 156

f("(~R∊R∘.×R)/R←1↓ιR")
17 27

```

# Answer
> 6 votes
# Julia, 24 bytes

```
s->(length(s),sizeof(s))

```

This creates a lambda function that returns a tuple of integers. The `length` function, when called on a string, returns the number of characters. The `sizeof` function returns the number of bytes in the input.

Try it online

# Answer
> 4 votes
# Rust, 42 bytes

```
let c=|a:&str|(a.chars().count(),a.len());

```

# Answer
> 4 votes
# Java, ~~241~~ ~~90~~ 89 bytes

```
int[]b(String s)throws Exception{return new int[]{s.length(),s.getBytes("utf8").length};}

```

# Answer
> 3 votes
# Pyth - ~~12~~ 9 bytes

Will try to get shorter.

```
lQh/l.BQ8

```

Test Suite.

# Answer
> 2 votes
# PowerShell, 57 bytes

```
$args|%{$_.Length;[Text.Encoding]::UTF8.GetByteCount($_)}

```

# Answer
> 2 votes
# R, 47 bytes

```
a<-commandArgs(TRUE);nchar(a,"c");nchar(a,"b")

```

Input: `(~R∊R∘.×R)/R←1↓ιR`

Output:

```
[1] 17
[2] 27

```

If printing line numbers alongside output isn't allowable under the "any format" then `cat` can fix the issue:

# R, 52 bytes

```
a<-commandArgs(TRUE);cat(nchar(a,"c"),nchar(a,"b"))

```

Input: `(~R∊R∘.×R)/R←1↓ιR`

Output: `17 27`

# Answer
> 2 votes
# C, ~~68~~ 67 bytes

```
b,c;main(t){for(;t=~getchar();b++)c+=2!=~t/64;printf("%d %d",c,b);}

```

This uses the same idea as my other answer.

Try it online on Ideone.

# Answer
> 2 votes
# Brainfuck, 163 bytes

```
,[>+<,]>[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]<

```

With linebreaks for readability:

```
,[>+<,]>
[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[
>++++++++++<[->-[>+>>]>[+[-<+>]>.
+>>]<<<<<]>[-]++++++++[<++++++>-
]>[<<+>>-]>[<<+>>-]<<]>]<[->>+++++
+++[<++++++>-]]<[.[-]<]<

```

The most important part is the first line. This counts the number of characters inputted. The rest is just the long junk required to print a number greater than 9.

EDIT: Since BF cannot input/output anything but ASCII numbers from 1-255, there would be no way to measure the UTF-8 chars.

# Answer
> 2 votes
# Scala, <sup>~~30~~</sup> 26 bytes

```
s=>s.size->s.getBytes.size

```

Try it online!

My first Scala answer! Thanks to user for making it work.

-4 bytes from user.

# Answer
> 1 votes
# Milky Way 1.6.2, 7 bytes

```
':y!^P!

```

---

### Explanation

```
'        ` read input from the command line
 :       ` duplicate the TOS
  y      ` push the length of the TOS
   !  !  ` output the TOS
    ^    ` pop the TOS
     P   ` push the length of the TOS in bytes

```

---

### Usage

```
./mw <path-to-code> -i <input>

```

# Answer
> 1 votes
# Stax, 6 bytes

```
á!╜¡tº

```

Run and debug it

## Explanation

```
%Px|k%P
%       get length
 P      pop and print with newline
  x     push input again
   |k   get byte array
     %  get length
      P pop and print with newline

```

# Answer
> 0 votes
## Perl 6, 33 bytes

```
$x=get;say $x.chars," ",$x.codes;

```

Based on this blog post at Perl6Advent.

# Answer
> 0 votes
# beeswax, ~~99~~ 87 bytes

A more compact version, 12 bytes shorter than the first:

```
p~5~q")~4~p")~7~g?<
>)'qq>@PPq>@Pp>Ag'd@{
     >@PPPq  @dNp"?{gAV_
     >@PPPP>@>?b>N{;

```

The same, as easier to follow hexagonal layout:

```
 p ~ 5 ~ q " ) ~ 4 ~ p " ) ~ 7 ~ g ? <
> ) ' q q > @ P P q > @ P p > A g ' d @ {
         > @ P P P q     @ d N p " ? { g A V _
        > @ P P P P > @ > ? b > N { ;

```

Output as `characters`, then `bytecount`, separated by a newline.

Example: the small letter `s` at the beginning of the line just tells the user that the program wants a string as input.

```
julia> beeswax("utf8bytecount.bswx")
s(~R∊R∘.×R)/R←1↓ιR
17
27
Program finished!

```

Empty string example:

```
julia> beeswax("utf8bytecount.bswx")
s
0
0
Program finished!

```

Beeswax pushes the characters of a string that’s entered at STDIN onto the global stack, coded as the values of their Unicode code points.

For easier understanding, here is the unwrapped version of the program above:

```
             >@{;    >@P@p >@PP@p>@P p
_VAg{?"pN>Ag"d?g~7~)"d~4~)"d~5~)"d@PPp
    ;{N< d?              <      < @PP<

```

For this example, the character `α` is entered at STDIN (code point `U+03B1`, decimal:`945`)

```
                                        gstack     lstack

_VA                                     [945,1]•   [0,0,0]•    enter string, push stack length on top of gstack
   g                                               [0,0,1]•    push gstack top value on top of local stack (lstack)
    {                                                          lstack 1st value to STDOUT (num. of characters)
     ?                                  [945]•                 pop gstack top value
      "                                                        skip next if lstack 1st >0
        N>                                                     print newline, redirect to right
          Ag                            [945,1]•   [0,0,1]•    push gstack length on top of gstack, push that value on lstack.
            "                                                  skip if lstack 1st > 0
              ?                         [945]•                 pop gstack top value
               g                                   [0,0,945]•  push gstack top value on lstack
                ~                                  [0,945,0]•  flip lstack 1st and 2nd
                 7                                 [0,945,7]•  lstack 1st=7
                  ~                                [0,7,945]•  flip lstack 1st and 2nd
                   )                               [0,7,7]•    lstack 1st = lstack 1st >>> 2nd  (LSR by 7)
                    "                                          skip next if top >0
                      ~4~)                         [0,0,0]•            flip,1st=4,flip,LSR by 4
                          "d                                   skip next if top >0... redirect to upper right
                           >@                                  redirect to right, flip lstack 1st and 3rd
                             PP@                   [2,0,0]•    increment lstack 1st twice, flip 1st and 3rd
                                p                              redirect to lower left
                                "                              (ignored instruction, not relevant)
         d?              <      <       []•                       redirect to left... pop gstack, redirect to upper right

         >Ag"d                          [0]•       [2,0,0]•    redir. right, push gstack length on gstack
                                                               push gstack top on lstack, skip next if lstack 1st > 0
                                                               redir. to upper right.
         >@                                        [0,0,2]•    redir right, flip lstack 1st/3rd
           {;                                                  output lstack 1st to STDOUT, terminate program

```

Basically, this program checks each codepoint value for the 1-byte, 2-byte, 3-byte and 4-byte codepoint limits.

If `n` is the codepoint value, then these limits for proper UTF-8 strings are:

```
codepoint 0...127         1-byte: n>>>7 = 0
          128...2047      2-byte: n>>>11= 0  → n>>>7>>>4
          2048...65535    3-byte: n>>>16= 0  → n>>>7>>>4>>>5
          65535...1114111 4-byte: the 3 byte check result is >0

```

You can find the numbers `7`,`4` and `5` for the shift instructions in the code above. If a check results in `0`, the lstack counter is incremented appropriately to tally the number of bytes of the entered string. The `@PP...@` constructs increment the byte counter. After each tally, the topmost Unicode point is popped from the gstack until it is empty. Then the byte count is output to STDOUT and the program terminated.

There are no checks for improper encoding like overlong ASCII encoding and illegal code points beyond `0x10FFFF`, but I think that’s fine ;)

# Answer
> 0 votes
# Swift 3, 37

`{($0.characters.count,$0.utf8.count)}` // where `$0` is `String`

## Usage

Test

`{($0.characters.count,$0.utf8.count)}("Hello, world")`

# Answer
> 0 votes
# Julia, 22 bytes

Improvement of Alex A.'s answer

```
s->length(s):sizeof(s)

```

Try it online!

---
Tags: code-golf, string, parsing, unicode
---


# Question
Title: (Error) quines, hello world, polyglots, oh my!
# Introduction

A quine is a program that outputs its own source code. For example, a well-known Python quine is `_='_=%r;print(end=_%%_)';print(end=_%_)`. Running it outputs `_='_=%r;print(end=_%%_)';print(end=_%_)`, therefore it is a valid quine. An error quine is similar to a regular quine, however it must output to STDERR. In Python (for example), this could be achieved by replacing both instances of `print` in the above code with `exit`. A polyglot is a program that is valid in multiple languages.

# Challenge

Write two **full programs** in two programming languages of your choice. The first one should be a quine, and the second an error quine. When concatenated (in any order, you can pick), it should form a Hello, World! program in a third programming language.

# Example

Say you have a language `A`* in which a valid quine is `123`, and another language `B`* where `abc` is an error quine. Then, `123abc` (or `abc123`) should be a valid Hello, World! program in language `C`\*. If this is the case, your answer should look similar to the following:

---

# A, B, C, score 3

## A, 3 bytes - Quine

```
123

```

Try it online!

## B, 3 bytes - Error quine

```
abc

```

Try it online!

## C, 6 bytes - Hello, World!

```
123abc

```

Try it online!

## Explanation (optional)

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus sem mi, dignissim a odio vehicula, tincidunt ultrices tellus. Etiam luctus scelerisque urna, ac sodales nisl rhoncus at. Cras ac accumsan velit. Integer eget mi nec diam suscipit pretium a ac massa. Praesent at enim nec nisl molestie aliquet nec sed lorem. Duis iaculis condimentum dui at ullamcorper. Fusce molestie iaculis dolor. Cras vel metus dictum, aliquam quam sit amet, gravida tortor. Praesent maximus quam porttitor, vulputate magna eu, rhoncus nunc. Sed accumsan dui ut sapien semper finibus. Nulla eget dictum justo.

---

# Scoring

Your score is the arithmetic mean of the lengths of the two quines (i.e. half the length of the Hello, World! program).

# Rules

* All three programming languages used must be different.
* The Hello, World! program should output exactly `Hello, World!`. A trailing newline is allowed.
* Standard loopholes are forbidden, except for storing information in the file name; if done so in either one of the quines, it will add \<length of file name\> bytes to the length of both that program and the Hello, World! program, therefore adding half of \<length of file name\> to your score. If done in the Hello, World! program, it adds the same amount to your score and bytecount for it, but not for either one of your quines. Note that, if you're not doing this, the file name will be assumed to be `.code.tio` even if not running on TIO.
* The regular quine **must** output to STDOUT and the error quine **must** output to STDERR. If STDOUT and STDERR do not exist in your language(s), use the closest equivalent(s). However, the Hello, World! program may output using any of the standard I/O methods. Also, the quine and Hello, World! programs may output anything to STDERR, and the error quine may output anything to STDOUT.
* If possible, please link to an online interpreter (e.g. TIO) to run your program on.
* Please explain your answer. This is not necessary, but it makes it easier for others to understand.
* Neither one of the quines may output a trailing newline unless that newline also occurs in the source code.
* Languages newer than the question are allowed. This means you could create your own language where `a` is a quine, `b` is an error quine, and `ab` is Hello, World!, and post an answer in that language with score 1, but expect many downvotes.
* Non-programming languages are allowed. A non-programming language is a language which doesn't satisfy both of these conditions:
    + Able to take two integers as input and print their sum
    + Able to take one integer as input and print a truthy value if it is prime, and a falsy value if it is not
* Different versions of the same language may be used. For example, your quine could be in Python 2 and your Hello, World! program in Python 3.
* This is , so shortest code in bytes wins!

<sub>\*Fun fact: these are all actual languages!</sub>

# Answer
> 8 votes
# , nameless language, Deadfish~, 4.5

## , 3 bytes

```
Uwp

```

Try it online: Copy-paste the code from above (or type it manually), and click on the 'timeout run' button.

## nameless language, 6 bytes

```
[[0]]

```

With trailing newline.

Try it online.

## Deadfish~, 9 bytes

```
[[0]]
Uwp

```

Try it online.

### Explanation:

**Y:**

```
U    # Begin scanning, ignoring any links, and record as string once another `U` is
     # encountered, while starting the string itself with a leading "U"
 wp  # "wp"
U    # Wraps around to the start of the program again, finishing the string "Uwp"
 w   # No-op
  p  # Print the stack

```

I'm pretty sure Y is the language with the shortest proper quine available, of just 2 bytes with `Up`.

**nameless language:**

nameless language is a brainfuck derivative using 0s and 1s in 4-bit parts for the builtins. It will also debug the pointers to STDERR by default, which starts with `[[0]]` for empty programs.

**Deadfish~:**

Basically every character we used in the Deadfish~ program is a no-op, except for the `w`, which is the builtin to print `Hello, World!` to STDOUT.

# Answer
> 24 votes
# C, Bash, C++, score 174.5 175

## C, 301 bytes - Quine

```
#include<stdio.h>
int main(){
#ifdef __cplusplus
printf("Hello, World!"
#else
char*c="#include<stdio.h>%cint main(){%c#ifdef __cplusplus%cprintf(%cHello, World!%c%c#else%cchar*c=%c%s%c;printf(c,10,10,10,34,34,10,10,34,c,34,10,10%c#endif%c);}//";printf(c,10,10,10,34,34,10,10,34,c,34,10,10
#endif
);}//

```

Try it online!

## Bash, 48 49 bytes - Error quine

```
.code.tio: line 1: .code.tio:: command not found

```

Try it online! (the trailing newline was added, see comments)

## C++, 349 350 bytes - Hello, World!

```
#include<stdio.h>
int main(){
#ifdef __cplusplus
printf("Hello, World!"
#else
char*c="#include<stdio.h>%cint main(){%c#ifdef __cplusplus%cprintf(%cHello, World!%c%c#else%cchar*c=%c%s%c;printf(c,10,10,10,34,34,10,10,34,c,34,10,10%c#endif%c);}//";printf(c,10,10,10,34,34,10,10,34,c,34,10,10
#endif
);}//.code.tio: line 1: .code.tio:: command not found

```

Try it online!

---

# Explainations and notes

The **C** *quine* is inspired by this C quine (the short version), and contains C++ code for the *Hello, World!*.

The **Bash** *error quine* works due to the TIO implementation, but given that error messages are generally implementation defined, it might be hard to print them in some standard way (other than directly outputting to stderr, which is just like a *regular quine*... how unoriginal would that be). The submitted Bash program may be an invalid Bash program, but it is still a valid *error quine* in Bash. (Edit: note the trailing newline that is now legal to output.)

The **C++** *Hello, World!* doesn't output a trailing newline, but the challenge doesn't require it. After the preprocessor preprocessing, the only code source left is the `main` function with a simple `printf` call.

What was used in this answer are similarities between C and C++, very useful for polyglots (C is not *entirely* contained by C++, but it is contained enough) (for example: the usage of the C standard library is almost the same in these two languages which allows for a single `#include` directive, the `main` function definition is also similar enough to factorize the beginning and end out of the preprocessor-picked variations). The preprocessor and the `__cplusplus` macro are almost necessary at this point as they allow the C and C++ interpreters (or compilers, whatever) to pick only a specific subset of the program. The trailing line comment `//` ensures that the concatenation with a TIO Bash error doesn't upsets the C++ parser as it will completely ignore it.

I didn't find a way to to golf it even further. An other approach or a different set of languages are probably to be considered. For example, maybe using Argh! or INTERCAL for the *error quine* (or any other language in which error output is part of the language specification (these languages are rare, even among esolangs)). It might also be more interesting to use an other strategy than this """polyglot""" that makes each language ignore the code designed for the other languages instead of actually running most of the code.

# Answer
> 10 votes
# MathGolf, gnuplot, Underload, score: 33.5

## MathGolf, 9 bytes (Quine)

```
ÿ'ÿ\_'ÿ\_

```

Try it online.

## gnuplot, 58 bytes (Error quine)

```

(Hello, World!)S
^
".code.tio", line 2: invalid command

```

With one leading and two trailing newlines.

Try it online.

## Underload, 67 bytes (Hello, World!)

```
ÿ'ÿ\_'ÿ\_
(Hello, World!)S
^
".code.tio", line 2: invalid command

```

With two trailing newlines.

Try it online.

### Explanation:

**MathGolf:**

```
ÿ          # Push a string of four characters:
 'ÿ\_      #  "'ÿ\_"
     'ÿ    # Push character "ÿ"
       \   # Swap the top two values on the stack
        _  # Duplicate the top value on the stack
           # (after which the entire stack joined together is output implicitly)

```

**gnuplot:**

I've never used gnuplot before, but I simply tried random languages on TIO that contains `(Hello, World!)S` for the Underload program, and result in an error quine at the same time, of which gnuplot was one of the few, and the shortest I could find.

It will ignore the leading newline, and then complain about the `(Hello, World!)S` being invalid on line 2. Everything after that is fortunately enough ignored.

**Underload:**

Underload will simply print everything between `(...)S`, which is the intended `Hello, World!` in this case. It does give an error due to the rest of the program, but we can ignore STDERR and only look at the STDOUT, which is allowed by default.

# Answer
> 8 votes
# V (vim), \>\<\>, Help, WarDoq!, score 16

## V, 6 bytes (Quine)

```
H2aH2a

```

Try it online!

```
H      # move cursor to first non-blank character (effectively no-op)
 2a    # twice append
   H2a # literal characters

```

---

## \>\<\>, 26 bytes (Error quine)

```
something smells fishy...

```

Try it online!

Note the trailing newline. Quoting from Esolangs:

> Although there are multiple reasons an error may occur, there is only one error message: *something smells fishy...*

---

## Help, WarDoq!, 32 bytes (*Hello, World!*)

```
H2aH2asomething smells fishy...

```

Try it online! Link is to an interpreter in CJam identical to the reference implementation described at Esolangs. The code (without the trailing newline, due to technical limitations) can also be run from the CJam interpreter linked at Esolangs, but it unhelpfully combines STDOUT and STDERR into one output field.

```
H                               # print 'Hello, World!'
 2                              # ignored
  a                             # throws an error: attempts to read two integers from STDIN and XOR them
   H2asomething smells fishy... # (not executed)

```

# Answer
> 5 votes
# Ruby, \>\<\>, Stax, score = 48 43

## Ruby, 60 bytes (quine)

```
"Hello, World!"
puts <<2*2,2
"Hello, World!"
puts <<2*2,2
2

```

Try it online!

## \>\<\>, 26 bytes (error quine)

```
something smells fishy...

```

Try it online!

## Stax, 86 bytes (hello world)

```
"Hello, World!"
puts <<2*2,2
"Hello, World!"
puts <<2*2,2
2
something smells fishy...

```

Try it online!

*-5 score thanks to Dingus*

# Answer
> 2 votes
# Perl 5, PHP, Perl 4 Score 84

## Perl 5, 75 bytes (Quine)

```
eval($s='printf(-1**2+1?"Hello, World!":"eval(\$s=%c%s%c);#",39,$s,39);');#

```

Try it online!

## PHP, 93 bytes (Error Quine)

```
PHP Parse error:  syntax error, unexpected 'Parse' (T_STRING) in Command line code on line 1

```

Try it online!

## Perl 4, 168 bytes (Hello World)

```
eval($s='printf(-1**2+1?"Hello, World!":"eval(\$s=%c%s%c);#",39,$s,39);');#PHP Parse error:  syntax error, unexpected 'Parse' (T_STRING) in Command line code on line 1

```

Try it online!

## EXPLANATION:

**EDIT**: Due to OP's decision about PHP errors I had to resort to more traditional tricks, sorry. Welcome to the classical comment!

* the difference between the quine and HelloWorld is that in Perl 4 the minus operator takes precedence over exponentiation (`-1**2+1` will be 2 and then truthy), while the contrary in Perl 5 (`-1**2+1` will be 0 and then falsy)
* The error quine is nothing special, notice the trailing newline
* Nothing more for the third, uses a comment

# Answer
> 2 votes
# Objective-C++/NASM/ARM Assembler, score ~~114.5~~ 115.5

## Objective-C++ (clang) `-fmodules`, quine, ~~188~~ 187 bytes

```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c,10);}%4$c";printf(s,34,s,R"(
.macro instruction x;.print"Hello, World!";.endm@)",10);}

```

Includes trailing newline.

I would post a link but unfortunately modules appear to be borked on both TIO and Wandbox.

When Travis decides to wake up, I will link a non-interactive demo.

You will see why I need Objective-C++ in a moment.

## NASM, error quine, ~~42~~ 44 bytes

```
t.:1: error: parser: instruction expected

```

Just your standard NASM error quine.

Requires the program to be named `t.`

The length depends on the filename, but nasm will only properly quine if the filename contains a dot and the first character isn't a dot.

Try it online!

## ARM Assembler (clang), Hello World, ~~230~~ 231 bytes

Uses the `.print` GAS directive.

```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c,10);}%4$c";printf(s,34,s,R"(
.macro instruction x;.print"Hello, World!";.endm@)",10);}
t.:1: error: parser: instruction expected

```

Try it online!

## Explanation

First, let's ungolf the Obj-C++ quine and remove the actual quine part to show what is going on:

```
@import std;
int main()
{
    auto fmt = "...";
    printf(fmt, '"', fmt, R"(...)", '\n');
}

```

So the ObjC++ quine is a fairly standard C++ quine, although it uses the Objective-C `@import` extension and a raw string literal. Other than that, there really isn't that much to explain.

You may ask, "why are you using `@import`? If you have modules, you can just do `import`".

The answer is that, in ARM assembly, `@` is a comment. And that is the magic (and literally the only reason we are using ObjC++).

So first, we make the ARM assembler completely ignore the first line *while also* `@import`ing `printf`.

I'd *love* to just use ObjC so I can have my implicit int, but `.print` requires a quoted string. I don't see any way to do this without raw string literals.

As for the assembly thing, I decided to use code from BOTH the NASM quine and the Obj-C++ quine, which I believe was the intended meaning of having the programs concatenated.

I could save a lot of bytes by just commenting out the NASM code though (it would go down to a score of 96, but I prefer this more creative solution.

For the assembler, I define a macro `instruction`:

```
.macro instruction x
    .print "Hello, World!"
.endm

```

Then, when I append the NASM quine, it is parsed as a bunch of labels followed by `instruction expected`:

```
.t:
1:
error:
parser:
        instruction  expected

```

which calls the `instruction` macro I just defined, executing the compile-time `.print "Hello, World!"` statement.

---

For the reference, here is the more boring one which comments out the NASM line.

# Objective-C++/NASM/ARM Assembler, boring version, score 96

## Objective-C++ (clang) `-fmodules`, quine, 149 bytes

Note: newline is no longer necessary.

```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c);}";printf(s,34,s,R"(
.print"Hello, World!"@)");}

```

## NASM, error quine, 44 bytes

```
t.:1: error: parser: instruction expected

```

Just like before, needs the filename to be `t.`.

## ARM Assembler (clang), Hello World, 192 bytes

```
@import std;int main(){auto s="@import std;int main(){auto s=%c%s%1$c;printf(s,34,s,R%1$c(%3$s)%1$c);}";printf(s,34,s,R"(
.print"Hello, World!"@)");}t.:1: error: parser: instruction expected

```

Try it online!

This version removes the trailing newline and just comments out the NASM error. The .print is directly run instead of requiring the macro.

However, the ARM program will still do the same thing without the NASM program. Therefore, I am (at least personally) going by the higher score because I feel it is more in the spirit of the challenge and not an ugly hack.

# Answer
> 1 votes
# Python 3, \>\<\>, Befunge-93, score 54

## Python 3, 82 bytes - Quine

```
"!dlroW ,olleH">':#,_@';_='"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';print(_%_)

```

Try it online!

```
"!dlroW ,olleH">':#,_@';_='"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';print(_%_)  # full program
"!dlroW ,olleH">':#,_@';                                                           # singleton comparison statement (effectively NOP)
                        _=                                                         # set variable _ to...
                          '"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';            # literal
                                                                       print(_     # output _ with a trailing newline...
                                                                              %    # with the %r replaced by...
                                                                               _   # _'s value...
                                                                                # including quotes...
                                                                              %    # and the %% replaced by %
                                                                                )  # end function call

```

## \>\<\>, 26 bytes - Error quine

```
something smells fishy...

```

Try it online!

```
s...  # trimmed program
s     # invalid command, causes fatal error "something smells fishy...\n"
 ...  # unreachable code

```

## Befunge-93, 108 bytes - Hello, World!

```
"!dlroW ,olleH">':#,_@';_='"!dlroW ,olleH">\':#,_@\';_=%r;print(_%%_)';print(_%_)
something smells fishy...

```

Try it online!

```
"!dlroW ,olleH">':#,_@...  # trimmed program
"                          # push charcodes of...
 !dlroW ,olleH             # literal...
"                          # separately onto stack
              "            # end literal
               >           # move right
                '          # NOP (unrecognized command)
                 :         # duplicate top of stack when going right, NOP when going left
                  #        # skip over next command in current direction
                   ,       # output top of stack as a character when going left, NOP when going right
                    _      # pop top of stack, go left if nonzero
                     @     # terminate
                      ...  # unreachable code

```

---
Tags: code-golf, quine, polyglot, hello-world
---


title: Fun With Permutations

text:
# Question
Title: Fun With Permutations
Who doesn't absolutely love permutations, right? I know, they are amazing––so much fun!

Well, why not take this fun and make it *funner*?

Here's the challenge:

Given an input in the exact form: `nPr`, where `n` is the pool taken from and `r` is the number of selections from that pool (and `n` and `r` are integers), output/return the exact number of permutations. For those of you that are a bit rusty with the terminology: Permutation, def. 2a.

However, this is where the challenge comes into play (makes it not too easy):

> You may not use any built in library, framework, or method for your permutation function. You may not use a factorial method, permutation method, or anything of the sort; you must write everything yourself.

If further clarification is needed, please, do not hesitate to tell me in the comments and I will promptly act accordingly.

Here is an I/O example:

Sample function is `permute(String) -> int`

Input:

```
permute("3P2")

```

Output:

```
6

```

This is code-golf, so shortest code wins!

# Answer
> 4 votes
# CJam, ~~15~~ 14 bytes

```
r~\;~\),>UXt:*

```

Try it online in the CJam interpreter.

### How it works

```
r              e# Read a token ("nPr") from STDIN.
 ~             e# Evaluate. This pushes the numbers n, Pi and r on the stack.
  \;           e# Discard Pi.
    ~          e# Take the bitwise NOT of r. Pushes -(r+1).
     \)        e# Increment n.
       ,       e# Turn n+1 into [0 ... n].
        >      e# Keep only the last r+1 elements.
         UXt   e# Replace the first element with 1.
               e# This avoid dealing with the egde case nP0 separately.
            :* e# Compute their product.

```

# Answer
> 4 votes
# Perl, 27 bytes

```
#!perl -pl61
$\*=$`-$%++for/P/..$'}{

```

Counting the shebang as 4, input is taken from stdin.

---

**Sample Usage**

```
$ echo 3P2 | perl npr.pl
6

$ echo 7P4 | perl npr.pl
840

```

# Answer
> 3 votes
# Haskell, ~~71~~ 66 bytes

```
p s|(u,_:x)<-span(/='P')s,(n,k)<-(read u,read x)=product[n-k+1..n]

```

Pretty straightforward stuff: split at the 'P' then take the product between (n-k+1) and n.

Thanks to nimi for their idea to use pattern guards rather than a `where` clause, it shaved off 5 bytes.

# Answer
> 2 votes
# Julia, ~~63~~ ~~58~~ 48 bytes

```
s->((n,r)=map(parse,split(s,"P"));prod(n-r+1:n))

```

This creates an unnamed function that accepts a string and returns an integer. To call it, give it a name, e.g. `f=s->...`.

Ungolfed:

```
function f(s::AbstractString)
    # Get the pool and number of selections as integers
    n, r = map(parse, split(s, "P"))

    # Return the product of each number between n-r+1 and n
    return prod(n-r+1:n)
end

```

This uses the fact that the number of permutations is *n*(*n*-1)(*n*-2)...(*n*-*k*+1).

Saved 10 bytes thanks to Glen O!

# Answer
> 2 votes
## Minkolang 0.11, ~~13~~ ~~25~~ 19 bytes

Thanks to **Sp3000** for suggesting this!

```
1nnd3&1N.[d1-]x$*N.

```

Try it here.

### Explanation

```
1        Push 1
n        Take integer from input (say, n)
n        Take integer from input (say, k); ignores non-numeric characters in the way
d3&1N.   Output 1 if k is 0
[   ]    Loop k times
 d1-     Duplicate top of stack and subtract 1
x        Dump top of stack
$*       Multiply all of it together
N.       Output as integer

```

This uses the same algorithm as Alex's: `n P k` = `n(n-1)(n-2)...(n-k+1)`.

# Answer
> 2 votes
# Bash + Linux utils, 33

```
jot -s\* ${1#*P} $[${1/P/-}+1]|bc

```

`jot` produces the sequence of `r` integers starting at `n-r+1`, and separates them with `*`. This expression is piped to `bc` for arithmetic evaluation.

# Answer
> 1 votes
# MATLAB, 54 bytes

```
[n,r]=strread(input(''),'%dP%d');disp(prod((n-r+1):n))

```

Tried to make it smaller, but one of the things MATLAB is really bad at is getting inputs. It takes 32 characters just to get the two numbers from the input string!

Fairly self explanatory code. Get the input in the form `%dP%d` where %d is an integer. Split that into `n` and `r`. Then display the product of every integer in the range `n-r+1` to `n`. Interestingly this works even for `xP0` giving the correct answer of 1. This is because in MATLAB the `prod()` function returns 1 if you try and do the product of an empty array. Whenever `r` is zero, the range will be an empty array, so bingo we get 1.

---

This also works perfectly with **Octave** as well. You can try it online here.

# Answer
> 1 votes
## Python 2, 66

```
def f(s):a,b=map(int,s.split('P'));P=1;exec"P*=a;a-=1;"*b;print P

```

Pretty straightforward. Processes the number input as `a,b`. Keeps a running product as `P`, which is multiplied by the first `b` terms of `a, a-1, a-2, ...`.

# Answer
> 1 votes
# Javascript, 59 57 bytes

```
s=>(f=(n,k)=>k?(n- --k)*f(n,k):1,f.apply(f,s.split('P')))

```

# Answer
> 1 votes
## TI-BASIC, 52 bytes

```
Ans→Str1
expr(sub(Ans,1,⁻1+inString(Ans,"P→P        ;n
1
If expr(Str1                               ;If n^2*r ≠ 0
prod(randIntNoRep(P,P+1-expr(Str1)/P²
Ans

```

TI-BASIC has a "product of a list" function, so getting around the restriction on builtins isn't too hard. However, TI-BASIC doesn't support empty lists—so we need to

To extract the two numbers, I extract the first number as a substring. This is *expensive*; it takes up the whole second line. To keep from needing to do this again for the second number, I set the variable P to that number, and evaluate the whole string using `expr(`, then divide by P².

Finally, I take a random permutation of the list between the two numbers (taking care to add one to the second number) and take the product.

# Answer
> 1 votes
## Java(594 - bytes)

```
import java.util.*;import java.lang.*;public class Perm {private String a;private static int[] nr=new int[2];private static int sum=1;Scanner in=new Scanner(System.in);public String input(){a=in.nextLine();return a;}public void converter(String a){this.a=a;String b=a.substring(0,1);String c=a.substring(2);nr[0]=Integer.parseInt(b);nr[1]=Integer.parseInt(c);}public int param(){for(int counter=0; counter < nr[1]; counter++){sum=sum*nr[0]--;}return sum;}public static void main(String args[]){Perm a;a=new Perm();String k=a.input();a.converter(k);int ans=a.param();System.out.println(ans);}}

```

# Answer
> 1 votes
# J, 23 bytes

```
^!._1/@(".;._1)@('P'&,)

```

An anonymous function. Example:

```
   f =. ^!._1/@(".;._1)@('P'&,)
   f '10P4'
5040

```

Explanation:

```
       (  ;._1)@('P'&,)   Split over 'P', and on each slice,
        ".                read a number.
      @                   Then,
^!._1/                    fold (/) with the built-in "stope function" (^!.k) for k=1.

```

The stope function I used might border on counting as a built-in... It rests somewhere between the generality of the multiplication operator and the specificity of the factorial operator.

# Answer
> 1 votes
# APL, 23

```
{{×/⍵↑⍳-⍺}/-⍎¨⍵⊂⍨⍵≠'P'}

```

Takes the string as argument. Explanation:

```
              ⍵⊂⍨⍵≠'P'  ⍝ Split by 'P'.
           -⍎¨          ⍝ Convert to numbers and negate making a vector (−n −r)
 {       }/             ⍝ Reduce it by a defined function, which
      ⍳-⍺               ⍝ makes a vector of numbers from 1 to n (⍺)
    ⍵↑                  ⍝ takes r last elements (⍵←−r)
  ×/                    ⍝ and multiplies them together.

```

# Answer
> 1 votes
## Ouroboros, ~~47~~ 45 bytes

Some of this is pretty ugly--I'd imagine it could be golfed further.

```
Sr.r-1(
)s.!+S1+.@@.@\<!@@*Ys.!+*S.!!4*.(sn1(

```

Each line of code in Ouroboros represents a snake eating its tail.

### Snake 1

`S` switches to the shared stack. `r.r` reads one number, duplicates it, and reads another. (Nonnumeric characters like `P` are skipped.) `-` subtracts the two. If the input was `7P2`, we now have `7`, `5` on the shared stack. Finally, `1(` eats the final character of the snake. Since this is the character that the instruction pointer is on, the snake dies.

### Snake 2

`)s` does nothing the first time through. `.!+` duplicates the top of snake 2's stack, checks if it's zero, and if so adds 1. On the first iteration, the stack is empty and treated as if it contained infinite zeros, so this pushes `1`; on later iterations, the stack contains a nonzero value and this has no effect.

Next, `S` switches to the shared stack, where we have the number `n` and a counter for calculating the product. `1+` increments the counter. `.@@.@\<!` duplicates both numbers and pushes 1 if `n` is still greater than or equal to the counter, 0 otherwise. `@@*Y` then multiplies the counter by this quantity and yanks a copy onto snake 2's stack.

`s.!+` switches back to snake 2's stack and uses the same code as earlier to convert the top number to 1 if it was 0 and keep it the same otherwise. Then `*` multiplies the result by the partial product that was sitting on this stack.

We now go back to the shared stack (`S`), duplicate the counter-or-zero (`.`), and negate it twice (`!!`) to turn a nonzero counter into a 1. `4*.(` multiplies this by 4, duplicates, and eats that many characters from the end of the snake.

* If we haven't reached the halting condition, we've got a 4 on the stack. The four characters after the `(` are eaten, and control loops around to the beginning of the code. Here `)` regurgitates four characters, `s` switches back to snake 2's stack, and execution continues.
* If the counter has passed `n`, we've got a 0 on the stack, and nothing is eaten. `sn` switches to snake 2's stack and outputs the top value as a number; then `1(` eats the last character and dies.

The result is that the product `(r+1)*(r+2)*...*n` is calculated and output.

### Try it out

```
// Define Stack class
function Stack() {
  this.stack = [];
  this.length = 0;
}
Stack.prototype.push = function(item) {
  this.stack.push(item);
  this.length++;
}
Stack.prototype.pop = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack.pop();
    this.length--;
  }
  return result;
}
Stack.prototype.top = function() {
  var result = 0;
  if (this.length > 0) {
    result = this.stack[this.length - 1];
  }
  return result;
}
Stack.prototype.toString = function() {
  return "" + this.stack;
}

// Define Snake class
function Snake(code) {
  this.code = code;
  this.length = this.code.length;
  this.ip = 0;
  this.ownStack = new Stack();
  this.currStack = this.ownStack;
  this.alive = true;
  this.wait = 0;
  this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
  if (!this.alive) {
    return null;
  }
  if (this.wait > 0) {
    this.wait--;
    return null;
  }
  var instruction = this.code.charAt(this.ip);
  var output = null;
  console.log("Executing instruction " + instruction);
  if (this.partialString !== null) {
    // We're in the middle of a double-quoted string
    if (instruction == '"') {
      // Close the string and push its character codes in reverse order
      for (var i = this.partialString.length - 1; i >= 0; i--) {
        this.currStack.push(this.partialString.charCodeAt(i));
      }
      this.partialString = null;
    } else {
      this.partialString += instruction;
    }
  } else if (instruction == '"') {
    this.partialString = "";
  } else if ("0" <= instruction && instruction <= "9") {
    if (this.partialNumber !== null) {
      this.partialNumber = this.partialNumber + instruction;  // NB: concatenation!
    } else {
      this.partialNumber = instruction;
    }
    next = this.code.charAt((this.ip + 1) % this.length);
    if (next < "0" || "9" < next) {
      // Next instruction is non-numeric, so end number and push it
      this.currStack.push(+this.partialNumber);
      this.partialNumber = null;
    }
  } else if ("a" <= instruction && instruction <= "f") {
    // a-f push numbers 10 through 15
    var value = instruction.charCodeAt(0) - 87;
    this.currStack.push(value);
  } else if (instruction == "$") {
    // Toggle the current stack
    if (this.currStack === this.ownStack) {
      this.currStack = this.program.sharedStack;
    } else {
      this.currStack = this.ownStack;
    }
  } else if (instruction == "s") {
    this.currStack = this.ownStack;
  } else if (instruction == "S") {
    this.currStack = this.program.sharedStack;
  } else if (instruction == "l") {
    this.currStack.push(this.ownStack.length);
  } else if (instruction == "L") {
    this.currStack.push(this.program.sharedStack.length);
  } else if (instruction == ".") {
    var item = this.currStack.pop();
    this.currStack.push(item);
    this.currStack.push(item);
  } else if (instruction == "m") {
    var item = this.ownStack.pop();
    this.program.sharedStack.push(item);
  } else if (instruction == "M") {
    var item = this.program.sharedStack.pop();
    this.ownStack.push(item);
  } else if (instruction == "y") {
    var item = this.ownStack.top();
    this.program.sharedStack.push(item);
  } else if (instruction == "Y") {
    var item = this.program.sharedStack.top();
    this.ownStack.push(item);
  } else if (instruction == "\\") {
    var top = this.currStack.pop();
    var next = this.currStack.pop()
    this.currStack.push(top);
    this.currStack.push(next);
  } else if (instruction == "@") {
    var c = this.currStack.pop();
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(c);
    this.currStack.push(a);
    this.currStack.push(b);
  } else if (instruction == ";") {
    this.currStack.pop();
  } else if (instruction == "+") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a + b);
  } else if (instruction == "-") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a - b);
  } else if (instruction == "*") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a * b);
  } else if (instruction == "/") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a / b);
  } else if (instruction == "%") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(a % b);
  } else if (instruction == "_") {
    this.currStack.push(-this.currStack.pop());
  } else if (instruction == "I") {
    var value = this.currStack.pop();
    if (value < 0) {
      this.currStack.push(Math.ceil(value));
    } else {
      this.currStack.push(Math.floor(value));
    }
  } else if (instruction == ">") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a > b));
  } else if (instruction == "<") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a < b));
  } else if (instruction == "=") {
    var b = this.currStack.pop();
    var a = this.currStack.pop();
    this.currStack.push(+(a == b));
  } else if (instruction == "!") {
    this.currStack.push(+ !this.currStack.pop());
  } else if (instruction == "?") {
    this.currStack.push(Math.random());
  } else if (instruction == "n") {
    output = "" + this.currStack.pop();
  } else if (instruction == "o") {
    output = String.fromCharCode(this.currStack.pop());
  } else if (instruction == "r") {
    var input = this.program.io.getNumber();
    this.currStack.push(input);
  } else if (instruction == "i") {
    var input = this.program.io.getChar();
    this.currStack.push(input);
  } else if (instruction == "(") {
    this.length -= Math.floor(this.currStack.pop());
    this.length = Math.max(this.length, 0);
  } else if (instruction == ")") {
    this.length += Math.floor(this.currStack.pop());
    this.length = Math.min(this.length, this.code.length);
  } else if (instruction == "w") {
    this.wait = this.currStack.pop();
  }
  // Any unrecognized character is a no-op
  if (this.ip >= this.length) {
    // We've swallowed the IP, so this snake dies
    this.alive = false;
    this.program.snakesLiving--;
  } else {
    // Increment IP and loop if appropriate
    this.ip = (this.ip + 1) % this.length;
  }
  return output;
}
Snake.prototype.getHighlightedCode = function() {
  var result = "";
  for (var i = 0; i < this.code.length; i++) {
    if (i == this.length) {
      result += '<span class="swallowedCode">';
    }
    if (i == this.ip) {
      if (this.wait > 0) {
        result += '<span class="nextActiveToken">';
      } else {
        result += '<span class="activeToken">';
      }
      result += escapeEntities(this.code.charAt(i)) + '</span>';
    } else {
      result += escapeEntities(this.code.charAt(i));
    }
  }
  if (this.length < this.code.length) {
    result += '</span>';
  }
  return result;
}

// Define Program class
function Program(source, speed, io) {
  this.sharedStack = new Stack();
  this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
    var snake = new Snake(snakeCode);
    snake.program = this;
    snake.sharedStack = this.sharedStack;
    return snake;
  }.bind(this));
  this.snakesLiving = this.snakes.length;
  this.io = io;
  this.speed = speed || 10;
  this.halting = false;
}
Program.prototype.run = function() {
  this.step();
  if (this.snakesLiving) {
    this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
  }
}
Program.prototype.step = function() {
   for (var s = 0; s < this.snakes.length; s++) {
    var output = this.snakes[s].step();
    if (output) {
      this.io.print(output);
    }
  }
  this.io.displaySource(this.snakes.map(function (snake) {
      return snake.getHighlightedCode();
    }).join("<br>"));
 }
Program.prototype.halt = function() {
  window.clearTimeout(this.timeout);
}

var ioFunctions = {
  print: function (item) {
    var stdout = document.getElementById('stdout');
    stdout.value += "" + item;
  },
  getChar: function () {
    if (inputData) {
      var inputChar = inputData[0];
      inputData = inputData.slice(1);
      result = inputChar.charCodeAt(0);
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  getNumber: function () {
    while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
      inputData = inputData.slice(1);
    }
    if (inputData) {
      var inputNumber = inputData.match(/\d+/)[0];
      inputData = inputData.slice(inputNumber.length);
      result = +inputNumber;
    } else {
      result = -1;
    }
    var stdinDisplay = document.getElementById('stdin-display');
    stdinDisplay.innerHTML = escapeEntities(inputData);
    return result;
  },
  displaySource: function (formattedCode) {
    var sourceDisplay = document.getElementById('source-display');
    sourceDisplay.innerHTML = formattedCode;
  }
};
var program = null;
var inputData = null;
function showEditor() {
  var source = document.getElementById('source'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');

  source.style.display = "block";
  stdin.style.display = "block";
  sourceDisplayWrapper.style.display = "none";
  stdinDisplayWrapper.style.display = "none";

  source.focus();
}
function hideEditor() {
  var source = document.getElementById('source'),
    sourceDisplay = document.getElementById('source-display'),
    sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
    stdin = document.getElementById('stdin'),
    stdinDisplay = document.getElementById('stdin-display'),
    stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');

  source.style.display = "none";
  stdin.style.display = "none";
  sourceDisplayWrapper.style.display = "block";
  stdinDisplayWrapper.style.display = "block";

  var sourceHeight = getComputedStyle(source).height,
    stdinHeight = getComputedStyle(stdin).height;
  sourceDisplayWrapper.style.minHeight = sourceHeight;
  sourceDisplayWrapper.style.maxHeight = sourceHeight;
  stdinDisplayWrapper.style.minHeight = stdinHeight;
  stdinDisplayWrapper.style.maxHeight = stdinHeight;
  sourceDisplay.textContent = source.value;
  stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
  return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function resetProgram() {
  var stdout = document.getElementById('stdout');
  stdout.value = null;
  if (program !== null) {
    program.halt();
  }
  program = null;
  inputData = null;
  showEditor();
}
function initProgram() {
  var source = document.getElementById('source'),
    stepsPerSecond = document.getElementById('steps-per-second'),
    stdin = document.getElementById('stdin');
  program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
  hideEditor();
  inputData = stdin.value;
}
function runBtnClick() {
  if (program === null || program.snakesLiving == 0) {
    resetProgram();
    initProgram();
  } else {
    program.halt();
    var stepsPerSecond = document.getElementById('steps-per-second');
    program.speed = +stepsPerSecond.innerHTML;
  }
  program.run();
}
function stepBtnClick() {
  if (program === null) {
    initProgram();
  } else {
    program.halt();
  }
  program.step();
}
function sourceDisplayClick() {
  resetProgram();
}
function stdinDisplayClick() {
    resetProgram();
}
```

```
.container {
    width: 100%;
}
.so-box {
    font-family:'Helvetica Neue', Arial, sans-serif;
    font-weight: bold;
    color: #fff;
    text-align: center;
    padding: .3em .7em;
    font-size: 1em;
    line-height: 1.1;
    border: 1px solid #c47b07;
    -webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
    text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
    background: #f88912;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
    display: inline-block;
    border-radius: 6px;
    float: left;
    margin-right: 25px;
    cursor: pointer;
}
.option {
    padding: 10px 20px;
    margin-right: 25px;
    float: left;
}
h1 {
    text-align: center;
    font-family: Georgia, 'Times New Roman', serif;
}
a {
    text-decoration: none;
}
input, textarea {
    box-sizing: border-box;
}
textarea {
    display: block;
    white-space: pre;
    overflow: auto;
    height: 50px;
    width: 100%;
    max-width: 100%;
    min-height: 25px;
}
span[contenteditable] {
    padding: 2px 6px;
    background: #cc7801;
    color: #fff;
}
#stdout-container, #stdin-container {
    height: auto;
    padding: 6px 0;
}
#reset {
    float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
    display: none;
    width: 100%;
    height: 100%;
    overflow: auto;
    border: 1px solid black;
    box-sizing: border-box;
}
#source-display , #stdin-display{
    font-family: monospace;
    white-space: pre;
    padding: 2px;
}
.activeToken {
    background: #f93;
}
.nextActiveToken {
    background: #bbb;
}
.swallowedCode{
    color: #999;
}
.clearfix:after {
    content:".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.clearfix {
    display: inline-block;
}
* html .clearfix {
    height: 1%;
}
.clearfix {
    display: block;
}
```

```
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">Sr.r-s1(
)s.!+S1+.@@.@\<!@@*Ys.!+*S.!!4*.(sn1(</textarea>
<div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off">3P2</textarea>
<div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>20</span></div></div>
```

# Answer
> 1 votes
# Husk, 11 bytes

```
FöΠ↑↔ḣmrx'P

```

Try it online!

**How?**

```
        x'P    # split input on the character 'P'
      mr       # and map each of the 2 strings to a value;
Fö             # now, fold over these 2 values by calculating
  Π            # the product of
   ↑           # the first r elements (where r = second value) of
     ḣ         # the series 1..n (where n = first value)
    ↔          # reversed

```

---
Tags: code-golf, math, permutations
---


title: Type the Alphabet - as fast as you can!

text:
# Question
Title: Type the Alphabet - as fast as you can!
Your task is to make a program that measures how fast you can type the letters of the English alphabet.

* The program shall only accept lowercase letters `a` to `z` in alphabetical order.
* Each letter is echoed as typed on the same line (without new line or any other separators between letters).
* If you type an invalid character the program shall output `Fail` *on a new line* and exit.
* If you type all 26 letters the program shall, *on a new line*, output the time in milliseconds it took from the first to the last letter and exit.
* The timer starts when you type the first letter, `a`.

Example outputs:

```
b
Fail

abcdefgg
Fail

abcdefghijklmnopqrstuvwxyz
6440

```

This is , so shortest answer in bytes wins.

# Answer
## HTML (JavaScript (ES6)), ~~129~~ ~~126~~ 117 bytes

```
<input id=i onfocus=l=0,n=Date.now onkeypress=event.which-97-l?i.outerHTML='Fail':24<l?i.outerHTML=n()-t:t=l++?t:n()>
```

Click in the input and start typing! Also, my typing sucks; I take about 5 seconds even with practice. Edit: Saved 2 bytes thanks to @HermanLauenstein by switching language. Saved 3 bytes thanks to @qw3n. Saved 9 bytes thanks to @tsh.
> 40 votes

# Answer
# 6502 machine code (C64 PAL), 189 165 bytes

```
00 C0 A9 17 8D 18 D0 A9 40 85 FE E6 FE 20 E4 FF F0 FB 20 D2 FF C5 FE 38 D0 38
C9 5A 18 F0 33 C9 41 D0 E8 A9 00 85 FC 85 FD A9 18 85 FB A9 7F 8D 0D DD A9 7F
8D 18 03 A9 C0 8D 19 03 A9 D8 8D 04 DD A9 03 8D 05 DD A9 01 8D 0E DD A9 81 8D
0D DD D0 B9 A9 7F 8D 0D DD A9 47 8D 18 03 A9 FE AD 19 03 CE 0E DD B0 14 A9 0D
20 D2 FF A4 FC A5 FD 20 91 B3 20 DD BD A9 01 A8 D0 04 A9 9D A0 C0 4C 1E AB 48
AD 0D DD 29 01 F0 14 E6 FC D0 02 E6 FD C6 FB D0 0A A9 18 85 FB CE 0E DD EE 0E
DD 68 40 0D C6 41 49 4C 00

```
* -24 bytes by inlining functions and not caring for other CIA2 interrupts

**Online demo** (Usage: `sys49152`)

---

### Explanation:

This would be a tiny program if it wasn't for the problem of an exact measurement of milliseconds on the C64. The system interrupt occurs *roughly* 60 times per second, which isn't even close. So we have to use a hardware timer here that gets its input ticks from the system clock.

On a PAL machine, the system clock is exactly 985248 Hz. Initializing the timer to 985 therefore gives something *close* to millisecond ticks, but it's a bit too fast, we'd have to count 986 cycles for every fourth tick, or hold the timer for a single cycle. This isn't possible, but we can hold the timer for 6 cycles with the sequence `DEC $DD0E`, `INC $DD0E`: `$DD0E` is the timer control register with bit 0 switching it on and off, and both instructions take 6 cycles, so the exact writes that stop and start the timer are exactly 6 cycles apart. Therefore we have to execute this sequence every 6\*4 = 24th tick. This still isn't *absolutely* exact, the timer will lag 1 millisecond behind after 8 minutes and 12 seconds, but it's probably good enough -- compensating for that one would take a *lot* of code.

**edit**: The start value for the timer must be 984, not 985, because these timers fire "on underflow", so a value of 0 will count one more cycle before firing. Code fixed, byte count unchanged.

Here's the commented disassembly listing:

```
         00 C0       .WORD $C000        ; load address
.C:c000  A9 17       LDA #$17           ; mode for upper/lower text
.C:c002  8D 18 D0    STA $D018          ; set in graphics chip
.C:c005  A9 40       LDA #$40           ; initialize expected character
.C:c007  85 FE       STA $FE            ; to 'a' - 1
.C:c009   .mainloop:
.C:c009  E6 FE       INC $FE            ; increment expected character
.C:c00b   .getchar:
.C:c00b  20 E4 FF    JSR $FFE4          ; read character from keyboard
.C:c00e  F0 FB       BEQ .getchar       ; until actual character entered
.C:c010  20 D2 FF    JSR $FFD2          ; output this character
.C:c013  C5 FE       CMP $FE            ; compare with expected
.C:c015  38          SEC                ; set carry as marker for error
.C:c016  D0 38       BNE .result        ; wrong character -> output result
.C:c018  C9 5A       CMP #$5A           ; compare with 'z'
.C:c01a  18          CLC                ; clear carry (no error)
.C:c01b  F0 33       BEQ .result        ; if 'z' entered, output result
.C:c01d  C9 41       CMP #$41           ; compare with 'a'
.C:c01f  D0 E8       BNE .mainloop      ; if not equal repeat main loop
.C:c021  A9 00       LDA #$00           ; initialize timer ticks to 0
.C:c023  85 FC       STA $FC
.C:c025  85 FD       STA $FD
.C:c027  A9 18       LDA #$18           ; counter for adjusting the timer
.C:c029  85 FB       STA $FB
.C:c02b  A9 7F       LDA #$7F           ; disable all CIA2 interrupts
.C:c02d  8D 0D DD    STA $DD0D
.C:c030  A9 7F       LDA #<.timertick   ; set NMI interrupt vector ...
.C:c032  8D 18 03    STA $0318
.C:c035  A9 C0       LDA #>.timertick
.C:c037  8D 19 03    STA $0319          ; ... to our own timer tick routine
.C:c03a  A9 D9       LDA #$D8           ; load timer with ...
.C:c03c  8D 04 DD    STA $DD04
.C:c03f  A9 03       LDA #$03
.C:c041  8D 05 DD    STA $DD05          ; ... 985 (-1) ticks (see description)
.C:c044  A9 01       LDA #$01           ; enable timer
.C:c046  8D 0E DD    STA $DD0E
.C:c049  A9 81       LDA #$81           ; enable timer interrupt
.C:c04b  8D 0D DD    STA $DD0D
.C:c04e  D0 B9       BNE .mainloop      ; repeat main loop
.C:c050   .result:
.C:c050  A9 7F       LDA #$7F           ; disable all CIA2 interrupts
.C:c052  8D 0D DD    STA $DD0D
.C:c055  A9 47       LDA #$47           ; set NMI interrupt vector ...
.C:c057  8D 18 03    STA $0318
.C:c05a  A9 FE       LDA #$FE
.C:c05c  AD 19 03    LDA $0319          ; ... back to system default
.C:c05f  CE 0E DD    DEC $DD0E          ; disable timer
.C:c062  B0 14       BCS .fail          ; if carry set, output fail
.C:c064  A9 0D       LDA #$0D           ; load newline
.C:c066  20 D2 FF    JSR $FFD2          ; and output
.C:c069  A4 FC       LDY $FC            ; load timer value in
.C:c06b  A5 FD       LDA $FD            ; A and Y
.C:c06d  20 91 B3    JSR $B391          ; convert to float
.C:c070  20 DD BD    JSR $BDDD          ; convert float to string
.C:c073  A9 01       LDA #$01           ; load address of
.C:c075  A8          TAY                ; string buffer
.C:c076  D0 04       BNE .out           ; and to output
.C:c078   .fail:
.C:c078  A9 9D       LDA #<.failstr     ; load address of "Fail" string
.C:c07a  A0 C0       LDY #>.failstr     ; in A and Y
.C:c07c   .out:
.C:c07c  4C 1E AB    JMP $AB1E          ; done; OS routine for string output
.C:c07f   .timertick:
.C:c07f  48          PHA                ; save accu
.C:c080  AD 0D DD    LDA $DD0D          ; load interrupt control register
.C:c083  29 01       AND #$01           ; to know whether it was a timer NMI
.C:c085  F0 14       BEQ .tickdone      ; if not -> done
.C:c087  E6 FC       INC $FC            ; increment timer ticks ...
.C:c089  D0 02       BNE .adjusttick
.C:c08b  E6 FD       INC $FD            ; high byte only on overflow
.C:c08d   .adjusttick:
.C:c08d  C6 FB       DEC $FB            ; decrement counter for adjusting
.C:c08f  D0 0A       BNE .tickdone      ; not 0 yet -> nothing to do
.C:c091  A9 18       LDA #$18           ; restore counter for adjusting
.C:c093  85 FB       STA $FB
.C:c095  CE 0E DD    DEC $DD0E          ; halt timer for exactly
.C:c098  EE 0E DD    INC $DD0E          ; 6 cycles
.C:c09b   .tickdone:
.C:c09b  68          PLA                ; restore accu
.C:c09c  40          RTI
.C:c09d   .failstr:
.C:c09d  0D C6 41    .BYTE $0D,"Fa"
.C:c0a0  49 4C 00    .BYTE "il",$00

```
> 37 votes

# Answer
# Bash \+ coreutils, ~~103~~ ~~99~~ 98 bytes

```
for((;c==p%26;r=`date +%s%3N`-(s=s?s:r),c=62#$c-9,p++))
{
read -N1 c
}
((c==p))||r=Fail
echo "
$r"

```

Must be run in a terminal.

### Test run

```
$ bash type.sh
abcdefghijklmnopqrstuvwxyz
3479
$ bash type.sh
abcz
Fail
$ bash type.sh 2>&- # typing '@' would print to STDERR
ab@
Fail
$ bash type.sh
A
Fail

```
> 15 votes

# Answer
# Python 2 + getch, 116 bytes

```
import time,getch
t=[i+97-ord(getch.getche())and exit("Fail")or time.time()for i in range(26)]
print(t[-1]-t[0])*1e3

```

Thanks to ovs and ElPedro for fixing the code and saving 57 bytes.
> 8 votes

# Answer
# Pascal (FPC), 176 bytes

```
Uses CRT,SysUtils;Var c:char;a:Real;Begin
for c:='a'to'z'do
if c=ReadKey then
begin Write(c);if c='a'then a:=Now;end
else
begin
Write('Fail');Halt;end;Write((Now-a)*864e5)
End.

```

Try it online!

Some tricks used in code for golfing:

* Use `Real` as a shorter alternative to `TDateTime`, because as defined here, `TDateTime` = `Double`, which is floating-point type.
* Instead of using `MilliSecondsBetween` for calculating time gap, this code multiply the difference between two floating-point values by `864e5`, which works because of the way Free Pascal encode `TDateTime` described here.

Note:

* `ReadKey` function doesn't actually print the key on the console, so manual writing to console with `Write(c)` is necessary.
* TIO get a score near `0` for typing the alphabet for obvious reason.
* The program prints time in floating-point notation, I guess that's allowed.
> 8 votes

# Answer
# SOGL V0.12, 35 bytes

```
"ζ¦F‘→I
]I!}Su[I:lzm≠?■Fail←z=?Suκ←

```

Try it Here! \- click run, and enter the alphabet in the input box. Note that it may be a little laggy because SOGL only pauses for input every 100 executed tokens (and SOGL is quite slow). If that bothers you, run `sleepBI=true` in the console.

**note:** don't run this in the compatibility mode - it'll just loop forever.

Explanation:

```
"ζ¦F‘    push "inputs.value" (yes, that is a word in SOGLs english dictionary)
     →   execute as JS, pushing the inputs contents
      I  named function I

]  }                do while POP is truthy
 I                    execute I
  !                   negate it - check if it's empty
    Su              push the current milliseconds since start
[                   loop
 I                    execute I
  :                   duplicate the result
   l                  let its length
    zm                mold the alphabet to that size
      ≠?              if that isn't equal to one of the result copies
        ■Fail           push "Fail"
             ←          and exit, implicitly outputting that
              z=?     if the other copy is equal to the alphabet
                 Su     push the milliseconds since start
                   κ    subtract the starting milliseconds from that
                    ←   and exit, implicitly outputting the result

```
> 7 votes

# Answer
# Java, ~~404~~ ~~388~~ ~~354~~ ~~348~~ ~~320~~ 318 bytes

```
import java.awt.*;import java.awt.event.*;interface M{static void main(String[]a){new Frame(){{add(new TextArea(){{addKeyListener(new KeyAdapter(){long t,i=64;public void keyPressed(KeyEvent e){t=t>0?t:e.getWhen();if(e.getKeyChar()!=++i|i>89){System.out.print(i>89?e.getWhen()-t:"Fail");dispose();}}});}});show();}};}}

```

And here I thought Java Console was already verbose..
Since Java has no way to raw listen for key-presses in the Console a.f.a.i.k., I use a GUI with `java.awt`.

-78 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

```
import java.awt.*;                 // Required import for Frame and TextField
import java.awt.event.*;           // Required import for KeyAdapter and KeyEvent
interface M{                       // Class
  static void main(String[]a){     //  Mandatory main-method
    new Frame(){                   //   Create the GUI-Frame
      {                            //    With an initialization-block
        add(new TextArea(){        //     Add an input-field
          {                        //      With it's own initialization-block
            addKeyListener(new KeyAdapter(){
                                   //       Add a KeyAdapter to the input-field
              long t,              //        Long to save the time
                   i=64;           //        Previous character, starting at code of 'a' -1
              public void keyPressed(KeyEvent e){
                                   //        Override the keyPressed-method:
                t=t>0?             //         If `t` is already set:
                   t               //          Leave it the same
                  :                //         Else:
                   e.getWhen();    //          Save the current time (== start the timer)
                if(e.getKeyCode()!=++i
                                   //         As soon as an incorrect character is pressed,
                   |i>89){         //         or we've reached 'z':
                  System.out.print(i>89?
                                   //          If we're at 'z':
                    e.getWhen()-t  //           Print the end-time in ms to the Console
                   :               //          Else (an incorrect character was pressed)
                    "Fail");       //           Print "Fail" to the Console
                  dispose();}      //          And exit the application
              }                    //        End of keyPressed-method
            });                    //       End of KeyAdapter
          }                        //      End of input-field initialization-block
        });                        //     End of input-field
        show();                    //     Initially show the Frame
      }                            //    End of Frame initialization-block
    };                             //   End of Frame
  }                                //  End of main-method
}                                  // End of class

```

**Example gif of success:** (Yes, I type the alphabet pretty slowly here..)
*Note: This is an old gif. Current version no longer prints key-presses to Console. And it no longer prints the time with digits after the decimal point.*

**Example gif of fail:**
*Note: This is an old gif. Current version no longer prints key-presses to Console.*
> 5 votes

# Answer
# C# (.NET Core), ~~245 + 13~~ ~~183 + 41~~ 177 + 41 bytes

+41 bytes for `using System;using static System.Console`.

Untested since I am on mobile and this does not run on TIO.

```
n=>{int c=ReadKey().KeyChar,x=0;try{if(c!=97)x/=x;var s=DateTime.Now;while(c<149)if(ReadKey().KeyChar!=c++)x/=x;Write((DateTime.Now-s).TotalMilliseconds);}catch{Write("Fail");}}

```
> 4 votes

# Answer
# Node.js, 240 213 bytes

```
require('readline',{stdin:i,stdout:o,exit:e}=process).emitKeypressEvents(i)
w=s=>o.write(s)
n=0
i.on('keypress',c=>w(c)&&c.charCodeAt()-97-n?e(w(`
Fail`)):!n++?s=d():n>25&&e(w(`
`+(d()-s)))).setRawMode(d=Date.now)

```

EDIT: Saved 27 bytes thanks to Jordan

Ungolfed version:

```
const readline = require('readline')

let index = 0
let start

readline.emitKeypressEvents(process.stdin)
process.stdin.setRawMode(true)

process.stdin.on('keypress', character => {
  process.stdout.write(character )

  // Lookup character in ASCII table
  if (character !== String.fromCharCode(97 + index) {
    process.stdout.write('\nFail')
    process.exit()
  }

  index++

  if (index === 1) {
    start = Date.now()
  }

  if (index === 26) {
    process.stdout.write('\n' + (Date.now() - start))
    process.exit()
  }
})

```
> 3 votes

# Answer
# C# (.NET Core), 184+13=197 173+13=186 bytes

```
()=>{var s=DateTime.Now;var i=97;while(i<123&&Console.ReadKey().KeyChar==i)if(i++<98)s=DateTime.Now;Console.Write(i>122?$"\n{(DateTime.Now-s).TotalMilliseconds}":"\nFail");}

```

Try it online!

Unfortunately TIO can't run this, but it's handy for getting byte count.

+13 for `using System;`

-1 by changing `i==123` to `i>122`. I was tempted to make this `i>'z'`.

### Acknowledgements

-10 bytes thanks to @raznagul

### Ungolfed

```
()=>{
    var s=DateTime.Now;
    var i=97;

    while(i<123&&Console.ReadKey().KeyChar==i)
        if(i++<98)
            s=DateTime.Now;

    Console.Write(i>122?
        $"\n{(DateTime.Now-s).TotalMilliseconds}":
        "\nFail"
    );
}

```
> 3 votes

# Answer
# C (gcc), 303 bytes

Works on \*nix systems. Standalone code removing the current terminal's canonical mode to allow reading characters without waiting for newlines:

/!\ Running this program will make the terminal almost unusable.

```
#import <stdlib.h>
#import <termios.h>
#define x gettimeofday(&t,0)
#define r t.tv_sec*1000+t.tv_usec/1000
c,i=97;main(){long s=0;struct termios n;struct timeval t;cfmakeraw(&n);n.c_lflag|=ECHO;tcsetattr(0,0,&n);for(;i<'d';){c=getchar();if(c!=i++)puts("\nFail"),exit(0);x;s=s?:r;}x;printf("\n%ld",r-s);}

```

**Ungolfed and commented:**

```
// needed in order to make gcc aware of struct termios
// and struct timeval sizes
#import <stdlib.h>
#import <termios.h>

// gets the time in a timeval structure, containing
// the number of seconds since the epoch, and the number
// of µsecs elapsed in that second
// (shorter than clock_gettime)
#define x gettimeofday(&t,0)
// convert a timeval structure to Epoch-millis
#define r t.tv_sec*1000+t.tv_usec/1000

// both integers
// c will contain the chars read on stdin
// 97 is 'a' in ASCII
c,i=97;

main(){
  long s=0; // will contain the timestamp of the 1st char entered
  struct timeval t; // will contain the timestamp read from gettimeofday

  // setting up the terminal
  struct termios n;
  cfmakeraw(&n);//create a raw terminal configuration
  n.c_lflag|=ECHO;//makes the terminal echo each character typed
  tcsetattr(0,0,&n);//applies the new settings

  // from 'a' to 'z'...
  for(;i<'{';){
    // read 1 char on stdin
    c=getchar();

    // if int value of the input char != expected one => fail&exit
    if(c!=i++)puts("\nFail"),exit(0);

    // macro x: get current timestamp
    x;

    // if not already set: set starting timestamp
    s=s?:r;
  }

  // get end of sequence timestamp
  x;

  // prints the end-start timestamps difference
  printf("\n%ld",r-s);
}

```

**Alternative solution (218 bytes):**

If configuring the terminal beforehand is allowed, then we can get rid of the portion of code handling that part.

Here is the same code without terminal manipulation:

```
#import <stdlib.h>
#define x gettimeofday(&t,0)
#define r t.tv_sec*1000+t.tv_usec/1000
c,i=97;main(){long s=0;struct timeval t;for(;i<'{';){c=getchar();if(c!=i++)puts("\nFail"),exit(0);x;s=s?:r;}x;printf("\n%ld",r-s);}

```

To make it work:

```
$ gcc golf.c
$ stty -icanon
$ a.out

```

**runtime example:**
> 3 votes

# Answer
# Commodore BASIC v2 - 113 bytes

Capital letters must be shifted.
Thanks to Felix Palmen for pointing out some typos, specs
try it

```
0d=64
1on-(f=26)gO5:gEa$:ifa$=""tH1
2iff=0tHt=ti
3f=f+1:ifa$<>cH(d+f)tH6
4?cH(14)a$;:gO1
5?:?(ti-t)/60*1000:eN
6?"Fail"

```
> 3 votes

# Answer
# Mathematica (notebook expression), 248 bytes

```
DynamicModule[{x={},s=0,t=0},EventHandler[Framed@Dynamic[If[x=={"a"}&&s<1,s=SessionTime[]];Which[x==a,If[t==0,t=SessionTime[]-s];1000t,x==a~Take~Length@x,""<>x,1>0,"Fail"]],Table[{"KeyDown",c}:>x~AppendTo~CurrentValue@"EventKey",{c,a=Alphabet[]}]]]

```

# How it works

```
DynamicModule[{x={},s=0,t=0},
  EventHandler[
    Framed@Dynamic[
      If[x=={"a"} && s<1,s=SessionTime[]];
      Which[
        x==a,If[t==0,t=SessionTime[]-s];1000t,
        x==a~Take~Length@x,""<>x,
        1>0,"Fail"]],
    Table[{"KeyDown",c}:>x~AppendTo~CurrentValue@"EventKey",
      {c,a=Alphabet[]}]]]

```

A `DynamicModule` with an `EventHandler` that responds to lowercase letter keypresses. The variables `x`, `s`, and `t` hold the letters pressed so far, the start time, and the end time, respectively. As soon as we notice `x` being equal to `{"a"}`, we start the time; we display either the total time spent, or the string built so far, or `"Fail"` depending on which condition is met.

We could save another byte with `t<1` rather than `t==0` if we can assume that nobody is fast enough to type the alphabet in less than one second :)

If you're trying this out in a Mathematica notebook, keep in mind that you have to click inside the frame before your keypresses will be registered. (This is the reason that we need the frame to begin with; if `Framed` is not there, then the entire object selected changes when a key is pressed, so it stops being selected and you'd have to click again.)
> 2 votes

# Answer
# MSX-BASIC, 126 characters

```
1C=97:GOSUB3:TIME=0
2IFASC(C$)<>CTHEN?"Fail":ENDELSEIFC=122THEN?TIME*20:ENDELSEC=C+1:GOSUB3:GOTO2
3C$=INKEY$:IFC$=""GOTO3
4RETURN

```

`TIME` is an internal MSX-BASIC variable that increases by one every 20 milliseconds.
> 2 votes

# Answer
# Perl 5, ~~79~~ 93 +31 (-MTerm::ReadKey -MTime::HiRes=time) bytes

```
$|=1;map{ReadKey eq$_||exit print"
Fail";$s||=time}a..z;print$/,0|1e3*(time-$s)

```

`$|=1` is not sufficient to set terminal in raw mode, `stty -icanon` should be run before or

```
ReadMode 3;map{ReadKey eq$_||exit print"
Fail";print;$s||=time}a..z;print$/,0|1e3*(time-$s)

```

to see characters in the terminal after running command : `stty echo` or `stty echo icanon`
> 2 votes

# Answer
# APL (Dyalog), SBCS, 114 153 bytes

Using a GUI form to handle keypress events:

```
t←⍬
a←819⌶⎕A
f←{⍬≡t:f ⍵⊣t⊢←⎕AI⋄⊃a≠⍞←3⊃⍵:⎕EX⎕A⊣⎕←'Fail'⋄'z'=a~←⊃a:⎕←3⊃⎕AI-t}
⎕DQ⎕A⎕WC'Form'('Event' 'KeyPress' 'f')

```

(Golfed by Adám; I think it would be odd for him to be awarding a bounty for an answer which is now mostly his golf rewrite, so that's here, and my original is below. This version handles the "exit on failure" part of the spec, too.\]

```
t←⍬
a←(819⌶)⎕A
∇w
'W'⎕WC'Form'('Event' 'KeyPress' 'f')
⎕DQ'W'
∇
∇f e
{26=≢a:t⊢←⎕TS}⍬
{e[3]=1↑a:{⍞←1↑a⋄a⊢←1↓a}⍬⋄⎕←'Fail'}⍬
{0=≢a:⎕←60 60 1e3⊥4↓⎕TS-t}⍬
∇
w

```

Image of it (the first posted version) in use, Dyalog APL 17.1:

---

### Explanation.

It's a function `w` which loads a GUI form and adds an event handler to it, and starts listening for events, and the call back which handles the alphabet.

Lambda functions are used to get guard pattern matching, instead of longer `:If ⋄ cond ⋄ code ⋄ :Else ⋄ code ⋄ :EndIF` syntax. Guards are `{cond: code}` pattern, and the `{}⍬` pattern is calling a function on an empty numeric vector just to make it run

```
t←⍬  ⍝ Variable for the time of starting typing

a←(819⌶)⎕A  ⍝ Variable for lowercase alphabet,
               cast from uppercase with I-beam 819

⍝ Function "w" makes window of type 'Form', called 'W', with event handler.
⍝ Callback function "f", and starts event loop.
∇w
'W'⎕WC'Form'('Event' 'KeyPress' 'f')
⎕DQ'W'
∇

⍝ event handler function "f" takes event "e"
∇f e

{26=≢a:t⊢←⎕TS}⍬    ⍝ lambda function (dfn)
                   ⍝ checks if there are 26 letters,
                   ⍝ (i.e. started typing) starts the timer.
                   ⍝ "t" is initialised first, for global scoping.

{e[3]=1↑a:{⍞←1↑a⋄a⊢←1↓a}⍬⋄⎕←'Fail'}⍬ ⍝ guard, if event[3] (key pressed)
                                     ⍝ is the next alphabet letter (first of "a")
                                     ⍝ print 1 from "a", drop 1 from "a"
                                     ⍝ else print "Fail".

{0=≢a:⎕←60 60 1e3⊥4↓⎕TS-t}⍬  ⍝ guard, if all the letters are gone,
                             ⍝ subtract current timestamp from stored,
                             ⍝ drop 4 elements (year, month, day, hour)
                             ⍝ base-convert min, sec, ms to pure ms
                             ⍝ and print.
∇

⍝ run it by calling function "w"
w

```
> 2 votes

# Answer
# C#, 154 152 + 13 = 165 bytes

Saved 2 bytes thanks to Ayb4btu's comments

```
x=>{
  long t=0,c=97;
  for(;Console.ReadKey().KeyChar==c++&&c<123;t=t<1?DateTime.Now.Ticks:t);
  Console.Write(c>122?"\n"+(DateTime.Now.Ticks-t)/1e4:"\nFail");
}

```

The code above has whitespace to make it fit in SE without a scrollbar. Whitespace isn't part of the byte count

and 13 bytes for `using System;`

It's similar to Ayb4btu's version but with the following differences:

* Storing datetime as a long, allows us to make `c` a long also, and short cut the declaration
* Loop doesn't need a separate break
* It's not actually shorter to use `$"interpreted strings"` versus adding a needed "\n" onto the milliseconds to make it a string for the inline if
* Using a `for` loop sometimes allows us to save chars over a while, though I think this one wouldn't save over the equivalent `while`

From Ayb4btu:

* `s=s==0` can become `s=s<1`, and `c==123` can become `c>122`

### Ungolfed

```
long t=0,c=97;

for (;                                         //no loop vars declared
  Console.ReadKey().KeyChar == c++ && c < 123; //loop test
  t = t < 1 ? DateTime.Now.Ticks : t          //post-loop assigns
) ;                                            //empty loop body!

//now just need to turn ticks into millis, 10,000 ticks per millis
Console.Write(c>122?"\n"+(DateTime.Now.Ticks-t)/1e4:"\nFail");

```
> 1 votes

# Answer
# Aceto, 70 bytes

```
d'|d 't9
$z=p zp1
!=   >#v
d,   1 +
cTpaXpn3
Io$'p"*F
|'!=ilnu
@ad,aF"

```

I start by setting a catch mark and mirroring horizontally(`@|`), if the value on the stack is truthy. It isn't initially, and later always will be. We will jump back here later if a wrong key is entered. Next, we push an a on the stack (`'a`), then we duplicate it and read a single character from the user (`d,`). If the two characters are not equal (`=!`), we "crash" (`$`) and jump back to the catch mark. Otherwise, we push another "a" and print it, then we set the current time (`'apT`).

Then we enter our "main loop": We "increment" the current character and "increment" the character (`'apToIc`), then we duplicate it, read a new character, compare it, and "crash" if it the characters aren't identical (`d,=!$`). If we didn't crash, we compare the current character to "z" (`d'z=|`), if it isn't equal, we print the character, then we push a 1 and jump "conditionally" (in this case: always) to the only `o` in the code (the begin of our main loop). If it was equal to z, we mirrored horizontally to some empty space on top. We print "z", then push the current time (minus the starting time; `t`) and then multiply the number 1000 (gotten by raising 10 to the third power; `91+3F`) by it (because we get seconds, not milliseconds). Then we print a newline, the time, and exit (`pX`).

If we ever crash (bad input by the user), we jump all the way to the beginning. Since we will now have some truthy value on the stack, we will mirror horizontally onto the `u`, which reverses the direction we're moving in. `n` prints a newline character, then we push `"Fail"` on the stack, print it, and exit (`pX`).
> 1 votes

# Answer
# Processing.org ~~133~~ 142

first code didn't exit

```
char k=97;int m;void draw(){if(key==k){m=m<1?millis():m;print(key=k++,k>122?"\n"+(millis()-m):"");}if(m>0&&key!=k-1){print("\nFail");exit();}}

```
> 0 votes

# Answer
# GCC, windows, 98 bytes

```
t;main(i){for(;i++<27;t=t?:clock())if(95+i-getche())return puts("\nFail");printf("\n%d",clock()-t);}

```

Requires no instantly input for the first key
> 0 votes

# Answer
**Ruby: 194 bytes**

```
require 'io/console'
a=[*"a".."z"]
c=0
s=
loop do
i=STDIN.getch
if i==a[c]
print i
s=Time.now if i=='a'
else
puts "\nFail"
exit
end
if i=='z'
puts "\n"+((Time.now-s)*1000).to_s
exit
end
c+=1
end

```
> 0 votes

# Answer
# Python 3, 107 bytes

```
from time import*;x=time();a=input();print((time()-x)*1000 if a=="abcdefghijklmnopqrstuvwxyz" else "Fail");

```

Outputs a floating point number. Relies on lowercase alphabet.
> 0 votes

# Answer
# Java (Android), 709 bytes

> And here I thought Java Console was already verbose.

*Imagine complaining about AWT* :omegalul:

```
package a;import android.widget.*;import android.text.*;public class Z extends android.app.Activity{long g;long f(){return System.currentTimeMillis();}public void onCreate(android.os.Bundle b){super.onCreate(b);EditText t=new EditText(this);t.setSingleLine();t.setInputType(144);t.addTextChangedListener(new TextWatcher(){public void beforeTextChanged(CharSequence s,int a,int b,int c){if(g<1)g=f();}public void onTextChanged(CharSequence s,int a,int b,int c){}public void afterTextChanged(Editable s){}});t.setOnEditorActionListener((x,y,z)->{t.setError((""+t.getText()).equals("abcdefghijklmnopqrstuvwxyz")?f()-g+"":"Fail");return true;});addContentView(t,new android.view.ViewGroup.LayoutParams(-1,-2));}}

```

Commented version:

```
// Android requires all Activities to be in a package.
package a;
// EditText
import android.widget.*;
// TextWatcher, Editable
import android.text.*;
// just use full package names for the rest

// yes, we need this entire signature.
public class Z extends android.app.Activity {
    // timer
    long g;
    // Wrapper because it is shorter than calling this behemoth
    // Gets the current time
    long f() {
        return System.currentTimeMillis();
    }

    // Activity entry point
    public void onCreate(android.os.Bundle b) {
        super.onCreate(b);
        // Android Studio doesn't have var. They abandoned Java 10 in favor of Kotlin.
        //  geeeeeeeeee I wonder why ANYone would abandon programming for Android in Java... :P
        EditText t = new EditText(this);
        // This sets the enter key to a submit key, allowing us to catch OnEditorAction
        t.setSingleLine();
        // no autocomplete 4 u
        // InputType.VISIBLE_PASSWORD
        t.setInputType(144);
        // The main reason this is so verbose is because the requirement needs us to start
        // timing on the first character TYPED. It would be much easier to add an onClick or onFocus
        // listener instead, but nooooo. :(
        t.addTextChangedListener(new TextWatcher() {
            // why
            public void beforeTextChanged(CharSequence s, int a, int b, int c) {
                // Start our timer the first time the user types something.
                if (g < 1) g = f();
            }
            // three
            public void onTextChanged(CharSequence s, int a, int b, int c) {
            }
            // methods?
            public void afterTextChanged(Editable s) {
            }
        });
        // When they hit submit, verify using the obvious way.
        // I _may_ be able to verify in TextWatcher, but TextWatcher is not char by char. IDK, I haven't experimented with it yet.
        t.setOnEditorActionListener((x, y, z) -> {
            // Show the result via setError, which is on a new line. :)
            t.setError(("" + t.getText()).equals("abcdefghijklmnopqrstuvwxyz") ? f() - g + "" : "Fail");
            return true;
        });
        // Append to the root view.
        // -1 == LayoutParams.MATCH_PARENT
        // -2 == LayoutParams.WRAP_CONTENT
        addContentView(t, new android.view.ViewGroup.LayoutParams(-1, -2));
    }
}

```

https://streamable.com/7xb1xl

Edit: I have gotten very good at this by the way, look at my mad skills.
> 0 votes

---
Tags: code-golf, date, alphabet, interactive
---


title: Can't see the forest for the keys

text:
# Question
Title: Can't see the forest for the keys
Write a program or function that takes in a nonempty list of integers in any reasonable convenient format such as `4, 0, -1, -6, 2` or `[4 0 -1 -6 2]`.

Print or return a string that depicts the list as an ASCII art forest where each number becomes a tree of proportional height. Each tree takes up four columns of text in the output as follows:

* A positive integer N becomes a tree whose base is `__|_` and top is  `^` , with N layers of  `/ \` in between.

For example, when N = 1 the tree is

```
  ^
 / \
__|_

```

when N = 2 the tree is

```
  ^
 / \
 / \
__|_

```

when N = 3 the tree is

```
  ^
 / \
 / \
 / \
__|_

```

and so on.
* A negative integer N becomes just like the corresponding positive tree except a vertical bar is between the branch slashes instead of a space.

For example, when N = -1 the tree is

```
  ^
 /|\
__|_

```

when N = -2 the tree is

```
  ^
 /|\
 /|\
__|_

```

when N = -3 the tree is

```
  ^
 /|\
 /|\
 /|\
__|_

```

and so on.
* When the integer is 0 there is technically no tree, just an empty space of four underscores:

```
____

```

The underscores at the base of each tree must line up in the output, i.e. all the trees must have their bases at the same level. Also, a single underscore is added to the end of the line of underscores after the last tree. This makes it so every tree has an empty column of "air" on either side of it.

As an example, the output for `4 0 -1 -6 2` would be

```
              ^
             /|\
  ^          /|\
 / \         /|\
 / \         /|\  ^
 / \      ^  /|\ / \
 / \     /|\ /|\ / \
__|_______|___|___|__

```

Note how the tree patterns always have a leading column of empty space but an underscore had to be added to pad the right side of the last tree.

Also:

* Trailing spaces on any lines are fine, but there should be no unnecessary leading spaces.
* Leading newlines are not allowed (the tallest tree should touch the top of the output text grid) and only up to one trailing newline is allowed.
* The list may contain any integers from -250 to 250 inclusive. Handling taller trees is not required.

**The shortest code in bytes wins.**

# More Examples

`3`:

```
  ^
 / \
 / \
 / \
__|__

```

`-2`:

```
  ^
 /|\
 /|\
__|__

```

`0`:

```
_____

```

`0, 0`:

```
_________

```

`0, 1, 0`:

```
      ^
     / \
______|______

```

`0, -1, 2, -3, 4`:

```
                  ^
              ^  / \
          ^  /|\ / \
      ^  / \ /|\ / \
     /|\ / \ /|\ / \
______|___|___|___|__

```

# Answer
# Pyth, 48 bytes

```
j_.t+sm.i,J\_?d++\|sm?>d0\ \|d\^Jms+Jmkd"/\\"QJd

```

Try it online: Demonstration or Test Suite

Too lazy for a full explanation. Here just short overview:

I generate the columns first. So the image:

```
      ^
  ^  /|\
 / \ /|\
__|___|__

```

gets generated as:

```
["_", "_/", "| ^", "_\", "_", "_//", "|||^", "_\\", "_"]

```

Notice, that I'm generating only the lower part (everything without the spaces). And I'm also generating them from bottom to top. This is done pretty straightforward.

Then I can use the `.t` method to append spaces to the strings, so that each string has an equal length. And afterwards I reverse the order and print.
> 6 votes

# Answer
# Python 2, 165 bytes

```
a=input()
l=max(map(abs,a))
while l+2:s=' _'[l<0];print(s+s.join((([' ^ ','//| \\\\'[x>0::2],'   '][cmp(abs(x),l)],'_|_')[l<0],s*3)[x==0]for x in a)+s).rstrip();l-=1

```

This is a full program that accepts a list as input. I'm still golfing this horrid mess.
> 7 votes

# Answer
# PHP, 231 ~~277~~ bytes

This challenge has a beautiful output.

```
$x=fgetcsv(STDIN);for(;$i<2+max(array_map(abs,$x));$i++)for($j=0;$j<count($x);){$_=$x[$j++];$o[$i].=!$i?$_?'__|_':____:(abs($_)>=$i?0>$_?' /|\\':' / \\':($i-1&&abs($_)==$i-1?'  ^ ':'    '));}echo implode("
",array_reverse($o))."_";

```

Reads a comma separated list (whitespaces are optional) from `STDIN`:

```
$ php trees.php
> 1, 2, 0, -4, 6

```

**Ungolfed**

```
$x=fgetcsv(STDIN);
for(;$i<2+max(array_map(abs,$x));$i++)
    for($j=0;$j<count($x);){
        $_=$x[$j++];
        $o[$i] .= !$i ? $_?'__|_':____
                      : (abs($_)>=$i ? 0>$_?' /|\\':' / \\'
                                     : ($i-1&&abs($_)==$i-1 ? '  ^ ' : '    '));
    }
echo implode("\n",array_reverse($o))."_";

```

**Edits**

* *Saved* **46 bytes**. Discarded array initialization, replaced `if/else` with ternary operators and moved some of the variables around to save a few bytes.
> 4 votes

# Answer
# Ruby, ~~157~~ ~~156~~ 153 characters

```
->h{r=[]
h.map{|i|j=i.abs
r+=[s=?_,?/*j+s,i==0?s:?^+(i>0?' ':?|)*j+?|,?\\*j+s].map{|l|l.rjust(h.map(&:abs).max+2).chars}}
r.transpose.map{|l|l*''}*$/+?_}

```

Written just because initially `Array.transpose` looked like a good idea. Not anymore.

Sample run:

```
2.1.5 :001 > puts ->h{r=[];h.map{|i|j=i.abs;r+=[s=?_,?/*j+s,i==0?s:?^+(i>0?' ':?|)*j+?|,?\\*j+s].map{|l|l.rjust(h.map(&:abs).max+2).chars}};r.transpose.map{|l|l*''}*$/+?_}[[4, 0, -1, -6, 2]]
              ^
             /|\
  ^          /|\
 / \         /|\
 / \         /|\  ^
 / \      ^  /|\ / \
 / \     /|\ /|\ / \
__|_______|___|___|__

```
> 2 votes

# Answer
# PowerShell, 167 bytes

```
$h=(($r=($args|%{$a,$x=$_,-$_-ge0
'_';'_'+'/'*$a;'|_'[!$_]+(' ','|')[$_-lt0]*$a+'^'*!!$_
'_'+'\'*$a})+'_')|% Le*|sort)[-1]
$z=$r|% *ht $h;--$h..0|%{-join($z|% Ch* $_)}

```

Try it online!

Explanation:

1. Draw a rotated forest line by line
2. Pad right and
3. Rotate -90.

Unrolled:

```
# a rotated forest with underscore after the last tree
$rotatedForest=$args|%{
    $abs,$x=$_,-$_-ge0
    '_'
    '_'+'/'*$abs
    '|_'[!$_]+(' ','|')[$_-lt0]*$abs+'^'*!!$_
    '_'+'\'*$abs
}
$rotatedForest += '_'

# calc height
$height = ($rotatedForest|% Length|sort)[-1]

# PadRight all trees
$z = $rotatedForest|% PadRight $height

# Rotate -90
--$height..0|%{
    -join($z|% Chars $_)
}

```
> 1 votes

# Answer
# C#, 318 bytes

I tried transposing the array. I'm not sure if that was the best solution.

```
string F(int[]a){int i=a.Length,j,w=i*4+1,h=0;string f="",o=f;for(;i-->0;){j=a[i];f+=","+" _,".PadLeft(j=j>0?j+3:-j+3,'\\')+(j>3?"^"+"|_,".PadLeft(j,a[i]<0?'|':' '):"_,")+" _,_".PadLeft(j+1,'/');h=h<j?j:h;}f="_".PadLeft(h=h>3?h:2,'\n')+f;for(i+=h<3?1:0;++i<h;)for(j=w;j-->0;)o+=f.Split(',')[j].PadLeft(h)[i];return o;}

```

Indentation and newlines for clarity:

```
string F(int[]a)
{
    int i=a.Length,
        j,
        w=i*4+1,
        h=0;
    string f="",o=f;
    for(;i-->0;){
        j=a[i];
        f+=","+" _,".PadLeft(j=j>0?j+3:-j+3,'\\')+(j>3?"^"+"|_,".PadLeft(j,a[i]<0?'|':' '):"_,")+" _,_".PadLeft(j+1,'/');
        h=h<j?j:h;
    }
    f="_".PadLeft(h=h>3?h:2,'\n')+f;
    for(i+=h<3?1:0;++i<h;)
        for(j=w;j-->0;)
            o+=f.Split(',')[j].PadLeft(h)[i];
    return o;
}

```
> 0 votes

# Answer
# Canvas, 41 bytes

```
Ｈ？¹⤢\ /＊¹０＜？ /∙|/╋｝ v∔↕_|__¶∔↕］_４×｝＋｝_；＋↕

```

Try it here!
> 0 votes

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