title: Make a slow error quine maker!

text:
# Question
Title: Make a slow error quine maker!
As part of his answer to *Make an Error Quine!*, @Falko proposed the following algorithm:

> ## How to create your own solution in 2 minutes?
>
> 1. Open a new file in an IDE of your choice.
> 2. Bang your head onto the keyboard in front of you.
> 3. Compile.
> 4. Replace the code with the compiler error message.
> 5. Repeat steps 3 and 4 until the code converges.
>
> I bet such a procedure terminates pretty quickly in most cases!

### Task

Your task is to prove him wrong.

Write a full program that satisfies the following:

1. When compiled or interpreted, it produces an error message that, when compiled or interpreted in turn, also results in an error message.
2. Repeating step 1 over and over again will eventually encounter a fixed point, i.e., an error quine.

### Additional rules

* The final error message must have a positive length. However, the previous error messages and the original source code may be empty.
* The original source code's length may not exceed 1024 bytes.
* Neither the original code or the code generated in any of the steps may produce non-error output.

The output has to be clearly identifiable as an error message, which has to be generated by the compiler/interpreter due to a syntax error, runtime error, undefined reference, etc.
* Your program may not receive any input or require any flags to produce the loop.
* Your program may rely on a specific implementation of its language or version thereof.

### Scoring

Your score is the **finite** number of steps your source code requires before producing an error quine. The submission with the highest score wins.

The length of the original source code will be used as tie breaker. Shorter is better.

### Example

In Chicken, the program

generates the following error message:

```
TypeError: Cannot read property 'NaN' of undefined

```

If this error message is, in turn, interpreted, it produces the error message

```
Error on line 1: expected 'chicken'

```

which, if interpreted in turn, produces itself.

Thus, the score of the empty Chicken program is 2.

### Counterexample

The PHP code

```
ab<?=c

```

generates the error message

```
PHP Parse error:  syntax error, unexpected '?' in Command line code on line 1

```

which produces itself when interpreted.

However, the second source code prints the message to STDOUT, making this sequence invalid.

# Answer
> 41 votes
# Bash, 9223372036854775810

Inspired by Doorknob's answer.

```
a='"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #"'
i=2**63
eval $a

```

It should be run with `bash < file.sh`, or use the same file name for each program, to get rid of the different file names in the error messages.

The first few errors are (with `LANG=C`):

```
bash: line 3: 2>/dev/null;if(((i=9223372036854775807)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

```

```
bash: line 1: 2>/dev/null;if(((i=9223372036854775806)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

```

```
bash: line 1: 2>/dev/null;if(((i=9223372036854775805)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

```

And finally:

```
bash: line 1: 2>/dev/null;if(((i=0)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

```

```
bash: line 1: 1: command not found

```

```
bash: line 1: bash:: command not found

```

which is an error quine.

# Answer
> 17 votes
# Pip 0.15.05.29, over 10100,000

*Technically not valid* because it requires the `-w` flag for warning output. That being said, Pip by design doesn't display any runtime errors unless they actually crash the program (infinite recursion, e.g.); the problems with this code are things that other languages would definitely complain about.

```
i:5**6**7d:"i:1d: Ssi?dRo--iRsRPda"Ssi?dRo--iRsRPda

```

The exact number of steps depends only on the value assigned to `i`, so it could be arbitrarily large (until the Python interpreter runs out of memory). Also, it would take longer than the age of the universe to complete the above sequence. (The question *did* specify "slow"!)

**Explanation:**

It took some combing through the interpreter before I found an error that would let me put arbitrary code into the warning message. After that, it was essentially modifying standard quine techniques. Example here uses an `i`-value of `5` for purposes of explanation.

```
i:5d:"i:1d: Ssi?dRo--iRsRPda"Ssi?dRo--iRsRPda

```

After setting `i`, store a string in `d` and then attempt to execute the `S`wap statement. Swap expects two variables (more accurately, lvalues). `s` is fine, but the second expression is `i?dRo--iRsRPda`. If `i` is true (nonzero, for our purposes), the ternary evaluates to `dRo--iRsRPd`, which uses `d` from earlier to form a near-quine--only with `i` decremented. This expression is not an lvalue, so Pip complains:

```
Attempting to swap non-lvalue i:4d:"i:1d: Ssi?dRo--iRsRPda"Ssi?dRo--iRsRPda

```

... which then starts the whole thing over again. (`Attempting to swap non-lvalue` is a bunch of no-ops: `At` calculates the ASCII value of `t = 10`, `n-l` subtracts newline minus each value of an empty list, and all the lowercase letters are just variables.)

The process continues in like fashion all the way down to:

```
Attempting to swap non-lvalue i:0d:"i:1d: Ssi?dRo--iRsRPda"Ssi?dRo--iRsRPda

```

When this is run, `i` is now false. The ternary expression evaluates to the else branch `a`--which is an lvalue. Thus, swap doesn't complain anymore. Instead, we get:

```
Referencing uninitialized variable a

```

And upon running this, at last, we have an actual syntax error:

```
R is not a unary operator
Fatal error while parsing, execution aborted.

```

... at which point, since the "program" starts with `R`, Pip will continue complaining that `R` is not a unary operator forever.

---

The best solution that doesn't use `-w` is of length 3:

```
$~

While scanning, ignored unrecognized character: '~'
Missing operator for $ meta-operator? Got None instead
Fatal error while parsing, execution aborted.

Missing operator for $ meta-operator? Got m instead
Fatal error while parsing, execution aborted.

M is not a unary operator
Fatal error while parsing, execution aborted.

```

# Answer
> 15 votes
# Julia, 3

A simple one just to get the ball rolling...

Initial program:

```
inquisition

```

Error 1:

```
inquisition not defined

```

It may not be defined, but if it's *Spanish*, it's also unexpected. Nobody expects the Spanish Inquisition.

Error 2:

```
syntax: extra token "not" after end of expression

```

Error 3:

```
syntax: extra token "token" after end of expression

```

The third error message, when submitted as a program, produces that same error, hence the score of 3.

Work in progress! Surely I can do better than 3.

# Answer
> 9 votes
# R, 5

Initial program:

```
1i*"5"

```

Error 1:

```
Error in (0+1i) * "5" : non-numeric argument to binary operator

```

Error 2:

```
Error: unexpected 'in' in "Error in"

```

Error 3:

```
Error: unexpected string constant in "Error 'in'"

```

Error 4:

```
Error: unexpected symbol in "Error: unexpected string"

```

Error 5 (Quine):

```
Error: unexpected symbol in "Error: unexpected symbol"

```

# Answer
> 7 votes
# Bash, 3

```
cp

```

Very rudimentary shell script to test it:

```
llama@llama:~$ s=$(bash -c 'cp' 2>&1); olds=asdf; while [ "$s" != "$olds" ]; do echo $s; echo '-----'; olds=$s; s=$(bash -c $s 2>&1); done
cp: missing file operand
Try 'cp --help' for more information.
-----
bash: cp:: command not found
bash: line 1: Try: command not found
-----
bash: bash:: command not found
bash: line 1: bash:: command not found
-----

```

# Answer
> 6 votes
# Ruby, 5

### Initial Program

```
q

```

### 1

```
undefined local variable or method `q' for #<Context:0x00000001045d70>
(repl):1:in `initialize'

```

### 2

```
(repl):2: syntax error, unexpected tIDENTIFIER, expecting end-of-input
(repl):1:in `initialize'
                       ^

```

### 3

```
(repl):1: syntax error, unexpected ':', expecting end-of-input
(repl):2: syntax error, unexpected t...
       ^

```

### 4

```
(repl):1: syntax error, unexpected ':', expecting end-of-input
(repl):1: syntax error, unexpected ':', expecting end-of-input
       ^

```

### 5 (Quine)

```
(repl):1: syntax error, unexpected ':', expecting end-of-input
(repl):1: syntax error, unexpected ':', expecting end-of-input
       ^

```

# Answer
> 6 votes
# Java, 5

These are very long... so I verified string equality using a Python script, **and** I generated this formatted post, so I wouldn't have to manually insert tabs on 400 lines.

### Initial Program

```
class Main {
  public static void main(String[] args) {
    System.out.println("hello world");
  }}
}

```

### 1

```
Main.java:5: error: class, interface, or enum expected
}
^
1 error

exit status 1

```

### 2

```
Main.java:1: error: class, interface, or enum expected
Main.java:5: error: class, interface, or enum expected
^
Main.java:1: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                         ^
Main.java:1: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                                    ^
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:5: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:1: error: = expected
Main.java:5: error: class, interface, or enum expected
                                              ^
Main.java:3: error: illegal start of type
^
^
Main.java:3: error: ';' expected
^
 ^
Main.java:6: error: ';' expected
exit status 1
    ^
Main.java:6: error: <identifier> expected
exit status 1
           ^
Main.java:6: error: reached end of file while parsing
exit status 1
             ^
10 errors

exit status 1

```

### 3

```
Main.java:1: error: class, interface, or enum expected
Main.java:1: error: class, interface, or enum expected
^
Main.java:1: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:1: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:1: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:2: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
         ^
Main.java:2: error: ';' expected
Main.java:5: error: class, interface, or enum expected
          ^
Main.java:2: error: illegal start of type
Main.java:5: error: class, interface, or enum expected
           ^
Main.java:2: error: = expected
Main.java:5: error: class, interface, or enum expected
                  ^
Main.java:2: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                         ^
Main.java:2: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                                    ^
Main.java:2: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:5: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:2: error: = expected
Main.java:5: error: class, interface, or enum expected
                                              ^
Main.java:3: error: illegal start of type
^
^
Main.java:4: error: = expected
Main.java:1: error: <identifier> expected
    ^
Main.java:4: error: <identifier> expected
Main.java:1: error: <identifier> expected
         ^
Main.java:4: error: ';' expected
Main.java:1: error: <identifier> expected
          ^
Main.java:4: error: illegal start of type
Main.java:1: error: <identifier> expected
           ^
Main.java:4: error: = expected
Main.java:1: error: <identifier> expected
                  ^
Main.java:5: error: '(' expected
Main.java:5: error: class, interface, or enum expected
    ^
Main.java:5: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
         ^
Main.java:5: error: ';' expected
Main.java:5: error: class, interface, or enum expected
          ^
Main.java:5: error: illegal start of type
Main.java:5: error: class, interface, or enum expected
           ^
Main.java:5: error: = expected
Main.java:5: error: class, interface, or enum expected
                  ^
Main.java:5: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                         ^
Main.java:5: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                                    ^
Main.java:5: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:5: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:5: error: = expected
Main.java:5: error: class, interface, or enum expected
                                              ^
Main.java:6: error: illegal start of type
                         ^
                         ^
Main.java:7: error: = expected
Main.java:1: error: <identifier> expected
    ^
Main.java:7: error: <identifier> expected
Main.java:1: error: <identifier> expected
         ^
Main.java:7: error: ';' expected
Main.java:1: error: <identifier> expected
          ^
Main.java:7: error: illegal start of type
Main.java:1: error: <identifier> expected
           ^
Main.java:7: error: = expected
Main.java:1: error: <identifier> expected
                  ^
Main.java:8: error: '(' expected
Main.java:5: error: class, interface, or enum expected
    ^
Main.java:8: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
         ^
Main.java:8: error: ';' expected
Main.java:5: error: class, interface, or enum expected
          ^
Main.java:8: error: illegal start of type
Main.java:5: error: class, interface, or enum expected
           ^
Main.java:8: error: = expected
Main.java:5: error: class, interface, or enum expected
                  ^
Main.java:8: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                         ^
Main.java:8: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                                    ^
Main.java:8: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:5: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:8: error: = expected
Main.java:5: error: class, interface, or enum expected
                                              ^
Main.java:9: error: illegal start of type
                                    ^
                                    ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
    ^
Main.java:10: error: <identifier> expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
         ^
Main.java:10: error: ';' expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
          ^
Main.java:10: error: illegal start of type
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
           ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                  ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                          ^
Main.java:10: error: illegal start of type
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                  ^
Main.java:10: error: <identifier> expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                   ^
Main.java:10: error: unclosed character literal
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                     ^
Main.java:10: error: ';' expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                       ^
Main.java:10: error: unclosed character literal
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                          ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                        ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                              ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                                         ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                                                ^
Main.java:11: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
         ^
Main.java:11: error: ';' expected
Main.java:5: error: class, interface, or enum expected
          ^
Main.java:11: error: illegal start of type
Main.java:5: error: class, interface, or enum expected
           ^
Main.java:11: error: = expected
Main.java:5: error: class, interface, or enum expected
                  ^
Main.java:11: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                         ^
Main.java:11: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                                    ^
Main.java:11: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:5: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:11: error: = expected
Main.java:5: error: class, interface, or enum expected
                                              ^
Main.java:12: error: illegal start of type
                                         ^
                                         ^
Main.java:12: error: <identifier> expected
                                         ^
                                          ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
   ^
Main.java:13: error: ';' expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
      ^
Main.java:13: error: <identifier> expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
              ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
               ^
Main.java:13: error: ';' expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
                  ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
                               ^
Main.java:13: error: unclosed character literal
  (use -source 1.4 or lower to use 'enum' as an identifier)
                                   ^
Main.java:13: error: unclosed character literal
  (use -source 1.4 or lower to use 'enum' as an identifier)
                                        ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
                                                          ^
Main.java:14: error: <identifier> expected
Main.java:1: error: = expected
         ^
Main.java:14: error: ';' expected
Main.java:1: error: = expected
          ^
Main.java:14: error: illegal start of type
Main.java:1: error: = expected
           ^
Main.java:14: error: = expected
Main.java:1: error: = expected
                  ^
Main.java:14: error: illegal start of type
Main.java:1: error: = expected
                    ^
Main.java:15: error: = expected
Main.java:5: error: class, interface, or enum expected
^
Main.java:15: error: illegal start of type
Main.java:5: error: class, interface, or enum expected
    ^
Main.java:15: error: = expected
Main.java:5: error: class, interface, or enum expected
         ^
Main.java:15: error: illegal start of type
Main.java:5: error: class, interface, or enum expected
          ^
Main.java:15: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
           ^
Main.java:15: error: = expected
Main.java:5: error: class, interface, or enum expected
             ^
Main.java:15: error: ';' expected
Main.java:5: error: class, interface, or enum expected
                  ^
Main.java:15: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                         ^
Main.java:15: error: <identifier> expected
Main.java:5: error: class, interface, or enum expected
                                    ^
Main.java:15: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:5: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:15: error: = expected
Main.java:5: error: class, interface, or enum expected
                                              ^
Main.java:16: error: illegal start of type
                                              ^
                                              ^
Main.java:17: error: = expected
Main.java:3: error: illegal start of type
    ^
Main.java:17: error: <identifier> expected
Main.java:3: error: illegal start of type
         ^
Main.java:17: error: ';' expected
Main.java:3: error: illegal start of type
          ^
Main.java:17: error: illegal start of type
Main.java:3: error: illegal start of type
           ^
Main.java:17: error: = expected
Main.java:3: error: illegal start of type
                  ^
100 errors

exit status 1

```

### 4

```
Main.java:1: error: class, interface, or enum expected
Main.java:1: error: class, interface, or enum expected
^
Main.java:1: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:1: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:1: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:2: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
         ^
Main.java:2: error: ';' expected
Main.java:1: error: class, interface, or enum expected
          ^
Main.java:2: error: illegal start of type
Main.java:1: error: class, interface, or enum expected
           ^
Main.java:2: error: = expected
Main.java:1: error: class, interface, or enum expected
                  ^
Main.java:2: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:2: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:2: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:2: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:3: error: illegal start of type
^
^
Main.java:4: error: = expected
Main.java:1: error: <identifier> expected
    ^
Main.java:4: error: <identifier> expected
Main.java:1: error: <identifier> expected
         ^
Main.java:4: error: ';' expected
Main.java:1: error: <identifier> expected
          ^
Main.java:4: error: illegal start of type
Main.java:1: error: <identifier> expected
           ^
Main.java:4: error: = expected
Main.java:1: error: <identifier> expected
                  ^
Main.java:5: error: '(' expected
Main.java:1: error: class, interface, or enum expected
    ^
Main.java:5: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
         ^
Main.java:5: error: ';' expected
Main.java:1: error: class, interface, or enum expected
          ^
Main.java:5: error: illegal start of type
Main.java:1: error: class, interface, or enum expected
           ^
Main.java:5: error: = expected
Main.java:1: error: class, interface, or enum expected
                  ^
Main.java:5: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:5: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:5: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:5: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:6: error: illegal start of type
                         ^
                         ^
Main.java:7: error: = expected
Main.java:1: error: <identifier> expected
    ^
Main.java:7: error: <identifier> expected
Main.java:1: error: <identifier> expected
         ^
Main.java:7: error: ';' expected
Main.java:1: error: <identifier> expected
          ^
Main.java:7: error: illegal start of type
Main.java:1: error: <identifier> expected
           ^
Main.java:7: error: = expected
Main.java:1: error: <identifier> expected
                  ^
Main.java:8: error: '(' expected
Main.java:1: error: class, interface, or enum expected
    ^
Main.java:8: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
         ^
Main.java:8: error: ';' expected
Main.java:1: error: class, interface, or enum expected
          ^
Main.java:8: error: illegal start of type
Main.java:1: error: class, interface, or enum expected
           ^
Main.java:8: error: = expected
Main.java:1: error: class, interface, or enum expected
                  ^
Main.java:8: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:8: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:8: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:8: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:9: error: illegal start of type
                                    ^
                                    ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
    ^
Main.java:10: error: <identifier> expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
         ^
Main.java:10: error: ';' expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
          ^
Main.java:10: error: illegal start of type
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
           ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                  ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                          ^
Main.java:10: error: illegal start of type
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                  ^
Main.java:10: error: <identifier> expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                   ^
Main.java:10: error: unclosed character literal
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                     ^
Main.java:10: error: ';' expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                       ^
Main.java:10: error: unclosed character literal
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                          ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                        ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                              ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                                         ^
Main.java:10: error: = expected
Main.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
                                                                                ^
Main.java:11: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
         ^
Main.java:11: error: ';' expected
Main.java:1: error: class, interface, or enum expected
          ^
Main.java:11: error: illegal start of type
Main.java:1: error: class, interface, or enum expected
           ^
Main.java:11: error: = expected
Main.java:1: error: class, interface, or enum expected
                  ^
Main.java:11: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:11: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:11: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:11: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:12: error: illegal start of type
                                         ^
                                         ^
Main.java:12: error: <identifier> expected
                                         ^
                                          ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
   ^
Main.java:13: error: ';' expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
      ^
Main.java:13: error: <identifier> expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
              ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
               ^
Main.java:13: error: ';' expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
                  ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
                               ^
Main.java:13: error: unclosed character literal
  (use -source 1.4 or lower to use 'enum' as an identifier)
                                   ^
Main.java:13: error: unclosed character literal
  (use -source 1.4 or lower to use 'enum' as an identifier)
                                        ^
Main.java:13: error: = expected
  (use -source 1.4 or lower to use 'enum' as an identifier)
                                                          ^
Main.java:14: error: <identifier> expected
Main.java:1: error: = expected
         ^
Main.java:14: error: ';' expected
Main.java:1: error: = expected
          ^
Main.java:14: error: illegal start of type
Main.java:1: error: = expected
           ^
Main.java:14: error: = expected
Main.java:1: error: = expected
                  ^
Main.java:14: error: illegal start of type
Main.java:1: error: = expected
                    ^
Main.java:15: error: = expected
Main.java:1: error: class, interface, or enum expected
^
Main.java:15: error: illegal start of type
Main.java:1: error: class, interface, or enum expected
    ^
Main.java:15: error: = expected
Main.java:1: error: class, interface, or enum expected
         ^
Main.java:15: error: illegal start of type
Main.java:1: error: class, interface, or enum expected
          ^
Main.java:15: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
           ^
Main.java:15: error: = expected
Main.java:1: error: class, interface, or enum expected
             ^
Main.java:15: error: ';' expected
Main.java:1: error: class, interface, or enum expected
                  ^
Main.java:15: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                         ^
Main.java:15: error: <identifier> expected
Main.java:1: error: class, interface, or enum expected
                                    ^
Main.java:15: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Main.java:1: error: class, interface, or enum expected
                                         ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Main.java:15: error: = expected
Main.java:1: error: class, interface, or enum expected
                                              ^
Main.java:16: error: illegal start of type
                                              ^
                                              ^
Main.java:17: error: = expected
Main.java:2: error: <identifier> expected
    ^
Main.java:17: error: <identifier> expected
Main.java:2: error: <identifier> expected
         ^
Main.java:17: error: ';' expected
Main.java:2: error: <identifier> expected
          ^
Main.java:17: error: illegal start of type
Main.java:2: error: <identifier> expected
           ^
Main.java:17: error: = expected
Main.java:2: error: <identifier> expected
                  ^
100 errors

exit status 1

```

### 5 (Quine) - Omitted because of post length.

**Edit:** While the initial post used repl.it for an online interpreter, you may now use https://ato.pxeger.com/ to avoid needing to create an account. The output will be different along the way, but it still reaches quine state in 5.

# Answer
> 2 votes
# Javascript, 3 error levels

This isn't that 'cleaver' or anything, but I found it rather weird...

**Error 0 (original):**

```
document.appendChild(HTMLAllCollection)

```

**Error 1:**

```
HierarchyRequestError

```

**Error 2:**

```
'HierarchyRequestError' is not defined

```

**Error 3 (quine):**

```
Excepted character ';'

```

This was all returned on Internet Explorer 11.0.9600.17416, being the errors translated to English.

---

**Printscreen:**

* The error messages are shown in Portuguese and can be easily translated to English

# Answer
> 1 votes
## Vyxal 3

Initial program

```
g

```

Error 1

```
Traceback (most recent call last):
  File "/home/Vyxal/mysite/vyxal/main.py", line 195, in execute_vyxal
    exec(code, locals() | globals())
  File "<string>", line 1, in <module>
  File "/home/Vyxal/mysite/vyxal/elements.py", line 3262, in monadic_minimum
    if len(lhs) == 0:
TypeError: object of type 'Zero' has no len()

```

Error 2

```
Traceback (most recent call last):
  File "/home/Vyxal/mysite/vyxal/main.py", line 195, in execute_vyxal
    exec(code, locals() | globals())
  File "<string>", line 141
SyntaxError: 'continue' not properly in loop

```

Error 3

```

Traceback (most recent call last):
  File "/home/Vyxal/mysite/vyxal/main.py", line 195, in execute_vyxal
    exec(code, locals() | globals())
  File "<string>", line 144
SyntaxError: 'continue' not properly in loop

```

For some reason the debug error message for the first 2 errors doesn't start with a newline, so the error is in line 141, which becomes line 144 after the newline is added, which stabilizes.

# Answer
> 1 votes
# K (ngn/k), 4

```
f:{

```

Error 1:

```
'parse
 f:{
    ^

```

Error 2:

```
'parse
     ^
      ^

```

Error 3:

```
'value
 'parse
  ^

```

Error 4:

```
'value
 'value
  ^

```

Which for some reason repeats itself.

`{` also works with the same amount of attempts needed.

# Answer
> 1 votes
## JavaScript (Google Chrome): 6 levels

Interesting how no one realized that `eval` would work! I started out with this strange script: `throw "=eval('throw 1')"`

The trick was to set the variable `Uncaught` (which is allowed), which is done to let it evaluate the rest of the code, throwing an error that will cause more errors. Finally, we predefine `eval` to shave off a few bytes for tiebreaking, and we make it even deeper. (This *can* be deeper, but this cost me too much of my insanity already!)

So, here's the resulting code and errors:

```
e=eval;throw `=e('throw "=e(\\\\"throw \`=e(\\'throw 1\\')\`\\\\")"')`
Uncaught =e('throw "=e(\\"throw `=e(\'throw 1\')`\\")"')
Uncaught =e("throw `=e('throw 1')`")
Uncaught =e('throw 1')
Uncaught 1
Uncaught SyntaxError: Unexpected number
Uncaught SyntaxError: Unexpected identifier 'SyntaxError'

```

Also, you can probably think of something simpler if the `Uncaught` part of the error message doesn't count (first line is code, rest is errors):

```
throw `throw "throw 'throw \\"throw \\\\'throw x\\\\'\\"'"`
throw "throw 'throw \"throw \\'throw x\\'\"'"
throw 'throw "throw \'throw x\'"'
throw "throw 'throw x'"
throw 'throw x'
throw x
ReferenceError: x is not defined
SyntaxError: Unexpected identifier 'ReferenceError'
SyntaxError: Unexpected identifier 'identifier'

```

Notice how `x` and `1` give the same amount of errors. I'm getting tired of the word `throw` now, so I guess I'll leave it to you to comment if you want to get this up to around 1024 bytes.

# Answer
> 1 votes
# Go, 4 errors

## Level 1

```
package main
func main() {
println(a)
}

```

Attempt This Online!

## Level 2

```
# command-line-arguments
../code.go:3:9: undefined: a

```

Attempt This Online!

## Level 3

```
../code.go:1:1: illegal character U+0023 '#'

```

Attempt This Online!

## Level 4 (loop)

```
../code.go:1:1: expected 'package', found '.'

```

Attempt This Online!

Every Go program with a compile-time error will have a score of 4, because of the first error (level 2) starting with `#`, which is an illegal character in Go code outside of strings. Then, Go will complain about not finding the `package` keyword at the start of the file, which is required for all Go source files.

# Answer
> 0 votes
## JS in Firefox 66.0; 3 error levels

Input: `6?4;`

Error #1 = Input #2: `missing : in conditional expression`

Error #2 = Input #3: `expected expression, got keyword 'in'`

Error #3 = Input #4 = Error #4: `unexpected token: identifier`

This is the highest I got.

---
Tags: code-challenge, quine, busy-beaver, error-message
---


title: Reimplement the wc coreutil

text:
# Question
Title: Reimplement the wc coreutil
This challenge is similar to this old one, but with some unclear parts of the spec hammered out and less strict I/O requirements.

---

Given an input of a string consisting of only printable ASCII and newlines, output its various metrics (byte, word, line count).

The metrics that you must output are as follows:

* Byte count. Since the input string stays within ASCII, this is also the character count.
* Word count. This is `wc`'s definition of a "word:" any sequence of non-whitespace. For example, `abc,def"ghi"` is one "word."
* Line count. This is self-explanatory. The input will always contain a trailing newline, which means line count is synonymous with "newline count." There will never be more than a single trailing newline.

The output must exactly replicate the default `wc` output (except for the file name):

```
llama@llama:~$ cat /dev/urandom | tr -cd 'A-Za-z \n' | head -90 > example.txt
llama@llama:~$ wc example.txt
  90  165 5501 example.txt

```

Note that the line count comes first, then word count, and finally byte count. Furthermore, each count must be left-padded with spaces such that they are all the same width. In the above example, `5501` is the "longest" number with 4 digits, so `165` is padded with one space and `90` with two. Finally, the numbers must all be joined into a single string with a space between each number.

Since this is , the shortest code in bytes will win.

(Oh, and by the way... you can't use the `wc` command in your answer. In case that wasn't obvious already.)

Test cases (`\n` represents a newline; you may optionally require an extra trailing newline as well):

```
"a b c d\n" -> "1 4 8"
"a b c d e f\n" -> " 1  6 12"
"  a b c d e f  \n" -> " 1  6 16"
"a\nb\nc\nd\n" -> "4 4 8"
"a\n\n\nb\nc\nd\n" -> " 6  4 10"
"abc123{}[]()...\n" -> " 1  1 16
"\n" -> "1 0 1"
"   \n" -> "1 0 4"
"\n\n\n\n\n" -> "5 0 5"
"\n\n\na\nb\n" -> "5 2 7"

```

# Answer
# Perl, 49 bytes

Added +3 for `-an0`

Input on STDIN or 1 or more filenames as arguments. Run as `perl -an0 wc.pl`

`wc.pl`:

```
/\z/g;pos=~//;printf"%@+d %@+d $`
",y/
//,~~@F

```

Explanation:

```
-n0      slurps the whole input into $_ and says we will do our own printing
-a       tells perl to split the input on whitespace into array @F
/\z/g    Matches the absolute end of the input. g modifier so the position
         is remembered in pos which will now contain the input length
pos=~//  An empy regex repeats the last succesful match, so /\z/ again.
         After that $` will contain the the number of input characters and
         the array @+ will contain the length of this number
printf   All preparation is complete, we can go print the result
"%@+d"   will become e.g. %6d if the number of characters is a number of
         length 6, so lines and words will get printed right aligned
         in a field of length 6.
$`       $` we can directly interpolate since it won't contain a %
y/\n//   Count the number of newlines in $_
~~@F     The array of words @F in scalar context gives the number of words

```
> 8 votes

# Answer
# Pyth, 21 bytes

```
jdm.[;l`lQ`ld[@bQcQ)Q

```

Test suite

Pyth has some very nice built-ins here. We start by making a list (`[`) of the newlines in the string (`@bQ`), the words in the string (`cQ)`) and the string itself (`Q`). Then, we pad (`.[`) the length of each string (`ld`) with spaces (`;` in this context) out to the length of the number of characters (`l`lQ`). Finally, join on spaces (`jd`).
> 7 votes

# Answer
# Python 2, ~~100~~ 77 bytes

This solution is a Python function that accepts a multi-line string and prints the required counts to stdout. Note that I use a format string to build a format string (which requires a `%%` to escape the first format placeholder).

*Edit: Saved 23 bytes due to print optimisations by Dennis.*

```
def d(b):c=len(b);a='%%%us'%len(`c`);print a%b.count('\n'),a%len(b.split()),c

```

Before the minifier, it looks like this:

```
def wc(text) :
    size = len(text);
    numfmt = '%%%us' % len(`size`);
    print numfmt % text.count('\n'), numfmt % len(text.split()), size

```
> 6 votes

# Answer
## Seriously, 39 bytes

```
"
 "╩╜l;$l╝@╜sl'
╜ck`#╛#"{:>%d}"%f`M' j

```

Try it online!

Explanation (newlines are replaced with `\n`):

```
"\n "╩╜l;$l╝@╜sl'\n╜ck`#╛#"{:>%d}"%f`M' j
"\n "                                      push a string containing a newline and a space
     ╩                                     push input to register 0 (we'll call it s)
      ╜l;                                  push two copies of len(s) (byte count)
         $l╝                               push len(str(len(s))) to register 1
                                            (this will serve as the field width in the output)
            @╜sl                           push word count by getting the length of the list formed by
                                            splitting s on spaces and newlines
                '\n╜c                      count newlines in input
                     k                     push stack to list
                      `#╛#"{:>%d}"%f`M     map:
                       #                     listify
                        ╛#                   push reg 1 (field width), listify
                          "{:>%d}"           push that string
                                  %          do old-style string formatting for field width
                                   f         do new-style string formatting to pad the field appropriately
                                      ' j  join on spaces

```
> 6 votes

# Answer
# POSIX awk, 79 75 67 65 bytes

```
{w+=NF;c+=length+1}END{d=length(c)"d %";printf"%"d d"d\n",NR,w,c}

```

Edit: saved 4 bytes since POSIX allows a bare `length`, saved 7 bytes by discounting the invocation part, and saved two bytes thanks to Doorknob's tip for adding `d %` to `d`.

This was originally for GNU awk, but best I can tell, it uses only POSIX awk functionality.

Better formatted:

```
gawk '{
  w += NF
  c += length($0) + 1  # length($0) misses the newline
}
END {
  d = length(c) # GNU awk's length returns the length of string representation of number
  printf "%"d"d %"d"d %d\n", NR, w, c
}'

```
> 6 votes

# Answer
# CJam, ~~31~~ 26 bytes

```
q_)/_S*S%@_]:,:s),f{Se[}S*

```

Try it online!

### How it works

```
q_                         e# Read all input from STDIN and push two copies.
  )                        e# Pop the last character (linefeed) of the second copy.
   /                       e# Split the remaining string at linefeeds.
    _                      e# Push a copy.
     S*                    e# Join the copy, separating by spaces.
       S%                  e# Split at runs of spaces.
         @_                e# Rotate the original input on top and push a copy.
           ]               e# Wrap all four items in an array.
            :,             e# Get the length of each item.
              :s           e# Cast the lengths (integers) to strings.
                )          e# Pop the last length (byte count).
                 ,         e# Get the number of digits.
                  f{Se[}   e# Left-pad all three length with spaces to that length.
                        S* e# Join, separating by spaces.

```
> 3 votes

# Answer
# AppleScript, 253 bytes

This assumes that AppleScript's text item delimiters are set to space (if I need to count the stuff to force that assumption, I'll add it).

```
set w to(display dialog""default answer"")'s text returned
set x to b(w)
set y to w's text item's number
set z to w's paragraph's number
a(x,z)&z&a(x,y)&y&" "&x
on a(x,n)
set o to" "
repeat b(x)-b(n)
set o to o&" "
end
o
end
on b(n)
count(n as text)
end
```
> 3 votes

# Answer
# Julia, ~~112~~ 81 bytes

```
f(s,n=endof,l="$(n(s))",g=r->lpad(n(split(s,r))-1,n(l)))=g(r"\n")" "g(r"\S+")" "l

```

This is a function that accepts a string and returns a string.

We save the following as function arguments:

* `n = endof` function, which gets the last index of an indexable collection (in this case is the length of the string)
* `l = "$(n(s))`, the length of the input converted to a string using interpolation
* A lambda function `g` that accepts a regular expression and returns the length - 1 of the input split on that regex, left padded with spaces to match the length of `l`.

We get the number of lines using `g(r"\n")` and the number of words using `g(r"\S+")`, then we join those together with `l` delimited by spaces.

Saved 31 bytes thanks to Dennis!
> 2 votes

# Answer
# MATL, 38 bytes

```
'\n'32cZtttnGnw-wPZvPYbnqbnvvV!3Z"vX:!

```

You can try it online! This shouldn't be so long though...

Explanation, for the calculation,

```
'\n'32cZt  %// Takes implicit input and replaces any \n with a space
tt         %// Duplicate that string twice
nGnw-w     %// Length of the string with \n's minus length with spaces to give number of \n's
PZvPYbnq   %// Take string with spaces, flip it, remove leading spaces, flip it again,
           %// split on spaces, find length and decrement for number of words
bn         %// get length of string with spaces, the number of characters

```

The last part does the output formatting

```
vvV!       %// concatenate the 3 numbers to a column vector, convert to string and transpose
3Z"v       %// make string '   ' and concatenate on the bottom of previous string
X:!        %// linearise and transpose to get correct output (impicitly printed)

```
> 2 votes

# Answer
# Jelly, 14 bytes

```
»⁶Ḳ¹ƇLṭċ⁷$;LWG

```

Try it online!

-1 thanks to Dennis.
> 2 votes

# Answer
## JavaScript (ES6), 115 bytes

```
s=>[/\n\/g,/\S+/g,/[^]/g].map(r=>l=(s.match(r)||[]).length).map(n=>(' '.repeat(99)+n).slice(-`${l}`.length)).join` `

```

Does not require any input. Formatting was painful. If there was an upper limit on the amount of padding I could reduce `(' '.repeat(99)+n)` to something shorter e.g. `` ${n}``.
> 1 votes

# Answer
## PowerShell, 140 bytes

```
param($a)$c="$((($l=($a-split"`n").Count-1),($w=($a-split"\S+").Count-1),($b=$a.length)|sort)[-1])".Length;
"{0,$c} {1,$c} {2,$c}"-f$l,$w,$b

```

(newline left in for clarity :D)

The first line takes input `$a`, and then the next part is all one statement. We're setting `$c` equal to *some-string's* `.length`. This will form our requisite padding. Inside the string is an immediate code block `$(...)`, so that code will be executed before evaluated into the string.

In the code block, we're sending three items through the `|sort` command, and then taking the biggest one `(...)[-1]`. This is where we're ensuring to get the columns to the correct width. The three items are `$l` the line count, where we `-split` on newlines, the `$w` word count, where we `-split` on whitespace, and `$b` the length.

The second line is our output using the `-f` operator (which is a pseudo-shorthand for `String.Format()`). It's another way of inserting expanded variables into strings. Here, we're saying that we want all of the output to be padded to the left so that each column is `$c` wide. The padding is done via spaces. The `0`, `1`, and `2` correspond to the `$l`, `$w`, and `$b` that are arguments to the format operator, so the line count, word count, and byte count are padded and output appropriately.

Note that this either requires the string to have already-expanded newlines (e.g., doing a `Get-Content` on a text file or something, and then either piping or saving that to a variable, then calling this code on that input), or use the PowerShell-styled escape characters with backticks (meaning  ``n` instead of `\n`).

**Example**

```
PS C:\Tools\Scripts\golfing> .\reimplement-wc.ps1 "This line`nis broken`ninto three lines.`n"
 3  7 38

```
> 1 votes

# Answer
# C, 180 178 bytes

```
#include <stdio.h>
#include <ctype.h>
main(b,w,l,c,d){d=' ';b=w=l=0;while((c=fgetc(stdin))!=EOF){if(!isspace(c)&&isspace(d))w++;b++;d=c;if(c==10)l++;}printf("%d %d %d\n",l,w,b);}

```
> 1 votes

# Answer
# Pip `-s`, 25 bytes

```
sX##a-#_._M[nNa`\S+`Na#a]

```

Takes the multiline string as a command-line argument. Try it online!

*Thanks to Dennis's CJam answer for making me realize that the longest number is always the character count.*

### Explanation

```
                           s is space; n is newline; a is 1st cmdline arg (implicit)
           [            ]  Construct a list of three elements:
            nNa             Number of newlines in a
               `\S+`Na      Regex search: number of runs of non-whitespace characters in a
                      #a    Length of a (i.e. number of characters in a)
          M                To each element of that list, map this function:
   #a                       Number of characters in a
  #                         Length of that number
     -#_                    Subtract length of each element
sX                          Construct a string of that many spaces
        ._                  Prepend it to the element
                           The resulting list is autoprinted, space-separated (-s flag)

```

---

Here's a 29-byte solution with flags `-rs` that takes input from stdin:

```
[#g`\S+`NST:gY#g+1]MsX#y-#_._

```

Try it online!
> 1 votes

# Answer
# Powershell, ~~123~~ 115 bytes

```
switch -r($args|% t*y){'\s'{$a=0}'\S'{$w+=!$a;$a=1}'(?s).'{$b++}'
'{$l++}}$c="$b".Length
"{0,$c} {1,$c} $b"-f$l,+$w

```

Test script:

```
$f = {

switch -r($args|% t*y){    # evaluate all matched cases
    '\s'   {$a=0}          # any whitespace (newline not included)
    '\S'   {$w+=!$a;$a=1}  # any not-whitespace (newline not included)
    '(?s).'{$b++}          # any char (newline included!)
    '`n'   {$l++}          # new line char
}
$c="$b".Length
"{0,$c} {1,$c} $b"-f$l,+$w

}

@(
    , ("a b c d`n", "1 4 8")
    , ("a b c d e f`n", " 1  6 12")
    , ("  a b c d e f  `n", " 1  6 16")
    , ("a`nb`nc`nd`n", "4 4 8")
    , ("a`n`n`nb`nc`nd`n", " 6  4 10")
    , ("abc123{}[]()...`n", " 1  1 16")
    , ("`n", "1 0 1")
    , ("   `n", "1 0 4")
    , ("`n`n`n`n`n", "5 0 5")
    , ("`n`n`na`nb`n", "5 2 7")
) | % {
    $s,$e = $_
    $r = &$f $s
    "$($e-eq$r): $r"
}

```

Output:

```
True: 1 4 8
True:  1  6 12
True:  1  6 16
True: 4 4 8
True:  6  4 10
True:  1  1 16
True: 1 0 1
True: 1 0 4
True: 5 0 5
True: 5 2 7

```

Explanation:

* `$args|% t*y` splits arument strings into chars
* `switch -r($args|% t*y)` evaluate *all matched cases*
    + `'\s'` case for any whitespace
    + `'\S'` case for any non-whitespace
    + `'(?s).'` case for any char (newline included)
    + `'\n'` case for newline char (newline represent itself)
* `$c="$b".Length` calculate a length of bytes number. $b is always max($l,$w,$b) by design
* `"{0,$c} {1,$c} $b"-f$l,+$w` format numbers with same length. The variable $w converts to int. It need for strings without words. Other variables formats 'as is' because 'The input will always contain a trailing newline' and $l and $b cannot be 0.
> 1 votes

# Answer
## Pascal, 248 bytes

This complete `program` requires a processor supporting “Extended Pascal” as defined by ISO standard 10206.

* The variable `input` possesses the built-in data type `text`. As such any newline character (sometimes it’s CR, sometimes LF, sometimes CR+LF, or something else) is *automagically* converted into a single space character (`' '`). In order to distinguish from a space character as *payload* of a line, and a space character that resulted from this conversion, you will need to query the function `EOLn`.
* A `text` variable is conceptually similar to a `file of char`. This `program` in fact counts *characters*, i. e. actually behaves like `wc ‑m`. However, since the task states that characters strictly draw from the ASCII character set, there is no difference.

```
program c(input,output);var l,w,c,z:integer value 0;p:char;begin p:=' ';while not EOF do begin c:=c+1;l:=l+ord(EOLn);w:=w+card([p]*[' ','   ']-[input^]);p:=input^;get(input)end;z:=trunc(ln(card([0..l,0..w,0..c]))/ln(10))+2;writeLn(l:z-1,w:z,c:z)end.

```

Ungolfed and annotated version:

```
{ By listing a `program` parameter of the spelling `input`,
  there’s an implicit `reset(input)` which implies a `get(input)`. }
program wordCount(input, output);
    var
        { `line`, `word` and `character` are singular, because they kind
          of enumerate these units as if input was a zero-based `array`. }
        line, word, character, width: integer value 0;
        previousCharacter: char;
    begin
        { This program counts “word beginnings” as words. This is the
          _change_ from “space character” _to_ “non-space character”. }
        previousCharacter := ' ';

        while not EOF(input) do
        begin
            character := character + 1;
            { As per POSIX specification a line is payload _plus_ one newline. }
            line := line + ord(EOLn(input));
            { The second character literal is an HT (horizontal tabulator). }
            word := word + card([previousCharacter] * [' ', '   '] - [input^]);

            { Prepare `previousCharacter` for _next_ iteration. }
            previousCharacter := input^;
            { Advance “reading cursor”. }
            get(input);
        end;

        { To produce POSIX-compliant output write:

            writeLn(line:1, ' ', word:1, ' ', character:1);

          As per task specification we will determine a common width though.
          We use ⌊ln(N) / ln(10)⌋ + 1 as the base formula, where N needs to be
          the largest number from `line`, `word` and `character`. This can be
          found by the expression |[0, line] ∪ [0, word] ∪ [0, character] ∩ ℤ|.
          We add another +1 for the space _between_ numbers. }
        width := trunc(ln(card([0..line, 0..word, 0..character])) / ln(10)) + 2;
        writeLn(line:width-1, word:width, character:width);
    end.

```
> 1 votes

# Answer
## Ruby, 108 bytes

```
f=->s{a=[s.count($/),s.split(/\S+/).size-1,s.size].map(&:to_s)
a.map{|b|" "*(a.map(&:size).max-b.size)+b}*" "}

```
> 0 votes

# Answer
# Perl, ~~71~~ ~~62~~ 61 bytes

*includes +1 for `-n`*

```
$;=length($b+=y///c);$w+=split$"}{printf"%$;d %$;d $b",$.,$w

```

Commented:

```
while (<>) {                         # implicit because of -n
    $; = length(                     # printf formatting: width
       $b += y///c                   # count characters
    );
    $w += split $"                   # count words
}{                                   # explicit: end while, begin END block
    printf "%$;d %$;d $b", $., $w    #  $. = $INPUT_LINE_NUMBER
}                                    # implicit because of -n

```
* Save another byte, again thanks to @TonHospel.
* Save 9 bytes thanks to @TonHospel showing me a few tricks of the trade!
> 0 votes

# Answer
# Lua, ~~74~~ 66 bytes

Golfed:

```
t=arg[1]_,l=t:gsub('\n','')_,w=t:gsub('%S+','')print(l,w,t:len())

```

Ungolfed:

```
text = arg[1]
_,lines = text:gsub('\n','')
_,words = text:gsub('%S+','')
print(lines, words, text:len())

```

Receives input through command line arguments.

We rename the first argument (`arg[1]`) to save bytes. `string.gsub` returns the number of replacements as well as the modified string, so we're using that to count first `'\n'` (newlines), then `'%S+'` (instances of one or more non-whitespace characters, as many as possible, i.e. words). We can use anything we want for the replacement string, so we use the empty string (`''`) to save bytes. Then we just use `string.len` to find the length of the string, i.e. the number of bytes. Then, finally, we print it all.
> 0 votes

# Answer
# Retina, 65

```
^((\S+)|(¶)|.)*
$#3 $#2 $.0
+`(\b(.)+ )(?!.*\b(?<-2>.)+$)
a$1
a
<space>

```

Try it Online!

The first stage is the actual wc program, the rest of it is for padding. The `a` placeholder thing is probably unnecessary, and some of the groups can probably be simplified a bit.
> 0 votes

# Answer
# Haskell, 140 bytes

```
import Text.Printf
w h=let{l=length;s=show.l;c=s h;m=s.words$h;n=s.lines$h;f=maximum$map l[c, m, n];p=printf"%*s"f}in p n++' ':p m++' ':p c

```

The ungolfed version is hereunder, with expanded variable and function names:

```
import Text.Printf

wc str =
  let charcount = show.length $ str
      wordcount = show.length.words $ str
      linecount = show.length.lines $ str
      fieldwidth = maximum $ map length [charcount, wordcount, linecount]
      printer = printf "%*s" fieldwidth
  in printer linecount ++ (' ' : printer wordcount ++ (' ' : printer charcount))

```

This is a function that accepts a string and returns a string. It just uses the `Prelude` functions `words` (resp. `lines`) to get the number of words (resp. lines) given that they seem to use the same definition as `wc`, then gets the longest value (as a string) amongst the counts and use the printf format taking the width amongst its arguments for formatting.
> 0 votes

# Answer
# 05AB1E, ~~24~~ 23 bytes

```
¨¶¡¹…
    S¡õK¹)€g§Zg>jJ¦

```

`j` is currently bugged, so could have been 21 bytes without the `§` and `J`..

Try it online or verify all test cases.

**Explanation:**

```
¨          # Remove the trailing newline of the (implicit) input
 ¶¡        # And split it on newlines
¹…
    S¡     # Take the first input again, and split it on [" \n\t"]
      õK   # Then remove all empty string items
¹          # And take the first input again as is
)          # Wrap all three value of the stack to a single list
 €g        # Take the length of each of the items
   §       # Cast the integers to strings (should have been implicit, but `j` is bugged)
    Z      # Take the max (always the last / amount of bytes) (without popping the list)
     g>    # Take the length + 1 of this max
       j   # Append leading spaces so all items or of this length
        J  # Join them together (should have been done by the `j` already, but it's bugged)
         ¦ # Remove the leading space (and output implicitly to STDOUT)

```
> 0 votes

# Answer
# Ruby `-p0`, 79 bytes

Includes a trailing space in the output.

```
a=[/
/,/\S+/,/./m].map{$_.scan(_1).size}
$_="%#{a.map{_1.to_s.size}.max}d "*3%a

```

Attempt This Online!

## Ruby `-p0`, 84 bytes

No trailing space.

```
a=[/
/,/\S+/,/./m].map{$_.scan(_1).size}
$_=["%#{a.map{_1.to_s.size}.max}d"]*3*" "%a

```

Attempt This Online!
> 0 votes

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


title: Just Friends… in code golf

text:
# Question
Title: Just Friends… in code golf
We already have challenges dealing with simulating vanilla Conway's Game of Life, Wireworld and rule 110, but so far none corresponding to a (specific) non-totalistic rule. So here is one.

In June 2000 David Bell described the Just Friends rule, which uses the same square grid and two states as regular Life but has the following transitions:

* A live cell remains live iff it has one or two live neighbours
* A dead cell becomes live iff it has two live neighbours **and they are not vertically or horizontally adjacent**

The birth restriction prevents the explosive behaviour that would otherwise be seen with birth-on-2-neighbours rules such as Seeds, and instead allows many interesting patterns. I've been searching for small oscillators of every period in this rule using apgsearch, and by that program alone I have found a stable reflector.

## Task

Given a Just Friends input pattern and number of generations, output the resulting pattern. The simulation grid, if bounded, must have size at least 40×40 and use either of the following boundary conditions:

* Wrap around like a torus
* Off-grid cells are dead

Pattern input and output may be in any reasonable format, such as binary matrices, lists of live cell positions and RLE.

This is ; fewest bytes wins.

## Test cases

These are in the form

```
input pattern
number of generations
output pattern.

```

```
....
.*..
.**.
....
1
....
.*..
.**.
....

......
..*...
..*...
.*....
......
......
......
12
......
......
......
....*.
....*.
...*..
......

.................
........*........
.................
......*.*........
.................
.**..............
.......**........
.................
.................
.................
.................
.................
.................
59
.................
.................
.................
.................
.........*.*..*..
..............*..
...........*.....
.................
.................
.................
.............*...
.............*...
.................

........................
...........*............
........................
......*....*.*..........
......*.................
.............*...*......
.....*.*...........**...
.................*......
........................
........................
...*.*..................
....................*.*.
.*.*....................
..................*.*...
........................
........................
......*.................
...**...........*.*.....
......*...*.............
.................*......
..........*.*....*......
........................
............*...........
........................
29
........................
............*...........
........................
..........*.*....*......
.................*......
......*...*.............
...**...........*.*.....
......*.................
........................
........................
..................*.*...
.*.*....................
....................*.*.
...*.*..................
........................
........................
.................*......
.....*.*...........**...
.............*...*......
......*.................
......*....*.*..........
........................
...........*............
........................

...............
.*.............
.*.***.........
..*...**.......
.....*..*......
..*...**.......
.*.***.........
.*.............
...............
15
...............
....*..........
....*.*****....
.....*.....**..
..........*..*.
.....*.....**..
....*.*****....
....*..........
...............

...........................
..........*.....*..........
..........*.....*..........
...........................
...........................
...........................
...........................
...........................
.*.......................*.
.*.........**.**.........*.
.*.......................*.
.*.........**.**.........*.
.*.......................*.
...........................
...........................
...........................
...........................
...........................
..........*.....*..........
..........*.....*..........
...........................
83
...........................
..........*.....*..........
..........*.....*..........
...........................
...........................
...........................
...........................
...........................
.*.......................*.
.*.........**.**.........*.
.*.......................*.
.*.........**.**.........*.
.*.......................*.
...........................
...........................
...........................
...........................
...........................
..........*.....*..........
..........*.....*..........
...........................

...........
..*........
..*......*.
....*....*.
.***.....*.
....*....*.
..*......*.
..*........
...........
21
...........
..*........
..*......*.
....*....*.
.***.....*.
....*....*.
..*......*.
..*........
...........

...............
...............
..**.**.*****..
..*.*.*.*****..
...***..**.**..
..*.*.*.*****..
..**.**.*****..
...............
...............
1
...............
....*..*.......
..*...*........
...............
.*.............
...............
..*...*........
....*..*.......
...............

```

# Answer
> 5 votes
# JavaScript (ES11), 136 bytes

Expects `(n)(binary_matrix)` and returns another binary matrix.

```
n=>g=m=>n--?g(m.map((r,y)=>r.map((v,x)=>[p=c=t=0,...'12587630'].map(d=>t+=(c|=p&(p=m[y+~-(d/3)]?.[x+d%3-1]),d)&&~~p)|6>>t&(v|~t&!c)))):m

```

Attempt This Online!

### Method

In order to get the neighbors of the cell at \\$(x,y)\\$, we use \\$d\in\\{0,1,2,3,5,6,7,8\\}\\$ and do:

$$\big(x+(d \bmod 3)-1,y+\lfloor d/3\rfloor-1\big)$$

which maps \\$d\\$ to:

$$\begin{matrix}0&1&2\\3&&5\\6&7&8\end{matrix}$$

More specifically, we start with \\$d=0\\$ and go clockwise, ending with \\$d=0\\$ again. While doing so, we keep track of the number of live neighbors in \\$t\\$ and set \\$c=1\\$ as soon as we detect two consecutive live cells.

The top-left cell is processed twice so that all consecutive pairs are tested (for the flag \\$c\\$), but we make sure to update \\$t\\$ only once. The distinction between the two passes is made possible by using the falsy integer `0` the first time and the truthy character `'0'` the second time.

Using \\$t\in\[0,8\]\\$, \\$c\in\\{0,1\\}\\$ and the current value \\$v\in\\{0,1\\}\\$ of the cell, we compute the new state with:

```
//     .-----------------> the LSB is set iff t=1 or t=2
//     |      .----------> always true if the cell is live
//     |      |      .---> true if t is even and c was not set
//   __|_     |    __|__
//  /    \    |   /     \
    6 >> t & (v | ~t & !c)

```

# Answer
> 3 votes
# Charcoal, 66 bytes

```
ＷＳ⊞υιυＦＮ«ＵＭυ⟦⟧ＦⅉＦＬθ«Ｊλκ⊞§υκ§.*⎇⁼*ＫＫ¬÷⊖№ＫＭ*²›⁼²№ＫＭ*№×²⪫ＫＭω**»⎚Ｅυ⪫κω

```

Try it online! Link is to verbose version of code. Takes input like the test cases except with a blank line between the pattern and number of generations. Explanation:

```
ＷＳ⊞υιυ

```

Read the pattern and write it to the canvas.

```
ＦＮ«

```

Repeat for each generation.

```
ＵＭυ⟦⟧

```

Start collecting the new pattern.

```
ＦⅉＦＬθ«Ｊλκ

```

For each cell...

```
⊞§υκ§.*⎇⁼*ＫＫ¬÷⊖№ＫＭ*²›⁼²№ＫＭ*№×²⪫ＫＭω**

```

... apply the generation rules to the cell.

```
»⎚Ｅυ⪫κω

```

Write the new pattern to the canvas.

# Answer
> 1 votes
# Wolfram Language (Mathematica) \+ my LifeFind package, 65 bytes

```
<<Life`
Last@CellularAutomaton[{RuleNumber@"12/2-a",2,{1,1}},##]&

```

---
Tags: code-golf, cellular-automata
---


title: Minkowski sum of two convex polygons

text:
# Question
Title: Minkowski sum of two convex polygons
## Background

**Minkowski addition** is a binary operation on two sets of points (usually geometric objects) in the Euclidean space. The Minkowski sum of two sets \\$A\\$ and \\$B\\$ is formally defined as follows:

$$ A+B = \\{\mathbf{a}+\mathbf{b}\\,|\\,\mathbf{a} \in A,\ \mathbf{b} \in B\\} $$

To say in plain English, given the origin and two figures, the Minkowski sum of the two figures is formed by the vector sum of each pair of points in the two figures. In the following image, the red shape is the Minkowski sum of the green and blue shapes.

It has an interesting property for two convex polygons: the edges of the original polygons are preserved (modulo translation) and sorted by polar angle (relevant info in Wikipedia), and therefore can be computed in \\$\mathcal{O}(m+n)\\$ (where \\$m\\$ and \\$n\\$ denote the number of vertices of two polygons respectively).

## Task

Given two convex polygons, compute their Minkowski sum.

Each polygon is given as an ordered list of \\$(x,y)\\$ coordinates, and the output polygon should be represented in the same way. You can choose the ordering of vertices (clockwise or counterclockwise), but your code should handle different starting points of the same polygon (`(0,0), (0,1), (1,0)` is the same as `(0,1), (1,0), (0,0)`). A point that is in the middle of a straight edge is not a vertex, and therefore should not appear in the output. (See the first test case)

You may take each coordinate pair as a single complex number. The coordinates are guaranteed to be integers.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
A = [(0, 0), (0, 1), (1, 0)]
B = [(0, 0), (0, 1), (1, 1), (1, 0)]
A + B = [(0, 0), (0, 2), (1, 2), (2, 1), (2, 0)]

A = [(-1, 0), (0, 1), (1, 0)]
B = [(1, 0), (0, -1), (-1, 0)]
A + B = [(-2, 0), (-1, 1), (1, 1), (2, 0), (1, -1), (-1, -1)]

A = [(0, 0), (0, 1), (1, 3), (2, 4), (4, 5), (5, 5)]
B = [(0, 0), (1, 3), (3, 6), (6, 8), (9, 9)]
A + B = [
  (0, 0), (0, 1), (1, 4), (2, 6), (4, 9),
  (5, 10), (8, 12), (10, 13), (13, 14), (14, 14)]

A = [(0, 1), (0, 2), (1, 2), (1, 1)]
B = [(1, 0), (1, 1), (2, 1), (2, 0)]
A + B = [(1, 1), (1, 3), (3, 3), (3, 1)]

```

# Answer
# , 74 58 bytes

Implements the algorithm outlined in the linked wiki article, so kinda works in \\$O(n + m)\\$ (but actually needs to sort the polygons first.) Takes in complex numbers for the coordinates.

```
+&({:@\:p)+,&d(+/\#~[(~:+)@%1&|.)@\:,&(p=.12 o.d=.[-_1&|.)

```

Try it online!

* `d=.[-_1&|.` `d` Translate the polygon to its edges as complex vectors from one point to the next.
* `p=.12 o.` The vectors polar angles.
* `,&d\:,&p` Merge-sort both polygons' edges based on their polar angles.
* `+/\` Transform back complex vectors -\> points.
* `#~[(~:+)@%1&|.` but only keep the points where the constructing vector \\$B\\$ divided by the previous vector \\$A\\$ has an imaginary part of 0, by checking that the conjugate equals itself. (So \\$B = cA\\$ for some \\$c \notin \mathbb{R} \\$.)
* `+&({:@\:p)` Translate the polygon back from `0j0` to the sum of the starting points.
> 3 votes

# Answer
# Jelly, 35 bytes

```
œ!3ZIZÆḊƲÐḟṢ2ịƊ€
+þẎQḟÇ$µS÷L⁸_æA/¥Þ

```

Try it online!

man this is ugly

```
œ!3ZIZÆḊƲÐḟṢ2ịƊ€    Helper Link; get all vertices that lie on an edge
œ!3                 Get all permutations of 3 vertices
   -----ƲÐḟ         Filter; remove triples where
   ZIZ              - the increments (edge vectors)
      ÆḊ            - have a non-zero determinant (keep elements with a 0 determinant; i.e. when they are collinear)
           ---Ɗ€    For each triple
           Ṣ        - sort it
            2ị      - and get the second (middle) item

+þẎQḟÇ$µS÷L⁸_æA/¥Þ  Main Link
+þ                  Product table over sum; get all pairwise sums
  Ẏ                 Tighten / flatten by one level; dump pairwise sums into a flat list of vertices
   Q                Remove duplicates
    ḟÇ$             Filter to remove (result of helper link); basically, delete vertices that lie on an edge between two other vertices
       µ            New monadic chain on the list of vertices
        S÷L         Sum / Length; arithmetic mean but not vectorizing
                 Þ  Sort
           ⁸        The left argument (list of kept vertices)
            ----¥   By order of
            _       - difference with mean point
             æA/    - atan2

```

Basically, pairwise sum, remove all elements that are the middle element of a collinear triple, and order by atan2 relative to the arithmetic mean of the points.
> 2 votes

# Answer
# Ruby, ~~133~~ 127 bytes

```
->a,b,*z{a.map{|x|b.map{|y|z|=[x+y]}
z.permutation(3){|i,j,k|q=(j-i)/k-=j;q==q.abs&&z-=[j]}}
z.sort_by{|w|(w*2-z[0]-z[1]).arg}}

```

Try it online!

Accepts arrays of complex numbers in input. Not really golfed.

The explanation should be straightforward: first get the sum of all the vertices, then remove all the points on the edges and sort by angle relative to the midpoint of the first edge.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 239 bytes

```
({p,q}=(Join[#,#[[;;2]]]&)/@((RotateLeft[#,First@OrderingBy[#,{Last,First}]-1]&)/@#);i = j = 1;res = {};While[i<Length@p-1||j<Length@q-1,AppendTo[res,p[[i]]+q[[j]]];t=Det@{p[[i+1]]-p[[i]],q[[j + 1]]-q[[j]]};If[t>=0,i++];If[t<=0,j++]];res)&

```

Try it online!

Thanks for the challenge, I have explored an interesting concept!

#### "Short" answer

Uses this optimized algorithm, accepts list of lists of coordinates, ordered counter-clockwise. Explained:

```
 ({p, q} =
            (*Must ensure cyclic indexing*)
            (PadRight[#,Length@# +2, #] &) /@
            (*Reorder the vertices in such a way that the first vertex of each polygon has the lowest              y-coordinate (in case of several such vertices pick the one   with the smallest x-coordinate*)
((RotateLeft[#,First@OrderingBy[#, {Last, First}] - 1] &) /@ #);
  (*Initialize two pointers and result*)
   i = j = 1; res = {};
   While[i < Length@p - 1 || j < Length@q - 1,
    AppendTo[res, p[[i]] + q[[j]]];
    (*Instead of ATan use cross product*)
    t = Det@{p[[i + 1]] - p[[i]], q[[j + 1]] - q[[j]]};
    If[t >= 0, i++]; If[t <= 0, j++]
     ]; res) &

```

#### Long answer (non-convex)

This non-golfed full-named code accepts coordinates (as a ragged list) of any two polygons (may be non-convex). Output a region for to show and list of non-collinear vertices of Minkowski sum:

```
minkowski[verts_] := With[{polys = Polygon /@ verts},
   (*Decompose the polygons into a disjoint union of convex parts*)
   coords = (PolygonCoordinates /@
        PolygonDecomposition[#, "Convex"]) & /@ polys;
   (*Find Minkowski sum for every convex parts as convex hulls
   and put them together*)
   region = RegionUnion @@ ConvexHullMesh /@ Flatten[
    (Table[Join @@ Outer[Plus, c1, c2, 1], {c1, #1}, {c2, #2}]) & @@
        coords
    , 1];
   (*Select only non-collinear vertices *)
   pickNonColl =
    With[{v = #},
    Pick[v, Function[{k},
        Nor @@ (RegionMember[ConvexHullMesh[#], k] & /@
            Subsets[Complement[v, {k}], {2}])] /@ v]] &;
   {region, pickNonColl@MeshCoordinates@region}
   ];

poly1 = {{-1, -1}, {-2, -4}, {-3, -1}, {-2, -2}};
poly2 = {{1, 1}, {2, 4}, {3, 1}, {2, 2}};
res = minkowski[{poly1, poly2}];
Show[res[[1]], Graphics[Polygon@{poly1, poly2}]]

```

```
poly1 = {{-1, 0}, {0, 1}, {1, 0}};
poly2 = {{1, 0}, {0, -1}, {-1, 0}};
res = minkowski[{poly1, poly2}];
res[[2]]

{{-2., 0.}, {-1., -1.}, {-1., 1.}, {1., 1.}, {1., -1.}, {2., 0.}}

```
> 0 votes

---
Tags: code-golf, math, geometry
---


title: Mirror a String in Place

text:
# Question
Title: Mirror a String in Place
Write a program that takes a string as input and modifies it by reversing the string in its place by mirroring the position. The first position goes to last, second to second last and so it goes on. In simple words, the string would be mirrored.

"In Place" means the program should use \\$O(1)\\$ additional memory regardless of the length of the string

## Test Cases

Input: `"Hello, World!"` Output: `"!dlroW ,olleH"`

Input: `"Hello"` Output: `"olleH"`

Input: `"A man a plan a canal Panama"` Output: `"amanaP lanac a nalp a nam A"`

Input: `"123456789"` Output: `"987654321"`

Input: `""` Output: `""`

# Answer
# x86 assembly (Linux) - ~~42~~ 26 bytes

`F6 D6 29 D4 B0 03 89 E1 CD 80 01 C1 43 89 DA 49 39 E1 7C 06 B0 04 CD 80 EB F5`

This is my first Assembly program. Reads from stdin, then outputs to stdout in reverse order. **Try it online.**

```
not dh       ; sys_read count = edx = 65280
sub esp,edx  ; allocate 65280 bytes on stack

mov al,3     ; 0x03 = "read" syscall
mov ecx,esp  ; sys_read buf = ecx = stack pointer
int 0x80     ; eax = sys_read(stdin, esp, 65280)

add ecx,eax  ; add read bytes to stack pointer

inc ebx      ; sys_write fd = 1 = stdout
mov edx,ebx  ; sys_write count = 1

reverse:
dec ecx      ;
cmp ecx,esp  ; check if we've gone too far
jl done      ;

mov al,4     ; 0x04 = "write" syscall
int 0x80     ; eax = sys_write(stdout, ecx, 1)

jmp reverse

done:

```

Disassembly

```
0:  f6 d6                   not    dh
2:  29 d4                   sub    esp,edx
4:  b0 03                   mov    al,0x3
6:  89 e1                   mov    ecx,esp
8:  cd 80                   int    0x80
a:  01 c1                   add    ecx,eax
c:  43                      inc    ebx
d:  89 da                   mov    edx,ebx
0000000f <reverse>:
f:  49                      dec    ecx
10: 39 e1                   cmp    ecx,esp
12: 7c 06                   jl     1a <done>
14: b0 04                   mov    al,0x4
16: cd 80                   int    0x80
18: eb f5                   jmp    f <reverse>

```
> 2 votes

# Answer
# C (gcc), ~~139~~ ~~134~~ 132 bytes

```
#define C strlen(a[1])
main(int n,char**a){for(n=0;n<C/2;){*(a[1]+n)^=**a=*(a[1]+n)^*(a[1]+C-n-1);*(a[1]+C-n++-1)^=**a;}puts(a[1]);}

```

Try it online!

Thanks for the "you can use `puts` suggestion from Neil that saved 2 bytes...

OK, assuming I understand the goal (which is big assumption), I think this one does the right thing... It reverses the string passed as the first commandline argument, then prints it. No additional storage is allocated to effect the reversal.

It works by XOR'ing each character of the string with the one it should be swapped with, then XOR'ing that composite value with each of the original characters. The temporary storage needed to complete the work are a `char` for holding the XOR composite, and an `int` string offset. The code overloads variables the compiler created for other purposes to avoid allocating additional memory for those temporary variables.

```
#define C strlen(a[1])       - just a shortcut to save space
main(int n,char**a){ ... }   - standard "this is a C program" stuff
for(n=0;n<C/2;){ ... }       - loop C/2 times (half the length of the string)
**a=*(a[1]+n)^*(a[1]+C-n-1); - set "*a[0]" to a composite of current swap chars
*(a[1]+n)^=**a...            - use composite to swap first char (w/ XOR)
*(a[1]+C-n++-1)^=**a;        - and repeat with the second char, increment "n"
puts(a[1]);                  - output the reversed string

```

If the rules allow for temporary variables, this could be shorter.
> 1 votes

# Answer
# Factor, 8 bytes

```
reverse!

```

Try it online!

Builtin. The documentation (and source code) for reverse! corroborates its O(1) additional memory usage beyond the string itself.
> 0 votes

# Answer
# Perl 5, 57 bytes

```
for$l(0...5*length){s/.{$l}\K(.)(.*)(.)(.{$l})/$3$2$1$4/}

```

Try it online!
> 0 votes

# Answer
# JavaScript, 14 bytes

```
s=>s.reverse()

```

Try it:

```
f=s=>s.reverse()

;[
  'Hello, World!',
  'Hello',
  'A man a plan a canal Panama',
  '123456789',
  ''
].forEach(s=>console.log(f([...s]).join``))
```
> 0 votes

---
Tags: code-golf, string, restricted-memory
---


# Question
Title: Find the first n digits of the square root of a number
Given two integers `m` and `n`, return the first `m` digits of `sqrt(n)`, with the decimal point. They will be given with a space in between.

You only have to produce `m` digits: so if `m=5, n=500`, then the output will be `22.360`, not `22.36067`.

**Do not use anything that will increase the precision of any operation.**

Test Cases:
`20 99` -\> `9.9498743710661995473`
`15 12345678` -\> `3513.64170057221`
`16 256` -\> `16.00000000000000`
`2 10000` -\> `10`

Shortest code wins.

# Answer
> 7 votes
## Python, 143 chars

```
m,n=map(int,raw_input().split())
d=10**m
n*=d*d
a=0
b=n
while a<b-1:c=(a+b)/2;a,b=[[c,b],[a,c]][c*c>n]
print('%d.%0*d'%(a/d,m,a%d))[:m+(a/d<d)]

```

Computes the answer by multiplying `n` by `10^2m`, doing an integer square root (using binary search), then "dividing" the result by `10^m`.

# Answer
> 5 votes
# Mathematica 66 272 240 chars

**New approach**

This uses the same, reasonably efficient (59 chars), method for obtaining the smallest useful convergent of `Sqrt[n]`. It takes a slightly different approach for dividing the numerator by the denominator, accurate to `m` places.

```
t = ToString; q = QuotientRemainder;
w = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)];
r = q[Numerator@w, k = Denominator@w];
h[{c_, d_, e_}] := {Append[c, q[d, e][[1]]], 10 q[d, k][[2]], k};
t@r[[1]] <> "." <> t@FromDigits@Nest[h, {{}, 10 r[[2]], k}, m][[1]]

```

**Example: Find the Square root of 5 accurate to 18 places**

```
n=5; m=18;
<run the above code>

(* out *)
"2.236067977499789696"

```

By the way, the convergent, w, for the above case is given below.

This is still long-winded but it works.

---

**Old approach**

The following 59 chars suffice to produce a fraction that will, in decimal form, solve the problem, assuming m, n are entered programmatically:

```
FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)]

```

When m=18, n=5, here's the fraction:

```
(* out *)
562882766124611619513723647/251728825683549488150424261

```

The trick is to convert this fraction into a decimal. The easy way is to use `N`;

```
N[%, m+1]
(* out *)
2.236067977499789696

```

However, `N` violates the rules by specifying the precision to work with.

---

Back to the drawing board:

```
q = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)];
f[{a_, n_, d_}] :=
   With[{q = QuotientRemainder[n, d]}, {Append[a, q[[1]]], q[[2]], d/10}]
   StringInsert[IntegerString@FromDigits@#[[1]],  ".", -1/Log[Denominator@#[[3]], 10]]
   &[NestWhile[f, {{}, Numerator@q, Denominator@q}, Length@#[[1]] < m &]]

```

Unfortunately, it takes another 205 characters (by my reckoning) to generate a decimal expression from the fraction. Surely there must be a more direct way to divide one integer by another to m decimal places!

# Answer
> 3 votes
## Haskell 126

```
main=interact$(\[x,y]->(\s->if '.'`elem`s then(x+1)`take`s else x`take`s)$(show.sqrt.fromIntegral)y++cycle"0").map read.words

```

Darn `sqrt` not taking `Int`s, and `fromIntegral` being so long!

# Answer
> 1 votes
**C# 41 chars**

```
Math.Sqrt(n).ToString().Substring(0,m+1);

```

# Answer
> 0 votes
**Version-1**

C# ***364*** Characters (Short Version)

```
using System;namespace X{class T{static void Main(string[] a){int m=int.Parse(Console.ReadLine()),n=int.Parse(Console.ReadLine());Console.WriteLine("{2}",f(n,m));}static string f(long s,int l){decimal x=s;for(int i=0;i<20;x=(((x*x)+s)/(2*x)),i++);var b=x.ToString(string.Format("F{0}",l));return(x.ToString().Contains("."))?b.Substring(0,l+1):b.Substring(0,l);}}}

```

code can be ran from OneIDE - http://ideone.com/9tZsD.

C# Normal Version

```
using System;

namespace X
{
    class T
    {
        static void Main(string[] a)
        {
            int m = int.Parse( Console.ReadLine()), n = int.Parse( Console.ReadLine());
            Console.WriteLine("m:{0}, n:{1} -> {2}", m, n, f(n,m));
        }
        static string f(long s,int l)
        {
            decimal x = s;
            for(int i = 0; i < 20; x = (((x * x) + s) / (2 * x)), i++) ;
            var b=x.ToString(string.Format("F{0}", l));
            return(x.ToString().Contains("."))?b.Substring(0,l+1):b.Substring(0,l);
        }
    }
}

```

# Answer
> 0 votes
## Pascal, 142 bytes

This full `program` requires a processor supporting features of “Extended Pascal” (ISO standard 10206). The `program` will crash if `m` is negative.

```
program p(input,output);var n,m:integer;p:string(maxInt);begin read(m,n);writeStr(p,sqrt(abs(n)):1:m);write(p:m+ord(index(p,'.')in[1..m]))end.

```

Ungolfed:

```
program findFirstNDigitsOfSquareRootOfANumber(input, output);
    var
        number, digit: integer;
        print: string(maxInt);
    begin
        readLn(digit, number);

        { `Sqrt` only works on non-negative integers and always returns
          the principal root as a `real` value. The `writeStr` routine is
          defined by Extended Pascal. The `:1` specifies the minimum width
          of the given argument. The write routines in combination with a
          `real` argument accept a second format specifier (here `:digit`)
          that disables scientific notation and determines the number of
          post-decimal (i.e. fractional) digits. }
        writeStr(print, sqrt(abs(number)):1:digit);

        { The format specifier `:digit…` in combination with a `string`
          argument specifies the _exact_ width. We will need to take
          account of the radix mark (`'.'`) _if_ it is printed, though. }
        writeLn(print:digit + ord(index(print, '.') in [1..digit]));
    end.

```

It is not possible to request `maxInt` digits since one `char` value will be occupied by the radix mark (`.`). You will probably need to replace `maxInt` by a sufficiently small natural number, though.

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