title: Drawing the Peano curve

text:
# Question
Title: Drawing the Peano curve
## Introduction

In geometry, the Peano curve is the first example of a space-filling curve to be discovered, by Giuseppe Peano in 1890. Peano's curve is a surjective, continuous function from the unit interval onto the unit square, however it is not injective. Peano was motivated by an earlier result of Georg Cantor that these two sets have the same cardinality. Because of this example, some authors use the phrase "Peano curve" to refer more generally to any space-filling curve.

## Challenge

The program takes an input which is an integer `n`, and outputs a drawing representing the `n`th iteration of the Peano curve, starting from the sideways 2 shown in the leftmost part of this image:

## Input

An integer `n` giving the iteration number of the Peano curve. Optional, additional input is described in the bonuses section.

## Output

A drawing of the `n`th iteration of the Peano curve. The drawing can be both ASCII art or a "real" drawing, whichever is easiest or shortest.

## Rules

* The input and output can be given in any convenient format (choose the most appropriate format for your language/solution).
* No need to handle **negative** values or **invalid input**
* Either a full program or a function are acceptable.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Bonuses

Since this shouldn't be a walk in the park (at least in most languages I can think of), bonus points are awarded for the following:

* -100 bytes if your code generates a gif of the construction of the Peano curves up to `n`.
* -100 bytes if your code draws a space-filling curve for any rectangular shape (the Peano curve only works for squares, obviously). You can assume that the input then takes on the form `n l w` where `n` has the same meaning as before (the number of the iteration), but where `l` and `w` become the length and width of the rectangle in which to draw the curve. If `l == w`, this becomes the regular Peano curve.

Negative scores are allowed (but are they possible...).

## Edit

Please include the output of your program in the solution for `n == 3 (l == w == 1)`.

# Answer
> 6 votes
# Mathematica, score 60 - 100 - 100 = -140

```
Graphics[PeanoCurve@a~Reverse~3~Scale~#2]~Animate~{a,1,#,1}&

```

Pure function. Takes `n` and `{l, w}` (width and height) as input, and gives an animated graphic as output. It first creates a *n*th order Peano curve with `PeanoCurve`. Since the *l* = *w* case still needs to create a Peano curve, we flip the expression at level 3, similar to DavidC's answer; for *l**w*, we just `Scale` the curve to the rectangle. This curve will still be space-filling, satisfying the second bonus. For the first bonus, we just `Animate` it over all sizes. Note that OP suggested that this was sufficiently different from DavidC's to warrant its own answer. The result for *n* = 3, *l* = *w* = 1 is as follows:

# Answer
> 13 votes
# GFA Basic 3.51 (Atari ST), ~~156~~ ~~134~~ 124 bytes

A manually edited listing in .LST format. All lines end with `CR`, including the last one.

```
PRO f(n)
DR "MA0,199"
p(n,90)
RET
PRO p(n,a)
I n
n=n-.5
DR "RT",a
p(n,-a)
DR "FD4"
p(n,a)
DR "FD4"
p(n,-a)
DR "LT",a
EN
RET

```

### Expanded and commented

```
PROCEDURE f(n)      ! main procedure, taking the number 'n' of iterations
  DRAW "MA0,199"    !   move the pen to absolute position (0, 199)
  p(n,90)           !   initial call to 'p' with 'a' = +90
RETURN              ! end of procedure
PROCEDURE p(n,a)    ! recursive procedure taking 'n' and the angle 'a'
  IF n              !   if 'n' is not equal to 0:
    n=n-0.5         !     subtract 0.5 from 'n'
    DRAW "RT",a     !     right turn of 'a' degrees
    p(n,-a)         !     recursive call with '-a'
    DRAW "FD4"      !     move the pen 4 pixels forward
    p(n,a)          !     recursive call with 'a'
    DRAW "FD4"      !     move the pen 4 pixels forward
    p(n,-a)         !     recursive call with '-a'
    DRAW "LT",a     !     left turn of 'a' degrees
  ENDIF             !   end
RETURN              ! end of procedure

```

### Example output

# Answer
> 10 votes
# Perl 6, 117 bytes

```
{map ->\y{|map {(((++$+y)%2+$++)%3**(y+$^v,*/3...*%3)??$^s[$++%2]!!'│')xx$_*3},<┌ ┐>,$_,<└ ┘>,1},^$_}o*R**3

```

Try it online!

0-indexed. Returns a 2D array of Unicode characters. The basic idea is that for lower rows, the expression

```
(x + (x+y)%2) % (3 ** trailing_zeros_in_base3(3*(y+1)))

```

yields the pattern

```
|....||....||....||....||..  % 3
..||....||....||....||....|  % 3
|................||........  % 9
..||....||....||....||....|  % 3
|....||....||....||....||..  % 3
........||................|  % 9
|....||....||....||....||..  % 3
..||....||....||....||....|  % 3
|..........................  % 27

```

For upper rows, the expression is

```
(x + (x+y+1)%2) % (3 ** trailing_zeros_in_base3(3*(y+3**n)))

```

### Explanation

```
{ ... }o*R**3  # Feed $_ = 3^n into block

map ->\y{ ... },^$_  # Map y = 0..3^n-1

|map { ... },<┌ ┐>,$_,<└ ┘>,1  # Map pairs (('┌','┐'),3^n) for upper rows
                               # and (('└','┘'),1) for lower rows.
                               # Block takes items as s and v

( ... )xx$_*3  # Evaluate 3^(n+1) times, returning a list

 (++$+y)%2  # (x+y+1)%2 for upper rows, (x+y)%2 for lower rows
(         +$++)  # Add x
                   (y+$^v,*/3...*%3)  # Count trailing zeros of 3*(y+v) in base 3
                3**  # nth power of 3
               %  # Modulo
??$^s[$++%2]  # If there's a remainder yield chars in s alternately
!!'│'         # otherwise yield '│'

```

# Answer
> 7 votes
# K (ngn/k), ~~37~~ ~~27~~ 26 bytes

```
{+y,(|'y:x,,~>+x),x}/1,&2*

```

Try it online!

returns a boolean matrix

`|'y` is syntax specific to ngn/k. other dialects require a `:` to make an each-ed verb monadic: `|:'y`

# Answer
> 5 votes
# Wolfram Language ~~83~~ 36 bytes, (possibly -48 bytes with bonus)

As of version 11.1, `PeanoCurve` is a built-in.

My original, clumsy submission wasted many bytes on `GeometricTransformation` and `ReflectionTransform.`

This much reduced version was suggested by **alephalpha**. `Reverse` was required to orient the output properly.

```
Graphics[Reverse/@#&/@PeanoCurve@#]&

```

**Example 36 bytes**

```
Graphics[Reverse/@#&/@PeanoCurve@#]&[3]

```

---

## Bonus

If this qualifies for the 100 pt bonus, it weighs in at 52 - 100 = -48 The code `[5]` was not counted, only the pure function.

```
Table[Graphics[Reverse/@#&/@PeanoCurve@#]&@k{k,#}&[5]

```

# Answer
> 5 votes
# HTML+SVG+JS, ~~224~~ 213 bytes

The output is mirrored horizontally.

```
n=>document.write(`<svg width=${w=3**n*9} height=${w}><path d="M1 ${(p=(n,z)=>n--&&(p(n,-z,a(a(p(n,-z,d+=z)),p(n,z))),d-=z))(n*2,r=d=x=y=1,a=_=>r+=`L${x+=~-(d&=3)%2*9} ${y+=(2-d)%2*9}`)&&r}"fill=#fff stroke=red>`)

```

Try it online! (prints the HTML)

```
(
n=>document.write(`<svg width=${w=3**n*9} height=${w}><path d="M1 ${(p=(n,z)=>n--&&(p(n,-z,a(a(p(n,-z,d+=z)),p(n,z))),d-=z))(n*2,r=d=x=y=1,a=_=>r+=`L${x+=~-(d&=3)%2*9} ${y+=(2-d)%2*9}`)&&r}"fill=#fff stroke=red>`)
)(3)
```

# Answer
> 4 votes
# BBC BASIC, 142 ASCII characters (130 bytes tokenised)

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

```
I.m:q=FNh(m,8,8,0)END
DEFFNh(n,x,y,i)
IFn F.i=0TO8q=FNh(n-1,x-i MOD3MOD2*2*x,y-i DIV3MOD2*2*y,i)DRAWBY(1AND36/2^i)*x,y*(12653/3^i MOD3-1)N.
=0

```

# Answer
> 4 votes
# Stax, 19 bytes

```
∩▐j>♣←╙~◘∩╗╢\a╘─Ràô

```

Run and debug it

Output for 3:

```
███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █
█ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███
█         █ █         █ █         █ █         █ █
█ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███
███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █
    █ █         █ █         █ █         █ █         █
███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █
█ ███ ███ ███ ███ ███ ███ ███ ███ █ █ ███ ███ ███ ███
█                                 █ █
█ ███ ███ ███ ███ ███ ███ ███ ███ █ █ ███ ███ ███ ███
███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █
    █ █         █ █         █ █         █ █         █
███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █
█ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███
█         █ █         █ █         █ █         █ █
█ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███
███ ███ ███ ███ █ █ ███ ███ ███ ███ ███ ███ ███ ███ █
                █ █                                 █
███ ███ ███ ███ █ █ ███ ███ ███ ███ ███ ███ ███ ███ █
█ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███
█         █ █         █ █         █ █         █ █
█ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███
███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █
    █ █         █ █         █ █         █ █         █
███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █ █ ███ ███ █
█ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███

```

# Answer
> 3 votes
## Logo, 89 bytes

```
to p:n:a
if:n>0[rt:a
p:n-1 0-:a
fw 5
p:n-1:a
fw 5
p:n-1 0-:a
lt:a]end
to f:n
p:n*2 90
end

```

Port of @Arnauld's Atari BASIC answer. To use, do something like this:

```
reset
f 3

```

---
Tags: code-golf, ascii-art, graphical-output, geometry, fractal
---


title: Resolve SAS macro variables

text:
# Question
Title: Resolve SAS macro variables
The SAS programming language is a clunky, archaic language dating back to 1966 that's still in use today. The original compiler was written in PL/I, and indeed much of the syntax derives from PL/I. SAS also has a preprocessor macro language which derives from that of PL/I as well. In this challenge, you'll be interpreting some simple elements of the SAS macro language.

In the SAS macro language, macro variables are defined using the `%let` keyword and printing to the log is done with `%put`. Statements end with semicolons. Here are some examples:

```
%let x = 5;
%let cool_beans =Cool beans;
%let what123=46.lel"{)-++;

```

Macro variable names are case insensitive and always match the regular expression `/[a-z_][a-z0-9_]*/i`. For the purposes of this challenge, we'll say the following:

* Macro variables can only hold values consisting entirely of printable ASCII characters *except* `;`, `&`, and `%`
* There will be no leading or trailing spaces in the values
* The values will never be more than 255 characters long
* Values may be empty
* Brackets and quotes in the values may be unmatched
* There can be any amount of space before and after the `=` in the `%let` statement and this space should be ignored
* There can be any amount of space before the terminal `;` in the `%let` statement and this space should similarly be ignored

When a macro variable is called, we say it "resolves" to its value. Macro variables are resolved by prepending `&`. There is an *optional* trailing `.` that denotes the end of the identifier. For example,

```
%put The value of x is &X..;

```

writes `The value of x is 5.` to the log. Note that two periods are required because a single period will be consumed by `&X.` and resolve to `5`. Also note that even though we defined `x` in lowercase, `&X` is the same as `&x` because macro variable names are case insensitive.

Here's where it gets tricky. Multiple `&`s can be strung together to resolve variables, and `&`s at the same level of nesting resolve at the same time. For example,

```
%let i = 1;
%let coolbeans1 = broseph;
%let broseph = 5;

%put &&coolbeans&i;  /* Prints broseph */
%put &&&coolbeans&i; /* Prints 5 */

```

The innermost `&`s resolve first, and resolution continues outward. Variable name matching is done greedily. In the second `%put` statement, the processor makes the following steps:

1. `&i` resolves to `1`, and the innermost leading `&` is consumed, giving us `&&coolbeans1`
2. `&coolbeans1` resolves to `broseph`, giving us `&broseph`
3. `&broseph` resolves to `5`.

If there are trailing `.`s, only a single `.` is consumed in resolution, even if there are multiple `&`s.

### Task

Given between 1 and 10 `%let` statements separated by newlines and a single `%put` statement, print or return the result of the `%put` statement. Input can be accepted in any standard way.

You can assume that the input will always be valid and that the `%let` statements will preceed the `%put` statement. Variables that are defined will not be redefined in later `%let` statements.

If actually run in SAS, there would be no issues with variables resolving to variables that don't exist and everything will be syntactically correct as described above.

### Examples

1. Input:

```
%let dude=stuff;
%let stuff=bEaNs;
%put &&dude..;

```

Output:

```
bEaNs.

```
2. Input:

```
%let __6 = 6__;
%put __6&__6;

```

Output:

```
__66__

```
3. Input:

```
%let i=1;
%let hOt1Dog = BUNS;
%put &&HoT&i.Dog are FUNS&i!");

```

Output:

```
BUNS are FUNS1!")

```
4. Input:

```
%let x = {*':TT7d;
%put SAS is weird.;

```

Output:

```
SAS is weird.

```
5. Input:

```
%let var1   =  Hm?;
%let var11 = var1;
%let UNUSED = ;
%put &&var11.....;

```

Output:

```
Hm?....

```

Note that `&&var11` matches `var11` since name matching is greedy. If there had been a `.`, i.e. `&&var1.1`, then `var1` would be matched and the extra 1 wouldn't be part of any name.

This is code golf, so the shortest solution in bytes wins!

# Answer
> 1 votes
# Python 3, ~~354~~ ~~341~~ 336 bytes

```
import re
S=re.sub
def f(x):
	r=x.splitlines();C=r[-1].strip('%put ');D=0
	while D!=C:
		D=C
		for a in sorted([l.strip('%let ').replace(" ","").split(';')[0].split('=')for l in r[:-1]],key=lambda y:-len(y[0])):
			s=1
			while s:C,s=re.subn('&'+a[0]+'(\.?)',a[1]+'\\1',S('+\.([^\.])','\\1',C),0,re.I)
	return S('+\.?','',C)

```

Try it online!

edit: some easy shortening

edit: reverse sort by -len(...) instead of \[::-1\] (5 bytes), thanks to Jonathan Frech!

## Ungolfed

```
import re
S=re.sub # new name for the function re.sub()
def f(x):
    r=x.splitlines() # input string to list of rows
    C=r[-1].strip('%put ') # get the string to put (from the last row)
    D=0
    while(D!=C): # iterate until the result does not change
        D=C
        for a in                                                                                : # iterate over the list of variables
                 sorted(                                                                          ,key=lambda y:len(y[0]),reverse=1) # sort list for greediness by decreasing var.name lengths
                        [l.strip('%let ') # cut the 'let' keyword
                                         .replace(" ","") # erase spaces
                                                         .split(';')[0] # cut parts after ';'
                                                                       .split('=') # create [variable_name,value] list
                                                                                for l in r[:-1]] # for each row but last
            s=1
            while(s): # iterate until the result does not change
                C,s=re.subn( # substitute
                            '&'+a[0]+'(\.?)', # &varname. or &varname
                                                 a[1]+'\\1', # to value. or value
                                                              S('+\.([^\.])','\\1',C), # in the string we can get from C erasing ('s)(.) sequences if the next char is not .
                                                                                0,re.I) # substituting is case insensitive
    return S('+\.?','',C) # erase smileys and one .

```

---
Tags: code-golf, parsing, interpreter
---


title: Compound interest with additions

text:
# Question
Title: Compound interest with additions
You have been given the charge to calculate the current balance as of the day that you perform the calculation for 330,000 individuals who worked for an average of 30 years spanning 300 years where the initial principal was `1` with an addition of `1` per day and interest rate set at `3%`.

You initially tried to use online compound interest with additions calculators to compute the sum. But all 10 calculators you tried had different results due to rounding errors. You decide to compose your own code which will assist in completing your charge.

## Input

Your task is write a function `f` which takes as input

* *`p`* Principal. A positive integer or decimal reflecting initial deposit.
* *`r`* Rate. A positive decimal reflecting the annual interest rate.
* *`t`* Time. An positive integer reflecting years to compute the compounding interest with additions.
* *`n`* Periods. A positive integer reflecting the number of periods per year to compound interest.
* *`a`* Addition. A positive integer or decimal which will be added to the current principal at the end of each period. Any number of additions can be deposited during *`t`*; for example, `10` additions of `20` can be deposited in a single day, or no deposits can be made during a period. For this question *`a`* will be a constant value, to avoid confusing users who expect output to be a single, consistent value.

## Output

The output can be an array of \\$n\\$ arrays of numbers, where each element is `[year, day, days, principal]` as follows:

* *`year`* The year as a positive integer within *`t`* years.
* *`doy`* (day of year): The day number within a year; \\$0 \le\\$ day \\$\le 360\\$ e.g. `days = 460` implies `year = 2` and `doy = 100$`.
* *`days`* The number of days since the initial deposit *`p`* was made.
* *`balance`* The current balance.

Other acceptable output formats:

* The above, but with elements of each array in a different (consistent) order;
* List of comma or space-delimited strings;
* The above, joined by newlines or tabs;
* `JSON` string representation of an array of objects;
* Spreadsheet;
* Any other formats permitted by default.

## Important

* Interest is compounded at the **end** of each period, which produces a new principal beginning at the next period. The addition, if any, is added to the new principal after interest is applied at the end of the period.
* "Leap day" and "leap years" are irrelevant to the question. The requirement for this question is to use the constant banker's year consisting of `360` days.

## Example

**Input**

```
p=1,r=0.03,t=1,n=12,a=10

```

**Output** (truncated, see stacksnippet). You need not output the labels "year", "day", etc.

```
[
      {
        "year": 1,
        "doy": 0,
        "days": 0,
        "balance": 1,
        "rate": 0.03,
        "addition": 0
      },
      { "year": 1,
        "doy": 30,
        "days": 30,
        "balance": 11.0025,
        "rate": 0.03,
        "addition": 10
      },...
      {
        "year": 1,
        "doy": 180,
        "days": 180,
        "balance": 61.391346409181246,
        "rate": 0.03,
        "addition": 10
      },...
      {
        "year": 1,
        "doy": 360,
        "days": 360,
        "balance": 122.69424361094278,
        "rate": 0.03,
        "addition": 10
      }
]

```

```
[
  {
    "year": 1,
    "DOY": 0,
    "days": 0,
    "balance": 1,
    "rate": 0.03,
    "addition": 0
  },
  {
    "year": 1,
    "DOY": 30,
    "days": 30,
    "balance": 11.0025,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 60,
    "days": 60,
    "balance": 21.03000625,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 90,
    "days": 90,
    "balance": 31.082581265625,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 120,
    "days": 120,
    "balance": 41.160287718789064,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 150,
    "days": 150,
    "balance": 51.26318843808603,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 180,
    "days": 180,
    "balance": 61.391346409181246,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 210,
    "days": 210,
    "balance": 71.5448247752042,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 240,
    "days": 240,
    "balance": 81.72368683714221,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 270,
    "days": 270,
    "balance": 91.92799605423507,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 300,
    "days": 300,
    "balance": 102.15781604437065,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 330,
    "days": 330,
    "balance": 112.41321058448158,
    "rate": 0.03,
    "addition": 10
  },
  {
    "year": 1,
    "DOY": 360,
    "days": 360,
    "balance": 122.69424361094278,
    "rate": 0.03,
    "addition": 10
  }
]
```

## Formula

You can use the formula at Saving and Investing

> If **D** represents the amount of a regular deposit, **r** the annual interest rate expressed as a decimal, **m** the number of equal compounding period (in a year), and **t** time in years, then the future value, **F**, of the account, is:

or any comparable formula which determines a future value that you decide or is available at the language that you use, for example the formulas located at

## Winning criteria

Shortest code in bytes.

# Answer
> 1 votes
## Haskell, ~~115~~ 112 bytes

```
d=360
(r#t)n a=zipWith(\y x->(max(ceiling$y/d)1,until(<=d)(-d+)$y*d/n,y*d/n,x))[0..t*n].iterate(\x->x+(x*r)/n+a)

```

Function `#` takes the parameters in order r, t, n, a, p and returns a list of 4-tuples (year, day, days, principal).

Try it online!

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


# Question
Title: Is it an arithmetico-geometric sequence?
An arithmetico-geometric sequence is the elementwise product of an arithmetic sequence and a geometric sequence. For example, `1 -4 12 -32` is the product of the arithmetic sequence `1 2 3 4` and the geometric sequence `1 -2 4 -8`. The nth term of an integer arithmetico-geometric sequence can be expressed as

$$a\_n = r^n \cdot (a\_0 + nd)$$

for some real number \\$d\\$, nonzero real \\$r\\$, and integer \\$a\_0\\$. Note that \\$r\\$ and \\$d\\$ are not necessarily integers.

For example, the sequence `2 11 36 100 256 624 1472 3392` has \\$a\_0 = 2\\$, \\$r = 2\\$, and \\$d = 3.5\\$.

### Input

An ordered list of \\$n \ge 2\\$ integers as input in any reasonable format. Since some definitions of geometric sequence allow \\$r=0\\$ and define \\$0^0 = 1\\$, whether an input is an arithmetico-geometric sequence will not depend on whether \\$r\\$ is allowed to be 0. For example, `123 0 0 0 0` will not occur as input.

### Output

Whether it is an arithmetico-geometric sequence. Output a truthy/falsy value, or two different consistent values.

### Test cases

True:

```
1 -4 12 -32
0 0 0
-192 0 432 -1296 2916 -5832 10935 -19683
2 11 36 100 256 624 1472 3392
-4374 729 972 567 270 117 48 19
24601 1337 42
0 -2718
-1 -1 0 4 16
2 4 8 16 32 64
2 3 4 5 6 7
0 2 8 24

```

False:

```
4 8 15 16 23 42
3 1 4 1
24601 42 1337
0 0 0 1
0 0 1 0 0
1 -1 0 4 16

```

# Answer
# Wolfram Language (Mathematica), 55 bytes

```
{}!=Solve[i=Range@Tr[1^#];(a+i*d)r^i==#,{r,a,d},Reals]&

```

Try it online!

`Solve` return all solution forms. The result is compared with `{}` to check if there is any solution.
> 2 votes

# Answer
# Perl 6, ~~184~~ ~~128~~ 135 bytes

```
{3>$_||->\x,\y,\z{?grep ->\r{min (x,{r&&r*$_+(y/r -x)*($×=r)}...*)Z==$_},x??map (y+*×sqrt(y²-x*z).narrow)/x,1,-1!!y&&z/y/2}(|.[^3])}

```

Try it online!

Computes \\$r\\$ and \\$d\\$ from the first three elements and checks whether the resulting sequence matches the input. Unfortunately, Rakudo throws an exception when dividing by zero, even when using floating-point numbers, costing ~9 bytes.

Enumerates the sequence using \\$a\_n=r \cdot a\_{n-1}+r^n \cdot d\\$.

Some improvements are inspired by Arnauld's JavaScript answer.

### Explanation

```
3>$_||  # Return true if there are less than three elements

->\x,\y,\z{ ... }(|.[^3])}  # Bind x,y,z to first three elements

# Candidates for r
x  # If x != 0
??map (y+*×sqrt(y²-x*z).narrow)/x,1,-1  # then solutions of quadratic equation
!!y&&z/y/2  # else solution of linear equation or 0 if y==0

?grep ->\r{ ... },  # Is there an r for which the following is true?

    ( ,                         ...*)  # Create infinite sequence
     x  # Start with x
       {                       }  # Compute next term
        r&&  # 0 if r==0
                (y/r -x)  # d
           r*$_  # r*a(n-1)
                          ($×=r)  # r^n
                +        *  # r*a(n-1)+d*r^n
                                     Z==$_  # Compare with each element of input
min  # All elements are equal?

```
> 2 votes

# Answer
# JavaScript (ES7), ~~135~~ 127 bytes

```
a=>!([x,y,z]=a,1/z)|!a.some(n=>n)|[y/x+(d=(y*y-x*z)**.5/x),y/x-d,z/y/2].some(r=>a.every((v,n)=>(v-(x+n*y/r-n*x)*r**n)**2<1e-9))

```

Try it online!

## How?

We use two preliminary tests to get rid of some special cases. For the main case, we try three different possible values of \\$r\\$ (and the corresponding values of \\$d\\$, which can be easily deduced) and test whether all terms of the input sequence are matching the guessed ones. Because of potential rounding errors, we actually test whether all squared differences are \\$\<10^{-9}\\$.

### Special case #1: less than 3 terms

If there are less than 3 terms, it's always possible to find a matching sequence. So we force a truthy value.

### Special case #2: only zeros

If all terms are equal to \\$0\\$, we can use \\$a\_0=0\\$, \\$d=0\\$ and any \\$r\neq 0\\$. So we force a truthy value.

### Main case with \\$a\_0=0\\$

If \\$a\_0=0\\$, the sequence can be simplified to:

$$a\_n=r^n\times n\times d$$

Which gives:

$$a\_1=r\times d\\ a\_2=2r^2\times d$$

We know that \\$d\\$ is not equal to \\$0\\$ (otherwise, we'd be in the special case #2). So we have \\$a\_1\neq 0\\$ and:

$$r=\frac{a\_2}{2a\_1}$$

### Main case with \\$a\_0\neq 0\\$

We have the following relation between \\$a\_{n+1}\\$ and \\$a\_n\\$:

$$a\_{n+1}=r.a\_n+r^{n+1}d$$

For \\$a\_{n+2}\\$, we have:

$$\begin{align}a\_{n+2}&=r.a\_{n+1}+r^{n+2}d\\ &=r(r.a\_n+r^{n+1}d)+r^{n+2}d\\ &=r^2a\_n+2r.r^{n+1}d\\ &=r^2a\_n+2r(a\_{n+1}-r.a\_n)\\ &=-r^2a\_n+2r.a\_{n+1} \end{align}$$

We notably have:

$$a\_2=-r^2a\_0+2r.a\_1$$

Leading to the following quadratic:

$$r^2a\_0-2r.a\_1+a\_2=0$$

Whose roots are:

$$r\_0=\frac{a\_1+\sqrt{{a\_1}^2-a\_0a\_2}}{a\_0}\\ r\_1=\frac{a\_1-\sqrt{{a\_1}^2-a\_0a\_2}}{a\_0}$$
> 2 votes

---
Tags: code-golf, math, decision-problem
---


title: Find the Infinity Words!

text:
# Question
Title: Find the Infinity Words!
(Note: This is a spin-off of my previous challenge Find the Swirling Words!)

### Definition of *Infinity Word*:

1. If you connect with curves all the characters of an *Infinity Word* on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.
2. All the even connection must be *down*, all the odd connections must be *up*.
3. You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.
4. The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.
5. Each word must be exactly 5 characters. Words \> 5 or \< 5 are not valid.
6. If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".
7. All the *Infinity Words* start and end with the same character.

**Here there are some examples:**

### Task:

Write a full program or function that will take a word from standard input and will output if is an *Infinity Word* or not. The output can be true/false, 1/0, 1/Null, etc.

**Test cases:**

```
Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO

```

### Rules:

1. Shortest code wins.

### Optional Task:

Find, as a list, as many *Infinity Words* as you can in an English dictionary. You can take for example as reference the complete list of English words here.

# Answer
# Jelly, ~~43 41 40 25 24 23 22 21 14~~ 13 bytes

-7 bytes thanks to fireflame241 (`0ị=1ị$`-\>`=ṚḢ` and use of `IIA⁼2,2` to test for the 4 rotations)

-1 Thanks to Kevin Cruijssen (use of previously unavailable nilad `Ø2` which yields `[2,2]`)

```
=ṚḢȧOIṠIIA⁼Ø2

```

**TryItOnline**
Or all test cases (plus "RULES")

### How?

An infinity word has:

1. the same first and last letter;
2. length 5;
3. no equal letters next to each other;
4. sum of its four alphabet deltas equal to zero;
5. sum of its four alphabet deltas signs equal to zero;
6. two positive alphabet deltas or two negative alphabet deltas in a row.

All but (1) and (equivalently) (4) may be boiled down to a condition that the alphabet delta signs are some rotation of `[1,1,-1,-1]` (where the sign of `0` is `0`)

fireflame241 noted that this is then equivalent to the deltas of the deltas of the alphabet delta signs being in `[[2,2],[2,-2],[-2,2],[-2,-2]]` which may be tested by the absolute values being equal to `[2,2]`!

### How?

```
=ṚḢȧOIṠIIA⁼Ø2 - Main link: word
 Ṛ            - reverse word
=             - equals? (vectorises)
  Ḣ           - head (is the first character equal to the last?)
   ȧ          - and
    O         - cast word to ordinals
     I        - increments - the alphabet deltas (or just [] if 1st != last)
      Ṡ       - sign (vectorises)
       I      - increments - deltas of those signs
        I     - increments - deltas of those
         A    - absolute value (vectorises)
           Ø2 - literal [2,2]
          ⁼   - equals? (non-vectorising version)

```
> 19 votes

# Answer
# Java 8, ~~231~~ ~~193~~ ~~185~~ ~~122~~ ~~103~~ 78 bytes

```
s->s.length==5&&(s[1]-s[0])*(s[3]-s[2])<0&(s[2]-s[1])*(s[4]-s[3])<0&s[4]==s[0]

```

Try it here.

-38 bytes thanks to *@dpa97* for reminding me to use `char[]` instead of `String`.
-63 bytes thanks to *@KarlNapf*'s derived formula.
-25 bytes by converting it from Java 7 to Java 8 (and now returning a boolean instead of integer).

**193 bytes answer:**

```
int c(char[]s){if(s.length!=5)return 0;int a=s[0],b=s[1],c=s[2],d=s[3],e=s[4],z=b-a,y=c-b,x=d-c,w=e-d;return e!=a?0:(z>0&y>0&x<0&w<0)|(z<0&y>0&x>0&w<0)|(z>0&y<0&x<0&w>0)|(z<0&y<0&x>0&w>0)?1:0;}

```

**Explanation:**

* If the length of the string isn't 5, we return `false`
* If the first character doesn't equal the last character, we return `false`
* Then we check the four valid cases one by one (let's indicate the five characters as 1 through 5), and return `true` if it complies to any of them (and `false` otherwise):
    1. If the five characters are distributed like: `1<2<3>4>5` (i.e. `ALPHA`)
    2. If the five characters are distributed like: `1>2<3<4>5` (i.e. `EAGLE`, `HARSH`, `NINON`, `PINUP`)
    3. If the five characters are distributed like: `1<2>3>4<5` (i.e. `RULER`)
    4. If the five characters are distributed like: `1>2>3<4<5` (i.e. `THEFT`, `WIDOW`)

These four rules can be simplified to `1*3<0 and 2*4<0` (thanks to *@KarlNapf*'s Python 2 answer).
> 11 votes

# Answer
## JavaScript (ES6), ~~91~~ ~~89~~ 87 bytes

*Saved 2 bytes thanks to Ismael Miguel*

```
s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

```

### How it works

We build a 4-bit bitmask `k` representing the 4 transitions between the 5 characters of the string:

```
k += p > c ? 1<<i : 0 / (p < c)

```
* if the previous character is higher than the next one, the bit is set
* if the previous character is lower then the next one, the bit is not set
* if the previous character is identical to the next one, the whole bitmask is forced to `NaN` so that the word is rejected (to comply with rule #6)

The valid bitmasks are the ones that have exactly two consecutive `1` transitions (the first and the last bits being considered as *consecutive* as well):

```
Binary | Decimal
-------+--------
0011   | 3
0110   | 6
1100   | 12
1001   | 9

```

In other words, these are the combinations which are:

* `k?` : greater than 0
* `!(k%3)` : **congruent to 0 modulo 3**
* lower than 15

The other conditions are:

* `!s[5]` : there's no more than 5 characters
* `s[0]==s[4]` : the 1st and the 5th characters are identical

**NB**: We don't explicitly check `k != 15` because any word following such a pattern will be rejected by this last condition.

### Test cases

```
let f =

s=>(k=0,[...s].reduce((p,c,i)=>(k+=p>c?1<<i:0/(p<c),c)),k?!(k%3)&&!s[5]&&s[0]==s[4]:!1)

console.log("Testing truthy words...");
console.log(f("ALPHA"));
console.log(f("EAGLE"));
console.log(f("HARSH"));
console.log(f("NINON"));
console.log(f("PINUP"));
console.log(f("RULER"));
console.log(f("THEFT"));
console.log(f("WIDOW"));

console.log("Testing falsy words...");
console.log(f("CUBIC"));
console.log(f("ERASE"));
console.log(f("FLUFF"));
console.log(f("LABEL"));
console.log(f("MODEM"));
console.log(f("RADAR"));
console.log(f("RIVER"));
console.log(f("SWISS"));
console.log(f("TRUST"));
console.log(f("KNEES"));
console.log(f("QUEEN"));
console.log(f("ORTHO"));
console.log(f("GROOVE"));
console.log(f("ONLY"));
console.log(f("CHARACTER"));
console.log(f("OFF"));
console.log(f("IT"));
console.log(f("ORTHO"));
```

### Initial version

For the record, my initial version was 63 bytes. It's passing all test cases successfully but fails to detect consecutive identical characters.

```
([a,b,c,d,e,f])=>!f&&a==e&&!(((a>b)+2*(b>c)+4*(c>d)+8*(d>e))%3)

```

Below is a 53-byte version suggested by Neil in the comments, which works (and fails) equally well:

```
([a,b,c,d,e,f])=>!f&&a==e&&!((a>b)-(b>c)+(c>d)-(d>e))

```

**Edit:** See Neil's answer for the fixed/completed version of the above code.
> 4 votes

# Answer
## JavaScript (ES6), 78 bytes

```
([a,b,c,d,e,f])=>a==e&&!(f||/(.)\1/.test(a+b+c+d+e)||(a>b)-(b>c)+(c>d)-(d>e))

```

Based on @Arnauld's incorrect code, but golfed and corrected. Works by first checking that the first character is the same as the fifth (thus guaranteeing 5 characters) and that the length of the string is no more than 5. After checking for consecutive duplicate characters, it remains to check the waviness of the string, which should have one peak and one trough two letters apart.

* If the peak and the trough are the middle and first/last letters, then the first two comparisons and the last two comparisons cancel out
* If the peak and the trough are the second and fourth letters, then the middle two comparisons and the outer two comparisons cancel out
* Otherwise, something fails to cancel and the overall expression returns false

Edit: Alternative 78-byte solution based on @KarlNapf's answer:

```
([a,b,c,d,e,f],g=(a,b)=>(a<b)-(a>b))=>a==e&&!f&&g(a,b)*g(c,d)+g(b,c)*g(d,e)<-1

```
> 4 votes

# Answer
# Python 2, ~~110~~ ~~87~~ 60 bytes

Saving 1 byte thanks to Neil

Requires input enclosed in quotes, e.g. `'KNEES'`

`True` if it is an infinity word, `False` if not and it has length of 5 and prints error message if wrong length

```
s=input()
a,b,c,d,e=map(cmp,s,s[1:]+s[0])
print a*c+b*d|e<-1

```

Inspired by xnor's answer using `map(cmp...`

```
s=input()
e=map(cmp,s,s[1:]+s[0])
print e[4]==0and e[0]*e[2]+e[1]*e[3]==-2and 5==len(s)

```

previous solution:

```
s=input()
d=[ord(x)-ord(y)for x,y in zip(s,s[1:])]
print s[0]==s[4]and d[0]*d[2]<0and d[1]*d[3]<0and 4==len(d)

```

Using the optimized logic of Kevin Cruijssen
> 3 votes

# Answer
## Python 2 exit code, 56 bytes

```
s=input()
v,w,x,y,z=map(cmp,s,s[1:]+s[0])
v*x+w*y|z>-2>_

```

Outputs via exit code: Error for False, and successful run for True.

Takes the string `s` with characters `abcde`, rotates it to `bcdea`, does an elementwise comparison of corresponding characters, and assigns them to five variables `v,w,x,y,z`. The wrong length gives an error.

The infinity words all have

```
v*x == -1
w*y == -1
z == 0

```

which can be checked jointly as `v*x+w*y|z == -2`. The chained comparison `v*x+w*y|z>-2>_` short-circuits if this is the case, and otherwise goes on to evaluate `-2>_` which gives a name error.
> 3 votes

# Answer
# PHP, 102 Bytes

```
for(;$i<strlen($w=$argv[1]);)$s.=($w[$i++]<=>$w[$i])+1;echo preg_match("#^(2200|0022|2002|0220)#",$s);

```
> 2 votes

# Answer
## Python 2, 71 bytes

```
lambda s:map(cmp,s,s[1:]+s[0])in[[m,n,-m,-n,0]for m in-1,1for n in-1,1]

```

Takes the string `s` with characters `abcde`, rotates it to `bcdea`, and does an elementwise comparison of corresponding characters.

```
a  b   cmp(a,b)
b  c   cmp(b,c)
c  d   cmp(c,d)
d  e   cmp(d,e)
e  a   cmp(e,a)

```

The result is a list of `-1, 0, 1`. Then, checks if the result is one of the valid sequences of up and downs:

```
[-1, -1, 1, 1, 0]
[-1, 1, 1, -1, 0]
[1, -1, -1, 1, 0]
[1, 1, -1, -1, 0]

```

as generated from the template `[m,n,-m,-n,0]` with `m,n=±1`. The last `0` checks that the first and last letter were equal, and the length ensures that the input string had length 5.

---

An alternative 71. Checks the conditions on comparisons while ensuring the right length.

```
def f(s):a,b,c,d,e=map(cmp,s,s[1:]+s*9)[:5];print a*c<0==e>b*d>len(s)-7

```
> 2 votes

# Answer
## R, 144 bytes

The answer is based off the logic of @Jonathan Allan. It could probably be golfed though.

```
s=strsplit(scan(,""),"")[[1]];d=diff(match(s,LETTERS));s[1]==tail(s,1)&length(s)==5&all(!rle(s)$l-1)&!sum(d)&!sum(sign(d))&any(rle(sign(d))$l>1)

```

R-fiddle test cases (vectorized example but same logic)
> 1 votes

# Answer
# Actually, ~~38~~ 27 bytes

This answer was largely inspired by Jonathan Allan's excellent Jelly answer. There are probably several places where this can be golfed, so golfing suggestions welcome! Try it online!

```
O;\♀-dY@♂s4R`0~;11({k`Míub*

```

**Ungolfing**

```
     Implicit input s.
O    Push the ordinals of s. Call this ords.
;    Duplicate ords.
\    Rotate one duplicate of ords left by 1.
♀-   Vectorized subtraction. This effectively gets the first differences of ords.
d    Pop ord_diff[-1] onto the stack. This is ords[0] - ords[-1].
Y    Logical negate ord_diff[-1], which returns 1 if s[0] == s[-1], else 0.
@    Swap (s[0] == s[-1]) with the rest of ord_diff.

♂s       Vectorized sgn() of ord_diff. This gets the signs of the first differences.
4R       Push the range [1..4] onto the stack.
`...`M   Map the following function over the range [1..4]. Variable x.
  0~;      Push -1 onto the stack twice.
  11       Push 1 onto the stack twice.
  (        Rotate x to TOS.
  {        Rotate the stack x times, effectively rotating the list [1, 1, -1, -1].
  k        Wrap it all up in a list.

     Stack: list of rotations of [1, 1, -1, -1], sgn(*ord_diff)
í    Get the 0-based index of sgn(*ord_diff) from the list of rotations. -1 if not found.
ub   This returns 1 only if sgn(*ord_diff) was found, else 0.
     This checks if the word loops like an infinity word.

*    Multiply the result of checking if the word s loops and the result of s[0] == s[-1].
     Implicit return.

```
> 1 votes

# Answer
# GNU Prolog, 47 bytes

```
i([A,B,C,D,A]):-A>B,B>C,C<D,D<A;i([B,C,D,A,B]).

```

Defines a predicate `i` which succeeds (infinitely many times, in fact) for an infinity word, thus outputting "yes" when run from the interpreter (as is usual for Prolog); fails for a candidate word whose first and last letters don't match, or isn't 5 letters long, thus outputting "no" when run from the interpreter; and crashes with a stack overflow if given a candidate word that isn't an infinity word, but which is five letters with the first and last two matching. (I'm not sure *why* it crashes; the recursive call should be treatable as a tailcall. Apparently GNU Prolog's optimizer isn't very good.) Succeeding is Prolog's equivalent of truthy, and failing the equivalent of falsey; a crash is definitely more falsey than truthy, and fixing it would make the solution substantially longer, so I hope this counts as a valid solution.

The algorithm is fairly simple (and indeed, the program is fairly readable); check whether the letters form one of the four patterns that make an infinity word, and if not, cyclicly permute and try again. We don't need to explicitly check for double letters as the `<` and `>` operators let us implicitly check that at the same time that we check that the deltas match.
> 1 votes

# Answer
# APL (Dyalog), ~~16~~ 15 bytes

```
0=16|3⊥×2-/⎕a⍳⍞

```

Try it online!
> 1 votes

# Answer
# TI-BASIC, 81 bytes

String to pass into the program is in Ans. Returns (and implicitly displays) 1 if the entered word is an Infinity Word, and 0 (or exits with an error message) if it isn't.

```
seq(inString("ABCDEFGHIJKLMNOPQRSTUVWXYZ",sub(Ans,A,1)),A,1,length(Ans
min(Ans(1)=Ans(5) and {2,2}=abs(deltaList(deltaList(deltaList(Ans)/abs(deltaList(Ans

```

Errors on any repeated characters, or non-5-letter-words.
> 1 votes

# Answer
# 05AB1E, 16 bytes

```
Ç¥DO_s.±¥¥Ä2DиQ*

```

Port of *@JonathanAllan*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
Ç             # Convert the (implicit) input string to a list of unicode values
              #  i.e. "RULES" → [82,85,76,69,82]
 ¥            # Take the deltas
              #  i.e. [82,85,76,69,82] → [3,-9,-7,13]
  DO          # Duplicate and take the sum
              #  i.e. [3,-9,-7,13] → 0
    _         # Check if that sum is exactly 0
              # (which means the first and last characters are equal)
              #  i.e. 0 and 0 → 1 (truthy)
 s            # Swap so the deltas are at the top of the stack again
  .±          # Get the sign of each
              #  i.e. [3,-9,-7,13] → [1,-1,-1,1]
    ¥         # Get the deltas of those signs
              #  i.e. [1,-1,-1,1] → [-2,0,2]
     ¥        # And then get the deltas of those
              #  i.e. [-2,0,2] → [2,2]
      Ä       # Convert them to their absolute values
       2Dи    # Repeat the 2 two times as list: [2,2]
          Q   # Check if they are equal
              #  i.e. [2,2] and [2,2] → 1 (truthy)
 *            # Check if both are truthy (and output implicitly)
              #  i.e. 1 and 1 → 1 (truthy)

```
> 1 votes

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


title: Dyadic Transpose

text:
# Question
Title: Dyadic Transpose
As with most APL symbols,  has different meanings when called with one argument (transpose) versus two arguments (dyadic transpose / reorder dimensions). This challenge concerns the latter, which acts similarly to `numpy.moveaxis` in Python or `permute` in MATLAB, but is more powerful.

## `order ⍉ A` when `order` has distinct entries

When all members of `order` are distinct, `order ⍉ A` is equivalent to:

* `numpy.moveaxis(A, tuple(range(len(A.shape)), order)` in Python, or
* `permute(A,order)` in MATLAB. Quoting from documentation of the latter:

> B = permute(A,order) rearranges the dimensions of A so that they are in the order specified by the vector order. The resulting array B has the same values as A but the order of the subscripts needed to access any particular element is rearranged as specified by order.

For example, suppose `A` is a 3D array, and let `B ← (2 0 1)⍉A`. Then B is such that `B[x0,x1,x2] = A[x2,x0,x1]` for all `x2,x0,x1`

## `order ⍉ A` when `order` has repeated entries

When `order` has repeated entries, we take a diagonal slice of the array. For example, let A be a 2x3x4 array. `B ← (0 0 1)⍉A` takes a diagonal slice along `A` to create `B` such that `B[x0,x1] = A[x0,x0,x1]`. Note that `B` is a 2x4 array: if it were 3x4, we would need to set `B[2, x1] = A[2, 2, x1]` which would be out of bounds of `A`. In general the `k`th dimension of `B` will be the minimum of all `A.shape[i]` such that `order[i] = k`.

## Example

Consider the dyadic transpose `order⍉A` where `order = [2, 1, 0]` and A is 3x4x5

```
    A =
[[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]
  [15 16 17 18 19]]

 [[20 21 22 23 24]
  [25 26 27 28 29]
  [30 31 32 33 34]
  [35 36 37 38 39]]

 [[40 41 42 43 44]
  [45 46 47 48 49]
  [50 51 52 53 54]
  [55 56 57 58 59]]]

```

The result is the 5x4x3 array B =

```
[[[ 0 20 40]
  [ 5 25 45]
  [10 30 50]
  [15 35 55]]

 [[ 1 21 41]
  [ 6 26 46]
  [11 31 51]
  [16 36 56]]

 [[ 2 22 42]
  [ 7 27 47]
  [12 32 52]
  [17 37 57]]

 [[ 3 23 43]
  [ 8 28 48]
  [13 33 53]
  [18 38 58]]

 [[ 4 24 44]
  [ 9 29 49]
  [14 34 54]
  [19 39 59]]]

```

Note that when, for example, (x0, x1, x2) = (4,1,2) we have `B[x0,x1,x2] = A[x2, x1, x0] = A[2,1,4] = 49`.

If instead `order = [0, 0, 0]` and `A` as above, then we would have the output `B` be the 1-dimensional size-3 array `B = [0, 26, 52]` so that `B[1] = B[x0] = A[x0,x0,x0] = A[1,1,1] = 26`

### Input

Here we use 0-indexing, but you may also use 1-indexing as is the APL default.

* A multidimensional or nested array `A`, of dimension *n* ≥ 1.
* A list `order` of *n* positive integers consisting of the integers {0,1,...,k} (or {1,...,k+1} for 1-index) for some *k* \< *n*, in any order, possibly with repetitions.

### Output

* A multidimensional or nested array representing the result of applying the dyadic transpose with those arguments. (The output will have dimension *k+1*.)

You may write a full program, function, etc. as allowed by the current standard on meta.

If your language has a builtin, it is encouraged to also write a solution without the builtin for the sake of an interesting answer.

### Test cases

Test cases on TIO

Reference Python implementation coming soon.

Note for reading test cases: in APL, the penultimate and ultimate axes of an array are along columns and rows in that order.

# Answer
> 4 votes
# APL (Dyalog Unicode), 34 bytesSBCS

This is my colleague's code (slightly modified from Roger Hui: *A History of APL in 50 Functions*, chapter 30), posted with explicit permission.

Anonymous tacit infix lambda (can be used as drop-in for ).

```
{⍵[(⊂⊂⍺)⌷¨,¨⍳⍺[⍋⍺]{⌊/⍵}⌸(⍴⍵)[⍋⍺]]}

```

Try it online!

`{``}` dfn;  is left argument (axes),  is right argument (array)
E.g. `[2,2,1]` and `[[[1,2],[3,4]]]`

`⍵[``]` index the array with:

`(⍴⍵)[``]` the shape (lengths of axes) of the array, indexed by:
`[1,2,2]`

`⍋⍺` the grading vector (the indices that would sort them) of the axes
`[3,1,2]`
`[2,1,2]`

`⍺[⍋⍺]{``}⌸` use the sorted axes as keys to group that, and for each group:
`[1,2,2]``{"1":[2],"2":[1,2]}`

`{⌊/⍵}` find the lowest axis length
`{"1":2,"2":1}``[2,1]`

generate the indices in a Cartesian system of those dimensions
`[[[1,1]],[[2,1]]]`

ensure that the indices of each coordinate is a vector (would be scalar if  is a vector)
`[[[1,1]],[[2,1]]]`

`(``)⌷¨` index into each of those with the following:

`⊂⊂⍺` the axes (doubly enclosed; once for  to select those cells along the first and only axis, and once for `¨` to pair up each vector on the right with the entire set of axes on the left)
`2 1 2`
`[[[1,1,1]],[[1,2,1]]]`
`[[1],[3]]`

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


title: Morse code generator in sound

text:
# Question
Title: Morse code generator in sound
Inspired by the Morse code question, and the Twinkle Twinkle little star question, write a program to accept a letter and generate the morse code audio for that letter.

# Answer
> 6 votes
## Windows PowerShell, 200

Makes a dot 70 ms long. Accordingly, a dash is 210 ms and the gap between both is 70 ms as well.

```
[char[]](-split' ☺ ☺    ☺ ☺  ☺       ☺  ☺☺           ☺☺☺ ☺ ☺  ☺   ☺☺ ☺  ☺☺☺  ☺☺  ☺☺ ☺  ☺      ☺   ☺    ☺  ☺☺ ☺  ☺ ☺ ☺☺ ☺☺  ')[[char]"$input".ToUpper()-65]|%{[Console]::Beep(880,70+140*$_)
sleep -m 70}

```

Since this contains control characters, here's a hexdump:

```
000: 5B 63 68 61 72 5B 5D 5D │ 28 2D 73 70 6C 69 74 27  [char[]](-split'
010: 00 01 20 01 00 00 00 20 │ 01 00 01 00 20 01 00 00   ☺ ☺    ☺ ☺  ☺
020: 20 00 20 00 00 01 00 20 │ 01 01 00 20 00 00 00 00       ☺  ☺☺
030: 20 00 00 20 00 01 01 01 │ 20 01 00 01 20 00 01 00       ☺☺☺ ☺ ☺  ☺
040: 00 20 01 01 20 01 00 20 │ 01 01 01 20 00 01 01 00    ☺☺ ☺  ☺☺☺  ☺☺
050: 20 01 01 00 01 20 00 01 │ 00 20 00 00 00 20 01 20   ☺☺ ☺  ☺      ☺
060: 00 00 01 20 00 00 00 01 │ 20 00 01 01 20 01 00 00    ☺    ☺  ☺☺ ☺
070: 01 20 01 00 01 01 20 01 │ 01 00 00 27 29 5B 5B 63  ☺ ☺ ☺☺ ☺☺  ')[[c
080: 68 61 72 5D 22 24 69 6E │ 70 75 74 22 2E 54 6F 55  har]"$input".ToU
090: 70 70 65 72 28 29 2D 36 │ 35 5D 7C 25 7B 5B 43 6F  pper()-65]|%{[Co
0A0: 6E 73 6F 6C 65 5D 3A 3A │ 42 65 65 70 28 38 38 30  nsole]::Beep(880
0B0: 2C 37 30 2B 31 34 30 2A │ 24 5F 29 0A 73 6C 65 65  ,70+140*$_)◙slee
0C0: 70 20 2D 6D 20 37 30 7D │                          p -m 70}

```

I have tried several variants pf packing the data more tightly, but PowerShell is quite verbose in unpacking them again, so I don't gain much, sadly.

# Answer
> 3 votes
Sure.

# VB.NET, ~~235~~ ~~223~~ ~~221~~ ~~218~~ ~~210~~ ~~209~~ ~~208~~ 209 characters

With the appropriate structures, it is **245 characters**.

Requires Option Strict to be Off for the latest one.

```
For Each c In"sl lsss lsls lss s ssls lls ssss ss slll lsl slss ll ls lll slls llsl sls sss l ssl sssl sll lssl lsll llss".Split()(Asc(UCase(Console.ReadKey.KeyChar))-65)
Console.Beep(1E3,200-(c="l")*400)
Next

```

Recent edits:

* Fixed the incorrect "b".
* Changed `999` to `1E3` so I can finally have that perfect thousand ;-)
* Used boolean-\>integer conversion to save 2 characters.

# Answer
> 3 votes
## QBASIC (236 characters)

I count each newline as one character because QBasic seems to work fine without carriage returns, at least when running in DOSBox. Note that it only supports letters, not digits or punctuation.

```
INPUT Y$:C&=2^(26-ASC(Y$)MOD 32):A&=31313855AND C&:B&=60257815AND C&:M&=29932103:GOSUB S
IF A&OR B&THEN M&=34172681:GOSUB S
IF A&THEN M&=9538602:GOSUB S
IF A&AND B&THEN M&=66070:GOSUB S
END
S:SOUND 750,SGN(M&AND C&)*2+1:SOUND 0,1:RETURN

```

# Answer
> 3 votes
## JScript .NET (174 characters)

A little-known programming language from Microsoft, it combines the (relative) terseness of JavaScript with the power of the .NET Common Language Runtime. Thanks minitech and Joey for Console.Beep.

This program accepts a single letter from standard input (A-Z or a-z only). It does not explicitly add intra-character pauses, but they do exist, at least on Windows 7.

### morse.js

```
function S(a){K.Beep(750,!!(a&C)*99+50)}import System;var K=Console,C=1<<26-K.Read()%32,A=31313855&C,B=60257815&C;S(29932103);(A||B)&&S(34172681);A&&S(9538602);A&&B&&S(66070)

```

Compile with:

> %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\jsc morse.js

### Explanation

Six 32-bit integers, of which 26 bits are used in each, serve as lookup tables. Each bit in a table corresponds to a letter of the alphabet, bit 25 used for A and bit 0 used for Z.

```
C = 1 << (26 - (K.Read() % 32)),

```

Because Morse code is a variable-length code that uses between 1 and 4 symbols for each letter, the tables 31313855 (bit 1) and 60257815 (bit 0) can together represent one less than the length of each letter's code.

```
A = 31313855 & C,
B = 60257815 & C;

```

The program uses additional lookup tables to store the dots and dashes for each letter. Using logic expressions of A and B, it stops once it has sent the correct number of symbols to the sound card.

```
S(29932103);
(A || B) && S(34172681);
A && S(9538602);
A && B && S(66070);

```

In each of the four lookup tables above, a zero represents a dot; a one represents a dash. `!!` (logical "not-not") is used to normalize false to 0 and true to 1 (to compensate for the differing locations of bits within the integer). The multiplication and addition of this value causes a dot to be a 50 ms, 750 Hz tone and a dash to be a (50 + 99) = 149 ms tone.

```
function S(a) {
  K.Beep(750, !!(a & C) * 99 + 50)
}

```

# Answer
> 1 votes
# Powershell, ~~184~~ 120 bytes

```
for($d='0;?3,>5:.H7<1/9@E42-6B8CG='[$args[0][0]-65]-42;$d-1){[Console]::Beep(880,200*($d%2*3+1))
$d=$d-shr1
sleep -m 70}

```

Test script:

```
$f = {

for($d='0;?3,>5:.H7<1/9@E42-6B8CG='[$args[0][0]-65]-42;$d-1){[Console]::Beep(880,200*(($d%2)*3+1))
$d=$d-shr1
sleep -m 70}

}

&$f "A"
sleep -m 700
&$f "B"

```

I used a timing setup for beginers:

* the `dot duration` is 200ms
* the `gap between elements` is less then `dot duration` (70 ms)
* the `dash duration` is 4 `dot durations`

---
Tags: code-golf, audio, morse
---


title: Morse code to standard output

text:
# Question
Title: Morse code to standard output
This question involves taking input in Morse code as . (period) and - (minus symbol), with spaces to separate the input. Your task is to convert the code to standard output. You can assume that the only input contains character symbols found in the International Morse Code alphabet, found here: http://en.wikipedia.org/wiki/Morse\_code#Letters.2C\_numbers.2C\_punctuation.

All output should use lowercase letters. A double space should be interpreted as a word space.

Sample input:

```
. -..- .- -- .--. .-.. . .-.-.-  ... --- ...

```

Output:

```
example. sos

```

Shortest code after two weeks wins.

# Answer
> 8 votes
# Mathematica 62

*Mathematica* allows us to cheat

```
f=ToLowerCase@StringDrop[WolframAlpha[". .- "<>#,"Result"],2]&

f@"."
f@". -..- .- -- .--. .-.. . .-.-.-"
f@".... .- ...- .  -.-- --- ..-  -- --- --- . -..  - --- -.. .- -.-- ..--.."

```

> e
>
> example.
>
> have you mooed today?

The first two symbols `.` and `.-` are necessary to interpret small codes correctly.

# Answer
> 23 votes
Drat, I was hoping to get here before the GolfScripters arrived :-(

Anyhoo...

# C: 228 characters:

```
char n,t,m[9],*c=" etianmsurwdkgohvf l pjbxcyzq  54 3   2& +    16=/   ( 7   8 90    $       ?_    \"  .    @   '  -        ;! )     ,    :";
main(){while(scanf("%s",m)>0){for(t=m[6]=n=0;m[n];n++)t+=t+1+(m[n]&1);putchar(c[t]);}}

```

---

I thought I'd add an explanation of how this works.

The input data is parsed according to the tree data in `*c`, which can be expanded as follows (using `·` to represent a vacant node):

```
                     dot <-- (start) --> dash
                e                               t
        i               a               n               m
    s       u       r       w       d       k       g       o
  h   v   f   ·   l   ·   p   j   b   x   c   y   z   q   ·   ·
 5 4 · 3 · · · 2 & · + · · · · 1 6 = / · · · ( · 7 · · · 8 · 9 0
····$·······?_····"··.····@···'··-········;!·)·····,····:·······

```

Starting at the top of the tree, work your way down while moving to the left for a dot and to the right for a dash. Then output whatever character you happen to be at when the input string ends (i.e., when a whitespace character is encountered). So for example, three dots and a dash will take you to `v` via `e`, `i` and `s`. Instead of explicitly checking for dots (ASCII `\x2e`) and dashes (ASCII `\x2d`), we only need to check the last bit (`m[n]&1`), which is 0 for `.` and 1 for `-`.

Six rows are enough to encode everything except `$`, which has 7 dot/dashes: `...-..-`, but since the input data is guaranteed to be valid, this can easily be fixed by truncating the input at 6 characters (`m[6]=0`) and interpreting `...-..` as `$` instead. We can also cut away the last 7 bytes from the tree data, since they are all empty and aren't needed if the input is valid.

# Answer
> 10 votes
## GolfScript (116 113 97 chars)

This includes non-printable characters used in a lookup table, so I'm giving it as xxd output:

```
0000000: 6e2d 2720 272f 7b60 7b5c 6261 7365 2035
0000010: 3925 2210 a9cd 238d 57aa 8c17 d25c d31b
0000020: 432d 783e 277a 3823 e146 e833 6423 23ac
0000030: e72a 39d5 021c 4e33 3b30 3138 dc51 2044
0000040: 3aa7 d001 df4b 2032 333f 36ae 51c3 223d
0000050: 7d2b 5b35 2d34 5d2f 2b32 3333 257d 256e
0000060: 2b

```

This decodes to a program equivalent to

```
n-' '/{`{\base 59%"\x10\xA9\xCD#\x8DW\xAA\x8C\x17\xD2\\\xD3\eC-x>'z8#\xE1F\xE83d##\xAC\xE7*9\xD5\x02\x1CN3;018\xDCQ D:\xA7\xD0\x01\xDFK 23?6\xAEQ\xC3"=}+[5-4]/+233%}%n+

```

which is essentially

```
n-' '/{`{\base 59%"MAGIC STRING"=}+[5-4]/+233%}%n+

```

This uses a (non-minimal) perfect hash based on the core idea of An optimal algorithm for generating minimal perfect hash functions; Czech, Havas and Majewski; 1992. Their basic idea is that you use two hash functions, `f1` and `f2`, together with a lookup table `g`, and the perfect hash is `(g[f1(str)] + g[f2(str)]) % m` (where `m` is the number of strings we wish to distinguish); the clever bit is the way they build `g`. Consider all of the values `f1(str)` and `f2(str)` for strings `str` of interest as nodes in an undirected graph, and add an edge between `f1(str)` and `f2(str)` for each string. They require not only that each edge be distinct, but that the graph be acyclic; then it is just a DFS to assign weights to the nodes (i.e. to populate the lookup table `g`) such that each edge has the required sum.

Czech et al generate random functions `f1` and `f2` which are expressed via lookup tables, but that's clearly no good: I searched for a suitable hash using simple base conversions with two distinct bases from -10 to 9. I also relaxed the acyclic requirement. I didn't want to assign the strings to values from 0 to 54, but to the corresponding ASCII codes, so rather than taking `(g[f1(str)] + g[f2(str)]) % m` I wanted `(g[f1(str)] + g[f2(str)]) % N` for some `N > 'z'`. But that allows freedom to try various `N` and see whether any of them allow a valid lookup table `g`, regardless of whether there are cycles. Unlike Czech et al I don't care if the search for the perfect hash function is O(n^4).

The graph generated by `-4base` and `5base` mod `59` is:

which is fairly nice apart from the biggest connected component, which has three cycles of length 1. We have to go up to `N=233` before we can find a `g` which is consistent.

# Answer
> 5 votes
# , 145 bytes

Translated a dot to a 2, a dash to a 1 and interpreting the number in ternary and taking the mod 89, which gives a unique number we can use in a hash table. The presence of a 13 (111 base-3) means adding 1 because ASCII 13 doesn't work in TIO.

```
cat(c(letters,0:9,".")[match(strtoi(chartr(".-","12",scan(,"",t=scan(,""))),3)%%89+1,utf8ToInt('DG,)62	5N*EHMAI.%"!4=@'))],sep='')

```

Try it online!

# , 236 bytes (non-competing)

This is *not* going to be competitive, but it lets us show off something interesting in R: store the Morse code tree inside a quoted language structure `m` and retrieve it from the code of dots and dashes very simply using the fact that `[[` can be applied recursively to lists. For example `m[[c(2,2,3,2)]]` retrieves dot, dot, dash, dot or "f".

```
m=quote(.(e(i(s(h(5,4),v(,3)),u(f,M(,2))),a(r(l,.(.(,.),)),w(p,j(,1)))),t(n(d(b(6),x),k(c,y)),m(g(z(7),q),o(D(8),S(9,0))))))
for(w in scan(,"",t=scan(,"")))
cat(chartr("MDS","-. ","if"(is.symbol(z<-m[[(utf8ToInt(w)==45)+2]]),z,z[[1]])))

```

Try it online!

# Answer
> 4 votes
## C, 169 chars

I couldn't find a better hash function..

(I posted the unminified code but counted it minified; to minify just do `:%s/ //g | %j!` in vim, then put the space in the string literal back.)

```
c, v = 1;

main() {
  while (c = getchar(), ~c)
    v = c < 33? putchar(
      "& etianmsurwdkgohvf.l.pjbxcyzq..54.3.;!2).+...,16=/:..(.7.?_8.9o\"...$...@...'..-"[v < 64? (v != 40)*v : v % 51 + 33]
    ), 1 : v * 2 + c % 2;
}

```

### Test run

(`morse.in` is just the whole alphabet in morse on separate lines):

```
% clang morse.c && ./a.out </tmp/morse.in
abcdefghijklmnopqrstuvwxyzO123456789.,?'!/()&:;=+-_"$@
% ./a.out <<<'. -..- .- -- .--. .-.. . .-.-.-  ... --- ...'
example. sos

```

### Explanation

This one is fairly straightforward. `c < 33` finds a whitespace/separator character (, `\n`, EOF, ...). `c % 2` translates a dot or dash into a bit. The idea is to create a unique number for each character simply by interpreting it as a binary number (after prefixing it with 1 to deal with the variable length) (this interpretation is the `v*2 + c%2` part). I then get a 137-char LUT, which I compacted by hashing the resulting value (`v < 64? v : v % 51 + 33`, constants found via trial-and-error and by looking at the distribution and try to find a huge gap). Unfortunately this hash function has a single collision, which is why I have to special-case the `40 → '&'` mapping.

# Answer
> 1 votes
# Powershell, 193 bytes

```
$n=1
-join("$args "|% t*y|%{if($_-32){$n=$n*2+($_-ne'.')}else{("  etianmsurwdkgohvf l pjbxcyzq  54 3   2& +~16=/   ( 7   8 90~~~?~ `"  .~@   '  -~~;! )~ ,~:~~~~$"-replace'~','    ')[$n]
$n=1}})

```

Less Golfed Test script:

```
$f = {

$n=1
-join(
    "$args "|% t*y|%{
        if($_-32){
            $n=$n*2+($_-ne'.')
        }else{
            ("  etianmsurwdkgohvf l pjbxcyzq  54 3   2& +~16=/   ( 7   8 90~~~?~ `"  .~@   '  -~~;! )~ ,~:~~~~$"-replace'~','    ')[$n]
            $n=1
        }
    }
)

}

@(
    ,("example. sos",". -..- .- -- .--. .-.. . .-.-.-  ... --- ...")
    ,("0123456789abcdefghijklmnopqrstuvwxyz","----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..")
    ,("hello world", ".... . .-.. .-.. ---  .-- --- .-. .-.. -..")
) | % {
    $expected,$s = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

```

Output:

```
True: example. sos
True: 0123456789abcdefghijklmnopqrstuvwxyz
True: hello world

```

# Answer
> 0 votes
# JavaScript (165 bytes, only implementing four planes.)

```
n=''.replace(/\./g,1).replace(/-/g,0).split(' ')
l='|te|mnai|ogkdwrus|cöqzycxbjpälüfvh'.split('|')
r=''
for(i in n){r+=l[n[i].length][parseInt(n[i],2)]}
alert(r)

```

The input should be assigned to `n`, execute the following code to get the output:

```
n='. -..- .- -- .--. .-.. .'.replace(/\./g,1).replace(/-/g,0).split(' ')
l='|te|mnai|ogkdwrus|cöqzycxbjpälüfvh'.split('|')
r=''
for(i in n) {r+=l[n[i].length][parseInt(n[i],2)]}
alert(r)

```

---
Tags: code-golf, hashing, morse
---


# Question
Title: Find the best period in which to have invested in a S&P500 index fund
Here are the annual returns for a hypothetical S&P 500 stock index fund for each calendar year from 1928 to 2017, expressed as a multiplier. So in 1928 you might say "the index went up by 37.88%" which I've represented here by 1.3788.

```
1.3788, 0.8809, 0.7152, 0.5293, 0.8485, 1.4659, 0.9406, 1.4137, 1.2792, 0.6141,  1.2521, 0.9455, 0.8471, 0.8214, 1.1243,  1.1945, 1.138, 1.3072, 0.8813, 1,  0.9935, 1.1026, 1.2178, 1.1646, 1.1178,  0.9338, 1.4502, 1.264, 1.0262, 0.8569,  1.3806, 1.0848, 0.9703, 1.2313, 0.8819,  1.1889, 1.1297, 1.0906, 0.8691, 1.2009,  1.0766, 0.8864, 1.001, 1.1079, 1.1563,  0.8263, 0.7028, 1.3155, 1.1915, 0.885,  1.0106, 1.1231, 1.2577, 0.9027, 1.1476,  1.1727, 1.014, 1.2633, 1.1462, 1.0203,  1.124, 1.2725, 0.9344, 1.2631, 1.0446,  1.0706, 0.9846, 1.3411, 1.2026, 1.3101,  1.2667, 1.1953, 0.8986, 0.8696, 0.7663,  1.2638, 1.0899, 1.03, 1.1362, 1.0353,  0.6151, 1.2345, 1.1278, 1, 1.1341,  1.296, 1.1139, 0.9927, 1.0954, 1.1942

```

Source: https://www.macrotrends.net/2526/sp-500-historical-annual-returns

## Challenge

Given as inputs:

* the array of annual returns (but see Rule 2. below)
* an array \\$X\\$ of \\$1\le K \le 90\\$ positive numbers (the amounts to invest in each year of the investment period)

write a program or function that outputs what would have been the "best" \\$K\\$ consecutive year period to have invested the amounts in \\$X\\$, where:

* each amount is invested at the beginning of a year.
* anything left after each year is reinvested at the beginning of each subsequent year.
* "best" means the largest amount at the end of the \\$K\\$ year period.

## Rules

1. This is , so the fewest bytes in each language wins. Standard rules apply. Explanations encouraged.
2. If you don't like the way I've represented the array of annual returns, you can change them to any other array of 90 numbers that you prefer.
3. You can output the best \\$K\\$ year period in any consistent manner (e.g. 0-indexed or 1-indexed, the first and/or the last year to have invested, etc.) but you need to say what your output represents if it isn't obvious.
4. In case of a tie, output any or all correct answers.

## Example calculation

Suppose \\$X = \[ 10000, 20000, 30000 \]\\$.

If you had invested these amounts in 1928, 1929, and 1930 (the 1-indices 1, 2, and 3) you would have ended up with 42743.10. Sad.

But if you had invested those amounts in 2014, 2015, and 2016 (the 1-indices 87, 88, and 89) you would have ended up with 66722.66. A bit better.

It turns out the *best* three year period to have invested these amounts would have been 1995, 1996, and 1997 (1-indices 68, 69, and 70), resulting in 91942.91. Nice.

## Test cases

1-indexed, first year of optimal period

```
[ 1, 2, 3 ]                          ->  68
[ 1 ]                                ->   6
* any array of length 90 *           ->   1
[ 1, 1 ]                             ->  27
[ 1, 2 ]                             ->   8
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]  ->  62
[ 1, 2, 3, 4, 5, 4, 3, 2, 1 ]        ->  64
* 1 repeated 20 times *              ->  53

```

# Answer
> 6 votes
# Jelly, 9 bytes

```
PÐƤ⁹L¤ƤḋM

```

A dyadic link which yields a list of all the maximal starting 1-based indices.

**Try it online!**

(or `ṡL}PÐƤ€ḋM`)

### How?

```
PÐƤ⁹L¤ƤḋM - Link: list of returns, list of nominal investments
      Ƥ   - for infixes of (the returns)...
          - ...of length:
     ¤    -               nilad followed by links as a nilad:
   ⁹      -                 chain's right argument (nominals)
    L     -                 length
          - ...do:
 ÐƤ       -        for post-fixes:
P         -          product
       ḋ  - dot-product (each) with (the nominals)
        M - maximal indices

```

# Answer
> 3 votes
# Japt, 25 bytes

```
ãVl)míV ®rÈ+YÌ *Yg}0
bUrw

```

Try it online!

0-indexed output.

Explanation, with `U` as the list of returns and `V` as the list of investments:

```
ã                       :Get subsections of U
 Vl)                    : with the same length as V
    m                   :For each of those sections
     í                  : pair each element with
      V                 : the corresponding element from V
        ®          0    :Calculate the investment results of each by:
         r        }     : for each year:
          È+            :  add the result of the previous year
            YÌ          :  to this year's investment
               *Yg      :  and multiply by this year's return

b                       :Get the index of
 Urw                    : the maximum

```

Bonus cheating answer:

# Japt, 13 bytes

```
OvUÎò3 ®n dÃq

```

Try it online!

Takes the list of returns as this array, which is an array of 90 strings where each string contains a base-10 integer padded to 1929 digits; I believe this technically meets the requirements. The "Try it" link only has the first element of the "returns" list because the full thing broke the permalink generator, but that's the only one that gets used. You can paste in the whole thing from the pastebin if you want.

Explanation:

As mentioned, only the first element of the "returns" array is actually used; every other element is 0 in the pastebin and ignored by the program. The first element is generated by this, which takes the string representation of a Japt program, turns each character into a 3 digit number, and joins those numbers into a new string of just digits. The code being encoded is this, which is basically my main answer adjusted to hard-code the returns. Then the "answer" program is just:

```
  UÎ             :Get the first element
    ò3           :Cut it into slices of length 3
       ®n        :Convert those strings to numbers
          dÃ     :Convert those numbers to characters
            q    :Join all the characters into one string
Ov               :Execute it as Japt

```

# Answer
> 2 votes
# JavaScript (ES6), 73 bytes

Takes input as `(annual_returns)(X)`. The result is 0-indexed.

```
a=>x=>a.map((_,i)=>x.map((c,j)=>(t=(t+c)*a[i+j])>m&&(r=i,m=t),t=0),m=0)|r

```

Try it online!

# Answer
> 2 votes
# J, 48 bytes

```
1+[:(i.>./)[:({:@[*{.@[+*/@])/"2[(|.@,."1)#@[]\]

```

Try it online!

## ungolfed

```
1 + [: (i. >./) [: ({:@[ * {.@[ + */@])/"2 [ |.@,."1 #@[ ]\ ]

```

## how

Take input list (eg, `123`) on left, data on right.

`#@[ ]\ ]` Chop up the data into infixes whose length matches the input:

```
1.3788 0.8809 0.7152
       0.8809 0.7152 0.5293
              0.7152 0.5293 0.8485

```

`[ ,."1` now zip each of those groups of 3 with the input list

```
1      2      3
1.3788 0.8809 0.7152
       1      2      3
       0.8809 0.7152 0.5293
              1      2      3
              0.7152 0.5293 0.8485

```

`|.@`  and reverse them:

```
3      2      1
0.7152 0.8809 1.3788

```

`(verb to insert)/"2` Between the items of each zipped group of 3, insert the verb in parentheses.

```
3             2             1
        VERB          VERB
0.7152        0.8809        1.3788

```

`({:@[ * {.@[ + */@])` is the inserted verb, which will reduce each item of the list of zipped groups of threes down to one number, which is the amount earned over that group of years:

```
          2. plus the first      1. */] = product of right args
             (top) item on left
              +-+     +--------+
              |2|  +  |    1   |
              +-+     |    *   |
                      | 1.3788 |
             *        +--------+

          0.8809

          3. Multiply that sum by the bottom
             number on the left.

```

`(i. >./)` Take the list thus reduced and find the index of the max.

`1 + [:` And add one

# Answer
> 1 votes
# Python 2, 97 bytes

```
lambda r,v:max(range(len(r)-len(v)+1),key=lambda i:reduce(lambda x,(a,b):(x+a)*b,zip(v,r[i:]),0))

```

Try it online!

Returns `0`-indexed

# Answer
> 1 votes
# Jelly, 11 bytes

```
ṡ⁹L¤U×\€UḋM

```

Try it online!

The return factor on a deposit is the cumulative product of the return factors in the years until the end of the `K` year period. If we're allowed to take the input in reverse and output a year number as 2018-\[end date\], the **10 bytes** solution `×\⁹L¤Ƥ×S€M` works.

```
ṡ                All overlapping slices of left input of length:
 ⁹L¤               length(right input)
                 Calculate cumulative returns list for each possible year:
    U              Reverse each element of the result
     ×\€           Take the cumulative product
        U          Reverse again
         ḋ      Dot product with the deposits list.
                The final balance when invested in each year.
          M     Get all indices of maximum values

```

# Answer
> 1 votes
# 05AB1E, ~~21~~ 20 bytes

```
Œsgùεø0©\vy`s®+*©]Zk

```

Way too long..

0-indexed.

Try it online or verify all test cases.

**Explanation:**

```
Œ                  # Get all sublists of the (implicit) input-list of stock-changes
 s                 # Swap to take the second (implicit) input-list of investments
  g                # And take its length
   ù               # Only leave sublists of that size
ε                  # Map each to:
 ø                 #  Create pairs with the second (implicit) input-list of investments
  0©               #  Store 0 in the register
    \              #  Discard the 0 from the stack
     vy            #  Loop `y` over the pairs
       `           #   Pop and push both values of the pair to the stack
        s          #   Swap them
         ®+        #   Add the value from the register to the investment amount
           *       #   And multiply it by the current number of the sublist
            ©      #   And then replace the value in the register with this
             ]     # Close both the loop and map
              Z    # Take the max of the mapped sublists (without popping the list)
               k   # Determine the index of that max (and output implicitly)

```

# Answer
> 0 votes
# Jelly, 15 bytes

```
ṡ⁹L¤ż€+Ṫ×Ḣʋƒ€0M

```

Try it online!

---
Tags: code-golf
---


title: Is this quadrilateral cyclic?

text:
# Question
Title: Is this quadrilateral cyclic?
In mathematics, a *cyclic quadrilateral* is one whose vertices all lie on the same circle. In other words, every vertex is on the circumcircle of the other three. For more information, see the MathWorld article.

### Examples

These quadrilaterals are cyclic:

This trapezoid is not cyclic.

<sub>(Images from Wikipedia)</sub>

### Objective

Given the coordinates of four vertices in counterclockwise order which form a convex quadrilateral, determine if the quadrilateral is cyclic.

Coordinates will be integers (note, however, that the circumcenter coordinates and circumradius are not necessarily integers.) As implied by the previous paragraph, no three points will be co-linear and no two coincident.

### I/O

You may take input using any reasonable format. In particular, `[[x1,x2,x3,x4],[y1,y2,y3,y4]]`, `[[x1,y1],[x2,y2],[x3,y3],[x4,y4]]` and complex numbers are all fine.

Output using any different consistent values for true and false.

### Test cases

True:

```
[0,0], [314,0], [314,1], [0,1]
[-5,5], [5,-5], [1337,42], [42,1337]
[104, -233], [109, -232], [112, -231], [123, -224]

```

False:

```
[0,0], [314,0], [314,100], [0,99]
[31,41],[59,26],[53,58],[0,314]

```

# Answer
> 12 votes
# Wolfram Language (Mathematica), 23 bytes

```
#∈Circumsphere@{##2}&

```

Try it online!

Takes four inputs: the lists `{x1,y1}`, `{x2,y2}`, `{x3,y3}`, and `{x4,y4}`. Checks if the first point lies on the circumcircle of the other three. Also works for checking if \\$n+1\\$ points in \\$\mathbb R^n\\$ are concyclic, provided the last \\$n\\$ of them are affinely independent (because `Circumsphere` is sad if you give it a degenerate input).

Alternatively, here is a mathematical approach:

# Wolfram Language (Mathematica), ~~29~~ ~~28~~ ~~25~~ 24 bytes

```
Det@{#^2+#2^2,##,1^#}^0&

```

Try it online!

Takes two lists as input: `{x1,x2,x3,x4}` and `{y1,y2,y3,y4}`. Returns `Indeterminate` when the four points are on a common circle, and `1` otherwise.

From the four points \\$(x\_1, y\_1), (x\_2,y\_2), (x\_3, y\_3), (x\_4, y\_4)\\$, this solution constructs the matrix below:

\\$\begin{bmatrix}x\_1^2 + y\_1^2 & x\_2^2 + y\_2^2 & x\_3^2 + y\_3^2 & x\_4^2 + y\_4^2 \\ x\_1 & x\_2 & x\_3 & x\_4 \\ y\_1 & y\_2 & y\_3 & y\_4 \\ 1 & 1 & 1 & 1 \end{bmatrix}\\$

The determinant of this matrix is 0 if and only if the four rows are linearly dependent, and a linear dependency between the rows is the same thing as the equation of a circle that's satisfied at all four points.

The shortest way I could think of to check if the determinant is 0 is to raise it to the 0-th power: `0^0` is `Indeterminate` while anything else gives `1`.

# Answer
> 11 votes
# Python 3, 70 bytes

```
lambda b,c,d,e,a=abs:a(a(b-d)*a(c-e)-a(b-c)*a(d-e)-a(c-d)*a(b-e))<1e-8

```

Try it online!

I use the Ptolemy's theorem.

> In a quadrilateral, if the sum of the products of its two pairs of opposite sides is equal to the product of its diagonals, then the quadrilateral can be inscribed in a circle.

`b`, `c`, `d`, `e` are complex numbers.

# Answer
> 8 votes
# Perl 6, 44 bytes

```
{!im ($^b-$^a)*($^d-$^c)/(($d-$a)*($b-$c)):}

```

Try it online!

Takes vertices as complex numbers. Uses the fact that the sum of opposite angles is 180° in a cyclic quadrilateral. The order of operations should guarantee that floating-point operations yield an exact result for (small enough) integers.

### Port of Misha Lavrov's TI-Basic solution, 33 bytes

```
{![*](map */*,($_ Z-.rotate)).im}

```

Try it online!

# Answer
> 6 votes
# JavaScript (ES6)

## Testing the angles, 114 bytes

Takes input as the array \\$\[x1,y1,x2,y2,x3,y3,x4,y4\]\\$. Returns a Boolean value.

```
a=>(F=i=>(A=Math.atan2)(a[i+3&7]-(y=a[i+1]),a[i+2&7]-a[i])-A(a[i+5&7]-y,a[i+4&7]-a[i]))(0)+F(2)+F(4)+F(6)==Math.PI

```

Try it online!

---

## Computing a determinant, 130 bytes

Takes input as \\$\[x1,x2,x3,x4\]\\$ and \\$\[y1,y2,y3,y4\]\\$ in currying syntax. Returns a Boolean value.

This one is equivalent to MishaLavrov's 2nd answer, with a rotated matrix.

```
x=>y=>!(g=a=>a+a?a.reduce((v,[r],i)=>v+(i&1?-r:r)*g(a.map(r=>r.slice(1)).filter(_=>i--)),0):1)(x.map((X,i)=>[1,Y=y[i],X,X*X+Y*Y]))

```

Try it online!

# Answer
> 6 votes
# TI-Basic (83 series), 21 bytes

```
e^(ΔList(ln(ΔList(augment(Ans,Ans
not(imag(Ans(1)Ans(3

```

Takes input as a list of four complex numbers in `Ans`. Returns `1` if the quadrilateral is cyclic and `0` otherwise.

This is nwellnhof's cross-ratio computation, in heavy disguise. If we start with values \\$z\_1, z\_2, z\_3, z\_4\\$, then:

* `ΔList(augment(Ans,Ans` computes the differences \\$z\_2-z\_1, z\_3-z\_2, z\_4-z\_3, z\_1-z\_4\\$ (and a few more redundant terms),
* `e^(ΔList(ln(` of that computes the ratios \\$\frac{z\_3-z\_2}{z\_2-z\_1}, \frac{z\_4-z\_3}{z\_3-z\_2}, \frac{z\_1-z\_4}{z\_4-z\_3}, \dots\\$.
* We check if the product of the first and third terms, which is \\$\frac{z\_3-z\_2}{z\_2-z\_1} \cdot \frac{z\_1-z\_4}{z\_4-z\_3}\\$, has no imaginary part. Note that this is the same as the cross-ratio \\$(z\_3,z\_1;z\_2,z\_4) = \frac{z\_2-z\_3}{z\_2-z\_1} : \frac{z\_4-z\_3}{z\_4-z\_1}\\$.

I did my best to check if numerical error is a problem, and it doesn't seem to be, but if anyone has good test cases for that, please let me know.

# Answer
> 3 votes
### JavaScript (ES6) (101 bytes)

```
p=>(h=(a,b)=>Math.hypot(p[a]-p[b],p[a+1]-p[b+1]))&&((h(2,4)*h(0,6)+h(0,2)*h(4,6)-h(0,4)*h(2,6))<1e-8)

```

Takes input as `[x1,y1,x2,y2,x3,y3,x4,y4]`, outputs a Boolean.

Checked based on $$ef=ac+bd$$ where \\$e,f\\$ are the diagonals and \\$a,b,c,d\\$ are the sides in order.

Try it online!

# Answer
> 2 votes
# Jelly, 11 bytes

```
²Sṭ;L€€ṖÆḊ¬

```

Try it online!

Uses the determinant approach from Misha Lavrov's Mathematica solution. Outputs 1 for true, 0 for false.

### How it works

```
²Sṭ;L€€ṖÆḊ¬  Main link (monad). Input: [[x1,x2,x3,x4], [y1,y2,y3,y4]]
²S           Square each scalar and add row-wise; [x1*x1+y1*y1, ...]
  ṭ          Append to the input
   ;L€€      Add two rows of [1,1,1,1]'s
       Ṗ     Remove an extra row
        ÆḊ¬  Is the determinant zero?

```

# Jelly, 12 bytes

```
Iµ÷×ƭ/÷SµḞ=A

```

Try it online!

Uses the convoluted cross-ratio approach from Misha Lavrov's TI-Basic solution. Outputs 1 for true, 0 for false.

### How it works

```
Iµ÷×ƭ/÷SµḞ=A  Main link (monad). Input: list of four complex numbers [z1,z2,z3,z4]
I             Increments; [z2-z1, z3-z2, z4-z3]
 µ            Refocus on above for sum function
  ÷×ƭ/÷S      (z2-z1)÷(z3-z2)×(z4-z3)÷(z4-z1)
        µ     Refocus again
         Ḟ=A  (real part) == (norm) within error margin
              i.e. imag part is negligible?

```

I believe both are golfable...

# Answer
> 2 votes
# APL (Dyalog Classic), 25 bytes

```
{0=-/|⍵}(-⌿2 3⍴2/⌽)×⊃-1↓⊢

```

Try it online!

Ptolemy's theorem, credit: Кирилл Малышев's answer

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


title: Electrical outlet

text:
# Question
Title: Electrical outlet
This is a problem from NCPC 2005. Roy has an apartment with only one single electrical outlet, but he has a bunch of power strips. Compute the maximum number of outlets he can have using the power strips he has. The number of outlets per power strip is given as input.

It turns out that if the number of outlets of the strips respectively are

$$p\_1, p\_2, \dots, p\_n$$

then the number of outlets is $$1 - n + \sum\_i p\_i$$ ,

or

$$1 + p\_1-1 + p\_2-1 + \dots + p\_n-1$$.

**The input to the *program or function* is a non-empty series of positive integers.**

## Examples

```
2 3 4
> 7
2 4 6
> 10
1 1 1 1 1 1 1 1
> 1
100 1000 10000
> 11098

```

# Answer
# Jelly, 3 bytes

```
’S‘

```

Decrement (all), sum, increment. Try it here.
> 23 votes

# Answer
## Retina, 3 bytes

```
 1

```

The trailing linefeed is significant.

Input is a space-separated list of unary numbers.

Try it online!

### Explanation

The code simply removes all spaces as well as the `1` after them from the string. Here is why that works:

Addition in unary is simple: just concatenate the numbers which is the same as removing the delimiters. Decrementing by 1 is also simple: just remove a `1` from each number. We want 1 more than the sum of the decremented inputs though, so we simply only remove the `1`s we find after spaces, thereby decrementing all but the first input.
> 29 votes

# Answer
## Hexagony, ~~18~~ 14 bytes

```
.?<_(@'")>{+.!

```

Unfolded:

```
  . ? <
 _ ( @ '
" ) > { +
 . ! . .
  . . .

```

Try it online!

I don't think side-length 2 is possible, but there ~~must~~ might be a more efficient side-length 3 solution that this.

This is the usual "decrement all, sum, increment" approach, but I'll have to add diagrams later to show how exactly it works in Hexagony.
> 9 votes

# Answer
## Python, 24 bytes

```
lambda*n:1-len(n)+sum(n)

```

Try it online
> 7 votes

# Answer
# Mathematica, 9 bytes

```
Tr[#-1]+1&

```
> 7 votes

# Answer
## Haskell, ~~17~~ 15 bytes

```
foldl1$(+).pred

```

Usage example: `( foldl1$(+).pred ) [2,4,6]` -\> `10`.

Old version, different approach, 17 bytes: `succ.sum.map pred`.
> 7 votes

# Answer
# J, 6 bytes

```
+/+1-#

```

Sum plus one minus length. Parenthesize and apply it, like so:

```
   (+/+1-#) 2 3 4
7

```
> 6 votes

# Answer
## Labyrinth, 9 bytes

```
"?;)!@
+(

```

Try it online!

The usual primer:

* Labyrinth is 2D and stack-based. Stacks have an infinite number of zeroes on the bottom.
* When the instruction pointer reaches a junction, it checks the top of the stack to determine where to turn next. Negative is left, zero is forward and positive is right.

Here we start at the top left `"`, a no-op, heading rightward. Next is `?`, which reads an int from STDIN (throwing away chars it can't parse as an integer, e.g. spaces). Now we have two cases:

If the input is positive, we turn right, performing:

```
(            decrement top of stack
+            add top two stack elements
             [continue loop]

```

If the input is zero (which occurs at EOF), we go straight ahead, performing:

```
;            pop zero from EOF
)            increment top of stack
!            output top of stack as number
@            halt program

```
> 6 votes

# Answer
# Pyth, 5 bytes

```
hstMQ

```

increment(sum(map(decrement, input)))
> 5 votes

# Answer
## ES6, 25 bytes

```
a=>a.map(n=>r+=n-1,r=1)|r

```
> 5 votes

# Answer
# MATL, 3 bytes

```
qsQ

```

Try it online.

## Explanation

```
qsQ
q      thread decrement over the input array
  s    sum
   Q   increment

```
> 5 votes

# Answer
## Starry, ~~26~~ 24 bytes

```
, + '`      + ** `, +'*.

```

Expects newline-separated integers. Try it online!

Thanks to @MartinBüttner for -2 bytes.

```
,           Read line as integer
 + '        Dupe and jump to label 1 if nonzero
`           Set label 0
      +     Push 1
 *          Sub
*           Add
 `          Set label 1
,           Read line as integer
 + '        Dupe and jump to label 0 if nonzero
*           Add
.           Output as integer

```

The loop is unrolled so that the first number is not decremented, negating the need to increment. Pushing numbers is expensive in Starry...
> 4 votes

# Answer
# 05AB1E, 4 bytes

Code:

```
E<O>

```

Explanation:

```
E     # Evaluates input
 <    # Decrement on list
  O   # Compute the total sum
   >  # Increment on the sum
      # Implicit: output top of the stack

```

Takes input like an array (e.g. `[3, 4, 5]`).
> 4 votes

# Answer
# Bash + GNU utilities, 16

If there are `N` power strips, then there should be `N-1` separators in the comma-separated input list. All we need to do is replace the separators with `- 1 +` and arithmetically evaluate:

```
sed s/,/-1+/g|bc

```

Or using the same trick:

# Pure Bash (no external utilities), 19

```
echo $[${1//,/-1+}]

```
> 4 votes

# Answer
# APL (NARS 2000), ~~13~~ 10 bytes

`{1+(+/⍵)-⍴∊⍵}`

Edit: Down to 10 with Lynn's (better) approach.

`{1++/1-⍨⍵}`
> 3 votes

# Answer
## CJam, 7 bytes

```
q~:(:+)

```

Test it here.

Same approach as Lynn's (decrement all, sum, increment). This also works for 8 bytes (and is maybe a bit more interesting):

```
q~{(+}*

```

This folds "decrement, add" over the list. By doing that, the decrement is only applied to all elements except the first, such that we don't need to take care of the increment separately.
> 3 votes

# Answer
# gs2, 5 bytes

(CP437-encoded.)

```
W&Φd'

```

That’s `read-nums dec m1 sum inc`.
> 3 votes

# Answer
## Seriously, 7 bytes

```
,;l@Σ-u

```

Try it online!

Explanation:

```
,;l@Σ-u
,        push input
 ;       dupe
  l@     push length (n), swap
    Σ-u  push sum, subtract n, add one

```
> 3 votes

# Answer
# C, ~~60~~ ~~59~~ 55 bytes

```
x;main(s){while(~scanf("%i",&x))s+=x-1;printf("%i",s);}

```
> 3 votes

# Answer
# Perl 6, 14 bytes

```
{1+[+] --«@_}

```

**usage**

```
my &f = {1+[+] --«@_}

say f([2,3,4]) # 7
say f([2,4,6]) # 10
say f([1,1,1,1,1,1,1,1]) # 1
say f([100,1000,10000]) # 11098

```
> 3 votes

# Answer
# Mornington Crescent,  ~~1909 1873~~  1839 bytes

```
Take Northern Line to Stockwell
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Embankment
Take Circle Line to Temple
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Blackfriars
Take Circle Line to Embankment
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Parsons Green
Take District Line to Embankment
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

```

Try it online!
> 3 votes

# Answer
# Perl 6, 20 bytes

```
put 1+sum --«@*ARGS

```

( You can use `<<` instead of `«` )

### Usage:

```
$ perl6 -e 'put 1+sum --«@*ARGS' 100 1000 10000
11098

```
> 2 votes

# Answer
# Perl 5 23+2=25 or 19+2=21

Requires `-ap` flags:

```
map{$.+=($_-1)}@F;$_=$.

```

Saved in a file and run as

```
perl -ap file.pl

```

EDIT: Another answer, smaller (19+2) but basically copied from dev-null answer:

```
$.+=$_-1for@F;$_=$.

```
> 2 votes

# Answer
## F#, 25 bytes

```
Seq.fold(fun s n->s+n-1)1

```

This is a function that takes in an array/list/sequence of integers and returns the required result.

### How it works:

`Seq.fold` allows you to apply a function to every element of a sequence while carrying some state around while it does so. The result of the function as applied to the first element will give the state that will be put into the function for the second element, and so forth. For example, to sum up the list `[1; 3; 4; 10]`, you'd write it like this:

```
Seq.fold (fun sum element -> sum + element) 0 [1; 3; 4; 10]
         (       function to apply        ) ^ (sequence to process)
                                     ( initial state )

```

Which would be applied like so:

```
// First, initial state  + first element
0 + 1  = 1
// Then, previous state + next element until the end of the sequence
1 + 3  = 4
4 + 4  = 8
8 + 10 = 18

```

With the last state being the return value of `Seq.fold`.
> 2 votes

# Answer
# , 5 chars / 7 bytes

```
ï⒭+‡_

```

`Try it here (Firefox only).`

Uses a custom encoding with 10-bit chars (thx @Dennis!). Run `encode('ï⒭+‡_')` in the JS console to get encoded form, and `decode(/*ENCODED TEXT HERE*/)` to decode encoded form.

# Explanation

Translates to Javascript ES6 as:

```
i=>i.reduce(($,_)=>$+--_)

```
> 2 votes

# Answer
## Python 3, 79 bytes

```
import sys
print(sum(map(lambda x: int(x)-1, sys.stdin.readline().split()))+1)

```
> 1 votes

# Answer
## Perl, 21 + 2 = 23 bytes

```
$a+=$_-1for@F;say++$a

```

Requires `-a` and `-E`:

```
$ perl -aE'$a+=$_-1for@F;say++$a'<<<'2 3 4'
7

```
> 1 votes

# Answer
## Ruby, 30 bytes

```
$*.inject(1){|s,v|s+=v.to_i-1}

```

Simple enough - starting from 1, add up the supplied numbers, each -1 (command line args are in `$*`). Shame `inject` is such a long word.
> 1 votes

# Answer
## PowerShell, 19 bytes

```
$args-join'-1+'|iex

```

Note that `1 + p1-1 + p2-1 + ... + pn-1` is equivalent to `p1-1 + p2-1 + ... + pn`.

Takes input as separate command-line arguments with `$args`. We `-join` those together with a `-1+` delimiter to create a string, such as `2-1+3-1+4`. The string is then piped to `Invoke-Expression` (similar to `eval`), and outputs the result.
> 1 votes

# Answer
## Brainfuck, 15 bytes

Assumption: The , operator returns 0 once all input has been exhausted, and there are no extension cords with 0 plugs. Also, the IO needs to be in byte values instead of ASCII character codes.

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

```

Explanation: This uses 2 registers. A "Value" accumulator register, representing the number of devices that can be plugged in, and a "current cord" register that keeps track of the value of the current cord. It starts off by incrementing the value by 1, for the existing outlet. Then, for each extension cord, it subtracts one from the value since a plug is being taken up, then increments the value by the number of plugs.

Most online interpreters don't operate in raw byte input mode. To test it online, use this code:

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

```
> 1 votes

# Answer
# PARI/GP, 17 bytes

Completely straightforward.

```
v->vecsum(v)-#v+1

```
> 1 votes

# Answer
# Pylons, 6

Takes a list of space separated numbers on the command line then sums them all and subtracts the length.

```
1(i)-s

```

How it works:

```
1   # Push 1 to the stack.
(   # Start a list.
 i  # Get command line input.
  ) # End a list.
-   # Subtract the top two elements of the stack. In the case where one of the elements is
    # a list, it does matrix subtraction.
s   # Sum the stack.
    # Print the stack implicitly.

```
> 1 votes

# Answer
# R, ~~24~~ 14 bytes

```
sum(1,scan()-1)

```

Edit: Fixed bug!
> 1 votes

# Answer
# Python, 10+22=32 bytes

```
s=input();print(sum(s)-len(s)+1)

```

Main issue is not having a default input variable in Python, or implicit printing.
> 1 votes

# Answer
# APL Nars 9 chars

```
{1++/⍵-1}

```

test

```
f←{1++/⍵-1}
  f 2 3 4
7
  f 2 4 6
10
  f 1 1 1 1 1 1 1 1
1
  f 100 1000 10000
11098

```
> 1 votes

# Answer
# TIS, 93 bytes

Code:

```
@0
MOV ANY ANY
@1
MOV UP ACC
JGZ G
SWP
ADD 1
MOV ACC DOWN
G:SUB 1
MOV ACC ANY
SWP
ADD ANY
SWP

```

Layout:

```
1 2 CC
I1 NUMERIC -
O1 NUMERIC -

```

Try it online!

Note that this solution requires the list to be terminated by a zero (or more accurately, a non-positive value).

With TIS, we'd need to choose one of the following a) a terminating character, b) a length-prefixed array, or c) a running output for every value. Otherwise, a program would never print any output because there (theoretically) could be more input on the way.

### Explanation:

Each node has two accumulators, called `ACC` and `BAK`. `BAK` can only be accessed by the `SWP` instruction, which swaps the values in `ACC` and `BAK`. In the following, I will use variables X and Y to track the values more directly. I'll also use Z as shorthand for the entire node 0.

Additionally, each node implicitly loops back to the top when it reaches the bottom.

```
                                  |    Input 0    | Input as whitespace-delimited numbers
                  +--------+------+--------+------+
                  | Node 0 |      | Node 1 |      |
Node 0 is just an +--------+      +--------+      |
extra memory cell | MOV ANY ANY   | MOV UP ACC    | Put input value into X
so we can perform |               | JGZ G         | If X>0, jump to label G
logic on input    |               | SWP           | Swap focus to Y
values easier     |               | ADD 1         | Y++
                  |               | MOV ACC DOWN  | Output the value Y
                  |               |               | (end program -- see note 1 below)
                  |               | G:SUB 1       | Label G: X--
                  |               | MOV ACC ANY   | Z = X (also see note 2 below)
                  |               | SWP           | Swap focus to Y
                  |               | ADD ANY       | Y += Z (also see note 2 below)
                  |               | SWP           | Swap focus to X
                  +---------------+---------------+
                                  |   Output 0    | Output as whitespace-delimited numbers

```

*Note 1, regarding the termination of this program:*

The TIS emulator I am using here will terminate the program once there is no more active processing. The most common reason for getting into such a state is to exhaust all available input, though things like deadlocks can also get us to this state.

Once the value in this program has been output, calculation will continue on at label G, mangling the data in the registers (it forgets which register is X and which is Y). However, it will quickly return to the line that reads input, and because the input will now be exhausted, the program will terminate.

Some minor modifications may be made to adjust the program to handle data after the terminator:

* Adding the instruction `HCF` just before the label G will cause the program to forcibly terminate at this point instead of relying on input exhaustion.
* Adding the instructions `SWP` and `JRO -99` just before the label G will cause the program to return to a good state, then jump back to top (relative jumps can't wrap, so anything further than -15 will always go to the top line; offhand, I think -7 is the exact value needed here). This turns the terminator into a 'print' instruction instead.
* The value Y could be reset to zero, in addition to the jump described above, to treat extended input as two or more distinct invocations.

*Note 2, regarding the use of `ANY` in node 1:*

The use of `ANY` on the two marked lines of Node 1 is possible due to an implementation detail (this quirk is true in both this emulator and in the original Zachtronics game).

When `ANY` is used as the source, it looks at the node's neighbors in this order: `LEFT`, `RIGHT`, `UP`, `DOWN`. When `ANY` is used as the destination, it looks at the neighbors in this order: `UP`, `LEFT`, `RIGHT`, `DOWN`. (The destination ordering is a consequence of both the source ordering and the order in which the nodes are run.)

Of course, the nodes not only need to be present but also be ready to send/receive a value to be selected.

Since `LEFT` appears before `UP` as a source, and before `DOWN` as a destination, `ANY` will always be `LEFT` in this case.

To make this program "implementation-independent", simply replace those two `ANY`s with `LEFT`s.

The reason that the `ANY`s in node 0 are of no concern is that node 0 only ever has one neighbor to talk to.
> 1 votes

# Answer
# K (oK), 6 bytes

```
1+/-1+

```

Try it online!
> 1 votes

# Answer
# Dodos, 27 bytes

```
	dot dip +
+

	dot dab dot

```

Try it online!

Explanation:

The `main` function (top line, implicitly named `main`) is called at the start of the program. It contains this command:

```
dot dip +

```

`+` is called on the tuple given as separate command-line arguments. This is `+`:

```

dot dab dot
```

The empty command simply returns the argument as-is. The other command, `dot dab dot`, returns `0`. It has to be able to convert any given tuple to zero, so here's how this does it, right-to-left:

First of all, `dot` returns a 1-element tuple that contains the sum of the input's elements. The actual sum doesn't matter here, what matters is that `dot` will always return a 1-element tuple, so that we can use `dab` on it to remove its first (i.e. only) element, since there's no built-in to empty a tuple. The sum of an empty tuple is `0`, so we just `dot` this empty tuple to return the singleton `0`.

After this process, the two results of the `+` function (the input and `0`) are implicitly concatenated. We now return to `main`.

The `dip` command will decrement each positive number by 1, and convert each 0 to 1, in `+`'s result. This will decrement each number of available outlets, and also increment the final 0, so we don't miss a free outlet.

Finally, the tuple will be `dot`ted again, so we're computing the number of available outlets over all of the power strips, minus the number of power strips, plus one (no strip occupies an outlet of the last strip).
> 0 votes

# Answer
# Common Lisp, 40 bytes

```
(lambda(x)(1+(-(reduce'+ x)(length x))))

```

Try it online!
> 0 votes

---
Tags: code-golf, number, arithmetic
---