title: "Hello, World!" in zero lines of code

text:
# Question
Title: "Hello, World!" in zero lines of code
NPM's sloc is a moderately popular tool for counting source lines of code in a file. The tool will attempt to strip out both single and multiline comments and count the remaining lines in order to get an estimate of the 'true' number of lines of code.

However, the parser used is based on regular expressions and is quite simple, so it can be tricked. In this challenge, you will need to construct a hello world program that `sloc` counts as *zero lines of code*.

## The challenge

1. Download `sloc`. If you have npm, this can be done via `npm i sloc`. We will use the latest version as of the time of posting, which is `0.2.1`. Or, use the online testing environment linked at the bottom of this post.
2. Select any language that `sloc` supports. A full list is available here.
3. Write a **full program** in that language that prints the exact string `Hello, World!` to stdout. The output may optionally have a trailing newline, but no other format is accepted. The program may output anything to stderr. However, to be considered a valid submission, `sloc` must see the program as zero lines of source code. You can verify this by running `sloc myprogram.ext`, which should read `Source : 0`.

## Example

The following Python program is a valid submission:

```
'''"""''';print("Hello, World!");"""'''"""

```

If I run `sloc hello.py`, I get:

```
---------- Result ------------

            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  0
       Block comment :  1
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

----------------------------

```

Why? Well, sloc uses `'''` or `"""` to determine if something is a mulitline comment in Python. However, it doesn't pair them up correctly. Thus Python parses our program as:

```
'''"""''';print("Hello, World!");"""'''"""
\-------/ \--------------------/ \-------/
 comment        active code       comment

```

But `sloc` parses it as:

```
'''"""''';print("Hello, World!");"""'''"""
\----/\----------------------------/\----/
comment          comment           comment

```

(This is not the shortest valid Python submission, so it shouldn't stop you looking for shorter ones)

## Scoring

The shortest program in bytes wins.

## A note on feasibility

It might be a reasonable question to ask whether this is possible for all languages. I don't know, but all the ones I've looked at so far (Python, C, HTML) have at least one solution. So there's a very good chance it is possible in your language.

There are a number of ideas that can work across multiple languages.

## Online test environment

Try it online!

You need to:

1. Type your code into the input box
2. Type the extension corresponding to your language into the command args (important!)

# Answer
# Haskell, ~~36~~ 35 bytes

```
{-{--}--}main=putStr"Hello, world!"

```

Try it online!

Test sloc

Since sloc is regex based it is a very good guess to think it cannot identify nested comments. And if we take a look we see that indeed it cannot. If we nest two comments as so:

```
{-{--}-}

```

sloc identifies one line of source and one line of comment. Based on these observations my best guess is that the regex it is using is

```
(\{-((?!-\}).)*-\}|--[^\n]*)

```

If we pop this into a regex engine we will see it matches the nested comment as so:

```
      code
      ^^
{-{--}-}
^^^^^^
comment

```

Ok so we broke it, however this has the opposite of the intended effect. We want sloc to think our code is a comment rather than our comment is code. So we add a "line comment marker" to the part of the comment sloc thinks is code, so that sloc thinks a line comment is being started.

```
{-{--}--}

```

So to sloc there are two comments the block comment `{-{--}` and the line comment `--}` but to haskell which actually parses comments, it is all one block comment.

So then we just add our code after. Sloc thinks this is still a comment and Haskell knows it is not.
> 43 votes

# Answer
# Java 6, ~~83~~ ~~68~~ 54 Bytes

The code :

```
/**/enum C{C;{System.out.print("Hello, World!");}}/**/

```

Although crashes immediately with error sent to stderr, prints the correct output. Thanks to `@Kevin Cruijssen` for the tip about removing the `System.exit(0)`.

And the result :

```
---------- Result ------------

            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  0
       Block comment :  1
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

----------------------------

```

Thanks @Razetime for the hint from @OlivierGrégoire answer.

---

My initial answer was in java 7+ with 83 Bytes (there's a comma missing) :

```
/**/interface C{static void main(String[]a){System.out.print("Hello World!");}}/**/

```
> 33 votes

# Answer
# Groovy, 28 bytes

```
/**/print"Hello, World!"/**/

```

Try it online!

---

# Squirrel, 30 bytes

```
/**/print("Hello, World!")/**/

```

Try it online!

---

# Swift, 30 bytes

```
/**/print("Hello, World!")/**/

```

Try it online!

---

# JavaScript (Node.js), 36 bytes

```
/**/console.log("Hello, World!")/**/

```

~~As a bonus, this also breaks SE's syntax highlighter.~~ (seems to be fixed)

Try it online!

---

# C (gcc), 38 bytes

```
/**/main(){puts("Hello, World!");}/**/

```

Try it online!

---

# Dart, 39 bytes

```
/**/main(){print("Hello, World!");}/**/

```

Try it online!

---

# Rust, 42 bytes

```
/**/fn main(){print!("Hello, World!")}/**/

```

Try it online!

---

# C++ (gcc), 48 bytes

```
/**/main(){__builtin_puts("Hello, World!");}/**/

```

Try it online!

---

# Scala, 52 bytes

```
/**/object H extends App{print("Hello, World!")}/**/

```

Try it online!

---

# Go, 69 bytes

```
/**/package main
import."fmt"
func main(){Print("Hello, World!")}/**/

```

Try it online!

---

# C# (.NET Core), 75 bytes

```
/**/class P{static void Main(){System.Console.Write("Hello, World!");}}/**/

```

Try it online!
> 33 votes

# Answer
# PHP, 33 bytes

Dewi Morgan claimed there was no possible solution, so that obviously made me look further into a way to do it :) (he then followed up with multiple 'shenanigans')

Thing is, we can simply do:

```
//<?php ob_clean()?>Hello, World!

```

The only downside (and what made me initially discard it) is that you must be using a SAPI that has buffering enabled by default. So, if you tried to run it with php cli, it will probably output the `//` *and* complain that there was no buffer to delete. But if ran from a web server (even built-in `php -S`), it will produce the expected `Hello World!`

sloc agrees that has no code:

```
---------- Result ------------

            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  1
       Block comment :  0
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

----------------------------

```
> 30 votes

# Answer
# JavaScript (V8), 28 bytes

```
/**/print`Hello, World!`/**/

```

Try it online!
> 24 votes

# Answer
# PHP, 17 chars *with backspace cheat*.

## Entry

```
//^H^HHello, World!

```

## Rationale

After the forward-slashes for the comment, there are two backspace characters which erase them from the output. Then, it outputs the target string.

So, whether this is legal depends on whether "output" can be grossly misinterpreted to mean "eventual visual output on some terminals". I suspect not, since the online testing env is probably the canonical env, and does not respect backspaces. So while maybe mildly interesting for the weaknesses found, this is unlikely to be a winner :)

However, that then means that **a legal solution is impossible in PHP.**

For any solution which does not include this cheat, we are stuck with two options:

1. Comments, then PHP opentag. This outputs `//`, and we've established that's illegal:

```
//<?php

```
2. PHP open tag, then comments. Lacking any preceding text to hide it from sloc, the open tag counts as a line of code.

```
<?php//

```

This argument relies on the assumption that comments are the *only* way to hide code from sloc.

However, the argument works just as well if we replace "comments" with "anything which causes bad output if placed before a PHP opentag; and won't hide the opentag from sloc if placed after it", which I *think* includes everything, since the regexes for PHP don't seem to have any exploitable backreferencing, but I may be making an incorrect assumption.

## Weaknesses found

Possibly-exploitable issues found with the sloc online testing env for PHP.

1. It treats `//` line and `/*...*/` comments correctly, but is sadly unaware of `#` line comments, or this would be 15 chars instead, standing a good chance of beating all languages other than those using compression or with the "Hello World!" string as a language construct. OK, or languages where `//` means `print` and the file extension can be set to .c or similar.
2. It does not check for a preceding unpaired `<?` or `<?php` before considering something code. To PHP, everything outside of `<?....?>` is output. This is the bug I exploited.
> 21 votes

# Answer
# HTML, ~~25~~ 23 bytes

-2 bytes thanks to anonymoose

```
<!-->Hello, World!<!-->

```

---

A side note on PHP:

Inspired by @Dewi Morgan's PHP answer, I wanted to see if I could find any other approaches which did not use the backspace cheat.

My first thought was that my HTML answer would instantly work as a PHP answer, however this is not the case. Even though PHP interprets everything outside of its `<?` `?>` tags as plain HTML, simply switching the extension from HTML to PHP causes sloc to interpret this as one line, and indeed it seems that sloc ignores HTML comments in PHP mode.

I was hoping that something like `//?>Hello, World!` would solve this for PHP, but while sloc interprets this as 0 lines (hooray!!) PHP simply ignores the closing tag meaning that the entire construct is output to the page.

So, for now I have to agree: it seems like a valid PHP solution without the backspace cheat (or using the `-r` flag) does not exist.
> 13 votes

# Answer
# Python, 32 bytes

```
"""'''""";print("Hello, World!")

```

`sloc` outputs

```
{ total: 1,
  source: 0,
  comment: 1,
  single: 0,
  block: 1,
  mixed: 0,
  empty: 0,
  todo: 0,
  blockEmpty: 0 }

```

Try it online
> 10 votes

# Answer
# Ruby, 46 bytes

```
=begin
=end =begin
puts "Hello, World!"
#=end

```

sloc output

```
---------- Result ------------

            Physical :  4
              Source :  0
             Comment :  4
 Single-line comment :  0
       Block comment :  4
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

```
> 10 votes

# Answer
# CSS, 38 bytes

```
/**/:after{content:"Hello, World!"/**/

```

CSS, despite not being an actual programming language, allows us to do basic output. This code creates a pseudo-element after every element on the page

Sloc's block comment detection is broken (as seen in other answers) and this is reported as 0 lines of source code. See the sloc output here.

The below snippet has been modified (40 bytes) so that the snippet runner and some browsers that style the \<html\> (causing a double-output) display properly.

```
/**/* :after{content:"Hello, World!"/**/
```
> 8 votes

# Answer
# Nim, 24 bytes

```
 #[]#echo"Hello, World!"

```

Try it online!

Verify sloc

sloc looks for `#` characters in Nim, but the regex is a little weird, as it cares about the position of the `#`. Presumably, this was done to try to work around the fact that it treats `##` comments separate from `#` comments. Specifically, sloc doesn't seem to know that Nim has block comments in the form of `#[` `]#`, so it treats `##` comments as block comments for its counting. This means that although we can take advantage of its misunderstanding of block comments fairly easily, we need a space at the start or it won't detect it. Or more accurately, it actually seems to detect it properly, somehow, despite there not seeming to be any code for block comments in the source. I'm really not quite sure why it works, I'd have to try to understand a regex for that.
> 7 votes

# Answer
# , 43 bytes

```
#!/usr/bin/rscript -e cat('Hello','World!')

```

Count the zero source lines of code

I'm not sure whether this is completely valid. It's a full program that must be launched directly from the shell (so it does not work in 'Try it Online' or 'rdrr.io' for instance, or when copy-pasted into the  console). Save as "helloworld.r" with execute permission, and run using `./helloworld.r` or, more verbosely, `exec helloworld.r > output.txt`.

does not support multi-line comments, so the 'pairing the comment delimiter' tricks available in other languages aren't possible. The only (single line) comment character is `#`, and everything following it up to the next newline is not executed. However, the shebang line starting with `#!` is counted by "sloc" as a comment, even though it will be read and interpreted by the program loader.

Usually, the shebang line simply tells the program loader which interpreter to use to run the rest of the program. So, this is a more-conventional 2-line (sloc=1)  program to accomplish the same task:

```
#!/usr/bin/rscript
cat('Hello','World!')

```

But - we can also include command-line arguments in the shebang line, and the rscript interpreter accepts the `-e` flag to pass it the program code as an argument, which is what the sloc=0 code does here.

So: the program is valid in  and the program code is run by , but it requires to be launched from the shell and uses the help of the program loader. Is this valid? I don't know. But it's the only way that I could think of to 'trick' sloc in a language without multi-line comments...
> 6 votes

# Answer
## Perl5

```
$ cat script.pl
#!/usr/bin/perl -Esay(Hello.chr(44).chr(32).world.chr(33))

```

```
$ ./script.pl
Hello, world!

```

```
sloc script.pl

---------- Result ------------

            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  1
       Block comment :  0
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

----------------------------

```
> 5 votes

# Answer
# Lua, 28 bytes

```
--[=[]=]print"Hello, World!"

```

Try it online!
> 5 votes

# Answer
# Python 2, 30 bytes

If using Python 2, nobody's solution can be improved slightly.

```
'''"""''';print"Hello, World!"

```

`sloc` outputs

```
{ total: 1,
  source: 0,
  comment: 1,
  single: 0,
  block: 1,
  mixed: 0,
  empty: 0,
  todo: 0,
  blockEmpty: 0 }

```

Try it online
> 5 votes

# Answer
# JavaScript (Browser), 34 Bytes

```
/**/console.log`Hello, World!`/**/

```

```
---------- Result ------------

            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  0
       Block comment :  1
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

----------------------------

```

# Python, 36 Bytes

```
'''#''';print("Hello, World!");"'''"

```

```
---------- Result ------------

            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  0
       Block comment :  1
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

----------------------------

```
> 4 votes

# Answer
# PHP, with various commandline shenanigans, 0-33

Depending how I read Command-line flags on front ends, various of these answers may apply.

I feel none do, so downvotes are fine and expected on this one :) I'm posting it more as an exploration of the problem-space, perhaps towards an eventual argument that a solution is not possible in PHP, than an answer that I expect to be accepted.

I've given my arguments against them all, summarized with **opinionated bold statements**, because that naturally makes the arguments more true. I'm very interested to hear counterarguments, or additional arguments, in the comments!

## php -r 'echo"Hello, World!";', 0

One interpretation is that nothing on the commandline counts, but that the entire commandline is treated as a kind of "language dialect name" for the entry.

Against: **All code should be counted**. Otherwise, this approach makes any contest where bytes matter trivial in almost any language, by offloading all work to the CLI. The parameters to the -r flag here are not a "flag to choose a language option", they are "code", and should be counted as such.

## PHP -r, 20

```
php -r 'echo"Hello, World!";'

```

It could be argued that, while we count the code on the CLI, the sloc requirement only applies to the contents of source files. If there is no source file, then there are no code lines in source files!

Against: **All counted code should be passed to sloc**. Every language lets you slap code in the cli params. The challenge isn't meant to degrade into "run hello world without using a source file", so this isn't an interesting solution to the challenge.

## PHP -r ignoring quotes, 29

```
php -r '/**/echo "Hello, World!";/**/'

```

So we can pass in a minimal code sample on the commandline, getting all the benefits of avoiding PHP's \<? requirement, without paying any significant penalty.

Against: **Necessary escaping of code should count as code**. There's no good argument FOR ignoring the quotes. Not-ignoring them makes challenges more interesting anyway.

So I'd argue that all characters which are counted should be passed to sloc, and this solution is wrapped in quotes, and the quotes should be counted. A quoted string counts as a code line in sloc. So, this fails the sloc test.

## PHP -r plus shell escapes, 33

```
php -r/**/echo\"Hello,\ World\!\"\;/**/

```

Against: **This is no longer PHP.** We're not, now, really coding in PHP, we're coding in (some shell) + PHP. If this were submitted as a bash script it'd count as 39 characters, and it'd fail the sloc test. We shouldn't get to reduce the count and pretend it passes, just by pretending it's run in one of the utilities the shell called.

## PHP with filepath and param ordering, 16.

This one's a two-parter! First, a file called `/x`, containing only our 13 character output string:

```
Hello, World!

```

Call it as:

```
php //x

```

Then, assuming 1) we count the filename as it is used on the commandline, and 2) we prepend that to the code we pass to sloc, because everything counted is code, sloc interprets it as a one-line comment.

Against: **both assumptions above are dumb.**

## PHP with various failed efforts, inf

Including these just as informational: trying both -r and a file specifier, to address the "depends how we concatenate" problem, above.

1. filename for comment, then -r for code.

php //x -r 'echo "hi"';

The -r param did not run if a filename preceded it on the line. Same was true of the `-B`, `-R`, `-E`, `-F` params.

Against: **Given the -r flag doesn't count, it's hard to see how this woulda been counted. And it doesn't work anyway.**

2. Maybe the BREF group didn't work because they need actual input lines to parse, since they control per-input-line behavior?

echo | php //x -B 'echo "hi"';

Same deal. They don't run if a filename for an empty file precedes them on the line. Same was true of the `-R`, `-E`, `-F` params.

Against: **This is now (some shell), and it doesn't work.**

3. The `-w` param is "Output source with stripped comments and whitespace." which almost sounds like an exact description of the challenge! Using `php -w x.php`, a source file like

/**/Hello, World!/**/

... feels like it should work.

Against: **A coding challenge requires that the code runs.** No actual code was executed, and I feel that's required, to be in the spirit of a coding challenge. More importantly, it doesn't work: without a leading `<?`, PHP doesn't see this as PHP code, so does not strip the comments.

4. Trying variations on this approach, turns out `-w` does not work with `-r`.
5. But `-w` does run with direct or piped input. However, these have the exact same problem as using a file: PHP requires the leading `<?`.
6. What about exploiting ini file params?

php -a -d cli.prompt='"Hello, World!"'

Against: **Doesn't run code, doesn't work.** Almost works, but also outputs "Interactive mode enabled\n\n".

## Exhaustive exploration of PHP-CLI args

Some push unwanted output to stdout that cannot be modified or redirected through config or code, so are unusable:

* `-a` Run interactively.
* `-h` Help.
* `-i` Show info.
* `--ini` list ini files.
* `-l` Lint.
* `-m` Module list.
* `--rf` function info.
* `--rc` class info.
* `--re` ext info.
* `--rz` Zend ext info.
* `--ri` ext config info.
* `-s` Prettyprint source.
* `-v` Version.

Some seem to offer no advantage over simpler alternatives:

* `-B` Begin code. No better than -r?
* `-E` Run at end. No better than -r?
* `-f` File. No better than default exec file param?
* `-F` File every line. No better than default exec file param?
* `-R` Run every line. No better than -r?

Some seem irrelevant, affecting neither perception as a comment, nor output:

* `-c` Config path. Irrelevant?
* `-e` Debug info. Irrelevant?
* `-H` Hide args from ps. Irrelevant?
* `-n` No Config. Irrelevant?
* `-S` Webserver. Irrelevant?
* `-t` Docroot. Irrelevant?

This leaves us with just four that look potentially exploitable.

* `-d` Define INI entry, which could include these likely candidates:
    + `auto_append_code`/`auto_prepend_code` could help somehow, but not sure how they'd be any better than the `-f` flag.
    + `cli.prompt` already tried above.
    + `memcache.*`/`opcache.*` could create output then modify code? Feels an invalid solution, though, even if it worked.
    + `filter.default` I think only filters input, not output and certainly not code.
    + `output_buffering` feels like a VERY likely candidate.
    + `output_handler` feels like a VERY likely candidate.
* `-r` Run code. Explored above, no success.
* `-w` Print stripped source. Explored above, no success.
* `-z` zend ext. Would require a zend extension that could help us.
> 4 votes

# Answer
976 9

JavaScript (Browser), 34 Bytes

```
/**/console.log`Hello, World!`/**/

```

## Result

```
            Physical :  1
              Source :  0
             Comment :  1
 Single-line comment :  0
       Block comment :  1
               Mixed :  0
 Empty block comment :  0
               Empty :  0
               To Do :  0

Number of files read :  1

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 30 bytes

```
/**/Write("Hello, World!")/**/

```

Try it online!
> 1 votes

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


# Question
Title: For what block sizes is this checksum valid?
**The input:**

As an example, take a list containing a number of bits (in this case, 32):

```
11000010000100111011000011001011

```

We can calculate a simple checksum of this data by dividing it into evenly sized blocks, and taking the XOR of each of them. For example, with eight bit blocks:

```
11000010
00010011
10110000
11001011

10101010

```

We then append this to the end, making it 40 bits:

```
1100001000010011101100001100101110101010

```

This will be the form your input is given in.

To validate a checksum in this form, you just take the XOR of each block, including the checksum. If it's valid, it will result in a string of zeroes.

**The challenge:**

I've got a bunch of data with checksums. The problem is, I don't remember what the block size was! Your task is to write a program or function which takes input of any length, and returns all of the block sizes where the checksum is valid.

Blocks with sizes that do not fit evenly into the input should be ignored (so `7` would not be allowed in the output given `00000000`). In the example above, the valid block sizes would be `[1, 2, 4, 8]`, and the invalid ones would be `[5, 10, 20]`.

Note that block sizes of one are possible (valid if the XOR of every bit in the string results in 0). A block the size of the entire string is not valid (so `8` would not be allowed in the output given `00000000`), and blocks with sizes less than two do not need to be handled.

You can produce output and take input in any reasonable manner, such as lists of bits, strings of `0`s and `1`s, integers representing the binary values, etc.

This is , so shortest answer in bytes per language wins!

**Test cases:**

```
1100100001000000  ->  [1, 2, 4]
010010100100      ->  [1, 2, 3]
0000000000        ->  [1, 2, 5]
101101000         ->  [1, 3]
10010110          ->  [1, 2]
10000000          ->  []
0101010           ->  []
11                ->  [1]
1                 ->  (does not need to be handled)
                  ->  (does not need to be handled)

```

# Answer
# 05AB1E, ~~10~~ 8 bytes

Input is a list of bits.

```
gÑ¨ʒιOÈP

```

Try it online!

**Commented**:

```
gÑ          # push the divisors of the length of the input
  ¨         # remove the last one (the length itself)
   ʒ        # filter this list on:
    ι       #   push [a[0::b], a[1::b], ..., a[(b - 1)::b]] where a is the input b the divisor
            #   this groups the digits from each group at the same index together
     O      #   sum each list
      ÈP    #   are all sums even?

```
> 11 votes

# Answer
# K (ngn/k), ~~33~~ ~~31~~ ~~28~~ ~~30~~ 33 bytes

```
{((|/2!+/#[;x]0N,)')_&~(!#x)!'#x}

```

Try it online!

Takes input as a list of `0`s and `1`s.

* `&~(!#x)!'#x` divisors of the length of the input
* `((...)')_...` drop records from the right side (divisors) if the left side (run on each divisor) is truthy
* `#[;x]0N,` split the input into equal pieces, each of length corresponding to the current divisor
* `|/2!+/` are there an odd number of 1's in any "column" of the split-out input?
> 8 votes

# Answer
# Add++, 29 bytes

```
D,g,@@,T2€BbB^
L,bLd1_Rþ%A$þg

```

Try it online!

I'm surprised Add++ was this short. Takes input as a list of bits

## How it works

```
D,		; Define a helper function
	g,	; called g
	@@,	; that takes 2 arguments e.g. [8 [1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 1 0 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 1 0]]
	T	; Split into chunks; [[1 1 0 0 0 0 1 0] [0 0 0 1 0 0 1 1] [1 0 1 1 0 0 0 0] [1 1 0 0 1 0 1 1] [1 0 1 0 1 0 1 0]]
	2€Bb	; Convert from binary; [67 200 13 211 85]
	B^	; Reduce by XOR; 0

L,		; Define an unnamed lambda
		; Example argument: [1 1 0 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 1 1 0 0 0 0 1 1 0 0 1 0 1 1 1 0 1 0 1 0 1 0]
	bL	; Length; 40
	d	; Duplicate; [40 40]
	1_	; Decrement; [40 39]
	R	; Range; [40 [1 2 3 ... 37 38 39]]
	þ%	; Filter false Mod; [1 2 4 5 8 10 20]
	A$	; Push the argument below; [[1 1 0 ... 0 1 0] [1 2 4 5 8 10 20]]
	þg	; Filter false on g; [1 2 4 8]

```
> 5 votes

# Answer
# Brachylog, 16 bytes

```
⟨{ġ\+ᵐ~×₂ᵐl}ᶠxl⟩

```

Try it online!

```
⟨{ġ\+ᵐ~×₂ᵐl}ᶠxl⟩
⟨            x ⟩ remove
              l  the input's length from
 {         }ᶠ    all results of:
  ġ               split the input into equal sized groups
   \              transpose
    +ᵐ            the sum of each column is
      ~×₂ᵐ        the result of a multiplication of some number by 2
          l       get the length of the block

```
> 5 votes

# Answer
# Husk, 12 bytes

```
fö¬ΣFz≠C¹hḊL

```

Try it online!

```
f               # filter truthy elements x of
          ḊL    # the divisors of the length of the input
         h      # except the last one (the length itself)
                # using this function:
 ö              # apply 4 operations:
  ¬             #   NOT
   Σ            #   the sum of
    F           #   folding each pair of elements by
     z          #     zipping each pair together by
      ≠         #     xor (not equal)
       C¹       #   to the input split into blocks of size x

```
> 5 votes

# Answer
# Ruby 2.7 `-nl`, ~~85~~ 75 bytes

*Saved a whooping 10 bytes, thanks to Dingus!*

```
p (1...~/$/).select{|i|~/$/%i+eval($_.scan(/.{#{i}}/).map{|i|i.to_i 2}*?^)<1}

```

Try it online!

TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, i.e., `_1`, which saves 2 bytes.
> 5 votes

# Answer
## SageMath, ~~99~~ 104 bytes

```
f=lambda s:[d for d in divisors(len(s))[:-1]if 0^eval("^".join(["0b"+s[x:x+d]for x in(0,d..len(s)-1)]))]

```

The two instances of the `^` operator here are actually different operators! Sage preprocesses the source code to treat `^` as exponentiation, but `eval` is just ordinary Python eval, which treats `^` as bitwise xor.

The expression `0^X` is used as a shorter way to express `X==0`. It works because 0⁰=1, whereas 0ⁿ=0 for non-zero n. (This trick was used by Julia Robinson in her work on Hilbert’s Tenth Problem, and is employed in the famous paper *Diophantine representation of the set of prime numbers*.)

This function takes its input as a string of zeroes and ones, and returns a list of numbers.

---

**Edit**: Thanks to ovs for pointing out that I had overlooked the part of the problem statement that says blocks the size of the whole string are not allowed.
> 4 votes

# Answer
# Jelly, 11 bytes

```
LÆḌs@^/ẸɗÐḟ

```

Try it online!

Input as a list of bits, the Footer does this for you

## How it works

```
LÆḌs@^/ẸɗÐḟ - Main link. Takes a list of bits, B, on the left
L           - Length of B
 ÆḌ         - Proper divisors
        ɗÐḟ - Filter proper divisors k, keeping those which return False:
   s@       -   Split B into pieces of length k
     ^/     -   Reduce columnwise by XOR
       Ẹ    -   Are any true?

```

Monads you could use instead of :

* `S`: Sum of columns
* `T`: Indexes of non-zero elements
* : Convert from binary
* : Convert from decimal
* : Generate an array which would yield the original argument under `T`
* : Maximum
* `§`: Sum of rows
> 3 votes

# Answer
# Perl 5 `-lF`, 68 bytes

```
map{@a=$i=0;//;map$a[$i++%$']+=$_,@F;@F%$_+(grep$_%2,@a)||say}1..$#F

```

Try it online!
> 3 votes

# Answer
# Python 3.8, 110 bytes

```
lambda n:(l:=len(n))and[b for b in range(1,l)if not(eval('^'.join('0o'+n[a:a+b]for a in range(0,l,b)))or l%b)]

```

Try it online!

Inputs a string of \\$1\\$s and \\$0\\$s and returns a list of all possible block sizes where the checksum is valid.
> 3 votes

# Answer
# Python 3, ~~94~~ 86 bytes

Input is a list of bits.

```
lambda s:[d for d in range(1,len(s))if~-any(len(s)%d+sum(s[x::d])%2for x in range(d))]

```

Try it online!

**Commented**:

```
lambda s:[                       ]    # lambda function with a list of digits s as input and a list of integers as output
  d for d in range(1,len(s))          # take the block size d in 1,2,...len(s)-1
    if ~-any(  for x in range(d))     # if for no index in 0,1,...,d-1
      len(s)%d                        #   the block size does not divide the input size
      +sum(s[x::d])%2                 #   or there is an odd number of 1's at this index

```

---

# Python 3.8, 86 bytes

Same length as a recursive function

```
f=lambda s,d=1,x=0:s[d:]and[x][d-x:]+f(s,d+(w:=len(s)%d+sum(s[x::d])%2+x//d>0),~-w*~x)

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 62 bytes

```
sTr/@Mod[i=0;1+##&@@s~Partition~UpTo@i++&/@s,2]~Cases~{1..}

```

Try it online!

Input a list of bits.

Xor gives the same result as the sum of its arguments mod 2, but `Xor` is not `Listable`, while `Plus` and `Mod` are.

Mathematica's `Listable` functions only reduce when all arguments are lists of the same length or scalars. Thus if the block size does not evenly divide the total length, so `Plus` remains unevaluated. The resulting expresion `Plus[...]` cannot be matched by `{1..}`.

```
Mod[i=0;1+##&@@s~Partition~UpTo@i++&/@s,2]  (* calculate bitwise complements of possible checksums of the input *)
% ~Cases~{1..}                              (* find those which only contain 1s *)
Tr/@ %                                      (* get the length of each. *)

```
> 3 votes

# Answer
# Scala, ~~95~~ 93 bytes

```
b=>1.to(b.size/2)filter{s=>b.grouped(s).reduce((_,_).zipped.map(_^_)).toSet==Set(b.size%s*2)}

```

Try it online!

Accepts input as a list of ints.

`b` is the input block. `1.to(b.size/2)` is a range of all possible block sizes, and `filter{s=>...}` is used to keep only those that divide `b` evenly and that result in a string of zeroes.

`b.grouped(s)` splits `b` into chunks of size `s`, then `reduce` is used to xor all the chunks together. The function to reduce with is `(_,_).zipped.map(_^_)` (the underscores are placeholders for actual parameters). `(_,_).zipped` zips the two lists together, and `map(_^_)` applies xor to each pair in both lists. Finally, `toSet` is invoked on the result of xor-ing the chunks together, so now it's either a `Set(0)` if it had only zeroes, or `Set(1)` or `Set(0,1)` if it had ones.

We can check both that this result is `Set(0)` and that `s` divides `b` evenly by comparing that set with `== Set(b.size % s * 2)`. `b.size % s * 2` will be 0 if `s` divides `b` evenly, but if not, it will be 2 or some higher number, not `1`. The result from earlier can only contain a `0` or `1`, so it will only match if `b.size % s` is `0` and the result from earlier is a `Set` with just a `0`, checking both conditions at once.
> 2 votes

# Answer
# JavaScript (ES10), 94 bytes

Expects a string.

```
s=>(g=k=>s[++k]?[(h=i=>(t=s.substr(i,k))?t[k-1]?'0b'+t^h(i+k):~0:0)(0)?[]:k,g(k)].flat():[])``

```

Try it online!

### Commented

```
s => (                         // s = input string
  g = k =>                     // g is a recursive function taking a block size k
    s[++k] ?                   //   increment k; if s[k] is defined:
      [                        //     begin an array:
        ( h = i =>             //       h is a recursive function taking a counter i
          (t = s.substr(i, k)) //         t is the next substring of maximum size k
          ?                    //         if it's non-empty:
            t[k - 1] ?         //           if the size of t is k:
              '0b' + t         //             convert it from binary to decimal
              ^                //             and XOR it with
              h(i + k)         //             the result of a recursive call to h
            :                  //           else:
              ~0               //             stop and invalidate the final result
                               //             (the length of s is not a multiple of k)
          :                    //         else:
            0                  //           stop
        )(0)                   //       initial call to h with i = 0
        ?                      //       if the result is not 0:
          []                   //         append an empty array (removed by flat())
        :                      //       else:
          k,                   //         append k
        g(k)                   //       append the result of a recursive call to g
      ].flat()                 //     end of array; flatten it
    :                          //   else:
      []                       //     stop
)``                            // initial call to g with k zero'ish

```
> 2 votes

# Answer
# Charcoal, 29 bytes

```
ＩΦＬθ∧ι¬∨﹪Ｌθι⌈﹪↨ΣＥ⪪θι⍘λ⊕Ｌθ⊕Ｌθ²

```

Try it online! Link is to verbose version of code. Explanation: Charcoal has no bitwise Or operator nor an easy way to reduce it over an array so I emulate it by performing a sum using a large base and then separately reducing each digit modulo 2.

```
   θ                            Input string
  Ｌ                             Length
 Φ                              Filter over implicit range
     ι                          Current value (i.e. is non-zero)
    ∧                           Logical And
      ¬                         Logical Not
         Ｌθ                     Length of input string
        ﹪                       Modulo (i.e. does not divide by)
           ι                    Current value
       ∨                        Logical Or
                  θ             Input string
                 ⪪ ι            Split into substrings of current length
                Ｅ               Map over substrings
                     λ          Current substring
                    ⍘           Convert string from base
                      ⊕Ｌθ       Incremented input length
               Σ                Take the sum
              ↨                 Convert to array using base
                         ⊕Ｌθ    Incremented input length
             ﹪              ²   Vectorised modulo by 2
            ⌈                   Take the maximum i.e. are any odd?
Ｉ                               Cast to string
                                Implicitly print

```
> 2 votes

# Answer
# Pip `-n`, 31 bytes

```
{!#y%a&!$BX(FB_My<>a)}FI1,--#Ya

```

Try it online!

Input as a string of 0s and 1s.

## Explanation

```
{!#y%a&!$BX(FB_My<>a)}FI1,--#Ya a → input
                        1,--#Ya range 1..length(a)-1
                             Ya store input in y
{                    }FI        filter each i by the following:
  #y%a                           length(a) mod i
 !                               logical not (is divisor)
      &                          and
                y<>a             input split into chunks of length i
            FB_M                 mapped from binary to decimal
        $BX(        )            folded by bitwise xor
       !                         logical not (checksum validity)
                                 is true?
                                join with newlines(-n flag)

```
> 2 votes

# Answer
# , 93 bytes

```
function(x,l=sum(x|1))which(!sapply(seq(l=l-1),function(n)l%%n|any(rowSums(matrix(x,n))%%2)))

```

Try it online!

For each `n` up to the length of the input minus 1, rearranges the input bits into a matrix with `n` rows: the checksum is valid if the sum of every row is an even number.
> 2 votes

# Answer
# Julia, 71 bytes

```
a->filter(i->L%i<1&&!any(xor(a[j:i:L]...) for j=1:i),1:(L=length(a))-1)

```

expects an `Array{Bool}`

Try it online!
> 2 votes

# Answer
# Haskell, 109 bytes

```
f s=[x|x<-[1..l s-1],rem(l s)x==0,not.or.foldr1(zipWith(/=))$x#map(=='1')s]
l=length
_#[]=[]
n#x=x:n#drop n x

```

Try it online!

If taking the input as a list of booleans counts as a reasonable manner it would go down to 99 (not sure if it does, though):

# Haskell, 99 bytes

```
f s=[x|x<-[1..l s-1],rem(l s)x==0,not.or.foldr1(zipWith(/=))$x#s]
l=length
_#[]=[]
n#x=x:n#drop n x

```

Try it online!
> 2 votes

---
Tags: code-golf, math, checksum
---


title: Advent of Code 2020, Day 2, Part 1

text:
# Question
Title: Advent of Code 2020, Day 2, Part 1
Today, my girlfriend and I started with this year's Advent of Code to improve our Python. So far we only did Day 1 and the first part of Day 2. The latter, I found to be very fun, so, to spice it up a little, and with a tip o' the head to Eric Wastl, here's my attempt at turning it into a Code Golf challenge.

## Task

Your task, should you accept it, would be to determine the number of lines where the number of occurrences of `char` in each `string` is at least `min` and at most `max`. With the above data, a valid entry will output `23`¹.

Valid entries shall not only work with the below two example data sets, but with any data set produced by the Advent of Code website's Day 2 Part 1 puzzle (so head on over there already - but just going with the examples is fine, too). **Other formats of input are not allowed. Specifically, the entry has to handle the newlines itself.**

I've posted an answer with my Ruby version along with this Question in the hopes that it will help.

## Input

* A multiline string where each line/element contains a number `min`, a number `max`, a character `char`, and a string `password`² (i.e., `min-max char: password`).
* `min` and `max` are positive integers, and `max` is guaranteed to be greater than or equal to `min`.
* As far as I can tell, the `password`s are all ASCII-alphabetical, as is the `char`.

## Output

* A number representing how many lines had at least `min` and at most `max` occurrences of `char` in `password`.

## Scoring

* The winner shall be the shortest entry by characters³, *not* bytes (to make sure that variable names such as ,  and  don't put contestants in the mood of the season at a disadvantage).

## (Shorter) Test Case

```
Output: 3
Input:
1-5 c: abcdefg
5-12 j: abcdefg
1-5 z: zzzzzzzz
3-3 h: hahaha
4-20 e: egejeqwee

```

## (Longer) Example

```
Output: 23
Input:
3-8 j: ksjjtvnjbjppjjjl
6-10 s: sszlkrsssss
1-4 z: znzfpz
7-11 m: dfkcbxmxmnmmtvmtdn
6-9 h: hlhhkhhhq
8-9 p: ppppppppvp
6-9 c: cccgccccmcch
5-8 g: bgkggjgtvggn
3-4 x: xxhk
10-12 h: hhhhhhhhhlhhhhdnh
5-6 j: zjjsjn
9-14 s: ksclwttsmpjtds
6-7 l: gtdcblql
1-4 d: dkndjkcd
1-6 k: kkkkkckmc
10-12 x: xxxxxxxxxrxl
2-5 v: fxdjtv
3-5 q: pjmkqdmqnzqppr
5-8 t: xtgtgtcht
6-11 j: nftjzjmfljqjrc
6-9 g: rskgggmgmwjggggvgb
11-12 v: vkvdmvdvvvdv
15-16 z: zzzzzzzzzzzzzzgxz
13-17 v: vvvvvvvvvvvvvvvvnv
9-14 j: clrfkrwhjtvzvqqj
1-12 l: lljljznslllffhblz
4-7 c: cccgcxclc
6-11 z: tbxqrzzbwbr
18-19 m: jmbmmqmshmczlphfgmf
1-5 s: ssvsq
4-5 k: kkkkw
4-7 f: fcqffxff
3-8 f: fffzthzf
9-12 v: vvvvvvvvvvvmvv
14-17 f: ftflcfffjtjrvfkffmvf
4-7 n: pnmnxnqqjp
6-7 r: rrrkrmr
4-13 k: drckdzxrsmzrkqckn
5-14 t: dttttttttttttt
13-14 v: vvvvfvvvvvvvvvv
7-12 j: jrljwnctjqjjxj
6-7 v: wchfzvm
1-8 d: dddddddzd
10-12 g: gvvzrglgrgggggggggg

```

---

¹: But, say `puts 23` (that is, without doing the actual work) is no valid entry.
²: On Advent of Code, the background to the puzzle is that you're helping a toboggan rental company with their computer trouble. For some reason, their password database has been jumbled up and you're trying to fix it, which requires you to figure out which passwords adhere to the password policy, which solely consists of a specific character (`char`) to be present at least and at most a certain number of times.
³: As determined via `wc -m`.

# Answer
> 8 votes
# Ruby, 56 characters

```
eval'㵰␼⹣潵湴筼汼氽縯層⬠⠮⤯㬨①⹴潟椮⸤☮瑯彩⤽㴽␧⹣潵湴⠤ㄩ紻'.encode('utf-16').b

```

Try it online!

Decompresses to:

```
p$<.count{|l|l=~/\d+ (.)/;($`.to_i..$&.to_i)===$'.count($1)}

```

Character scoring allows these sort of shenanigans!

This is also a great showcase of Ruby's regex global variables. Given a line:

```
3-8 j: ksjjtvnjbjppjjjl

```

Our regex matches here:

```
3-8 j: ksjjtvnjbjppjjjl
  \-/
  Regex matches here

```

Then `$'` is the part after the regex, `$&` is the part that matches the regex, `$`` is the part before the regex, and `$1` matches the character to count, so we have:

```
$` = '3-'
$& = '8 j'
$1 = 'j'
$' = ': ksjjtvnjbjppjjjl'

```

Since Ruby's `to_i` just ignores garbage after a numeric string, we can just cast it to int.

### Ruby `-n`, 60 characters

```
~/\d+ (.)/;($`.to_i..$&.to_i)===$'.count($1)||$.-=1
END{p$.}

```

Try it online!

# Answer
> 6 votes
# Python 3, 71 characters

```
exec(bytes("浩潰瑲爠੥㵦慬扭慤砠攺慶⡬敲献扵✨尨⭤⸩尨⭤⸩⸨⠩⬮尩㽮Ⱗ❲⠫ㅜ㴼尢∴挮畯瑮∨㍜⤢㴼㉜✩砬⤩",'U16')[2:])

```

Try it online!

Decompresses to:

```
import re
f=lambda x:eval(re.sub('(\d+).(\d+).(.)(.+)\n?',r'+(\1<="\4".count("\3")<=\2)',x))

```

Note we need to name the function even though it's not recursive since we are wrapping in `exec`.

This is probably not optimal, since we shouldn't have to use regexes here, but parsing the format is so painful using only Python stdlib.

# Answer
> 6 votes
# GAWK, 87 bytes

```
split($1,b,"-")sub(":",a,$2){n=b[1];x=b[2];c=split($3,y,$2);t+=n<c&&--c<=x}END{print t}

```

Try it online!

It's pretty brute force, but there are a few GAWK'isms that shorten things a bit.

First, doing the "split" and "sub" calls in the test condition section means not having to use `;` characters.

Then taking advantage of the fact that uninitialized variables are treating like empty strings (when strings are called for), means it’s possible to use `a` instead of `""` and save one character.

The code also relies on the fact that when a uninitialized variable is treated like an integer, its value is 0

# Answer
> 6 votes
# 05AB1E, 16 bytes

```
|ʒ#ć'-¡ŸsR`н¢å}g

```

Try it online!

This is technically a character counter with a twist!

*-2 bytes thanks to ovs!*

At the time of writing, this answer is winning!

# How?

```
|                     # Convert the input into a list
 ʒ#                   # For each element in each line
   ć'-¡Ÿ              # Parse the range
        sR`           # Unpack the string and character
           н          # Parse the character
            ¢å        # Is the number of occurences in the range?
              }g      # How many lines have this condition?

```

# Answer
> 5 votes
# Jelly, ~~25~~ 19 bytes=chars

```
ḲµḢ⁾-ryViḢċ@¥/
ỴÇƇL

```

Try it online!

```
ḲµḢ⁾-ryViḢċ@¥/    Monadic helper link:
 µ                Consider
Ḳ                 the argument split on spaces.
  Ḣ               Pop the first element,
   ⁾-ry           replace the hyphen with "r" (inclusive range dyad),
       V          and eval.
        i         Find the index (or 0 if not found) in that range of
          ċ       the number of occurrences of
         Ḣ @      the first element of
            ¥/    the first remaining element of the split input in the second.

ỴÇƇL              Main link:
Ỵ                 split on newlines,
  Ƈ               filter by
 Ç                helper link (is the password valid?),
   L              length.

```

# Answer
> 5 votes
# Ruby, 80 74 characters, thanks to pppery

```
p $<.count{|l|a,b,c,s=l.split /[- ]/;a.to_i>=x=s.count(c[0])and x<=b.to_i}

```

Try it online

or if you dislike "magic" numbers:

```
p $<.count{|l|a,b,c,s,s=l.split /[- :]/;a.to_i>=x=s.count(c)and x<=b.to_i}

```

Try it online

# Answer
> 4 votes
# Python 3, 121 characters

```
def f(x,z=0):
 for l in x.splitlines():n,p=l.split(":");m,o=n.split("-");z+=int(m)<=p.count(o[-1])<=int(o[:-1])
 return z

```

Try it online!

# Answer
> 4 votes
# Oracle SQL, 231/186/117 bytes

```
with p as (select regexp_substr(s,'\d+') l,
regexp_substr(s,'\d+',1,2) u,
regexp_substr(s,'\w+',1,3) j,
regexp_substr(s,'\w+',1,4) p from test)
select count(*) from p where length(regexp_replace(p,'[^'||j||']','')) between l and u;

```

Try it online!

The obvious shortening takes it down to 186 bytes with a marked decrease in legibility.

```
select count(*) from test where length(regexp_replace(regexp_substr(s,'\w+',1,4),'[^'||regexp_substr(s,'\w+',1,3)||']','')) between regexp_substr(s,'\d+') and regexp_substr(s,'\d+',1,2);

```

Using `regexp_replace` to construct a regular expression to match the full input takes us down to 117 bytes.

```
select count(*) from test where regexp_like(s,regexp_replace(s,'(\w+)-(\w+) (\w): \w+',':[^\3]+(\3[^\3]*){\1,\2}$'));

```

The regular expression is:

```
: start at the colon
[^\3]+ read in the space and any other characters not the key
(\3[^\3]*) the key character followed by any number of non-key characters
{\1,\2} exactly lowerbound-upperbound times
$ end of string

```

# Answer
> 3 votes
# Ruby, ~~138~~ 130 characters, thanks to pppery

```
n=0;$<.readlines.each{|s|i,a,c,p=s.match(/(\d+)-(\d+) (.): (.*)/).to_a.drop(1);m=p.count(c);n+=1 if (m>=i.to_i&&m<=a.to_i)};puts n

```

Try it online

# Answer
> 3 votes
# Scala, 84 characters

```
_ split "\n"count{case s"$m-$n $c:$s"=>val o=s.count(c(0)==_);m.toInt<=o&o<=n.toInt}

```

Try it online

# Answer
> 3 votes
# JavaScript (ES6),  ~~89 ... 84~~  83 bytes / chars

```
s=>s[S='split']`
`.map(s=>t+=([m,M,c]=s[S](/\W/),k=s[S](c).length-2)>=m&k<=M,t=0)|t

```

Try it online!

### Commented

```
s =>                  // s = input string
s[S = 'split']`\n`    // split it on line-feeds
.map(s =>             // for each line s:
  t +=                //   update t:
    ( [m, M, c] =     //     [m, M, c] = [min, max, char] obtained by ...
      s[S](/\W/),     //     ... splitting s on non-alphanumerical characters
      k = s[S](c)     //     k = number of occurrences of c in s, minus 1
          .length - 2 //         (so we have to subtract 2 from the length of the array)
    ) >= m &          //     increment t if k is greater than or equal to m
    k <= M,           //     and less than or equal to M
  t = 0               //   starting with t = 0
) | t                 // end of map(); return t

```

# Answer
> 3 votes
# Retina, 43 bytes

```
%~`(.+)-(.+) (.): .+
[^$3]¶¶^$3$3{$1,$2}$
1

```

Try it online! Explanation:

```
%`

```

Loop over each line of the input.

```
(.+)-(.+) (.): .+
[^$3]¶¶^$3$3{$1,$2}$

```

Write a script that deletes everything other than the desired character, then matches the required range of characters, plus one (for the character itself).

```
~`

```

Evaluate that script on the line of input.

```
1

```

Sum the number of successful matches.

As an example, the script for the line `6-10 s: sszlkrsssss` is

```
[^s]

^ss{6,10}$

```

The first stage deletes everything except `s`, leaving `ssssssss` (1 for the `s` itself and 7 occurrences in the string). The second stage then checks that there are between 7 and 11 occurrences.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 90 characters

```
Count[FromDigits/@(#≤{#5~StringCount~#3}≤#2)&@@@S[#~S~"
","-"|" "|":"],1>0]&
S=StringSplit

```

Try it online!

# Answer
> 3 votes
# Pip `-r`, 21 characters

```
$+Y{a<=cNd<=b}MUg@+XW

```

Try it online!

### Explanation

```
$+Y{a<=cNd<=b}MUg@+XW
                       g is lines of stdin (due to -r flag); XW is builtin for regex \w
                  +XW  Construct the regex \w+
                g@     Get all matches in each element of list g: this converts each line
                        into a list containing the two numbers, the char, and the password
   {         }MU       Map this function, calling it on the four elements of each sublist:
    a                   The first number
     <=                 is less than or equal to
       cNd              the number of occurrences of the char in the password
          <=            which is less than or equal to
            b           the second number
                       The results are 1 if the condition is true, 0 otherwise
$+Y                    Fold the list of 1s and 0s on addition (the Y is just there to make
                        this operation lower precedence than MU)

```

---

As a bonus, here's a **29-character** port of Sisyphus' elegant Ruby solution using regex match variables:

```
{a~XI.s.CXX$`<=$1N$'<=-$0}MSg

```

Try it online!

Explanation:

```
{                        }MSg  Map this function to each line and sum the results:
   XI.s.CXX                     Construct this regex: -?\d+ (.)
 a~                             Find the first match in the line (everything from the
                                 hyphen through the char)
           $`                   The part left of the match (the first number)
             <=                 is less than or equal to
                 N              the number of occurrences of
               $1               capture group 1 (the char) in
                  $'            the part right of the match (the password, with an extra
                                 colon and space that don't matter)
                    <=          which is less than or equal to
                      -$0       the whole match, treated as a number, negated (the
                                 second number)

```

# Answer
> 2 votes
# Charcoal, 35 bytes

```
ＷΦ⪪Ｓ κ«≔Ｉ⪪§ι⁰-θ⊞υ№…·⌊θ⌈θ№⊟ι§⊟ι⁰»ＩΣυ

```

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

```
ＷΦ⪪Ｓ κ«

```

Loop over the input, splitting each line on spaces.

```
≔Ｉ⪪§ι⁰-θ

```

Extract the numbers from the first part of the string.

```
⊞υ№…·⌊θ⌈θ№⊟ι§⊟ι⁰

```

Create a range across those numbers and check whether the count of characters in the string occurs within the range.

```
»ＩΣυ

```

Output the total number of matches.

# Answer
> 2 votes
# Perl 5, 56 characters

Run with `perl -nE`. Takes input in the usual Perl ways: as standard input or as filenames passed as command line args.

```
/-(.+) (.):/;{$x=()=/$2/g};$i++if$x>$`&&$x-2<$1}{say$i+0

```

Gotta love those arcane regex semantics.

Explanation:

```
/-(.+) (.):/

```

First, we get the minimum, maximum, and character to match into the `$``, `$1`, and `$2` variables, respectively (`$`` is the "everything before the match" string, which is our first number).

```
{$x=()=/$2/g}

```

Then we see how many `$2` there are in the string and store that number in `$x`. Note that we'll overcount by one, since we're also counting the instance before the colon. The `=()=` is creatively called the "Saturn" operator and is one of the Perl "secret" operators. We wrap this in a block so that the regex variables (which are block-local for some reason) don't overwrite our `$1` and `$2` from the first match.

```
$i++if$x>$`&&$x-2<$1

```

Increment the variable `$i` if the number of matches (correcting for our earlier overcount) is between the min and the max. It's times like these that make me really wish Perl had Python's transitive comparison operators.

```
}{say$i+0

```

Another secret operator to take us to the end of the script, then we print the number of correct lines. We throw `+0` at the end because `$i` starts out undefined, and we need to print zero if there were no matches at all.

You can learn about the secret operators I used here, and several others, on the relevant CPAN page.

# Answer
> 2 votes
# Java (JDK), ~~281~~ ~~271~~ ~~249~~ 244 bytes

```
int c,n,i,j;for(String[]x=s[i=n=c=0].split("\n"),a,r;i<x.length;n+=Integer.parseInt(r[0])>c|Integer.parseInt(r[1])<c?0:1)for(r=(a=x[i++].split(" "))[j=c=0].split("-");j<a[2].length();)if(a[1].charAt(0)==a[2].charAt(j++))c++;System.out.print(n);

```

Try it online!

Edit: Thanks @ceilingcat for -11 bytes.

# Answer
> 2 votes
# C (gcc), ~~130~~ ~~128~~ 127 bytes

-1 byte thanks to ceilingat

```
m,M,l,d,t;f(S,n,c)char**S,c;{for(t=n;n--;t-=d<m|d>M,S++)for(d=!sscanf(*S,"%d-%d %c: %n",&m,&M,&c,&l);l[*S];)d+=l++[*S]==c;n=t;}

```

Try it online!

# Answer
> 1 votes
# Javascript, 106 chars

```
s=>eval(s.replace(/(.+)-(.+)(.): (.+)/g,(m,l,r,c,p)=>"+"+eval(`p.replace(/${c}/g,x=>--l*--r),l>=0&r>=0`)))

```

Test:

```
f=s=>eval(s.replace(/(.+)-(.+)(.): (.+)/g,(m,l,r,c,p)=>"+"+eval(`p.replace(/${c}/g,x=>--l*--r),l>=0&r>=0`)))

console.log(f(`1-5 c: abcdefg
5-12 j: abcdefg
1-5 z: zzzzzzzz
3-3 h: hahaha
4-20 e: egejeqwee`))

console.log(f(`3-8 j: ksjjtvnjbjppjjjl
6-10 s: sszlkrsssss
1-4 z: znzfpz
7-11 m: dfkcbxmxmnmmtvmtdn
6-9 h: hlhhkhhhq
8-9 p: ppppppppvp
6-9 c: cccgccccmcch
5-8 g: bgkggjgtvggn
3-4 x: xxhk
10-12 h: hhhhhhhhhlhhhhdnh
5-6 j: zjjsjn
9-14 s: ksclwttsmpjtds
6-7 l: gtdcblql
1-4 d: dkndjkcd
1-6 k: kkkkkckmc
10-12 x: xxxxxxxxxrxl
2-5 v: fxdjtv
3-5 q: pjmkqdmqnzqppr
5-8 t: xtgtgtcht
6-11 j: nftjzjmfljqjrc
6-9 g: rskgggmgmwjggggvgb
11-12 v: vkvdmvdvvvdv
15-16 z: zzzzzzzzzzzzzzgxz
13-17 v: vvvvvvvvvvvvvvvvnv
9-14 j: clrfkrwhjtvzvqqj
1-12 l: lljljznslllffhblz
4-7 c: cccgcxclc
6-11 z: tbxqrzzbwbr
18-19 m: jmbmmqmshmczlphfgmf
1-5 s: ssvsq
4-5 k: kkkkw
4-7 f: fcqffxff
3-8 f: fffzthzf
9-12 v: vvvvvvvvvvvmvv
14-17 f: ftflcfffjtjrvfkffmvf
4-7 n: pnmnxnqqjp
6-7 r: rrrkrmr
4-13 k: drckdzxrsmzrkqckn
5-14 t: dttttttttttttt
13-14 v: vvvvfvvvvvvvvvv
7-12 j: jrljwnctjqjjxj
6-7 v: wchfzvm
1-8 d: dddddddzd
10-12 g: gvvzrglgrgggggggggg`))
```

# Answer
> 1 votes
# SmileBASIC 4, 198 characters

```
@0:S=INSTR(I$[0]," ")C=I$[0][S+1]N=S+3
REPEAT N=INSTR(N+1,I$[0],C)INC M,N>0UNTIL N<0
H=INSTR(I$[0],"-")
U=VAL(LEFT$(I$[0],H))
V=VAL(MID$(I$[0],H+1,S-H-1))
INC O,M>=U&&M<=V:IF LEN(I$)GOTO@0'newline char here
?O

```

---

Receives input through I$\[\]. Simply parses the min-max char information and searches through each string of the string array, doing a tally and summing up the number of true hits.

---

Single-line (ish) version (same number of characters):

```
@0:S=INSTR(I$[0]," ")C=I$[0][S+1]N=S+3REPEAT N=INSTR(N+1,I$[0],C)INC M,N>0UNTIL N<0H=INSTR(I$[0],"-")U=VAL(LEFT$(I$[0],H))V=VAL(MID$(I$[0],H+1,S-H-1))INC O,M>=U&&M<=V:IF LEN(I$)GOTO@0
?O

```

# Answer
> 0 votes
# Japt `-x`, 20 bytes

Takes input as an array of lines.

```
m¸£OvXÎr-'õ)øXÌèXÅÎÎ

```

Try it

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


title: This question has its ups and downs

text:
# Question
Title: This question has its ups and downs
Input will consist of the following characters:

* `^`: Go up one
* `v`: Go down one
* or `k`: Go up two
* or `j`: Go down two

For example, the following input:

```
^^▲^v▼▲^^v

```

would produce the following output:

```
        ^
   ^   ^ v
  ▲ v ▲

 ^   ▼
^

```

Escape sequences that move the cursor such as `\e[B` are not allowed. You must produce the output using spaces and newlines.

Here are a few more test cases.

```
▲v^v^v^v^v^v^v^v▲

```

```
                ▲
▲ ^ ^ ^ ^ ^ ^ ^
 v v v v v v v v

```

```
^^^^^^^▲▲▲▼▼▼vvvvvv

```

```
         ▲

        ▲ ▼

       ▲   ▼

      ^     ▼
     ^       v
    ^         v
   ^           v
  ^             v
 ^               v
^                 v

```

```
v^^vv^^vvv^v^v^^^vvvv^^v^^vv

```

```
  ^   ^         ^
 ^ v ^ v       ^ v       ^
v   v   v ^ ^ ^   v   ^ ^ v
         v v v     v ^ v   v
                    v

```

# Answer
# Pyth, 27 bytes

```
jCm.<.[*5lzd\ =+Ztx"v ^k"dz

```

Try it online: Demonstration or Test Suite

I use `k` and `j` instead of  and . There are lots of leading and trailing empty lines. You have to search quite a bit to find the image. Here's a **34 byte** version, that removes all leading and trailing empty lines.

```
j.sCm.<.[*5lzd\ =+Ztx"v ^k"dz]*lzd

```

Try it online: Demonstration or Test Suite

### Explanation:

```
jCm.<.[*5lzd\ =+Ztx"v ^k"dz  implicit: Z = 0
  m                       z  map each char d from input string z to:
                  x"v ^k"d     find d in the string "v ^k", -1 if not found
                 t             -1, that gives -2 for j, -1 for v, 1 for ^ and 2 for k
              =+Z              add this number to Z
     .[*5lzd\                  append spaces on the left and on the right of d,
                               creating a 5*len(input_string) long string
   .<           Z              rotate this string to the left by Z chars
jC                           transpose and print on lines

```
> 9 votes

# Answer
# Unreadable, ~~2199~~ ~~2145~~ ~~2134~~ ~~2104~~ ~~2087~~ 2084 bytes

Supports both `k`/`j` as well as / syntax.

In good Unreadable tradition, here is the program formatted in proportional font, to obfuscate the distinction between apostrophes and double-quotes:

> '""""""'""""""""'"""'""'""'""'""'"""'"""""'""""""'""'""'""'""'"""'""'""""""'""""""'""""""""'"""'""'""'"""""""'""""""""'"""'""""""""""'""""'""""'""""'""""'""""'""""""'""'""'""'""'""'"""'""'"""'""""""'""'""'""'""'"""'"""""""""'"""""'""""""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'"""'""""'""""""'""'""'""'""'""'"""'"""""""""'"""""""'""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'""'"""'""'""'"""'""""""'"""'"""""""""'"""""""'"""'""'"""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'"""'"""""""""'""'"""""""'"""'"""""""""'""'""'""'"""""""'"""'"""'""'""'"""'""'"""'"""""""""'"""""""'""'""'""'""'""'"""'"""'""'""'"""'""""""'"""'"""""""""'"""""""'"""'"""""""""'""'""'"""""""'"""'"""""""""'""'""'""'""'"""""""'"""'"""'""'""'"""'""'"""'"""""""""'"""""""'""'""'""'""'""'"""'""'""'"""'"""'"""""'""""""'""'""'""'""'"""'""""""""'"""""""'""'""'""'""'"""'""""'""""'"""""""""'"""""""'""'""'""'"""'""""""'""'""'""'"""'""'"""""""'""'""'""'"""'"""'""""""'""'""'"""'""'"""""""'""'""'"""'""""""'""'"""'""""""""'"""""""'""'"""'"""""'""""""'"""'""""""""'"""""""'"""'""""'""""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'"""""""""'"""""""'""'""'"""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'"""'""""""'""'"""'""'"""""""'""'"""'""""""'""'"""""""'""""""""'"""'""'"""""""'""'"""'"""""'""""""""'""""""'""'""'""'"""'""'"""""""'""'""'""'"""'""""'""""""'""'"""'""""""""'"""""""'""'"""'""""""'""'""'"""'""'"""""""'""'""'"""'"""""'""""""""'""""""'""'"""'""'"""""""'""'"""'""""'""""""'"""'""'"""""""'""""""""'"""'"""""'""""""""'""""""""'""""""'"""'""""""""'""""""""'"""""""'"""'""""""'"""""""'"""'""'"""""""'"""""""'"""'"""""'""'""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""'""""'""""'""""""'""'"""'""'""'""'""'""'""""""'"""'""'""'""'""'"""'"""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""'""""""""'"""'""""""""'""""""""'"""""""'""""""""'"""'"'"""""""""'""""""'""'""""""'"""'""'""'"""""""'"""'""""""""'"""""""'""'"""""""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'"""'"""""""'"""""""'"""'""""""'""""""""'"""'""'""'"""""""'"""'"'"""""""'""'"""

This was an amazing challenge. Thank you for posting!

## Explanation

To get a feel for what Unreadable can and can’t do, imagine Brainfuck with an infinite tape in both directions, but instead of a memory pointer moving one cell at a time, you can access any memory cell by dereferencing a pointer. This comes in quite handy in this solution, although other arithmetic operations — including modulo — have to be done by hand.

Here is the program as pseudocode with director’s commentary:

```
// Initialize memory pointer. Why 5 will be explained at the very end!
ptr = 5

// FIRST PASS:
// Read all characters from stdin, store them in memory, and also keep track of the
// current line number at each character.

// We need the +1 here so that EOF, which is -1, ends the loop. We increment ptr by 2
// because we use two memory cells for each input character: one contains the actual
// character (which we store here); the other will contain the line number at which the
// character occurs (updated at the end of this loop body).
while ch = (*(ptr += 2) = read) + 1:

    // At this point, ch will be one more than the actual value.
    // However, the most code-economical way for the following loop is to
    // decrement inside the while condition. This way we get one fewer
    // iteration than the value of ch. Thus, the +1 comes in handy.

    // We are now going to calculate modulo 4 and 5. Why? Because
    // the mod 4 and 5 values of the desired input characters are:
    //
    //  ch  %5  %4
    //  ^   1
    //  v   2
    //  k   3
    //  j   4
    //  ▲   0   2
    //  ▼   0   0
    //
    // As you can see, %5 allows us to differentiate all of them except ▲/▼,
    // so we use %4 to differentiate between those two.

    mod4 = 0      // read Update 2 to find out why mod5 = 0 is missing
    while --ch:
        mod5 = mod5 ? mod5 + 1 : -4
        mod4 = mod4 ? mod4 + 1 : -3

    // At the end of this loop, the value of mod5 is ch % 5, except that it
    // uses negative numbers: -4 instead of 1, -3 instead of 2, etc. up to 0.
    // Similarly, mod4 is ch % 4 with negative numbers.

    // How many lines do we need to go up or down?
    // We deliberately store a value 1 higher here, which serves two purposes.
    // One, as already stated, while loops are shorter in code if the decrement
    // happens inside the while condition. Secondly, the number 1 ('""") is
    // much shorter than 0 ('""""""""'""").
    up = (mod5 ? mod5+1 ? mod5+3 ? 1 : 3 : 2 : mod4 ? 3 : 1)
    dn = (mod5 ? mod5+2 ? mod5+4 ? 1 : 3 : 2 : mod4 ? 1 : 3)

    // As an aside, here’s the reason I made the modulos negative. The -1 instruction
    // is much longer than the +1 instruction. In the above while loop, we only have
    // two negative numbers (-3 and -4). If they were positive, then the conditions in
    // the above ternaries, such as mod5+3, would have to be mod5-3 etc. instead. There
    // are many more of those, so the code would be longer.

    // Update the line numbers. The variables updated here are:
    // curLine = current line number (initially 0)
    // minLine = smallest linenum so far, relative to curLine (always non-positive)
    // maxLine = highest linenum so far, relative to curLine (always non-negative)
    // This way, we will know the vertical extent of our foray at the end.

    while --up:
        curLine--
        minLine ? minLine++ : no-op
        maxLine++

    while --dn:
        curLine++
        minLine--
        maxLine ? maxLine-- : no-op

    // Store the current line number in memory, but +1 (for a later while loop)
    *(ptr + 1) = curLine + 1

// At the end of this, minLine and maxLine are still relative to curLine.
// The real minimum line number is curLine + minLine.
// The real maximum line number is curLine + maxLine.
// The total number of lines to output is maxLine - minLine.

// Calculate the number of lines (into maxLine) and the real minimum
// line number (into curLine) in a single loop. Note that maxLine is
// now off by 1 because it started at 0 and thus the very line in which
// everything began was never counted.
while (++minLine) - 1:
  curLine--
  maxLine++

// Make all the row numbers in memory positive by adding curLine to all of them.
while (++curLine) - 1:
  ptr2 = ptr + 1
  while (ptr2 -= 2) - 2:    // Why -2? Read until end!
    *ptr2++

// Finally, output line by line. At each line, we go through the memory, output the
// characters whose the line number is 0, and decrement that line number. This way,
// characters “come into view” in each line by passing across the line number 0.
while (--maxLine) + 2:    // +2 because maxLine is off by 1
  ptr3 = 5
  while (ptr -= 2) - 5:
    print (*((ptr3 += 2) + 1) = *(ptr3 + 1) - 1) ? 32 : *ptr3   // 32 = space
  ptr = ptr3 + 2
  print 10  // newline

```

So much for the program logic. Now we need to **translate this to Unreadable** and use a few more interesting golfing tricks.

Variables are always dereferenced numerically in Unreadable (e.g. `a = 1` becomes something like `*(1) = 1`). Some numerical literals are longer than others; the shortest is 1, followed by 2, etc. To show just how much longer negative numbers are, here are the numbers from -1 to 7:

```
-1  '""""""""'""""""""'"""  22
 0  '""""""""'"""           13
 1  '"""                     4
 2  '""'"""                  7
 3  '""'""'"""              10
 4  '""'""'""'"""           13
 5  '""'""'""'""'"""        16
 6  '""'""'""'""'""'"""     19
 7  '""'""'""'""'""'""'"""  22

```

Clearly, we want to **allocate variable #1 to the one that occurs most frequently** in the code. In the first while loop, this is definitely `mod5`, which comes up 10 times. But we don’t need `mod5` anymore after the first while loop, so we can re-allocate the same memory location to other variables we use later on. These are `ptr2` and `ptr3`. Now the variable is referenced 21 times in total. (If you’re trying to count the number of occurrences yourself, remember to count something like `a++` twice, once for getting the value and once for setting it.)

There’s only one other variable that we can re-use; after we calculated the modulo values, `ch` is no longer needed. `up` and `dn` come up the same number of times, so either is fine. Let’s merge `ch` with `up`.

This leaves a total of 8 unique variables. We could allocate variables 0 to 7 and then start the memory block (containing the characters and line numbers) at 8. But! Since 7 is the same length in code as −1, we could as well use variables −1 to 6 and start the memory block at 7. This way, every reference to the start position of the memory block is slightly shorter in code! This leaves us with the following assignments:

```
-1    dn
 0                      ← ptr or minLine?
 1    mod5, ptr2, ptr3
 2    curLine
 3    maxLine
 4                      ← ptr or minLine?
 5    ch, up
 6    mod4
 7... [data block]

```

Now **this explains the initialization at the very top:** it’s 5 because it’s 7 (the beginning of the memory block) minus 2 (the obligatory increment in the first while condition). The same goes for the other two occurrences of 5 in the last loop.

Note that, since 0 and 4 are the same length in code, `ptr` and `minLine` could be allocated either way around. ... Or could they?

**What about the mysterious 2 in the second-last while loop?** Shouldn’t this be a 6? We only want to decrement the numbers in the data block, right? Once we reach 6, we’re outside the data block and we should stop! It would be a buffer overflow bug error failure security vulnerability!

Well, think about what happens if we don’t stop. We decrement variables 6 and 4. Variable 6 is `mod4`. That’s only used in the first while loop and no longer needed here, so no harm done. What about variable 4? What do you think, should variable 4 be `ptr` or should it be `minLine`? That’s right, `minLine` is no longer used at this point either! Thus, variable #4 is `minLine` and we can safely decrement it and do no damage!

**UPDATE 1!** Golfed from 2199 to 2145 bytes by realizing that `dn` can *also* be merged with `mod5`, even though `mod5` is still used in the calculation of the value for `dn`! New variable assignment is now:

```
 0    ptr
 1    mod5, dn, ptr2, ptr3
 2    curLine
 3    maxLine
 4    minLine
 5    ch, up
 6    mod4
 7... [data block]

```

**UPDATE 2!** Golfed from 2145 to 2134 bytes by realizing that, since `mod5` is now in the same variable as `dn`, which is counted to 0 in a while loop, `mod5` no longer needs to be explicitly initialized to 0.

**UPDATE 3!** Golfed from 2134 to 2104 bytes by realizing two things. First, although the “negative modulo” idea was worth it for `mod5`, the same reasoning does not apply to `mod4` because we never test against `mod4+2` etc. Therefore, changing `mod4 ? mod4+1 : -3` to `mod4 ? mod4-1 : 3` takes us to 2110 bytes. Second, since `mod4` is always 0 or 2, we can initialize `mod4` to 2 instead of 0 and reverse the two ternaries (`mod4 ? 3 : 1` instead of `mod4 ? 1 : 3`).

**UPDATE 4!** Golfed from 2104 to 2087 bytes by realizing that the while loop that calculates the modulo values always runs at least once, and in such a case, Unreadable allows you to re-use the last statement’s value in another expression. Thus, instead of `while --ch: [...]; up = (mod5 ? mod5+1 ? [...]` we now have `up = ((while --ch: [...]) ? mod5+1 ? [...]` (and inside that while loop, we calculate `mod4` first, so that `mod5` is the last statement).

**UPDATE 5!** Golfed from 2087 to 2084 bytes by realizing that instead of writing out the constants `32` and `10` (space and newline), I can store the number 10 in the (now unused) variable #2 (let’s call it `ten`). Instead of `ptr3 = 5` we write `ten = (ptr3 = 5) + 5`, then `32` becomes `ten+22` and `print 10` becomes `print ten`.
> 16 votes

# Answer
# CJam, 37 bytes

```
r_,2*:L3*S*f{\_iImd8-g\8>)*L+:L\t}zN*

```

This prints empty lines before and after the desired output, which has been allowed by the OP.

Try it online in the CJam interpreter.

### How it works

```
r_     e# Read a token from STDIN and push a copy.
,2*:L  e# Compute its length, double it and save it in L.
3*S*   e# Push a string of 6L spaces.
f{     e# For each character C in the input, push C and the string of spaces; then
  \    e#   Swap C with the string of spaces.
  _i   e#   Push a copy of C and cast it to integer.
  Imd  e#   Push quotient and remainder of its division by 18.
  8-g  e#   Push the sign((C%18) - 8). Gives -1 for ^ and ▲, 1 for v and ▼.
  \    e#   Swap the result with the quotient.
  8>)  e#   Push ((C/18) > 1) + 1. Gives 2 for ▲ and ▼, 1 for ^ and v.
  *    e#   Multiply both results. This pushes the correct step value.
  L+:L e#   Add the product to L, updating L.
  \t   e#   Replace the space at index L with C.
}      e# We've built the columns of the output.
z      e# Zip; transpose rows with columns.
N*     e# Join the rows, separating by linefeeds.

```
> 7 votes

# Answer
## Python 2, 102

```
s=input()
j=3*len(s)
exec"w='';i=j=j-1\nfor c in s:i-='kv_^j'.find(c)-2;w+=i and' 'or c\nprint w;"*2*j

```

Prints line by line.

Loops through characters in the input and tracks the current height. The height is updated by one of `+2, +1, -1, -2` as computed by `'kv_^j'.find(c)-2`. There's probably a mod chain that's shorter

When the current height equals the line number (which can be negative), we append the current character to the line, and otherwise append a space. Then, we print the line. Actually, it's shorter to start the height at the current line number and subtract the height changes, appending the character when the value hits `0`.

The line numbers encompass a large enough range that a sequence of up-two or down-two will stay within it. Actually, there's a good amount of excess. If we had an upper bound on the input length, it would be shorter to write, say `j=999`.

Surprisingly, `i and' 'or c` was shorter than the usual `[' ',c][i==0]`. Note that `i` can be negative, which cuts out some usual tricks.
> 3 votes

# Answer
# MATLAB, 116

```
function o=u(a)
x=0;y=1;o='';for c=a b=find(c=='j^ vk')-3;y=y+b;if y<1 o=[zeros(1-y,x);o];y=1;end
x=x+1;o(y,x)=c;end

```

It's a start. The `j` and `k` make it a pain in the neck as I can't find a way to mathematically map from `j^vk` to `[-2 -1 1 2]` and with MATLAB not recognising the Unicode (apparently both up and down have a value of 26 in MATLAB. Go figure!), there are a lot of bytes wasted doing the mapping.

By drawing inspiration from @xnors solution, the code can be reduced by another 14 characters by mapping the control character inside the for loop.

There are also many bytes wasted trying to account for if the input string sends the pattern back below the index at which it started (maybe if there was a limit on the string length I could simplify that bit).

And in its readable form:

```
function o=u(a)
%We start in the top left corner.
x=0; %Although the x coordinate is 1 less than it should be as we add one before storing the character
y=1;
o=''; %Start with a blank array
for c=a
    %Map the current character to [-2 -1 1 2] for 'j^vk' respectively.
    b=find(c=='j^ vk')-3;
    y=y+b; %Offset y by our character
    if y<1 %If it goes out of range of the array
        o=[zeros(1-y,x); o]; %Add enough extra lines to the array. This is a bit of a hack as 0 prints as a space in MATLAB.
        y=1; %Reset the y index as we have now rearranged the array
    end
    x=x+1; %Move to the next x coordinate (this is why we start at x=0
    o(y,x)=c; %Store the control character in the x'th position at the correct height.
end

```
> 2 votes

# Answer
# JavaScript (ES6), 140

Test running the snippet below in a EcmaScript 6 compliant browser (tested on Firefox) .

```
f=s=>[...s].map(c=>{for(t=r[y+=c>'▲'?2:c>'v'?-2:c>'^'?1:-1]||x;y<0;y++)r=[,...r];r[y]=t+x.slice(t.length)+c,x+=' '},y=0,r=[x=''])&&r.join`
`

// Less golfed

f=s=>(
  y=0,
  x='',
  r=[],
  [...s].forEach( c =>
    {
      y += c > '▲' ? 2 : c > 'v' ? -2 : c > '^' ? 1 : -1;
      t = r[y] || x;
      while (y < 0)
      {
        y++;
        r = [,...r]
      }
      r[y] = t + x.slice(t.length) + c;
      x += ' '
    }
  ),
  r.join`\n`
)

//Test

;[
  '^^▲^v▼▲^^v'
, '▲v^v^v^v^v^v^v^v▲'
, '^^^^^^^▲▲▲▼▼▼vvvvvv'
, 'v^^vv^^vvv^v^v^^^vvvv^^v^^vv'
].forEach(t=>document.write(`${t}<pre>${f(t)}</pre>`))
```

```
pre { border:1px solid #777 }
```
> 2 votes

# Answer
## GS2, 34 bytes

This one correctly calculates the output bounds so no excess whitespace is produced. Here's my solution in hex

```
5e 20 76 6a 05 3e 26 ea 30 e0 6d 40 28 26 cf d3
31 e9 d0 4d 42 5e e2 b1 40 2e e8 29 cf d3 5c e9
9a 54

```

A little explanation is in order. On the stack we have user input as an array of ascii codes. The program starts in a string literal because of the `05`. Here we go.

```
  5e 20 76 6a      # ascii for "^ vj"
  05               # finish string literal and push to stack
  3e               # index - find index in array or -1 if not found
  26               # decrement
ea                 # map array using block of 3 instructions (indented)

  30               # add
e0                 # create a block of 1 instruction
6d                 # scan (create running total array of array using block)
40                 # duplicate top of stack
28                 # get minimum of array
26                 # decrement
cf                 # pop from stack into register D (this is the "highest" the path goes)

  d3               # push onto stack from register D
  31               # subtract
e9                 # map array using block of 2 instructions

d0                 # push onto stack from register A (unitialized, so it contains stdin)

  4d               # itemize - make singleton array (also is single char string)
  42               # swap top two elements in stack
  5e               # rjust - right justify string
e2                 # make block from 3 instructions
b1                 # zipwith - evaluate block using parallel inputs from two arrays
40                 # duplicate top of stack

  2e               # get length of array/string
e8                 # map array using block of 1 instruction
29                 # get maximum of array
cf                 # pop from stack into register D (this is the "lowest" the path goes)

  d3               # push from register D onto stack
  5c               # ljust - left justify string
e9                 # map array using block of two instructions
9a                 # transpose array of arrays
54                 # show-lines - add a newline to end of each element in array

```

## GS2, 24 bytes

I also have a 24 byte solution that doesn't take as much care calculating output size, and ends up with extra whitespace. I prefer the one with the whitespace kept to a minimum though.

```
5e 20 76 6a 05 3e 26 ea 30 e0 6d d0 08 4d 42 d1
30 5e d1 5c 09 b1 9a 54

```
> 1 votes

# Answer
# Crayon, 13 bytes (non-competing)

```
O"^ vj"\CynIq

```

Try it online! Uses the real arrows because why not.

Non-competing because Crayon is way newer than this challenge.

### How it works

Crayon is a stack-based language designed to be killer at ASCII-art challenges. It is built around the basis of a 2-dimensional output "canvas", and a "crayon", a cursor that travels around this canvas. Anything that is sent to output is drawn on the canvas at the position of the crayon, and in the direction the crayon is facing. By default, the crayon points East (to the right).

```
O"^ v▼"\CynIq   Implicit: input string is on top of the stack
O               For each char I in the input string:
 "^ v▼"          Push this string.
       \         Swap the top two items (so I is on top).
        C        Take the index of I in the string.
                 This returns 3 for ▼, 2 for v, 0 for ^, and -1 for ▲.
         y       Move the crayon by this number of spaces on the Y-axis (south).
          n      Move the crayon one position north.
                 The crayon has now been translated 2 positions south for ▼,
                 1 south for v, 1 north for ^, and 2 north for ▲.
           Iq    Draw I at the crayon. This automatically moves the crayon forward
                 by the length of I, which is 1 in this case.

```
> 1 votes

# Answer
# Husk, 30 bytes

```
↔T' z:mR' λm+a▼¹)∫m-2m€"v ^▲"¹

```

Try it online! or Verify all tests

Uses a few ideas from the Pyth answer, and the lambda can be shortened.

Since  and  are in Husk's codepage, you can see the testcases in their full glory!

## Explanation

```
↔T' z:mR' λm+a▼¹)∫m-2m€"v ^▲"¹
                     m€"v ^▲"  get the indices of each char in the string
                  m-2          subtract 2 from each
                 ∫             cumulative sum
          λm+a▼¹)              add abs(minimum) to each
      mR'                      map each n to n spaces
    z:                         join the spaces with the input
 T'                            Transpose. padding with spaces
↔                              reverse

```
> 1 votes

# Answer
# pb \- 136 bytes

```
^w[B!0]{>}v[3*X]<[X]<b[1]^[Y]^>w[B!0]{t[B]<vw[B=0]{v}>w[T=107]{^^b[T]t[0]}w[T=94]{^b[T]t[0]}w[T=118]{vb[T]t[0]}w[T!0]{vvb[T]t[0]}^[Y]^>}

```

Uses `k` and `j` instead of  and .

A couple of notes:

* `Escape sequences that move the cursor such as \e[B are not allowed. You must produce the output using spaces and newlines.` I do follow this rule! pb uses the concept of a "brush" to output characters. The brush moves around the "canvas" and can print a character immediately below it. However, the actual implementation prints the character using spaces and newlines.
* I wasn't going to bother with this challenge even though I thought it would be fun with pb until I saw the ruling that `You are allowed trailing spaces and/or empty lines`. This is for a couple of reasons:
    + pb can't *not* have trailing spaces. It always produces rectangular output, padding with spaces if necessary.
    + This program produces a lot of empty lines. It doesn't know how tall the output is going to be when it starts making it, so for an input of length `n` it starts at `Y=3n+1`. The `-1` is because it's going down `3n` from `Y=-1`, and starting at `Y=2n-1` fails for an input of all `k`.

You can watch this program in action on YouTube! This version is slightly modified in that it only goes down to `n-1`. It works for this input, but will fail for others. It does, however, capture a lot nicer.

With comments:

```
^w[B!0]{>}             # Go to the end of the input
v[3*X]                 # Go down 3 times the current X value
<[X]<                  # Go to X=-1 (off screen, won't be printed)
b[1]                   # Leave a non-zero value to find later
^[Y]^>                 # Back to the beginning of the input
w[B!0]{                # For every byte of input:
    t[B]                 # Copy it to T
    <vw[B=0]{v}>         # Go 1 to the right of the character to the left
                         # (either the last one printed or the value at X=-1)
                         # Move the correct amount for each character and print it:
    w[T=107]{^^b[T]t[0]} # k
    w[T=94]{^b[T]t[0]}   # ^
    w[T=118]{vb[T]t[0]}  # v
    w[T!0]{vvb[T]t[0]}   # j (Every other possibility sets T to 0, so if T is not 0
                         #    it must be j. T!0 is shorter than T=106)
    ^[Y]^>               # To the next byte of input to restart the loop
}

```
> 0 votes

# Answer
# Ceylon, 447 bytes

```
import ceylon.language{o=null,v=variable,s=shared}s void y(){v L c;v L f;v L l;v Integer i=0;class L(v L?p,v L?n){s v String t="";s L u=>p else(f=p=L(o,this));s L d=>n else(l=n=L(this,o));s void a(Character c)=>t=t+" ".repeat(i-t.size)+c.string;}f=l=c=L(o,o);for(x in process.readLine()else""){switch(x)case('^'){c=c.u;}case('v'){c=c.d;}case('▲'|'k'){c=c.u.u;}case('▼'|'j'){c=c.d.d;}else{}c.a(x);i++;}print(f.t);while(f!=l){f=f.d;print(f.t);}}

```

Or with line breaks for "readability": `import ceylon.language{o=null,v=variable,s=shared}s void y(){v L c;v L f;v L l;v Integer i=0;class L(v L?p,v L?n){s v String t="";s L u=>p else(f=p=L(o,this));s L d=>n else(l=n=L(this,o));s void a(Character c)=>t=t+" ".repeat(i-t.size)+c.string;}f=l=c=L(o,o);for(x in process.readLine()else""){switch(x)case('^'){c=c.u;}case('v'){c=c.d;}case('▲'|'k'){c=c.u.u;}case('▼'|'j'){c=c.d.d;}else{}c.a(x);i++;}print(f.t);while(f!=l){f=f.d;print(f.t);}}`

This works with both the ▲/▼ and the j/k input (If we had to support just one of them, the program would be 8 bytes shorter). The last output line is empty when the starting position was on it (i.e. the first input was a  or `^` and we never got below that again later). Input which is not one of the specified characters will simply be printed as-is, without switching the line:

```
v^^vv^^vvv^v^v^^^Hellovvvv^^v^^vv

```

```
  ^   ^         ^Hello
 ^ v ^ v       ^      v       ^
v   v   v ^ ^ ^        v   ^ ^ v
         v v v          v ^ v   v
                         v

```

Here is a formatted version (753 bytes):

```
shared void y() {
    variable L c;
    variable L f;
    variable L l;
    variable Integer i = 0;
    class L(variable L? p, variable L? n) {
        shared variable String t = "";
        shared L u => p else (f = p = L(null, this));
        shared L d => n else (l = n = L(this, null));
        shared void a(Character c) => t = t + " ".repeat(i - t.size) + c.string;
    }
    f = l = c = L(null, null);
    for (x in process.readLine() else "") {
        switch (x)
        case ('^') { c = c.u; }
        case ('v') { c = c.d; }
        case ('▲' | 'k') { c = c.u.u; }
        case ('▼' | 'j') { c = c.d.d; }
        else {}
        c.a(x);
        i++;
    }
    print(f.t);
    while (f != l) {
        f = f.d;
        print(f.t);
    }
}

```

This is an almost straight-forward "object-oriented" program ... the (local) class `L` (line buffer) stores a line of text (in `t`), as well as (nullable) pointers to the next (`n`) and previous (`p`) line. The (not nullable) attributes `u` (for up) and `d` (for down) initialize those if needed (with a reverse pointer to itself), and in this case also keep track of the first and last line overall (in the `f` and `l` variables).

The `a` (append) method appends a character to this line, including some spaces eventually necessary.

`c` is the current line. We parse the input string (using `readLine` as the input should be on one line) using a switch statement which updates the current line, and then calls the append method.

After parsing is done, we iterate over the lines from the first to the last, printing each of them. (This destroys the `f` pointer, if it were needed afterwards, we should have used a separate variable for this.)

Some used tricks for golfing:

* Some stuff which in other languages would be keywords are actually just identifiers in the `ceylon.language` package, and can be renamed with an alias import – we used this for the annotations `shared` (used 5×) and `variable` (used 6×), as well as for the object `null` (used 4×):

```
import ceylon.language{o=null,v=variable,s=shared}

```

(Trivia: The Formatter in the Ceylon IDE formats some built-in language annotations, between them `variable` and `shared`, by putting them in the same line as the annotated declaration, contrasted to custom annotations, which are put on a separate line above the declaration. This makes the formatted version of the golfed program unreadable, therefore I changed the alias-imports back for this version.)

`this`, `void`, `case`, `else` are actual keywords and cannot be renamed this way, and `Integer`, `String` and `Character` appear just once each, so there is nothing to be gained by importing.
* Originally I also had a separate ScreenBuffer class (which kept track of the linked list of line buffers, the current index, and so on), but as there was only ever one object of it, it was optimized away.
* That Screenbuffer class also had `up` and `down` methods, which were called from the parser (and just did `currentLine = currentLine.up` respectively `currentLine = currentLine.down`). It showed that directly doing this in the parser's switch is shorter. It also allowed to write `currentLine = currentLine.up.up` (which later became `c = c.u.u`) instead of `currentLine = currentLine.up;currentLine = currentLine.up`.
* Originally we did pass the current index as an argument into the append method (and even to the parser from the loop) – having it a variable in the containing function is shorter.
* Originally my printAll method used the current pointer and moved it first up until the current line was empty, and then down while printing each line. This broke when using ▲ and ▼ to jump over lines, so we had to explicitly append something in those jumped lines instead. Keeping track of first/last line proved easier (though it made it necessary to use two print statements, because there is no do-while-loop in Ceylon).
* Originally I had something like this:

```
  String? input = process.readLine();
  if(exists input) {
     for(x in input) {
         ...
     }
  }

```

`process.readLine` returns `null` if there is no line which can be read (because the input has been closed), and the Ceylon compiler requires me to checkfor that before I access `input`. As in this case I want to do nothing, I can equivalently use the `else` operator which returns its first argument if not null, and otherwise its second argument, saving the variable and the if-statement. (This also would allow us to encode a default input for testing: `for (x in process.readLine() else "^^▲^v▼▲^^v") {`)
> 0 votes

# Answer
# JavaScript (ES6), 228 bytes

```
E=(r,p=(' '[M='repeat'](Z=r.length)+',')[M](Z*4),i=Z*2,k=0)=>Z>k?E(r,(p.split(',').map((o,q)=>q==i?o.slice(0,k)+r[k]+o.slice(k++):o)).join`,`,i+(H={'^':-1,k:-2,j:2,v:1})[r[k]],k):p.split(',').join`
`.replace(/\s+\n$|^\s+\n/g,'')

```

Well, here is a (rather long) recursive solution that passes all of the test cases given. It was a nice challenge. This uses `k` and `j` in place of  and .

## Test Snippet

Although the submission itself can only handle `k,j`, the following snippet can handle both `k,j` and `▼,▲`.

```
E=(r,p=(' '[M='repeat'](Z=r.length)+',')[M](Z*4),i=Z*2,k=0)=>Z>k?E(r,(p.split(',').map((o,q)=>q==i?o.slice(0,k)+r[k]+o.slice(k++):o)).join`,`,i+(H={'^':-1,k:-2,j:2,v:1})[r[k]],k):p.split(',').join`
`.replace(/\s+\n$|^\s+\n/g,'')
```

```
Input: <input type="text" oninput=o.textContent=E(this.value.replace(/▲/g,'k').replace(/▼/g,'j'))></input>
<pre id='o'></pre>
```
> 0 votes

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