# Question
Title: Shortest program that throws StackOverflow Error
Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in *java*, the program should throw `java.lang.StackOverflowError`.

**You are not allowed to define a function that calls itself** or a new class(except the one containing `main` in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

# Answer
# Befunge, 1

I don't know Befunge, but...

```
1

```

from Stack overflow code golf
> 90 votes

# Answer
### Python (2.7.3), 35 characters

```
import sys
sys.setrecursionlimit(1)

```

This operation itself succeeds, but both script and interactive will immediately throw `RuntimeError: 'maximum recursion depth exceeded'` afterward as a consequence.

Inspired by elssar's answer.
> 51 votes

# Answer
## Coq

```
Compute 70000.

```

`70000` is just syntactic sugar for `S (S ( ... (S O) ...))` with 70000 `S`'s. I think it's the type checker that causes the stack overflow.

Here's a warning that is printed before the command is executed:

```
Warning: Stack overflow or segmentation fault happens when working with large
numbers in nat (observed threshold may vary from 5000 to 70000 depending on
your system limits and on the command executed).

```
> 21 votes

# Answer
## Javascript 24 characters

Browser dependent answer (must have access to `apply`):

```
eval.apply(0,Array(999999))

```
* `eval` was the shortest global function name that I could find (anyone know of one that is shorter?)
* `apply` allows us to convert an array into function parameters, the first parameter being the context of the function (`this`)
* `Array(999999)` will create an array with the listed length. Not sure what the maximum number of arguments is, but it's less than this, and more than `99999`

IE9:

```
SCRIPT28: Out of stack space
SCRIPT2343: Stack overflow at line: 20

```

Chrome 24:

```
Uncaught RangeError: Maximum call stack size exceeded

```

FireFox 18

```
RangeError: arguments array passed to Function.prototype.apply is too large

```

**Note** — Due to the single threaded nature of javascript, infinite loops end up locking the UI and never throwing an exception.

```
while(1);
for(;;);

```

Neither of these qualify.

**Update** — this shaves off three characters:

```
eval.apply(0,Array(1e7))

```
> 20 votes

# Answer
# Java - 35

```
class S{static{new S();}{new S();}}

```
> 20 votes

# Answer
# Python 2.7 (12 chars)

```
exec('{'*99)

```

results in a «s\_push: parser stack overflow»
> 17 votes

# Answer
# Mathematica, 4 chars

```
x=2x

```

> $RecursionLimit::reclim: Recursion depth of 1024 exceeded. \>\>
> 13 votes

# Answer
**Clojure, 12 chars**

```
(#(%%)#(%%))

```

Running in the repl:

```
user=> (#(%%)#(%%))
StackOverflowError   user/eval404/fn--407 (NO_SOURCE_FILE:1)

```
> 12 votes

# Answer
# Java - 113 chars

I think this stays within the spirit of the "no self-calling methods" rule. It doesn't do it explicitly, and it even goes through a Java language construct.

```
public class S {
    public String toString() {
        return ""+this;
    }
    public static void main(String[] a) {
        new S().toString();
    }
}

```

Condensed Version:

```
public class S{public String toString(){return ""+this;}public static void main(String[] a){new S().toString();}}

```
> 12 votes

# Answer
# C, 19 bytes

```
main(){int i[~0u];}

```
> 12 votes

# Answer
## GolfScript (8 chars)

```
{]}333*`

```

Result:

```
$ golfscript.rb overflow.gs
golfscript.rb:246:in `initialize': stack level too deep (SystemStackError)
from /home/pjt33/bin/golfscript.rb:130:in `new'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `map'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
from /home/pjt33/bin/golfscript.rb:130:in `map'
from /home/pjt33/bin/golfscript.rb:130:in `ginspect'
 ... 993 levels...
from (eval):4
from /home/pjt33/bin/golfscript.rb:293:in `call'
from /home/pjt33/bin/golfscript.rb:293:in `go'
from /home/pjt33/bin/golfscript.rb:485

```

Basically this creates a heavily nested data structure and then overflows the stack when trying to turn it into a string.
> 10 votes

# Answer
# x86 assembly, NASM syntax, 7 bytes

```
db"Pëý"

```

"Pëý" is 50 EB FD in hexadecimal, and

```
_loop:
push eax
jmp _loop

```

in x86 assembly.
> 10 votes

# Answer
## **Ruby, 12**

```
eval"[]"*9e3

```

Gives

```
SystemStackError: stack level too deep

```

Presumably system-dependent, but you can add orders of magnitude by bumping the last digit up (not recommended).

Edit for explanation: Similarly to some other examples, this creates a string of `[][][]`...repeated 9000 times, then evaluates it: the rightmost `[]` is parsed as a function call to the rest, and so on. If it actually got to the beginning, it would throw an ArgumentError because `[]` is an object with a `[]` method that requires one argument, but my machine throws an error a little before the stack is over nine thousand.
> 8 votes

# Answer
# Rebol (11 Chars)

```
do s:[do s]

```

Yields:

```
>> do(s:[do s])
** Internal error: stack overflow
** Where: do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do do do do do do do do
do do do do do do do do do do do do...

```

Though Rebol has functions, closures, and objects...this doesn't define any of those. It defines a data structure, which in the code-as-data paradigm can be treated as code using DO.

We can probe into the question of *"what is S"* with the REPL:

```
>> s: [do s]
== [do s]

>> type? s
== block!

>> length? s
== 2

>> type? first s
== word!

>> type? second s
== word!

```

DO never turns this into a function, it invokes the evaluator in the current environment on the structure.
> 8 votes

# Answer
# Casio Calculator, 11 keypresses

It's quite hard to count bytes/tokens in this "language" - I've given the number of keypresses required, excluding Shift, Alpha (the second shift key) and `=` at the end - this certainly fits into 1 byte per keypress.

Tested on the *fx-85GT PLUS* model, which is a standard, non-graphing, "non-programmable" scientific calculator. Other models will work.

Just stack up 11 cube roots:

`3√` `3√` `3√` `3√`
`3√` `3√` `3√` `3√`
`3√` `3√` `3√`

It doesn't even give a syntax error about the missing number under the square root.

This doesn't seem to work with square roots.

Alternatively, repeat `cos(` 31 times.

## Output

```
Stack ERROR

[AC]  :Cancel
[<][>]:Goto

```

I believe that this qualifies as a stack overflow. The stack seems to be tiny...
> 8 votes

# Answer
# C, 35 characters

```
main(){for(;;)*(int*)alloca(1)=0;}

```
> 7 votes

# Answer
# FORTH, 13 bytes

```
BEGIN 1 AGAIN

```

overflows the value stack
> 7 votes

# Answer
# Common Lisp, 7 characters

```
#1='#1#

```
> 7 votes

# Answer
## Python - 11 chars

```
exec'('*999

```

---

```
>>> exec'('*999
s_push: parser stack overflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

```
> 7 votes

# Answer
# Postscript, 7

```
{1}loop

```

Eg.

```
$ gsnd
GPL Ghostscript 9.06 (2012-08-08)
Copyright (C) 2012 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
GS>{1}loop
Error: /stackoverflow in 1
Operand stack:
   --nostringval--
Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   %loop_continue   --nostringval--   --nostringval--   false   1   %stopped_push   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   %loop_continue
Dictionary stack:
   --dict:1168/1684(ro)(G)--   --dict:0/20(G)--   --dict:77/200(L)--
Current allocation mode is local
Last OS error: No such file or directory
Current file position is 8
GS<1>

```
> 6 votes

# Answer
## Haskell (GHC, no optimization), 25

```
main=print$sum[1..999999]

```

sum is lazy in the total. This piles up a bunch of thunks, then tries to evaluate them all at the end, resulting in a stack overflow.
> 6 votes

# Answer
## PHP 5.4, 33 characters

```
for($n=1e5;$n--;)$a=(object)[$a];

```

This causes a stack overflow when the nested stdClass objects are automatically destroyed:

```
$ gdb -q php
Reading symbols from /usr/bin/php...(no debugging symbols found)...done.
(gdb) set pagination 0
(gdb) r -nr 'for($n=1e5;$n--;)$a=(object)[$a];'
Starting program: /usr/bin/php -nr 'for($n=1e5;$n--;)$a=(object)[$a];'
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x00000000006debce in zend_objects_store_del_ref_by_handle_ex ()
(gdb) bt
#0  0x00000000006debce in zend_objects_store_del_ref_by_handle_ex ()
#1  0x00000000006dee73 in zend_objects_store_del_ref ()
#2  0x00000000006a91ca in _zval_ptr_dtor ()
#3  0x00000000006c5f78 in zend_hash_destroy ()
#4  0x00000000006d909c in zend_object_std_dtor ()
#5  0x00000000006d9129 in zend_objects_free_object_storage ()
#6  0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex ()
#7  0x00000000006dee73 in zend_objects_store_del_ref ()
#8  0x00000000006a91ca in _zval_ptr_dtor ()
#9  0x00000000006c5f78 in zend_hash_destroy ()
#10 0x00000000006d909c in zend_object_std_dtor ()
#11 0x00000000006d9129 in zend_objects_free_object_storage ()
[...]
#125694 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex ()
#125695 0x00000000006dee73 in zend_objects_store_del_ref ()
#125696 0x00000000006a91ca in _zval_ptr_dtor ()
#125697 0x00000000006c5f78 in zend_hash_destroy ()
#125698 0x00000000006d909c in zend_object_std_dtor ()
#125699 0x00000000006d9129 in zend_objects_free_object_storage ()
#125700 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex ()
#125701 0x00000000006dee73 in zend_objects_store_del_ref ()
#125702 0x00000000006a91ca in _zval_ptr_dtor ()
#125703 0x00000000006c4945 in ?? ()
#125704 0x00000000006c6481 in zend_hash_reverse_apply ()
#125705 0x00000000006a94e1 in ?? ()
#125706 0x00000000006b80e7 in ?? ()
#125707 0x0000000000657ae5 in php_request_shutdown ()
#125708 0x0000000000761a18 in ?? ()
#125709 0x000000000042c420 in ?? ()
#125710 0x00007ffff5b6976d in __libc_start_main (main=0x42bf50, argc=3, ubp_av=0x7fffffffe738, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe728) at libc-start.c:226
#125711 0x000000000042c4b5 in _start ()

```
> 5 votes

# Answer
# Q/k (16 chars)

Not sure if this is in the spirit of the challenge but I *don't think* it breaks the rules:

```
s:{f`};f:{s`};f`

```
> 5 votes

# Answer
# C#: 106 86 58 46 32 28

**32**: Getters can SO your machine easy in C#:

```
public int a{get{return a;}}

```
> 5 votes

# Answer
A bunch in the same style:

## Python, 30

```
(lambda x:x(x))(lambda y:y(y))

```

## Javascript, 38

```
(function(x){x(x)})(function(y){y(y)})

```

## Lua, 44

```
(function(x) x(x) end)(function(y) y(y) end)

```
> 5 votes

# Answer
# LaTeX: 8 characters

```
\end\end

```

This is the same code used in this answer. Essentially, the `\end` macro expands itself repeatedly, resulting in a stack overflow: `TeX capacity exceeded, sorry [input stack size=5000]`. A more detailed explanation can be found here.
> 5 votes

# Answer
# INTERCAL, 12 bytes

```
(1)DO(1)NEXT

```

## Explanation:

`NEXT` is INTERCAL's version of a subroutine call (or, at least, the closest you can get). It pushes the current position onto the `NEXT` stack and jumps to the given label.

However, if the `NEXT` stack length exceeds 80, you get what's pretty much the INTERCAL version of a stack overflow:

```
ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON
    ON THE WAY TO 1
        CORRECT SOURCE AND RESUBNIT

```

Try it on Ideone..
> 5 votes

# Answer
# Mornington Crescent, ~~139~~ 133

```
Take Northern Line to Bank
Take Circle Line to Temple
Take Circle Line to Temple
Take Circle Line to Bank
Take Northern Line to Angel

```
> 5 votes

# Answer
# X86 assembly (AT&T), 33 characters

Note that although I'm using the label `main` as a jump target, this is *not* a recursive function.

```
.globl main
main:push $0;jmp main

```
> 4 votes

# Answer
# Python (17):

```
c='exec c';exec c

```
> 4 votes

# Answer
## C -- 34 characters, no libraries

Though competative with Job's answer,

```
o(){O();}
O(){o();o();}
main(){o();}

```

violates the spirt of the challenge by showing how to evade the restriction on constructing a simple recursion. You can save 4 character by removing one call from `O`, but gcc is smart enough to recongnise that if you use `-O3`.1

The trick is quite general and can be done in fortran 77, too (142 characters):

```
      program o
      i=j()
      stop
      end
      function j()
      j=k()
      end
      function k()
      k=j()
      k=j()
      end

```

Again, gcc can optimize away a single call in each.

---

1 I suppose it inlines one of them and then applys tail recursion elimination. How cool is that!?!.
> 3 votes

# Answer
## Groovy (27 chars)

```
a=[:];b=[a:a];a.b=b;print b

```

And so it goes:

```
Caught: java.lang.StackOverflowError
    java.lang.StackOverflowError

```
> 3 votes

# Answer
## Python, real stack overflow: 38

```
a=[];eval("[x "+"for x in a "*800+"]")

```

Error message:

```
s_push: parser stack overflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

```

Explanation:

```
[x for x in a for x in a]

```

is the same as

```
y = []
for x in a:
    for x in a:
        y.append(x)

```

so the above eval produces 800 nested for loops :)
> 3 votes

# Answer
## Tcl, 15 chars

```
interp r {} 1;a

```

gives

> too many nested evaluations (infinite loop?)

the `interp r` stands for `interp recursionlimit` (you can abbreviate subcommands). `a` calls (because not known) `unknown`, which calls a lot of other stuff.
> 3 votes

# Answer
# J, 3 chars

```
$:1

```

This does call itself. But it does not define a function that calls itself. Rather $: keeps invoking the largest verb it is enclosed in.

```
$:1
|stack error
|       $:1

```
> 3 votes

# Answer
# Javascript, ES6 21

```
eval('{'.repeat(1e7))

```

Due to the nature of javascript, nesting a bunch of blocks causes a stackoverflow.

For more information see https://stackoverflow.com/questions/17306367/why-does-nesting-a-bunch-of-blocks-causes-a-stack-overflow-in-javascript

```
eval('('.repeat(1e7))

eval('['.repeat(1e7))

```

Other similar cases

```
eval('+'.repeat(1e7))

eval('-'.repeat(1e7))

```
> 3 votes

# Answer
# Vitsy, 1 byte

Obviously non-competing due to language creation date.

This feature of my language was entirely unintended. Because of how loops work in my language, they can be finicky if you don't match braces. So, for a one-byte solution, I give you this:

```
[
```

Posted on my Showcase your language one vote at a time! answer...

> The shortest stack overflow error you'll ever see.
>
> Basically, in Vitsy, the `[` represents "start while loop". While in a while loop, the program will wrap around the line - which means it starts another while loop, which wraps around the line and starts another while...
>
> You get it.

Try it online!
> 3 votes

# Answer
# Brachylog, 4 bytes

```
$G~l

```

Try it online!

### Explanation

`$G` is `1,000,000,000`. `$G~l` is thus: *“Create a list of length 1,000,000,000”*, which does not fit the stack.
> 3 votes

# Answer
# Groovy, 5 bytes

```
run()

```

Example execution:

```
$ groovy -e "run()"
Caught: java.lang.StackOverflowError
java.lang.StackOverflowError
    at script_from_command_line.run(script_from_command_line)
    at script_from_command_line.run(script_from_command_line:1)
    at script_from_command_line.run(script_from_command_line:1)
    ...

```

works as a command line script (groovy -e), standalone groovy script, and in the groovy shell.

We are not defining a new function here so not breaking the rules as far as I can understand.

This works because the groovy compiler adds an implicit run method behind the scenes and calling this method ourselves causes a StackOverflowException.

Essentially the above run() call gets translated to something like the below code by the groovy compiler before its handed off for execution by the jvm:

```
// class generated by groovy compiler
class ScriptName {
  def args

  def main(args) {
    new ScriptName(args: args).run()
  }

  def run() {
    // user code start
    run() // our call
    // user code end
  }
}

```
> 3 votes

# Answer
## VBScript, 101 characters

Not the smallest script, but created as a proof of concept

```
i=2
s="sub[2](b):i=i+1:d=replace(b,i-1,i):execute d:call getref("""&i&""")(d):end sub"
execute s
[2]s

```

This code creates new named functions on the fly by executing a string that creates a function and giving the new function this string as a parameter. The function creates a new function and calls it. Results in a `Microsoft VBScript runtime error: Out of stack space: 'execute'` error.
> 2 votes

# Answer
Scheme:

```
((lambda (x) (x x)) (lambda (x) (x x))

```
> 2 votes

# Answer
**Burlesque, 5 characters**

```
1R@p^

```

Range from one to infinity, push all elements to stack -\> StackOverflow.
> 2 votes

# Answer
# PERL, 19 chars

```
sub c{sub d{c()}d}c

```

Originally I posted this solution (11 chars), but I overlook that rule *"You are not allowed to define a function that calls itself"*:

```
sub c{c()}c

```

It's a pitty that PERL doesn't allow this `sub c{c}c` \- would look really cute :-)
> 2 votes

# Answer
# LI, 1 byte

```
R

```

`R`eruns the program with the given input. Every time this is done, another two functions are added to the interpreter's stack (one interpreting the program string and another interpreting the function `R`), eventually overflowing the stack.
> 2 votes

# Answer
# Lua

```
function b()b()end b() --stack overflow

```

Alternatively,

```
a={}setmetatable(a,{__index=function()return a.a end})a(a.a) --C stack overflow

```
> 1 votes

# Answer
# dc, 7 chars

```
[ddx]dx

```

You may watch how it consumes memory :-)

```
dc -e'[ddx]dx' & watch -n 1 "ps l|grep $!|grep -v grep"

```
> 1 votes

# Answer
Java + SnakeYaml and a quirk over jva.awt.point :P; length=104

```
class A{public static void main(String[]a){new org.yaml.snakeyaml.Yaml().dump(new java.awt.Point());}}

```
> 1 votes

# Answer
# *C#*

## (59)

With a `Main` method:

```
static void Main(){unsafe{int* p=stackalloc int[1000000];}}

```

## (39)

Just the code that causes the exception:

```
unsafe{int* p=stackalloc int[1000000];}

```
> 1 votes

# Answer
**x86\_64 ASM - 7 bytes**

```
48 81 EC 00 00 60 09

```

Here is a mnemonic version.

```
SUB RSP, 0x9600000

```

This instruction by setting the stack pointer to above the maximum size, (at least on Unix) Since the stack grows downwards we use subtraction instead of addition.

You could probably also exchange RSP with RBP top set the base pointer of stack to overflow. This would require you to change EC to ED in the hex representation.

Although this doesn't throw an error, the stack is overflowed as we set the size that the stack is filled to a number above the maximum stack size.

You could improve this answer to 4 bytes if you are using an operating system with a stack size to less than one byte.

```
48 81 EC FF

```
> 1 votes

# Answer
# TECO, 4 bytes

I was thinking about what tasks would be best to do in TECO, and realized that infinite loops and stack overflows are among its greatest talents.

```
<[a>

```

Pushes the contents of register `a` to the stack in an infinite loop.

Result of running code:

```
*<[a>$$
?PDO   Push-down list overflow

```
> 1 votes

# Answer
## Neoscript, 22 bytes

```
try 1/0;catch e retry;

```

The division by 0 crash and execute the catch block, which call the try..catch block again, the division by 0 crash and excute the catch block again, etc...
> 1 votes

# Answer
# SmileBASIC, 63 bytes

```
PRGEDIT 1FOR I=0TO 16384PRGSET"GOSUB"+(@_+HEX$(I))*2NEXT
EXEC 1

```

Error: `Stack overflow in 1:16385`

This generates code like:

```
GOSUB @_0@_0
GOSUB @_1@_1
...

```

No recursion is used, just 16385 `GOSUB`s, enough to fill the call stack.

### And a boring and possibly cheating answer in 10 bytes:

```
@A
GOSUB@A

```

Error: `Stack overflow in 0:2`
> 1 votes

# Answer
# Whitespace, 12 bytes - Fills the stack

```

```

Try it online!

## Explanation

```
nssn ; Declare label ''
sssn ; Push 0
nsnn ; Jump to label ''

```

Cloned from Shortest program that continually allocates memory. Whitespace is actually somewhat competitive for this question, I'm surprised we hadn't already had an answer.

This program loops and continuously pushes the value 0 to the stack, causing the stack to grow until the interpreter crashes (with the equivalent of a stack overflow error in whatever language the interpreter uses).
> 1 votes

# Answer
# Braingolf, 5 bytes

```
1[l>]

```

Pushes a 1, then repeatedly pushes the length of the stack and moves it to the beginning of the stack. The loop will only exit if the first item in the stack is 0, so this loop will continually increase the length of the stack until eventually it reaches python3's deque limit.
> 1 votes

# Answer
# GW-Basic, 18 bytes

In GW-Basic there's no separate stack overflow error as such; when the stack overflows you get error 7, ‘Out of memory’. The trick is to make sure you got this because you've ran out of stack space and not for some other reason. Enter:

```
CLEAR,,241:?SIN(0)

```

This will immediately result in:

```
Out of memory
Ok

```

The number `241` is important. Firstly, it cannot be `0` because that will yield error 5 ‘Illegal function call’. But it also cannot be `240` or less, because although you will get the out of memory error above, `CLEAR` won't actually have adjusted the stack space. So in that case the error isn't a real stack overflow, but it acts more like an illegal argument error of sorts. ‘This is too small for us to work with at all, no can do, sorry.’ You can easily check this:

```
CLEAR,,999
Ok
CLEAR,,1
Out of memory
Ok
?SIN(0)
 0
Ok
CLEAR,,240
Out of memory
Ok
?SIN(0)
 0
Ok
CLEAR,,241
Ok
?SIN(0)
Out of memory

```
> 1 votes

# Answer
# C#: 62 (full program)

(full program, not excerpt like other one, although it's based on it)

```
class A{static int a{get{return a;}} static void Main(){a=a;}}

```
> 0 votes

# Answer
## R - 5 (plus 18 for the command line switch)

Using a ridiculously small memory allocation (`--max-mem-size=32M`), you can do this easily:

```
1:1e9

```

I tried this without setting the memory limit, and that caused my computer to hang. I don't know if it would have overflowed or not. If not, a score of 6 (`1:1e99`) would surely do it.
> 0 votes

# Answer
# fish shell (14 characters)

In my opinion, this doesn't count as declaring a function that calls itself. Could be shorter if this pull request would be applied (by one character), but considering it wasn't yet (and I'm not going to do this just to make my code shorter), this has to work.

```
alias ls ll;ls

```
> 0 votes

# Answer
In Java : 131 characters

```
public class HelloWorld{public HelloWorld(){main(new String[]{"3","4"});}public static void main(String []args){new HelloWorld();}}

```
> 0 votes

# Answer
## Batch (7 chars)

It requires CALL or the execution of the calling batch ends right after starting itself again.

```
CALL %0

```

I'm not defining a function which calls itself, hence Batch doesn't even have functions. Also I did not create any classes. So this is valid.
> 0 votes

# Answer
# Node.js REPL (15)

```
eval(RegExp.$1)

```

Sample session:

```
> eval(RegExp.$1)
RangeError: Maximum call stack size exceeded
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)
    at eval (eval at <anonymous> (repl:1:12), <anonymous>:1:12)

```
> 0 votes

# Answer
## C, 24 characters (no cheating)

```
x(){main();}main(){x();}

```

Compile with default `cc` settings and ignore warnings.

## C, 10 characters (with cheat)

```
X{Y;}Y{X;}

```

compile with:

```
cc -DX='x()' -DY='main()'

```
> 0 votes

# Answer
# CoffeeScript/Javascript - Only in Chrome (24 chars)

Sorry for waking up an old post

This only works in Google Chrome (tested in Firefox and Chrome):

```
JSON.stringify a:5,->a:5

```

http://coffeescript.org/#try:JSON.stringify%20a%3A5%2C-%3Ea%3A5

This is not converting a circular structure to JSON. Actually, it uses the replacer function: the replacer function returns another object so the object ends up stringifying that object whose replacer also returns an object.

It gets compiled to the following JavaScript:

```
JSON.stringify({
  a: 5
}, function() {
  return {
    a: 5
  };
});

```

Tested on Chrome 39.
> 0 votes

# Answer
# Lua, 29 bytes

This one causes a stack overflow by generating a new function every call and calling it.

```
l=loadstring s='l(s)()'l(s)()

```

Here are some other creative answers:

## 9 bytes:

```
dofile'a'

```

This causes a C-stack overflow. Requires you put it in a file named `a`.

## 39 bytes:

```
package.loaded.a=z require'a'

```

This causes a C-stack overflow. Requires to be put in a file named `a` and requires `LUA_PATH=a`.
> 0 votes

# Answer
## Ruby - Proc fun - 18

```
a=->(b){b[b]};a[a]

```

Basic recursive solution. In `irb` ends up with:

```
SystemStackError: stack level too deep

```
> 0 votes

# Answer
# ANTLR4 / Java, 103 Bytes

```
grammar P;
r:(C|N)+;
C:(('p'|'i')P);
P:(N|S)*;
N:[0-9]+;
S:[A-Za-z0-9_]*;
WS:[ \r\n]+ -> skip;

```

**To use**: Better create a new directory to put the file in, I used the common aliases shown on the antlr4 site.

```
antlr4 P.g4 && javac P*.java && echo 'Press Ctrl-D in 5 secs.' && grun P r -gui

```

Don't have **any** idea why this works, and I think it can be golfed much.
> 0 votes

# Answer
## Rust, 29 bytes

```
fn main(){let a=[0;9000000];}

```

I hadn't thought it would be that easy. It actually gives segmentation fault, but given that it's rust, I'm pretty sure it's the stack that throws in the towel.

I wonder if the compiler ought to give a warning about stuff like this?
> 0 votes

# Answer
# Java (OpenJDK 9), 70 bytes

```
public class Main{public static void main(String[] args){main(args);}}

```

Try it online!
> -1 votes

---
Tags: code-golf
---


title: Old Cordless Phone

text:
# Question
Title: Old Cordless Phone
I need to call my friends but the buttons of my cordless phone are not working properly. The only buttons I can press are \[Up\], \[Down\] and \[Call\]. \[Up\] and \[Down\] can be used to navigate in my recent calls and \[Call\] can be used to call the selected name. My phone has a list that holds `N` recent calls, and I know that all the friends I need to call are in this list.

---

# Task:

You'll receive a number `N` and a list of names `L`:

* `N` is the number of recent calls my phone can remember;
* `L` has the names in the order I need to call.

You must output the number of button presses I need to make in an optimal arrangement of the recent call list.

---

# Example:

### -\> Input:

Calling Anna, Bob and then Anna again. With a recent calls list of size 5.

```
5
Anna
Bob
Anna

```

### -\> Output:

Possible optimal arrangement: `Anna, Foo, Bar, Foobar, Bob`

```
5    # Key presses: [Call] Anna, [Up] + [Call] Bob, [Down] + [Call] Anna

```

### More test cases:

```
Input: 5, Anna, Bob, Carl
Output: 5

Input: 5, Anna, Bob, Carl, Anna
Output: 8

Input: 5, A, B, C, D, E, A
Output: 11

Input: 6, A, B, C, D, E, A
Output: 12

Input: 4, A, B, C, B, A
Output: 10

```

---

# Rules:

* Your cursor will always start in the first position of the list;
* You can take the input `N` and `L` from any source: keyboard, parameters, file, etc;
* The names in the list can be in any reasonable format such as: strings, integers, chars;
* When you reach the end of the recent calls list and presses \[Down\] again, your cursor wraps around. The same happens when you're at the begining of the recent calls list and presses \[Up\];
* When you call someone, that person's name will be moved to the first position of the recent calls list and the rest will be pushed down;
* When you call someone, your cursor will be moved to the first position;
* A friend name cannot appear more than once in the recent calls list;
* You can fill your recent calls list with dummy entries (see example);
* The number of friends to call will not be greater than `N`.

# Answer
> 2 votes
# Ruby, ~~97~~ ~~95~~ 94 bytes

```
->n,a{r=a.size;1.upto(r-1){|i|r+=[p=a[(a[0,i].rindex(a[i])||i-2)+1...i].uniq.size,n-p].min};r}

```

Try it online!

In an optimal arrangement, the first name will take one press (`Call`). Names that have not been called yet take two presses (`Up` `Call`), and names that have take varying numbers depending on how many other unique names have been called since then and whether that places them closer to the top or the bottom of the list.

I think this is a strategy similar or identical to WaffleCohn's.

# Answer
> 3 votes
# Python 3, ~~195~~ ~~185~~ 164 bytes

*-4 bytes thanks to @notjagan*
*-27 bytes thanks to @FelipeNardiBatista*

```
lambda n,l:min(g([*x],l,n)for x in permutations(range(n)))
def g(x,l,n,r=0):
 for p in l:a=x.index(p);x=[x.pop(a)]+x;r-=~min(a,n-a)
 return r
from itertools import*

```

Try it online!

`L` is taken as a list of integers from `[0, N)`

# Answer
> 1 votes
# JavaScript (SpiderMonkey), 213 143 bytes

```
(N,L)=>L.reduce((t,v,i)=>{x=0,a=[v]
for(j=i;j-->=0&!~a.indexOf(L[j]);x++)a+=L[j]+","
return i?t+((x=L.indexOf(v)-i?x:1)<N-x?x:N-x):t},L.length)

```

Try it online!

Generates an optimal arrangement of the given names then counts the number of key presses.

Skipped the generation and just counted how many key presses it would take each name in the optimal arrangement

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


title: Calculating BPM with inputs

text:
# Question
Title: Calculating BPM with inputs
Program the shortest code that will calculate the average BPM (Beats per Minute) using 8 data points of time passed. This is my first post, and I haven't seen a question similar to this. Since I am a fan of rhythm games, it would be nice to have a small handy tool to calculate BPM using your own keyboard and your own sense of rhythm (if you have one...)

# Challenge

* All inputs must be singular. (i.e. Only pressing "enter" as "input")
* Your program must take at least 9 inputs. (To create 8 data points of time passed.)
* Your program should output the BPM of the keypresses rounded at 2 decimal points. (i.e. 178.35)
* **Timing starts at first input. Not start of program**

This is , so the shortest answer wins.

# Example Input and Output

Provide at least one example input and output. Make sure they match your own description of what the input should look like.

Input:

```
> [Enter-Key]
# User waits 1 second
...  7 more inputs
> [Enter-Key]

```

Output:

```
> 60

```

**Current winner is KarlKastor at 22 Bytes using Pyth**

**Even though the winner was using Pyth, the Matlab answer was a notable answer.**

# Answer
> 1 votes
# Pyth, 22 bytes

```
 wJ.d0 mw8.Rc480-.d0J2

```

(yes there's a leading space)

Input is 'enter' presses.

If additional output is allowed I can remove the spaces and get a score of 20 bytes.

## explanation

```
 wJ.d0 mw8.Rc480-.d0J2
 w                      # take the first input
                        # (space) throw the result away
  J.d0                  # store the current system time in J
       mw8              # take 8 inputs and throw the result away
                 -.d0J  # difference of current time and J
             c480       # divide 480 by this
           .R         2 # round to 2 decimal places

```

# Answer
> 9 votes
# MATLAB/Octave, ~~58 56~~ 55 bytes

Thanks @LuisMendo for -1 byte!

```
input('');tic;for k=1:7;input('');end;fix(48e3/toc)/100

```

You have to press enter 9 times. (Also works in Octave.)

Here you see it in action, left MATLAB, right Octave:

# Answer
> 7 votes
# JavaScript (ES6), ~~77~~ 74 bytes

```
(i=8,n=Date.now,t)=>onclick=_=>(t=t||n(),i--||alert((48e6/(n()-t)|0)/100))

```

Creates an `onclick` event on the global `window` object. Send beats by clicking anywhere in the window.

## Test Snippet

```
let f=
(i=8,n=Date.now,t)=>onclick=_=>(t=t||n(),i--||alert((48e6/(n()-t)|0)/100))

f()
document.write("Running... click anywhere here")
```

```
*{user-select:none}
```

# Answer
> 6 votes
# Python 3, 93 92 81 bytes

Saved 11 bytes thanks to Felipe.

```
import time
a,*l,b=[input()or time.time()for i in' '*9]
print(round(480/(b-a),2))

```

# Answer
> 5 votes
## **Javascript, 100, 84 thanks to Powelles, 82 bytes thanks to Justin Mariner**

```
z=>{(a=alert)();i=0;s=(n=Date.now)();while(i++<8)a();a((48e4/(n()-s)).toFixed(2))}

```

```
(z=>{(a=alert)();i=0;s=(n=Date.now)();while(i++<8)a();a((48e4/(n()-s)).toFixed(2))})();
```

# Answer
> 5 votes
# Bash + common Linux utilities, 58

```
script -tt -c'sed -n 9q'
sed '1c2k0
s/ 2/+/;$a480r/p' t|dc

```

# Answer
> 4 votes
# Java 1.5+, ~~345~~ ~~339~~ ~~361~~ 337 bytes

-34 bytes thanks to Michael for pointing out I forgot to fix my imports

```
import java.awt.event.*;class B{public static void main(String[]a){new java.awt.Frame(){{addKeyListener(new KeyAdapter(){long x=System.currentTimeMillis();int b=0;public void keyPressed(KeyEvent e){if(e.getKeyChar()==' '&&b++==9){System.out.println(Math.round(6000000.0*b/(System.currentTimeMillis()-x))/100.0);}}});setVisible(1>0);}};}}

```

Listens to the user as they press the space bar. Then, when the user has pressed it 9 times, prints back to the user the current BPM:

*Image has debug messages not present in golfed code.*

---

# Ungolfed:

```
import java.awt.event.*;

class B {
    public static void main(String[] a) {
        new java.awt.Frame() {
            {
                addKeyListener(new KeyAdapter() {
                    long x = System.currentTimeMillis();
                    int b = 0;

                    public void keyPressed(KeyEvent e) {
                        if (e.getKeyChar() == ' ' && b++ == 9) {
                            System.out
                                    .println(Math.round(6000000.0 * b
                                            / (System.currentTimeMillis() - x)) / 100.0);
                        }
                    }
                });
                setVisible(1 > 0);
            }
        };
    }
}

```

---

Kinda fun to try and get a highscore...

```
KEY PRESS0 AT 250ms.
KEY PRESS1 AT 343ms.
KEY PRESS2 AT 468ms.
KEY PRESS3 AT 563ms.
KEY PRESS4 AT 672ms.
KEY PRESS5 AT 781ms.
KEY PRESS6 AT 880ms.
KEY PRESS7 AT 989ms.
485

```

# Answer
> 3 votes
# C# (.NET Core), ~~193~~ ~~206~~ ~~189~~ ~~186~~ ~~155~~ ~~143~~ 137 bytes

*-47 bytes thanks to TheLethalCoder*
*-4 bytes thanks to Nazar554*
*-16 bytes thanks to Luc*
*-2 bytes thanks to Kamil Drakari*

```
_=>{var x=new long[9];for(int i=0;i<9;){Console.ReadKey();x[i++]=DateTime.Now.Ticks;}return Math.Round(48e8/(x[8]-x[0]),2);}

```

Also added to byte count:

```
using System;

```

Whole program:

```
namespace System
{
    class A
    {
        static void Main()
        {
            Func<int, double> f = _ =>
            {
                var x = new long[9];
                for (int i = 0; i < 9; )
                {
                    Console.ReadKey();
                    x[i++] = DateTime.Now.Ticks;
                }
                return Math.Round(48e8 / (x[8] - x[0]), 2);
            };
            Console.WriteLine(f(0));
        }
    }
}

```

# Answer
> 2 votes
# Python + curses, 122 bytes

```
import curses as C,time as T
s=C.initscr()
C.cbreak()
t=0
exec's.getch();t=t or T.time()'*9
print'%.2f'%(540/(T.time()-t))

```

Requires the `curses` module to be loaded.

-9 bytes thanks to Felipe Nardi Batista

# Answer
> 2 votes
## C++, 150 bytes

```
#include<iostream>
#include<ctime>
#define G getchar()
void f(){G;auto s=clock();G;G;G;G;G;G;G;G;std::cout<<round(6000/(double(clock()-s)/8000))/100;}

```

# Answer
> 2 votes
## vba, 57

```
msgbox"":x=timer:for i=1to 8:msgbox"":next:?480/(timer-x)

```

press enter, or click on the OK in the message box.

# Answer
> 2 votes
# Python 3, 74 bytes

```
from timeit import*;print('%.2f'%(480/timeit('input()',input(),number=8)))

```

Try it online!

This will give you silly numbers in TIO since it runs all the inputs at once but it does work. `timeit()` returns the execution time of the statement `'input()'` in seconds excluding the setup parameter `input()`. TIO with a 1s delay per input for validation.

# Answer
> 1 votes
# Java 8, ~~180~~ 135 bytes

*-45 bytes thanks to @SocraticPhoenix suggesting to use `System.in` directly.*

```
x->{System.in.read();long t=System.nanoTime(),i=0;for(;i++<8;System.in.read());System.out.printf("%.2f",4.8e11/(System.nanoTime()-t));}

```

An anonymous lambda function with an unused argument that must be assigned to a functional interface method that throws an `Exception` (example below). Reads from console; beats are sent by pressing `enter`.

## Ungolfed w/ Surrounding Test Code

```
public class A {
    interface F{void f(Object x) throws Exception;}

    public static void main(String[]a) throws Exception {
        F f =

        x->{
            System.in.read();
            long t=System.nanoTime(),i=0;
            for(;i++<8;System.in.read());
            System.out.printf("%.2f",4.8e11/(System.nanoTime()-t));
        }

        ;
        f.f(null);
    }
}

```

# Answer
> 1 votes
# R, ~~79~~ 84 bytes

```
scan();s=Sys.time;x=s();replicate(8,scan());cat(round(60/as.numeric((s()-x)/8),d=2))

```

Only works when using enter, since that will end scan immediately. Explicitly uses `print` for its `digits` argument, handling the rounding.

```
> scan();s=Sys.time;x=s();replicate(8,scan());cat(round(60/as.numeric((s()-x)/8),d=2))
1:
Read 0 items
numeric(0)
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
1:
Read 0 items
[[1]]
numeric(0)

[[2]]
numeric(0)

[[3]]
numeric(0)

[[4]]
numeric(0)

[[5]]
numeric(0)

[[6]]
numeric(0)

[[7]]
numeric(0)

[[8]]
numeric(0)

[1] 439.47

```

# Answer
> 1 votes
# C#, 117 bytes

There's already a C# (.NET Core) answer that this one builds on. Added interpolated string (that .NET Core seems to lack) for output and shaved some bytes by using long array instead of DateTime.

```
_=>{var d=new long[9];for(var i=0;i<9;){Console.ReadKey();d[i++]=DateTime.Now.Ticks;}return$"{48e8/(d[8]-d[0]):n2}";}

```

## Humane version

```
class Program
{
    static void Main()
    {
        Func<int, string> f = _ =>
        {
            var d = new long[9];
            for (var i = 0; i < 9;)
            {
                Console.ReadKey();   // Switch these two to "automate" key presses.
                //Thread.Sleep(100);

                d[i++] = DateTime.Now.Ticks;
            }
            return $"{48e8 / (d[8] - d[0]):n2}";
        };

        var result = f(1);
        Console.WriteLine();
        Console.WriteLine(result);
        Console.ReadKey(true);
    }
}

```

# Answer
> 0 votes
# Ruby, 58 bytes

```
gets;t=Time.now;8.times{gets};p (480/(Time.now-t)).round 2

```

---
Tags: code-golf
---


title: Four In A Row: AI Tournament

text:
# Question
Title: Four In A Row: AI Tournament
# Four-In-A-Row AI Tournament

Today, we will be playing a Four-In-A-Row tournament. However, it is not us humans playing... instead, we must have our computers battle instead! This challenge is completely in C#.

## **Rules**

### Basic Game Rules

If you have never played, there are simple rules. 2 players take turns putting pieces into a 6x7 grid. The player chooses one of the 7 holes at the top of the grid, and puts a piece in. Gravity pulls the piece down, until it hits another piece underneath it.

The game is won when a player gets four of their pieces in a straight line, either vertical or horizontal. Diagonal lines **do not** count in this challenge, as I was lazy when programming my simulator. This will also make it easier for you to code your AIs.

### Code Format

You will write code that goes into a function that gets called when it is your turn. You can receive an argument, `states[,] board` where `states` is an enum with `defender, attacker, empty`. This represents the occupation of a space. Your method must return an int.

### Game Ending

The game ends when someone gets a four-in-a-row, or makes an illegal move. An illegal move is when your program returns an int that is 1) off the board (\< 0 or \> 6) or in a column that is completely filled. In the case of an illegal move, the opponent immediately wins.

Additionally, if your program exits the function or the program, you automatically lose the match. If your program causes a runtime error, you lose the match. **You *are* allowed to try to make the other program cause a runtime error.**

### Variables

You are not allowed to access any variables, properties, or run any methods outside of your function's scope. You are not allowed to define any variables outside of your function's scope.

One exception is the `Dictionary<string, object>` names `variables` I have provided for your convenience. It is in the class `Programs`, so it will keep it's data for the whole match. However, the opponent uses the same dictionary to save its data. One strategy is to sabotage the enemy program by modifying the data it uses.

### Closing the Loopholes

Your submission may not make any external requests, for example to an online API. Your submission may not include a library that is made to solve four-in-a-row games. As a rule of thumb, your program shouldn't need to use anything except `system` or anything included in the `system` library.

You may not exploit any loopholes, either stated or implied in the rules, unless you have asked me through comments and I agreed.

### Tournament Format

This is a tournament, so the AI will be competing against each other. I will post the first answer. The next person will have to beat my program. To beat a program, you must never lose to it. You are only required to beat the program right before you. This process goes on until an answer has not been superseded after one week.

You may answer as many times as you want, but you may not counter your own program.

You may make edits to your code until it has been superseded.

In a nutshell, you must write a program that never loses to its predecessor.

### Testing

Click here to see my match simulation. Paste in your code in the `Programs.cs` file, in your corresponding function. The attacker is the one who is trying to supersede a program. The defender is the one whos program is attempting to hold its place. The defender always moves first.

After your program has been pasted in, run it. The console will open, and it will run the simulation.

### Submission Format

Your submission must be in C#. Your submission must compile correctly. Your submission must follow this format:

```
#<answer number>
[Previous](<Permalink to previous answer>)

    CODE HERE
    CODE HERE

```

### TL;DR

Basically, you will be coding AIs to compete in four-in-a-row. However, read the whole thing if you want to compete!

# Good luck!

# Answer
> 0 votes
# 1

First answer!

```
if(!variables.ContainsKey("randy")){
    variables["randy"] = new Random();
}
return ((Random)variables["randy"]).Next(0, 7);

```

---
Tags: king-of-the-hill, c#
---


# Question
Title: Counting up and down while doubling the increments
## Input:

A non-empty list / vector where each element holds a value/character, indicating if you'll count **up** or **down**. I'll use `1` and `-1`, but you may choose whatever you like. You can only use two values, you can't use `1,2,3...` and `-1,-2,-3...`, for up and down respectively.

## Challenge:

You'll use the numbers in the geometric series **1, 2, 4, 8, 16, 32...**. Every time you start counting up or down, you'll count in increments of **1**, then **2**, then **4** and so on. If you change and start counting the other way then you'll subtract **1**, then **2**, then **4** and so on. The output shall be the number you get to in the end.

### Examples:

In the example below, the first line is the input, the second line is the numbers you're counting up/down, the third line is the cumulative sum, and the last line is the output.

**Example 1:**

```
1   1   1   1   1   1   1   1   1   1
1   2   4   8   16  32  64  128 256 512
1   3   7   15  31  63  127 255 511 1023
1023

```

**Example 2:**

```
1   1   1   1   1   1   -1  -1  -1  -1  1   1   1
1   2   4   8   16  32  -1  -2  -4  -8  1   2   4
1   3   7   15  31  63  62  60  56  48  49  51  55
55

```

As you can see, the first `1` or `-1` "resets" the value we're counting, and consecutive sequences of `1` or `-1` means doubling the value.

**Example 3:**

```
-1  -1  1   1   -1  -1  -1
-1  -2  1   2   -1  -2  -4
-1  -3  -2  0   -1  -3  -7
-7

```

---

Some additional test cases to account for some potential corner cases.

The input is on the first line. The output is on the second.

```
1
1
-------
-1
-1
-------
-1   1  -1   1  -1   1  -1   1  -1   1  -1   1
0

```

---

This is so the shortest submission in each language wins.

# Answer
## Husk, 3 bytes

```
ṁḋg

```

Try it online!

## Explanation

```
ṁḋg
  g  Group equal adjacent elements,
ṁ    take sum of
 ḋ   base-2 decoding of each group.

```
> 19 votes

# Answer
# MATL, 6 bytes

```
Y'Wq*s

```

Try it online! Or verify all test cases.

### Explanation

Consider input `[1 1 1 1 1 1 -1 -1 -1 -1 1 1 1]`.

```
     % Implicit input
     % STACK: [1 1 1 1 1 1 -1 -1 -1 -1 1 1 1]
Y'   % Run-length encoding
     % STACK: [1 -1 1], [6 4 3]
W    % Exponentiation with base 2, element-wise
     % STACK: [1 -1 1], [64 16 8]
q    % Subtract 1
     % STACK: [1 -1 1], [63 15 7]
*    % Multiply, element-wise
     % STACK: [63 -15 7]
s    % sum of array
     % STACK: 55
     % Implicit display

```
> 6 votes

# Answer
# Japt, ~~8~~ 6 bytes

*-2 bytes thanks to @ETHproductions*

```
ò¦ xì2

```

Try it online!

## Explanation

Implicit input: `[1, 1, 1, -1, -1, -1, -1, 1, 1]`

```
ò¦

```

Partition input array (`ò`) between different (`¦`) elements:
`[[1, 1, 1], [-1, -1, -1, -1], [1, 1]]`

```
ì2

```

Map each partition to itself parsed as an array of base-`2` digits (`ì`): `[7, -15, 3]`

```
x

```

Get the sum (`x`) of the resulting array: `-5`
> 6 votes

# Answer
# Cubix, 65 bytes

```
W(?\q.p)w.;0.w;/0>I!U-unP(nwUs;q\^q:;^!u?P(w!u+w.;;>2p!u/@Os..sr\

```

Try it online!

```
        W ( ? \
        q . p )
        w . ; 0
        . w ; /
0 > I ! U - u n P ( n w U s ; q
\ ^ q : ; ^ ! u ? P ( w ! u + w
. ; ; > 2 p ! u / @ O s . . s r
\ . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

Watch it run

As a brief explanation of this:

* Read in each integer (1 or -1) and compare it to previous. If:
    + the same push it to the bottom as the start of a counter
    + else bring counter to top and increment/decrement it as appropriate.
* Once input is finished bring each counter to the top and handling negatives do 2 ^ counter - 1
* Sum the results and output
> 5 votes

# Answer
## JavaScript (ES6), 38 bytes

```
a=>a.map(e=>r+=d=d*e>0?d+d:e,r=d=0)&&r

```
> 4 votes

# Answer
# Python 3, ~~57~~ 56 bytes

*-1 byte thanks to @notjagan*

```
f=lambda a,*s,m=1:m*a+(s>()and f(*s,m=(m*2)**(a==s[0])))

```

Try it online!
> 3 votes

# Answer
# , 32 bytes

```
sum((2^(R=rle(scan()))$l-1)*R$v)

```

Try it online!

This is the same method as a few others here.

With the input of `-1 -1 1 1 -1 -1 -1`

* Do a Run Length Encoding on the input. Results with lengths of `2, 2, 3` and values `-1, 1, -1`
* Do 2 to power of lengths - 1. Results in `3, 3, 7`
* Multiply by the RLE values giving `-3, 3, -7`
* Return the sum `-7`
> 3 votes

# Answer
# Jelly, 4 bytes

```
ŒgḄS

```

Try it online!
> 2 votes

# Answer
# C++14, 58 bytes

```
[](auto v,int&s){int p=s=0;for(auto x:v)s+=p=x*p<1?x:2*p;}

```

Takes input via the `v` argument (`std::vector`, or any iterable container), outputs to the `s` argument (by reference). Each element of `v` must be either `1` or `-1`.

Example usage and test cases.
> 2 votes

# Answer
# Brachylog, 13 bytes

```
ḅ⟨{ȧᵐ~ḃ}×h⟩ᵐ+

```

Try it online!

Brachylog uses `_` instead of `-`.

Explanation:

```
?ḅ⟨{ȧᵐ~ḃ}×h⟩ᵐ+. Predicate (implicit ?.)
?               The input
 ḅ              A list where its elements' elements are equal, and when concatenated is ?
            ᵐ   The result of mapping this predicate over ?
  ⟨        ⟩      The result of forking two predicates over ? with a third
   {    }           The result of this predicate on ?
     ᵐ                The result of mapping this predicate over ?
    ȧ                   The absolute value of ?
      ~               An input where the result of this predicate over it is ?
       ḃ                A list that represents the digits of ? in base I (default 2)
          h         An object that is the first element of ?
         ×          A number that is the product of ?
             +  A number that is the sum of ?
              . The output

```
> 2 votes

# Answer
# Python, ~~76~~ 72 bytes

```
f=lambda s,k=1:len(s)and(f(s,s[0])if s[0]*abs(k)/k-1else k+f(s[1:],2*k))

```

Try it online!
> 1 votes

# Answer
# Pyth, 12 bytes

```
sm*edt^2hdr8

```

Try it online!
> 1 votes

# Answer
# PHP, 51 bytes

```
while($d=$argv[++$i])$s+=$x=$d*$x>0?2*$x:$d;echo$s;

```

Run with `-n` or try it online.
> 1 votes

# Answer
## CJam (13 bytes)

```
{e`{(*2b}%1b}

```

Online test suite. This is an anonymous block (function) which takes an array of ints on the stack and leaves an int on the stack. The last test shows that it handles an empty array correctly, giving 0.

The approach is straightforward run-length encoding followed by a manual run-length decode of each run and base conversion. Using the built-in for run-length decode I get one byte more with `{e`1/:e~2fb1b}` or `{e`{ae~2b}%1b}`.
> 1 votes

# Answer
# 05AB1E, 6 bytes

```
γε2β}O

```

Try it online!
> 1 votes

# Answer
## Haskell, ~~54~~ 53 bytes

```
k#(a:b:c)=k+last(b:[k*2|a==b])#(b:c)
k#_=k
(#)=<<head

```

Try it online!

A simple recursion that either doubles the accumulator `k` or resets it to `1`/`-1` and adds the values of each step.
> 1 votes

# Answer
# Mathematica, 60 bytes

```
Tr[Last@*Accumulate/@(#[[1]]2^(Range@Tr[1^#]-1)&/@Split@#)]&

```
> 0 votes

# Answer
# Mathematica, 25 bytes

```
Tr[Fold[#+##&]/@Split@#]&

```
> 0 votes

# Answer
# Java, 91 bytes

```
int f(int[]a){int s=0,r=0,i=-1;while(++i<a.length)r+=s=s!=0&s>0==a[i]>0?2*s:a[i];return r;}

```
> 0 votes

# Answer
# Pyth, 11 bytes

```
s.b*t^2NYr8

```

Try it online

### How it works

```
         r8    run-length encode input
 .b            map (N, Y) ↦
     ^2N           2^N
    t              minus 1
   *    Y          times Y
s              sum

```
> 0 votes

---
Tags: code-golf, number, sequence
---


# Question
Title: Conways's Game of Life: Most newborn generating starting pattern
## General rules

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

* Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
* Any live cell with two or three live neighbours lives on to the next generation.
* Any live cell with more than three live neighbours dies, as if by overpopulation.
* Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously. The rules continue to be applied repeatedly to create further generations. (Source: Wikipedia )

---

## Specific rules

For this challenge, we will modify a few rules:

* The grid is not infinite. We will provide in the inputs the size of the grid. It will **not** act as a Torus either.
* The game stops when the grid reach a state it has already reached before. This prevents patterns infinite loop and can manage empty grids too.

---

## Challenge

Write a program/function that takes four positive integer as input:

* `x`: starting pattern width
* `y`: starting pattern height
* `n`: grid width
* `m`: grid height

and finds the starting pattern that will generate the most amount of cells through the whole game, and outputs that number. (You can also outputs the corresponding pattern if needed)

The patterns is always centered on the grid. If you need to center with odd numbers, the pattern should be slightly closer to the upper left corner. Refer to that drawing for better understanding where the green area is the pattern already centered:

---

## Specifications

* Standard I/O rules apply.
* Standard loopholes are forbidden.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
* Your code will be scored in bytes, usually in the encoding UTF-8, unless - specified otherwise.
* Explanations, even for "practical" languages, are encouraged.

---

## Example

Let's do a small example together. For this example, the pattern size will be `x = y = 3` and the grid size will be `n = m = 3`

The program will test any possible starting pattern. After running it, we find that the maximum amount of generated cells during one whole game is `11`.

It is obtained following those steps:

Green cells are alive, lime cells are newborn and brown cells just died. One out of two grid is just the transition between two states. The starting pattern is the first state of the game, in the upper left corner. The game ended when there was no living cells left, but most of the time the game end with a repeating infinite pattern.

Here we can get to `11` by counting every lime cells during the transitions. It corresponds to the total amount of generated cells through the whole game.

---

## Test cases

```
Input            Output

3 3 3 3          11,    *[[0, 0, 1], [1, 1, 0], [0, 0, 1]]
3 3 5 5          46,    *[[0, 0, 1], [1, 1, 1], [0, 0, 1]]
3 3 12 12        596,   *[[1, 0, 1], [1, 1, 1], [1, 1, 1]]
2 3 6 3          18,    *[[0, 1], [1, 1], [0, 1]]
3 2 5 5          34,    *[[0, 1, 0], [1, 1, 1]]
4 4 9 9          1067,  *[[1, 0, 1, 1], [1, 1, 0, 1], [0, 0, 0, 1], [1, 0, 1, 1]]

```

* *not needed, just here to help you debugging*

Good luck..

---

## Disclaimer

*Thank you @totallyhuman for your Fibonacci Sequence post, from which I borrowed the presentation style. I found it very clear and I hope you don't mind me using the same layout ;)*

> This challenge differs from basic Game of Life implementation since it asks to test out every starting pattern possible, count the number of generated cells for each of those and check for infinite repeating pattern.

# Answer
# Pyth, ~~65~~ 63 bytes

```
M}3-BGHeSm+F.n<VVM.:.ugVVuCmsM.:++0k03G2NNd)2muCm.[Hk0GQd^^U2EE

```

Test suite

Input is taken as:

```
n,m
x
y

```

On the input `3,3,12,12`, I got 594, not 596, with the same grid as the OP, so I'm not sure what's up.

**How it works:**

`^^U2EE`: Generate all possible patterns

`muCm.[Hk0GQd`: Pad them to the appropriate size. Written as pad, rotate, repeat.

`uCmsM.:++0k03G2N`: Generate the number of live neighbors for each cells. Written as pad, take subsequences of size 3, sum them, rotate, repeat.

`M}3-BGH ... gVV ... N`: Pair that with the original grid, use both to calculate the new cells. We do this by checking whether live neighbors including the center, optionally minus whether it was alive, contains a 3. I really like this `VV` trick, so I wrote a helper function (`M}3-BGH`) so I could do it twice. (see below)

`.u ... d)`: Do that until it stops changing, return all intermediate steps.

`.: ... 2`: Take all consecutive pairs.

`<VVM`: Map each pair to the number of new cells born. I'm particularly proud of `<VVM`, I thought that was very clever.

`m+F.n`: Map each grid to its total number of cells born.

`eS`: Max
> 2 votes

---
Tags: code-golf, array, game-of-life
---


title: Risky Phone Plan

text:
# Question
Title: Risky Phone Plan
You have a phone plan that lets you talk 180 minutes a day. Every day that you go over your daily limit you have to pay a fine of **F = Men**, where *M* is the number of minutes you went over and *n* is the number of days you have gone over (e.g if I went 20 minutes over the daily limit and it's my 2nd day going over, I have to pay 20\*e2 = 147.78).

You will be given a list of 12-hour clock times. Even-indexed times represent the start of a phone call, odd-indexed times represent the end of a phone call. Using this list find out how much money the person has to pay in fines.

# Notes

* Please use an approximation of *e* that is at least as accurate as 2.718
* You never need to round your answers or include a currency symbol.
* The first time in the list will always be an A.M (morning) time.
* Remember that in 12-hour time `1` comes after `12` (you can think of `12` as `0`).
* A day starts at 12:00 AM and ends at 11:59 PM
* If a number is lower than the previous time, then that means that it is in the opposite (A.M./P.M) time range.
* A call will never start in one day and end in another.

# Test Cases

```
10:30
2:30
5:30
6:30

```

This person made two phone calls in one day. One from 10:30 A.M. to 2:30 P.M., another from 5:30 P.M to 6:30 P.M. In total, they talked for 5 hours this day, going 120 minutes over the daily limit. Since it's their first offense, they have to pay 120\*e = `$326.19` (yes, their phone plan is quite Draconic).

---

```
10:30
11:45
5:15
6:45
8:20
9:20
5:30
7:50
2:30
3:30

```

This person made several phone calls over 2 days. The first day they were on the phone from 10:30-11:45 A.M, 5:15-6:45 P.M., and 8:20-9:20 PM using a total of 225 minutes. That is an overage of 45 minutes. So their fine for the day is 45\*e = $122.32.

The next day they talked from 5:30-7:50 A.M and 2:30-3:30 P.M., a total of 200 minutes. They went over by 20 minutes, and since it's their second offense they pay 20\*e2 = $147.78

You output their total fee as $122.32 + $147.78 = `$270.10`

---

```
10:30
11:30
6:30
7:30
9:45
11:00
10:25
11:25
8:45
9:45
6:00
8:00
2:30
4:30

```
* **Day 1:**
    + 10:30-11:30 A.M., 6:30-7:30 P.M., 9:45-11:00 P.M. = 195 minutes
    + Fee: 15\*e = $40.77
* **Day 2:**
    + 10:25-11:25 A.M., 8:45-9:45 P.M. = 120 minutes
    + Fee: $0
* **Day 3:**
    + 6:00 - 8:00 A.M., 2:30-4:30 P.M. = 240 minutes
    + Fee: 60\*e2 = $443.34

Output: $40.77 + $0 + $443.34 = `$484.11`

# Answer
# Perl 5, 185 bytes

```
@c=map{s/(.+):(.+)/$1%12*60+$2/er}<>;while(@c){$s=shift@c;$e=shift@c;$p+=0>($k=$e-$s)?720+$k:$k;if($e>$c[0]||$k<0){if($m||!@c){$f+=0>($p-=180)?0:$p*exp++$d;$p=0}$m=!$m}}printf'$%.2f',$f

```

Try it online!
> 1 votes

---
Tags: code-golf, clock
---


title: 2D partitioned cumulative sum

text:
# Question
Title: 2D partitioned cumulative sum
### Challenge

Given a matrix **M** with **r** rows and **c** columns, and two Boolean lists **V** of length **r** and **H** of length **c**, calculate the partitioned cumulative vertical and horizontal sums.

### Rules

* **r** and **c** are greater than or equal to one
* **H** and **V** begin with a true value
* The values in **M** are within your language's reasonable numeric domain.
* Partitioning and summing begins in the top left corner.

### Walk through

Given **M**:

```
┌──────────────┐
│ 1  2  3  4  5│
│ 6  7  8  9 10│
│11 12 13 14 15│
│16 17 18 19 20│
└──────────────┘

```

**H**: `1 0 1 0 0`

**V**: `1 1 0 1`

Split **M** into groups of columns, beginning a new group at every true value of **H**

```
┌─────┬────────┐
│ 1  2│ 3  4  5│
│ 6  7│ 8  9 10│
│11 12│13 14 15│
│16 17│18 19 20│
└─────┴────────┘

```

Split each group of columns into groups of rows, beginning a new group at every true value of **V**:

```
┌─────┬────────┐
│ 1  2│ 3  4  5│
├─────┼────────┤
│ 6  7│ 8  9 10│
│11 12│13 14 15│
├─────┼────────┤
│16 17│18 19 20│
└─────┴────────┘

```

Cumulatively sum each cell horizontally:

```
┌─────┬────────┐
│ 1  3│ 3  7 12│
├─────┼────────┤
│ 6 13│ 8 17 27│
│11 23│13 27 42│
├─────┼────────┤
│16 33│18 37 57│
└─────┴────────┘

```

Cumulatively sum each cell vertically:

```
┌─────┬────────┐
│ 1  3│ 3  7 12│
├─────┼────────┤
│ 6 13│ 8 17 27│
│17 36│21 44 69│
├─────┼────────┤
│16 33│18 37 57│
└─────┴────────┘

```

Result:

```
┌──────────────┐
│ 1  3  3  7 12│
│ 6 13  8 17 27│
│17 36 21 44 69│
│16 33 18 37 57│
└──────────────┘

```

### Additional test cases

**M**:

```
┌───────────┐
│15 11 11 17│
│13 20 18  8│
└───────────┘

```

**H**: `1 0 0 1`**V**: `1 0`

Result:

```
┌───────────┐
│15 26 37 17│
│28 59 88 25│
└───────────┘

```

**M**:

```
┌─┐
│7│
└─┘

```

Result (**H** and **V** must be `1`):

```
┌─┐
│7│
└─┘

```

**M**:

```
┌──┐
│ 3│
│-1│
│ 4│
└──┘

```

**V**: `1 1 0` (**H** must be `1`)

Result:

```
┌──┐
│ 3│
│-1│
│ 3│
└──┘

```

**M**:

```
┌───────────────────────────────────────────────────────┐
│10    7.7 1.9 1.5 5.4  1.2 7.8 0.6 4.3 1.2  4.5 5.4 0.3│
│ 2.3  3.8 4.1 4.5 1    7.7 3   3.4 6.9 5.8  9.5 1.3 7.5│
│ 9.1  3.7 7.2 9.8 3.9 10   7.6 9.6 7.3 6.2  3.3 9.2 9.4│
│ 4.3  4.9 7.6 2   1.4  5.8 8.1 2.4 1.1 2.3  7.3 3.6 6  │
│ 9.3 10   5.8 9.6 5.7  8.1 2.1 3.9 4   1.3  6.3 3.1 9  │
│ 6.6  1.4 0.5 6.5 4.6  2.1 7.5 4.3 9   7.2  2.8 3.6 4.6│
│ 1.7  9.9 2.4 4.5 1.3  2.6 6.4 7.8 6.2 3.2 10   5.2 8.9│
│ 9.9  5.3 4.5 6.3 1.4  3.1 2.3 7.9 7.8 7.9  9.6 4   5.8│
└───────────────────────────────────────────────────────┘

```

**H**: `1 0 0 1 0 1 1 1 0 1 1 1 0`

**V**: `1 0 0 0 0 1 0 0`

Result:

```
┌────────────────────────────────────────────────────────────────┐
│10   17.7 19.6  1.5  6.9  1.2  7.8  0.6  4.9  1.2  4.5  5.4  5.7│
│12.3 23.8 29.8  6   12.4  8.9 10.8  4   15.2  7   14    6.7 14.5│
│21.4 36.6 49.8 15.8 26.1 18.9 18.4 13.6 32.1 13.2 17.3 15.9 33.1│
│25.7 45.8 66.6 17.8 29.5 24.7 26.5 16   35.6 15.5 24.6 19.5 42.7│
│35   65.1 91.7 27.4 44.8 32.8 28.6 19.9 43.5 16.8 30.9 22.6 54.8│
│ 6.6  8    8.5  6.5 11.1  2.1  7.5  4.3 13.3  7.2  2.8  3.6  8.2│
│ 8.3 19.6 22.5 11   16.9  4.7 13.9 12.1 27.3 10.4 12.8  8.8 22.3│
│18.2 34.8 42.2 17.3 24.6  7.8 16.2 20   43   18.3 22.4 12.8 32.1│
└────────────────────────────────────────────────────────────────┘

```

# Answer
> 9 votes
# Jelly, 10 bytes

```
Zœṗ@+\€Ẏð/

```

Try it online! and The Last Test Case (With a `G` at the end for readability).

Input is taken as a list `[M, H, V]`.

## Explanation

```
Zœṗ@+\€Ẏð/  Input: [M, H, V]
        ð/  Insert the previous (f) as a dyadic link
            Forms f( f(M, H) , V)
            For f(x, y):
Z             Transpose x
 œṗ@          Partition the rows of x^T at each true in y
    +\€       Compute the cumulative sums in each partition
       Ẏ      Tighten (Joins all the lists at the next depth)

```

# Answer
> 7 votes
# APL (Dyalog), 13 bytes

Takes ist of **V H M** as argument.

```
{⍉⊃,/+\¨⍺⊂⍵}/

```

Try it online!

`{``}/` insert (reduce by) the following anonymous function, where the term in the left is represented by ⍺ and the term on the right is represented by ⍵. Due to APL functions being right associative, this is therefore **V** *f* (**H** *f* **M**).

`⍺⊂⍵` partition ⍵ according to ⍺

`+\¨` cumulative sum of each part

`,/` reduce by concatenation (this encloses the result to reduce rank)

disclose

transpose

# Answer
> 6 votes
# Python 2 \+ numpy, 143 138 117 115 110 108 bytes

<sup>-21 bytes thanks to Adám!</sup>

```
lambda M,*L:reduce(lambda m,l:vstack(map(lambda p:cumsum(p,0),split(m,*where(l)))).T,L,M)
from numpy import*

```

Try it online!

# Answer
> 5 votes
# Jelly,  ~~15~~  14 bytes

```
œṗ+\€Ẏ
ḢçÐ€Zð⁺

```

A dyadic link taking `H,V` on the left and `M` on the right and returning the resulting matrix.

**Try it online!**

Alternatively as a single line also for 14: `Ḣœṗ+\€Ẏ$¥Ð€Zð⁺`

### How?

```
œṗ+\€Ẏ - Link 1: partition and cumSum: list of partition bools, list of values
œṗ     - partition (the values) at truthy indexes (of the bools)
    €  - for €ach part:
  +\   -   cumulative reduce by addition
     Ẏ - tighten (flattens back into a list)

ḢçÐ€Zð⁺ - Main link: list of lists, [H,V]; list of lists, M
      ⁺ - perform this twice:
     ð  - [it's a dyadic chain for the second pass, first pass is dyadic implicitly]
Ḣ       -   head, pop it & modify (so H the first time, V the second)
  Ð€    -   map across right: (M the first time, the intermediate result the second)
 ç      -     the last link (1) as a dyad
    Z   -   transpose the result (do the rows first time, and the columns the second)

```

---

Previous:

```
œṗ@+\€Ẏ
ç€Zç€⁵Z

```

A full program printing a representation of the result.

# Answer
> 4 votes
# MATL, 19 bytes

```
,!ix"0GYs@12XQ!g]v!

```

Inputs are `M` (matrix), `H` (column vector), `V` (column vector). The row separator is `;`.

Try it online! Or verify all test cases: , , , , .

### Explanation

This does the cumulative sum horizontally, then vertically.

```
,          % Do the following twice
  !        %   First time this inputs M implicitly. Transpose. Second time
           %   it transposes the result of the horizontal cumulative sum
  ix       %   Input H (first time) or V (second time). Delete it; but gets
           %   copied into clipboard G
  "        %   For each column of the matrix
    0G     %     Push most recent input: H (first time) or V (second)
    Ys     %     Cumulative sum. This produces a vector of integer values
           %     such that all columns (first time) or rows (second) of M
           %     with the same value in this vector should be cumulatively
           %     summed
    @      %     Push current column of M transposed (first time) or M after
           %     horizontal cumulative sum (second time)
    12XQ   %     Cumulative sum. Gives a cell array of row vectors
    !g     %     Join those vectors into one row vector
  ]        %   End
  v        %   Concatenate the row vectors vertically into a matrix
  !        %   Transpose. This corrects for the fact that each column vector
           %   of the matrix was cumulatively summed into a row vector
           % Implicit end. Implicit display

```

# Answer
> 3 votes
# , 20 bytes

```
;@(<@(+/\);.1|:)&.>/

```

Try it online!

Input is taken as an array of boxes containing `[V, H, M]`.

## Explanation

```
;@(<@(+/\);.1|:)&.>/  Input: [V H M]
  (     g      )   /  Insert g and reduce (right-to-left)
                      Forms V g H g M = V g (H g M)
                & >     Unbox each
             |:         Transpose the right arg
          ;.1           Partition
      +/\               Reduce each prefix using addition (cumulative sum)
   <@                   Box each partition
;@                      Raze (Concatenate the contents in each box)
                &.>     Box the result

```

# Answer
> 2 votes
# Mathematica, 212 bytes

```
(T=Transpose;A=AppendTo;J=Flatten;f[s_]:=Block[{},t=2;r=1;w={};While[t<=Length@s,If[s[[t]]==0,r++,w~A~r;r=1];t++];w~A~r];K[x_,y_]:=Accumulate/@#&/@(FoldPairList[TakeDrop,#,f@y]&/@x);d=J/@K[#,#2];T[J/@K[T@d,#3]])&

```

**input**
\[M,H,V\]

> \[{{15, 11, 11, 17}, {13, 20, 18, 8}}, {1, 0, 0, 1}, {1, 0}\]

# Answer
> 2 votes
# C# (.NET Core), 164 bytes

```
(M,H,V)=>{int a=M.Length,b=M[0].Length,i,j;for(i=0;i<a;i++)for(j=0;j<b;j++)if(!H[j])M[i][j]+=M[i][j-1];for(i=0;i<a;i++)for(j=0;j<b;j++)if(!V[i])M[i][j]+=M[i-1][j];}

```

Try it online!

Basically it does exactly as specified in the OP. It first iterates to sum horizontally and then it iterates again to sum vertically.

# Answer
> 2 votes
# Haskell, ~~129 bytes~~ 119 bytes

```
s m v=tail$scanl(\a(x,s)->if s then x else zipWith(+)a x)[](zip m v)
t=foldr(zipWith(:))$repeat[]
f m h v=t$s(t$s m v)h

```

Try it online!

*Saved 10 bytes thanks to @ceasedtoturncounterclockwis*

`t` (for transpose) switches rows and columns. A quick explanation:

```
foldr(zipWith(:))(repeat[])(r1,...,rn) =
zipWith(:) r1 (zipWith(:) r2 (... zipWith(:) rn (repeat [])))

```

Read from right to left: we browse rows from bottom to up, and push each value in its destination column.

`s` is basically a rolling sum of vectors, but resets when a True value arises in `v`

`f` sums the rows with `s` following `v` and do the same with the columns following `h`

# Answer
> 1 votes
## JavaScript (ES6), 88 bytes

```
(a,h,v)=>a.map(b=>b.map((e,i)=>t=h[i]?e:t+e)).map((b,j)=>t=v[j]?b:t.map((e,i)=>e+b[i]))

```

# Answer
> 0 votes
# Jelly, 31 bytes

```
+\€€
œṗḊZ€⁵œṗ$€Ḋ€Ç€ÇZ€€Z€;/€€;/

```

Try it online!

Gah this is way too long for Jelly xD

BTW, 11/31 bytes in this program consists of euro characters. That's over a third of the program!

---
Tags: code-golf, arithmetic, matrix, subsequence
---


# Question
Title: Given a list of circles, output the area of the smallest containing rectangle
You will be given a list of radii, you must output the area of the smallest rectangle which they will all fit in.

For example, given the list `[5,3,1.5]` you would output `157.460`.

This is the image:

The width is 15.7460 and the height is 10, so the area is 157.460

Rules:

* You get the list via stdin or function argument, output the answer via stdout or function return.
* The radii will have at most 2 decimal places.
* The list will have a length between 2 and 6.
* The output should be accurate to 3 decimal places or more.
* If you need, π = 3.1416.

Test cases:

* `[5,3,1.5] = 157.460`
* `[9,4,8,2] = 733.431` \- working here.
* `[18,3,1] = 1296.000`

Shortest code in bytes wins.

# Answer
> 17 votes
# Python 2 + PySCIPOpt, 267 bytes

```
from pyscipopt import*
R=input()
m=Model()
V,C=m.addVar,m.addCons
a,b,c=V(),V(),V()
m.setObjective(c)
C(a*b<=c)
P=[]
for r in R:
 x,y=V(),V();C(r<=x);C(x<=a-r);C(r<=y);C(y<=b-r)
 for u,v,s in P:C((x-u)**2+(y-v)**2>=(r+s)**2)
 P+=(x,y,r),
m.optimize()
m.printBestSol()

```

### How it works

We write the problem as follows: minimize *c* over variables *a*, *b*, *c*, *x*1, *y*1, …, *x**n*, *y**n*, where

* *ab**c*;
* *r**i**x**i**a**r**i* and *r**i**y**i**b**y**i*, for 1 ≤ *i**n*;
* (*x**i**x**j*)2 \+ (*y**i**y**j*)2 ≥ (*r**i* \+ *r**j*)2, for 1 ≤ *j* \< *i**n*.

Obviously, we’re using an external optimization library on these constraints, but you can’t just feed them to any old optimizer—even Mathematica’s `NMinimize` gets stuck at local minima for these tiny test cases. If you stare closely at the constraints, you’ll see that they constitute a quadratically-constrained quadratic program, and finding the global optimum for a non-convex QCQP is NP-hard. So we need some incredibly high-powered magic. I chose the industrial-strength solver SCIP, which is the only global QCQP solver I could find with so much as a free license for academic use. Happily, it has some very nice Python bindings.

### Input and output

Pass the radius list on stdin, like `[5,3,1.5]`. The output shows `objective value:` rectangle area, `x1`, `x2` rectangle dimensions, `x3` rectangle area again, `x4`, `x5` first circle center coordinates, `x6`, `x7` second circle center coordinates, etc.

### Test cases

### `[5,3,1.5]``157.459666673757`

```
SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 0.04
Solving Nodes      : 187
Primal Bound       : +1.57459666673757e+02 (9 solutions)
Dual Bound         : +1.57459666673757e+02
Gap                : 0.00 %
objective value:                     157.459666673757
x1                                                 10   (obj:0)
x2                                   15.7459666673757   (obj:0)
x3                                   157.459666673757   (obj:1)
x4                                                  5   (obj:0)
x5                                                  5   (obj:0)
x6                                                  7   (obj:0)
x7                                   12.7459666673757   (obj:0)
x8                                                1.5   (obj:0)
x9                                   10.4972522849871   (obj:0)

```

### `[9,4,8,2]``709.061485909243`

This is better than the OP’s solution. The exact dimensions are 18 by 29 + 6√3.

```
SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 1.07
Solving Nodes      : 4650
Primal Bound       : +7.09061485909243e+02 (6 solutions)
Dual Bound         : +7.09061485909243e+02
Gap                : 0.00 %
objective value:                     709.061485909243
x1                                                 18   (obj:0)
x2                                   39.3923047727357   (obj:0)
x3                                   709.061485909243   (obj:1)
x4                                                  9   (obj:0)
x5                                   30.3923047727357   (obj:0)
x6                                                 14   (obj:0)
x7                                   18.3923048064677   (obj:0)
x8                                                  8   (obj:0)
x9                                                  8   (obj:0)
x10                                                 2   (obj:0)
x11                                  19.6154311552252   (obj:0)

```

### `[18,3,1]``1295.999999999`

```
SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 0.00
Solving Nodes      : 13
Primal Bound       : +1.29599999999900e+03 (4 solutions)
Dual Bound         : +1.29599999999900e+03
Gap                : 0.00 %
objective value:                       1295.999999999
x1                                   35.9999999999722   (obj:0)
x2                                                 36   (obj:0)
x3                                     1295.999999999   (obj:1)
x4                                   17.9999999999722   (obj:0)
x5                                                 18   (obj:0)
x6                                   32.8552571627738   (obj:0)
x7                                                  3   (obj:0)
x8                                                  1   (obj:0)
x9                                                  1   (obj:0)

```

### Bonus cases

### `[1,2,3,4,5]``230.244214912998`

```
SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 401.31
Solving Nodes      : 1400341
Primal Bound       : +2.30244214912998e+02 (16 solutions)
Dual Bound         : +2.30244214912998e+02
Gap                : 0.00 %
objective value:                     230.244214912998
x1                                   13.9282031800476   (obj:0)
x2                                    16.530790960676   (obj:0)
x3                                   230.244214912998   (obj:1)
x4                                                  1   (obj:0)
x5                                   9.60188492354373   (obj:0)
x6                                    11.757778088743   (obj:0)
x7                                   3.17450418828415   (obj:0)
x8                                                  3   (obj:0)
x9                                    13.530790960676   (obj:0)
x10                                  9.92820318004764   (obj:0)
x11                                   12.530790960676   (obj:0)
x12                                                 5   (obj:0)
x13                                                 5   (obj:0)

```

### `[3,4,5,6,7]``553.918025310597`

```
SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 90.28
Solving Nodes      : 248281
Primal Bound       : +5.53918025310597e+02 (18 solutions)
Dual Bound         : +5.53918025310597e+02
Gap                : 0.00 %
objective value:                     553.918025310597
x1                                   21.9544511351279   (obj:0)
x2                                   25.2303290086403   (obj:0)
x3                                   553.918025310597   (obj:1)
x4                                                  3   (obj:0)
x5                                   14.4852813557912   (obj:0)
x6                                   4.87198593295855   (obj:0)
x7                                   21.2303290086403   (obj:0)
x8                                   16.9544511351279   (obj:0)
x9                                                  5   (obj:0)
x10                                                 6   (obj:0)
x11                                                 6   (obj:0)
x12                                  14.9544511351279   (obj:0)
x13                                  16.8321595389753   (obj:0)

```

### `[3,4,5,6,7,8]``777.87455544487`

```
SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 218.29
Solving Nodes      : 551316
Primal Bound       : +7.77874555444870e+02 (29 solutions)
Dual Bound         : +7.77874555444870e+02
Gap                : 0.00 %
objective value:                      777.87455544487
x1                                   29.9626413867546   (obj:0)
x2                                   25.9614813640722   (obj:0)
x3                                    777.87455544487   (obj:1)
x4                                   13.7325948669477   (obj:0)
x5                                   15.3563780595534   (obj:0)
x6                                   16.0504838821134   (obj:0)
x7                                   21.9614813640722   (obj:0)
x8                                   24.9626413867546   (obj:0)
x9                                   20.7071098175984   (obj:0)
x10                                                 6   (obj:0)
x11                                  19.9614813640722   (obj:0)
x12                                                 7   (obj:0)
x13                                                 7   (obj:0)
x14                                  21.9626413867546   (obj:0)
x15                                  8.05799919177801   (obj:0)

```

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


title: ASCII reflections in a box

text:
# Question
Title: ASCII reflections in a box
# ASCII reflections in a box

You probably all know the *Law of Reflection*, in this challenge you'll visualize the trajectory of a ball in a box.

Related: ASCII Ball in Box Animation and ASCII Doodling: Laser in a Box

### Task

You're given three integer pairs `W,H`, `x,y` and `dx,dy` \- the first represents the size of the box, the second the starting position and the third pair is the direction in which the ball starts moving.

The task is to visualize the movement of the ball until it stops rolling, this happens as soon as the ball is at a position that it was before or it hits a corner.

The character `*` shall visualize the trajectory of the ball and `+` marks its final position, the rest of the box must consist of  (whitespace).

### Examples

To lay it out a bit clearer, in these examples `_` will represent a whitespace. Also the intermediate stages are only here for clarification, you'll only need to output the last stage, these examples are `1`-indexed.

---

Given `W = 3, H = 5`, `x = 3, y = 2` and `dx = -1, dy = 1`:

```
___    ___    ___    ___
__*    __*    __*    __*
___ -> _*_ -> _*_ -> _+_
___    *__    *__    *_*
___    ___    _*_    _*_

```
* Ball starts at point `(3,2)` and
* moves in direction `(-1,1)`, hits the wall at `(1,4)` and
* gets reflected, new direction is `(1,1)`. It hits the wall again at `(2,5)`
* where it gets gets reflected. The new direction is `(1,-1)` and it hits the wall immediately at `(3,4)`,
* again it gets reflected into the direction `(-1,-1)`. It would now travel through points `(2,3),(1,2)`, reflected etc. but since it already visited the position `(2,3)` it stops there.

---

This example demonstrates, what happens if a ball hits a corner. For this let `W = 7, H = 3`, `x = 1, y = 3` and `dx = 1, dy = -1`:

```
_______    __*____    __*____    __*___+
_______ -> _*_____ -> _*_*___ -> _*_*_*_
*______    *______    *___*__    *___*__

```
* Start position is `(1,3)`,
* the ball now travels in direction `(1,-1)` until it hits the wall at `(3,1)`
* where it gets reflected into the new direction `(1,1)`.
* At `(5,3)` it gets reflected and travels into the new direction `(1,-1)`. It comes to an abrupt stop at `(7,1)` because that's a corner.

---

Given `W = 10, H = 6`, `x = 6, y = 6` and `dx = 1, dy = 1`:

```
__________    __________    ________*_    ________*_    ________*_    __*_____*_    __*_____*_
__________    _________*    _________*    _______*_*    _______*_*    _*_____*_*    _*_*___*_*
__________ -> ________*_ -> ________*_ -> ______*_*_ -> *_____*_*_ -> *_____*_*_ -> *___*_*_*_
__________    _______*__    _______*__    _____*_*__    _*___*_*__    _*___*_*__    _*___+_*__
__________    ______*___    ______*___    ____*_*___    __*_*_*___    __*_*_*___    __*_*_*___
_____*____    _____*____    _____*____    ___*_*____    ___*_*____    ___*_*____    ___*_*____

```

### Input specification

The input consists of the three integer pairs `W,H`, `x,y` and `dx,dy`, you may take input in any format that makes most sense for your programming language and the order doesn't matter. However the accepted input must not encode more information than these pairs contain (see this answer for an example).

* `W,H >= 1`
* `x,y` are either `1`-indexed (`1 <= x <= W` and `1 <= y <= H`) or `0`-indexed (`0 <= x < W` and `0 <= y < H`), please specify what indexing you chose
* `dx,dy` are always either `-1` or `1`

Invalid input can be ignored.

### Output specification

1. No leading whitespaces are allowed
2. Trailing whitespaces may be omitted
3. Trailing whitespaces are not allowed if they don't fit the box
4. Trailing newlines (*after* all output related lines) are allowed

Let's take the first example:

```
       (good by 2)
__*
_+     (good by 2)
*_*_   (bad by 3)
       (bad by 4)
_*_
       (good by 4)

```

### Test cases

Assuming the input has the format `(W,H,x,y,dx,dy)` and `1`-indexing was chosen, here are some test cases (again `_` is here to represent whitespaces!):

Input: 1,1,1,1,1,1

Output:

```
+

```

Input: 3,3,3,3,1,1

Output:

```
___
___
__+

```

Input: 3,3,3,3,-1,-1

Output:

```
+__
_*_
__*

```

Input: 7,3,1,3,1,-1

Output:

```
__*___+
_*_*_*_
*___*__

```

Input: 10,6,6,6,1,1

Output:

```
__*_____*_
_*_*___*_*
*___*_*_*_
_*___+_*__
__*_*_*___
___*_*____

```

Input: 21,7,6,4,-1,-1

Output:

```
__*_______*_______*__
_*_*_____*_*_____*_*_
*___*___*___*___*___*
_*___*_*_____*_*___*_
__*___*_______+___*__
___*_*_________*_*___
____*___________*____

```

---

This is , so the shortest program/function wins, but any effort is appreciated.

# Answer
> 8 votes
# Charcoal, 50 bytes

```
ＵＯＮＮ ＪＮＮ↷ＮＷ⁼ ＫＫ«*¿¬ＫＫ«↷²¶*¿¬ＫＫ«↷²¶↷²*¿¬ＫＫ«↷²¶»»»»+

```

Try it online! Link is to verbose version of code. Takes five inputs: `w`, `h`, `x`, `y`, `a`. `x` and `y` are zero-indexed. `a` represents `dx` and `dy` according to the following encoding:

```
a mod 8 == 1 => dx = 1, dy = 1
a mod 8 == 3 => dx = -1, dy = 1
a mod 8 == 5 => dx = -1, dy = -1
a mod 8 == 7 => dx = 1, dy = -1

```

Explanation:

```
ＵＯＮＮ

```

(note trailing space) Fills the background with spaces to the input width and height. (Normally each square of the background is an empty string, which is then converted to a space on output.)

```
ＪＮＮ

```

Moves the cursor to the initial coordinates.

```
↷Ｎ

```

Rotates to the initial angle.

```
Ｗ⁼ ＫＫ«

```

Repeats as long as the current square is a space.

```
    *

```

Prints an asterisk and moves forward in the current direction.

```
    ¿¬ＫＫ«

```

If the cursor moved outside of the original oblong,

```
        ↷²¶*

```

Rotate the direction, then print a newline (which conveniently takes us back to the previous square) and an asterisk, which moves in the new direction.

```
        ¿¬ＫＫ«

```

If the cursor moved back outside of the original oblong,

```
            ↷²¶↷²*

```

Take the cursor back to the previous square, then rotate again, thus printing the asterisk in the other direction.

```
            ¿¬ＫＫ«

```

If the cursor is still outside of the oblong, we must be at a corner.

```
                ↷²¶

```

So go back to the previous square and give up.

```
»»»»+

```

When we can't move any more, print a "+" sign and stop.

# Answer
> 2 votes
# Desmos Calculator - Non Competing to Help Further Knowledge

Try it online!

**Inputs:**

```
X as X position to Start
Y as Y position to Start
s as slope -> -1 for dX/dY = -1, +1 for dX/dY = +1
h as height of box, with 0-indexing
w as width of box, with 0-indexing

```

**Intermediates:**

```
Let b = gcd(h,w),
Let c = |b-(X-sY)%2b| Or |b-mod(X-sY,2b)|

```

**Formula, abbreviated:**

```
(|b-(x+y)%2b|-c)(|b-(x-y)%2b|-c)=0

```

**Outputs:**

```
x as x position, 0-indexed, where the ball will land when released
y as y position, 0-indexed, where the ball will land when released

```

**How it Works:**

```
(|b-(x+y)%2b|-c)*(|b-(x-y)%2b|-c)=0
                ^ OR operation - |b-(x+y)%2b|-c=0 or |b-(x-y)%2b|-c=0
|b-(x+/-y)%2b|-c = 0
|b-(x+/-y)%2b| = c
|b-(x+/-y)%2b| = c means (b-(x+/-y))%2b = + or -c
b-(x+/-y)%2b = +/- c -> b +/- c = (x+/-y)%2b -> (x+/-y) = n*2*b + b +/- c
Where n is integer.  This will force patterns to repeat every 2b steps in x and y.
Initial pattern n=0: (x +/- y) = b +/- c -> y = +/- x + b +/- c
In the x positive and y positive plane only, these correspond to lines of positive and
negative slope, set at intercept b, offset by c on either side.

```

Program fails to meet final criterion - stopping at intersection point and marking with a +, so is submitted as non-competitive for information to help others complete the challenge. Note that to get Desmos to work when c = 0 or c=b, a small offset factor of 0.01 was introduced, as Desmos seems to have bounds of Mod(A,B) of (0,B) instead of \[0,B)

# Answer
> 1 votes
# Python 3, ~~293~~ 279 bytes

```
w,h,x,y,i,j=map(int,input().split());x-=1;y-=1;l=[x[::]for x in[[' ']*w]*h]
while 1:
 a,b=((x,i)in[(0,-1),(w-1,1)]),((y,j)in[(0,-1),(h-1,1)])
 if a and b or l[y][x]!=' ':l[y][x]='+';break
 i,j=i*(-a*2+1),j*(-b*2+1);l[y][x]='*';x+=i;y+=j
print('\n'.join([''.join(x) for x in l]))

```

Try it online!

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


# Question
Title: Output Rhombus Sequence without Nested Loops
The following is the rhombus sequence.

```
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

```

Your task is to output this, taking no input and using standard output methods (STDOUT, list of numbers or list of strings, etc.).

There's a hitch. You may only use up to one loop - no nested loops. Recursion counts as a loop, so you can either recurse or loop, not both. Non-standard languages will be dealt with on a case-by-case basis.

This is , so shortest program in bytes wins. This is , so you may not take any input whatsoever.

# Answer
# Mathematica, 23 bytes

```
((10^#-1)/9)^2&~Array~9

```

Try it online!
> 8 votes

# Answer
# 05AB1E, 7 bytes

Only one for-loop here

```
TG1N×n,

```

Uses the **05AB1E** encoding. Try it online!

Explanation:

```
TG        # For N in range(1, 10):
  1N×     # Push a string of N 1's
     n    # Square that number
      ,   # Pop and print with a newline

```
> 5 votes

# Answer
# Python 2, ~~32~~ 31 bytes

-1 byte thanks to officialaimm

```
o=0
exec"o=o*10+1;print o*o;"*9

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~42 40 38~~ 35 bytes

*-2 thanks to @officialaimm*

I ported Jenny\_mathy's Mathematica answer to Python, because the arithmetic approach is much shorter:

```
i=1;exec"print(10**i/9)**2;i+=1;"*9

```

**Try it online!**

# Exaplanation

* `i=1` \- Initializes a variable `i` to `1`.
* `exec"..."*9` \- Executes `...` 9 times.
* `print(10**i/9)**2` \- Prints 10 *i* and divides the result by 9, which then gets sqaured.
* `i+=1` \- Increment `i` and execute again.

---

# Python 2, 37 bytes

```
for i in range(9):print(10**-~i/9)**2

```

**Try it online!**

---

# Python 2, 63 bytes

This is the initial version.

```
l='123456789'
for i in l:s=l.index(i);print l[:s]+l[:s+1][::-1]

```

**Try it online!**
> 2 votes

# Answer
# Jelly, 5 bytes

```
9ŒḄ€Y

```

Try it online!

This only uses one mapping loop () since `ŒḄ` (palindromize) is a builtin already. Explanation:

```
9ŒḄ€Y
9     9
   €  Map (our looping construct)
 ŒḄ     Palindromize (make range)
    Y Join by newlines.

```
> 2 votes

# Answer
# SOGL V0.12, ~~8~~ 7 bytes

```
9∫Δø∑ΓO

```

Try it Here!

Explanation:

```
9∫       do 9 times, pushing 1-indexed counter
  Δ        get 1-indexed (last inclusive) range
   ø∑      join together
     Γ     palindromise
      O    output it

```
> 1 votes

# Answer
# Dyalog APL, 20 bytes

```
⍪(' '~⍨∘⍕⍳,1↓⌽∘⍳)¨⍳9

```

Try it online!

**How?**

`¨⍳9` \- for each in range 1..9

`⍳,` \- produce the range of this number

`1↓⌽∘⍳` \- appended to itself reversed without the last item

\- format to string

`' '~⍨` \- remove spaces

\- output vertically

## 17 bytes, doesn't work because of precision issues

```
⌽⍕×⍨⍪(10⊥1⍴⍨⊢)¨⍳9

```

This one uses the `i` ones squared identity, but replaces the first one on the last line with a `0`, because the decoding rounds it up.
> 1 votes

# Answer
# Brachylog, 15 bytes

```
9⟦₁{⟦₁⟨kc↔⟩cẉ}ᵐ

```

Try it online!

Yeah this doesn't feel much declarative...
> 1 votes

# Answer
# Vim \+ coreutils, 42 bytes

```
i1⏎12<Esc>qqYp$ylp<C-a>q6@qggqqjYpv$!rev⏎kJd2lq7@q

```

Try it online!

### Ungolfed/Explanation

```
i1⏎12<Esc>                                          " start with lines 1,12 in the buffer
          qq           q6@q                         " record macro and run it 6 times:
            Yp                                      "  - duplicate line
              $ylp                                  "  - duplicate last character
                  <C-a>                             "  - increment it
                           gg                       " go to the beginning (buffer is now: 1,12,123,...,12..89)
                             qq               q7@q  " record macro and run it 6 times:
                               jYp                  "  - go to line below and duplicate it
                                  v$!rev⏎           "  - mark it and reverse it
                                         kJ         "  - join the line above with the current one
                                           d2l      "  - remove the space and character that are too much

```
> 1 votes

# Answer
# C#, 101 bytes

```
using System.Linq;_=>new int[9].Select((n,i)=>"123456789".Substring(0,i+1)+"87654321".Substring(8-i))

```

Try it online!

---

Or the loop approach for 111 bytes:

```
_=>{var a=new string[9];for(int i=0;i<9;)a[i]="123456789".Substring(0,++i)+"87654321".Substring(9-i);return a;}

```

Try it online!
> 1 votes

# Answer
# Pyth, 11 bytes

```
jm^s*d\12S9

```

Try it online!

---

## How does this work?

```
 m       S9         - Map over [1...9]
  ^s    2           - The square of the integer formed by:
    *d\1            - the string with n consecutive 1s.
j                   - Join by newlines

```
> 0 votes

# Answer
# Haskell, ~~39~~ 32 bytes

No for loops/recursion at all, makes use of list comprehension:

```
[[1..x]++[x-1,x-2..1]|x<-[1..9]]

```

Try it online!
> 0 votes

# Answer
# Scala, 69 bytes

There is only one "loop", when I iterate over `(1 to 9)`. But you could consider that there are loops in `reverse` and `Range` instanciations.

```
(1 to 9).map(x=>println(((1 to x)++(1 to x-1).reverse).mkString("")))

```

Try it online!
> 0 votes

# Answer
# Google Sheets, 66 bytes

```
=ArrayFormula(Join("
",REPT(1,ROW(A1:A8))^2,"12345678987654321"))

```

No loops, just a matrix. It would only be 46 bytes but Sheets only has 15 decimal points of precision so the last number is displayed as `12345678987654300` or `1.23457E+1621` so I had to add it manually.
> 0 votes

# Answer
# AHK, 55 bytes

```
a=1
Loop,9{
b:=a**2
Send %b%`n
a:=a 1
}
Send {VK08 2}1

```

This was too stupid of a result for me to not post. AHK messes rounds the last output to `12345678987654320` so we backspace twice and add a `1`.
> 0 votes

# Answer
# QBIC, 17 bytes

```
[9|?((z^a-1)/9)^2

```

From oeis.
> 0 votes

# Answer
# , 18 bytes

```
cumsum(10^(0:8))^2

```

Returns the values.

Try it online!

Due to floating point precision issues, the last number is `12345678987654320` which is equal to `12345678987654321` in R, as the footer shows. In the header, it sets the options to get the numbers to print in non-scientific notation.
> 0 votes

# Answer
# Javascript 66 bytes

Returns an array of strings representing the numbers in the sequence (necessary because 12345678987654321 is too large to be accurately represented as an int in Javascript)

```
o=>Array(9).fill``.map(x=>(x+(n=n*10+1)*n).replace(0,1),n=0)

```

## Explanation

```
o=>                               // o is unused input (saves 1 byte vs ())
    Array(9)                      // create an array of length 9
        .fill``                   // fill it with empty strings
                                  // we must fill it with something, because map skips
                                  // empty entries
        .map(                     // loop over the array and return a new array with the
                                  // values returned by the callback
            x=>(                  // x is the element in the array
                (x+(n=n*10+1)*n)  // make n 1, 11, 111, 1111, etc, and get the string
                                  // value of n^2
                    .replace(0,1) // replace 0's with 1's (necessary for
                                  // 12345678987654321, because
                                  // 111111111^2 = 12345678987654320 in javascript)
            ),
            n=0                   // n^2 is the rhombus number at each stage
        )

```
> 0 votes

# Answer
## Kotlin, 46 bytes

```
(1..9).map{"1".repeat(it).toLong()}.map{it*it}

```
> 0 votes

# Answer
# PHP, ~~38~~ 37 bytes

```
for(;$i<9**8;)echo(($i.='1')**2)."
";

```

with warnings

# PHP, ~~42~~ 41 bytes

```
for($i=0;$i<9**8;)echo(($i.='1')**2)."
";

```

without warnings
> 0 votes

# Answer
# Swift, 76 bytes

```
import Foundation
for i in 1...9{print(Int(pow((pow(10,Double(i))-1)/9,2)))}

```

**Try it online!**

If printing as an array of lines is allowed, here is **74 byte** approach:

```
import Foundation
print((1...9).map{Int(pow((pow(10,Double($0))-1)/9,2))})

```

**Try it online!**
> 0 votes

# Answer
# Perl 5, 22 bytes

```
say((1x$_)**2)for 1..9

```

Try it online!

Using Jenny\_mathy's formula to save a lot of bytes.
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, sequence
---