title: Output the Juggler sequence

text:
# Question
Title: Output the Juggler sequence
The Juggler sequence is described as follows. Beginning with an input \\$a\_1\\$, the next term is defined by the recurrence relation

$$a\_{k+1} = \begin{cases} \left\lfloor a\_k ^ \frac 1 2 \right\rfloor,\text{ if } a\_k \text{ is even} \\ \left\lfloor a\_k ^ \frac 3 2 \right\rfloor,\text{ if } a\_k \text{ is odd} \\ \end{cases}$$

The sequence terminates when it reaches 1, as all subsequent terms would then be 1.

## Task

Given an input \\$n\\$ greater than or equal to 2, write a program/function/generator/etc. that outputs/returns the respective juggler sequence. The output can be in any reasonable form. You may not use a built-in that computes the juggler sequence, or any built-in that directly yields the result. You may assume that the sequence terminates in \\$1\\$.

## Test Cases

```
Input: output
2: 2, 1
3: 3, 5, 11, 36, 6, 2, 1
4: 4, 2, 1
5: 5, 11, 36, 6, 2, 1

```

This is a code golf. Shortest code in bytes wins.

# Answer
> 8 votes
# Jelly, ~~12~~ ~~11~~ 10 bytes

```
*BṪ×½Ḟµ’Ð¿

```

*Thanks to @Sp3000 for golfing off 1 byte!*

Try it online!

### How it works

```
*BṪ×½Ḟµ’Ð¿    Main link. Input: n

*B            Elevate n to all of its digits in base 2.
  Ṫ           Extract the last power.
              This yields n ** (n % 2).
   ×½         Multiply with sqrt(n). This yields n ** (n % 2 + 0.5).
     Ḟ        Floor.

      µ       Push the previous chain on the stack and begin a new, monadic chain.
        Ð¿    Repeat the previous chain while...
       ’        n - 1 is non-zero.
              Collect all intermediate results in an array.

```

# Answer
> 10 votes
# Julia, ~~64~~ ~~50~~ ~~48~~ ~~42~~ ~~32~~ 30 bytes

```
g(x)=[x;x<3||g(x^(x%2+.5)÷1)]

```

This is a recursive function that accepts an integer and returns a float array.

We build an array by concatenating the input with the next term of the sequence, computed as *x* to the power of its parity plus 1/2. This gives us either *x*1/2 or *x*1+1/2 = *x*3/2. Integer division by 1 gets the floor. When the condition *x* \< 3 is true, the final element will be a Boolean rather than a numeric value, but since the array is not of type `Any`, this is cast to have the same type as the rest of the array.

Saved 14 bytes thanks to Dennis!

# Answer
> 8 votes
# JavaScript (ES7), ~~45~~ 33 bytes

```
f=n=>n<2?n:n+","+f(n**(.5+n%2)|0)

```

## Explanation

Recursive approach. Returns a comma-separated string of numbers.

```
f=n=>
  n<2?n:          // stop when n == 1
  n               // return n at the start of the list
  +","+f(         // add the rest of the sequence to the list
    n**(.5+n%2)|0 // juggler algorithm
  )

```

## Test

`**` not used in test for browser compatibility.

```
f=n=>n<2?n:n+","+f(Math.pow(n,.5+n%2)|0)
```

```
<input type="number" oninput="result.textContent=f(+this.value)" />
<pre id="result"></pre>
```

# Answer
> 7 votes
# Mathematica, ~~40~~ 39 bytes

*Thanks to Martin Büttner for saving 1 byte.*

```
NestWhileList[⌊#^.5#^#~Mod~2⌋&,#,#>1&]&

```

**Test case**

```
%[5]
(* {5,11,36,6,2,1} *)

```

# Answer
> 6 votes
# MATL, ~~13~~ 12 bytes

```
`tt2\.5+^ktq

```

Try it online!

Explanation

```
`     % do...while loop
tt   % duplicate top of stack twice, takes implicit input on first iteration
2\    % take a_k mod 2
.5+^  % adds 0.5, to give 1.5 if odd, 0.5 if even, and takes a_k^(0.5 or 1.5)
kt    % Rounds down, and duplicates
q     % Decrement by 1 and use for termination condition---if it is 0, loop will finish

```

Thanks Luis for saving a byte!

# Answer
> 6 votes
# Pyth, ~~14~~ 12 bytes

```
.us@*B@N2NNQ

```

Demonstration

We start with a cumulative reduce, `.u`, which in this case starts at the input and applies a function until the result repeats, at which point it outputs all of the intermediate results.

The function takes the previous value as `N`. It starts by taking its square root with `@N2`. Next, it bifurcates that value on multiplication by `N` with `*B ... N`. This creates the list `[N ** .5, (N ** .5) * N]`, the unfloored results for the even and odd cases. Next, the appropriate unfloored result is selected by indexing into the list with `@ ... N`. Since Pyth has modular indexing, no out-of-bounds errors are thrown. Finally, the result is floored with `s`.

# Answer
> 5 votes
## Minkolang 0.15, 25 bytes

```
ndN(d$7;r2%2*1+;YdNd1=,).

```

Try it here!

### Explanation

```
n                            Take number from input => n
 dN                          Duplicate and output as number
   (                         Open while loop
    d                        Duplicate top of stack => n, n
     $7                      Push 0.5
       ;                     Pop b,a and push a**b => n, sqrt(n)
        r                    Reverse stack => sqrt(n), n
         2%                  Modulo by 2
           2*                Multiply by 2
             1+              Add 1 => sqrt(n), [1 if even, 3 if odd]
               ;             Pop b,a and push a**b => sqrt(n)**{1,3}
                Y            Floor top of stack
                 dN          Duplicate and output as number
                   d1=,      Duplicate and => 0 if 1, 1 otherwise
                       ).    Pop top of stack and end while loop if 0, then stop.

```

# Answer
> 3 votes
# APL, ~~28~~ ~~24~~ 16 bytes

```
{⌊⍵*.5+2|⎕←⍵}⍣=⎕

```

This is a program that accepts an integer and prints the successive outputs on separate lines.

Explanation:

```
{           }⍣=⎕   ⍝ Apply the function until the result is the input
 ⌊⍵*.5+2|⎕←⍵       ⍝ Print the input, compute floor(input^(input % 2 + 0.5))

```

Try it online

Saved 8 bytes thanks to Dennis!

# Answer
> 3 votes
## TSQL, 89 bytes

Input goes in `@N`:

```
DECLARE @N INT = 5;

```

Code:

```
WITH N AS(SELECT @N N UNION ALL SELECT POWER(N,N%2+.5) N FROM N WHERE N>1)SELECT * FROM N

```

# Answer
> 2 votes
## Java 7, ~~83~~ 71 bytes

```
void g(int a){System.out.println(a);if(a>1)g((int)Math.pow(a,a%2+.5));}

```

I originally used a typical `for` loop, but I had to jump through hoops to get it working right. After ~~stealing~~ borrowing user81655's idea to recurse instead, I got it down twelve bytes.

# Answer
> 2 votes
# Python 3, ~~57~~, ~~45~~, ~~43~~, 41 bytes

Better Solution with suggestion from @mathmandan

```
def a(n):print(n);n<2or a(n**(.5+n%2)//1)

```

This method will print each number on a new line

Previous Solution: Cut down to 43 bytes after xnor's recommendation

```
a=lambda n:[n][:n<2]or[n]+a(n**(n%2+.5)//1)

```

You can call the above by doing `a(10)` which returns `[10, 3.0, 5.0, 11.0, 36.0, 6.0, 2.0, 1.0]`

The above will output the values as floats. If you want them as integers, then we can just add an extra 2 bytes for 43 bytes:

```
def a(n):print(n);n<2or a(int(n**(.5+n%2)))

```

# Answer
> 2 votes
# R, ~~54~~  51 bytes

```
z=n=scan();while(n>1){n=n^(.5+n%%2)%/%1;z=c(z,n)};z

```

Saved 3 bytes thanks to plannapus.

# Answer
> 2 votes
# Haskell, 70 bytes

Haskell doesn't have integer `sqrt` built-in, but I think there may be something shorter than `floor.sqrt.fromInteger`.

```
s=floor.sqrt.fromInteger
f n|odd n=s$n^3|1<2=s n
g 1=[1]
g n=n:g(f n)

```

# Answer
> 2 votes
# Oracle SQL 11.2, 128 bytes

```
WITH v(i)AS(SELECT :1 FROM DUAL UNION ALL SELECT FLOOR(DECODE(MOD(i,2),0,SQRT(i),POWER(i,1.5)))FROM v WHERE i>1)SELECT i FROM v;

```

Un-golfed

```
WITH v(i) AS
(
  SELECT :1 FROM DUAL
  UNION ALL
--  SELECT FLOOR(POWER(i,0.5+MOD(i,2))) FROM v WHERE i>1
  SELECT FLOOR(DECODE(MOD(i,2),0,SQRT(i),POWER(i,1.5))) FROM v WHERE i>1
)
SELECT * FROM v;

```

Adding MOD(i,2) to .5 is shorter but there is a bug with POWER(2,.5) :

```
SELECT POWER(4,.5), FLOOR(POWER(4,.5)), TO_CHAR(POWER(4,.5)) FROM DUAL

```

gives

```
2   1   1,99999999999999999999999999999999999999

```

# Answer
> 2 votes
# CJam, 18 bytes

```
ri{__2%.5+#i_(}g]p

```

**Test it here**

Similar to David's MATL answer.

# Answer
> 2 votes
## TI-Basic, 30 Bytes

```
Prompt A
Repeat A=1
Disp A
int(A^(remainder(A,2)+.5->A
End
1

```

# Answer
> 2 votes
# Vyxal, 10 bytes

```
λ∷d›½e⌊;İJ

```

Try it Online!

# Answer
> 1 votes
# JavaScript ES6, ~~109~~ 102 bytes

```
s=>(f=n=>n==1?n:n%2?Math.pow(n,3/2)|0:Math.sqrt(n)|0,a=[s],eval("while(f(s)-1)a.push(s=f(s))"),a+",1")

```

I *know* this can be golfed. Returns a string of comma-separated numbers.

# Answer
> 1 votes
# C++, 122 bytes

```
#include <iostream>
void f(int n){int i;while(n^1){std::cout<<n<<',';for(i=n*n;i*i>(n%2?n*n*n:n);i--);n=i;}std::cout<<1;}

```

# Answer
> 1 votes
# C, ~~64~~ ~~63~~ 61 bytes

```
t;q(n){for(;!t;n=pow(n,.5+n%2))printf("%d%c ",n,n^1?44:t++);}

```

# Answer
> 1 votes
# Retina, 144 bytes

Input and output are in unary.

The 2nd-to-last line contains a space, and the two middle lines and the last line are empty.

```
{`(\b|)11+$
$&¶$&
m-1=`^(?=^(11)*(1?)).*$
$&,$2
(1+),1$
$1;,
1(?=1*;)
$%_
1+;
$%_
;|,

m-1=`^
1:
+`(1+):(11\1)
1 $2:
1+:$|:1+

-1=`(1+\b)
$#1

```

**Try it online**

### Explanation

```
{`(\b|)11+$                 # Loop, Duplicate last line
$&¶$&
m-1=`^(?=^(11)*(1?)).*$     # Append ,n%2 to that line (number modulo 2)
$&,$2
(1+),1$                     # Cube that number if odd
$1;,
1(?=1*;)
$%_
1+;
$%_
;|,                         # (Last stage of cubing number)

m-1=`^                      # Integer square root of that number,
1:                          #   borrowed and modified from another user's answer
+`(1+):(11\1)
1 $2:
1+:$|:1+

-1=`(1+\b)
$#1

```

Integer square root in Retina, by Digital Trauma

# Answer
> 1 votes
# Husk, ~~14~~ 12 bytes

```
U¡o⌊?^1.5√%2

```

Try it online!

## Explanation

```
U¡ȯ⌊?^1.5√%2
 ¡             iterate over the input infinitely, creating a list
  ȯ            with the following three functions:
               take the previous result
          %2   modulo 2
    ?^1.5      if truthy, raise to 3/2th power
         √     else take square root
   ⌊           floor the result
U              cut the list at fixed point

```

# Answer
> 1 votes
# 05AB1E, ~~12~~ 9 bytes

```
Δ=DÉ·>;mï

```

-3 bytes thanks to *@ovs*.

Outputs each result on a separate line.

Try it online or verify some more test cases.

**Explanation:**

```
Δ          # Loop until the result no longer changes:
 =         #  Print the current value with trailing newline (without popping)
           #  (which will be the implicit input-integer in the first iteration)
  D        #  Duplicate the value
   É       #  Pop the copy, and check if it's odd (1 if odd; 0 if even)
    ·      #  Double that
     >     #  Increase it by 1
      ;    #  Halve it
       m   #  Take the current value to the power this 1/2 or 3/2
        ï  #  And then cast it to an integer to floor it

```

# Answer
> 1 votes
# Jelly, 7 bytes

```
*Ḃ×½ḞµƬ

```

Try it online!

Basically Dennis' method, but updated to use the modern version of Jelly. I initially had 9 bytes, but switching to the `×½` method saved 2 bytes.

## How it works

```
*Ḃ×½ḞµƬ - Main link. Takes n on the left
     µ  - Group the previous links into a monad f(n):
 Ḃ      -   Bit; n % 2
*       -   n ** (n % 2)
   ½    -   n ** (1 / 2)
  ×     -   n ** (n % 2 + 1 / 2)
    Ḟ   -   Floor
      Ƭ - Repeatedly apply f(n), yielding [n, f(n), f(f(n)), ..., 1]

```

# Answer
> 1 votes
# Factor, 52 bytes

```
[ [ 3 dupn . odd? 3/2 .5 ? ^ 1 /i dup 1 > ] loop . ]

```

Try it online!

# Answer
> 1 votes
# Lua, 49 bytes

```
b=...repeat a=b print(a)b=b^(.5+b%2)//1until a==b

```

Try it online!

# Answer
> 1 votes
# Vyxal, 55 bitsv2, 6.875 bytes

```
∷.+e⌊)↔

```

Try it Online!

## Explained

```
∷.+e⌊)↔
     )↔  # Generate until fixed point, starting with the input:
∷.+      #   Add the bit parity of the argument to 0.5 (0.5 if even, 1.5 if odd)
   e     #   And raise the argument to that number
    ⌊    #   Floor it.

```

Created with the help of Luminespire.

# Answer
> 1 votes
# Nibbles, 7.5 bytes (15 nibbles)

```
`.$^^$^3%$~-2

```

Attempt This Online!

```
`.              # iterate while unique
  $             # starting with input:
        %$~     #  result-so-far modulo-2
      ^3        #  3 to the power of that (so: 3 or 1)
    ^$          #  result-so-far to the power of that
   ^       -2   #  floor square-root

```

# Answer
> 0 votes
# TI BASIC, 43 bytes

I'm pulling a Thomas Kwa and answering this one on my mobile.

```
Input N
Repeat N=1
Disp N
remainder(N,2->B
If not(B:int(sqrt(N->N
If B:int(N^1.5->N
End
1

```

Replace `sqrt` with the actual symbol on your calculator. Displays a linefeed separated list of numbers, which is a reasonable format.

# Answer
> 0 votes
# JavaScript ES6, 76 bytes

Is a generator named `j`. To use, set `a = j(<your value>);`. To see the next value in the sequence, enter `a.next().value`.

```
function*j(N){for(yield N;N-1;)yield N=(N%2?Math.pow(N,3/2):Math.sqrt(N))|0}

```

Ungolfed:

```
function* juggler(N){
    yield N;
    while(N!=1){
        N = Math.floor(N % 2 ? Math.pow(N,3/2) : Math.sqrt(N));
        yield N;
    }
}

```

# Answer
> 0 votes
# C#, 62 bytes

```
string f(int n)=>n+(n<2?"":","+f((int)Math.Pow(n,.5+n%2)));

```

Inspired by @user81655 and @Alex A., I used recursion.

# Answer
> 0 votes
# dc, ~~22~~ 21 bytes

```
[pd2%2*1+^vd1<F]dsFxn

```

Explained:

```
[                # Begin macro definition
 p               # Peek at top of stack (print without popping, followed by newline)
 d               # Duplicate top of stack
 2%              # Mod 2: If even, 0; if odd, 1
 2*1+            # If even: 0*2+1==1; if odd: 1*2+1==3
 ^v              # Raise, then square root: equivalent to `^(0.5)' or `^(1.5)'
 d1<F            # If result is not 1, run macro again
]dsFx            # Duplicate macro, store as `F', execute
n                # Print the final "1"

```

There's a bug: When the input is `1`, the output consists of two `1`s.

# Answer
> 0 votes
# Perl 5, 34 bytes

33, plus 1 for `-pE` instead of `-e`

```
say;($_=int$_**($_%2+.5))-1&&redo

```

## Explanation

First, `-p` sets the variable `$_` equal to the input from stdin. Then we start a block of code:

> 1. `say` prints `$_`.
> 2. `$_=int$_**($_%2+.5)` sets `$_` equal to the integer part of {`$_` to the power of {{`$_` modulo 2} + 0.5}}, due to the magic of order of operations (operator precedence). This assignment returns the new value of `$_`, and
> 3. `(...)-1&&redo` tests that returned value, minus 1. If the difference is 0, do nothing; otherwise, redo this block.

Finally, `-p` prints `$_`.

## Of equal length

Also uses `-p`.

```
say()-($_=int$_**($_%2+.5))&&redo

```

This: prints `$_`; assigns as above; tests whether the return value of `say` (which is 1), minus the new value of `$_`, is 0, and redoes the block if so; then prints `$_` at the end.

# Answer
> 0 votes
# F# 77 bytes

Doesn't terminate at 1, but keeps going.

```
let j=Seq.unfold(fun x->Some(x,floor(match x%2. with 0.->x**0.5|1.->x**1.5)))

```

Usage:

```
j 3.;;
> val it : seq<float> = seq [3.0; 5.0; 11.0; 36.0; ...]

```

Version that actually terminates at 1, 100 bytes

```
let j=Seq.unfold(fun x->if x=1. then None else Some(x,floor(match x%2. with 0.->x**0.5|1.->x**1.5)))

```

Ungolfed

```
let juggle input =
    let next x =
        floor
            (match x % 2. with
                | 0. -> x ** 0.5
                | 1. -> x ** 1.5
                | _ -> failwith "this should never happen") // addressing a compiler warning
    Seq.unfold (fun x -> if x = 1. then None else Some(x, next x)) input

```

# Answer
> 0 votes
# Raku, 30 bytes

```
{$_,{floor $_**(.5+$_%2)}...1}

```

Try it online!

This anonymous function returns the sequence of Juggler numbers. `{ floor $_ ** (.5 + $_ % 2) }` evaluates each successive term of the sequence, the `floor` of the previous number `$_` raised to a power which is one-half plus the that number modulo 2.

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


title: Tips for golfing in Pascal

text:
# Question
Title: Tips for golfing in Pascal
What general tips do you have for golfing code in Pascal?

I know this is a tricky language very few people use this but I would like to know any tips from the professionals out there :)

I'm looking for tips that can reduce code size (every byte counts!) with special functions or even crazy combinations

Please post each tip as a separate answer, and avoid tips not specific to Pascal (e.g. remove whitespace, etc.)

# Answer
> 7 votes
## Avoid `Integer`

```
VAR var1: Integer; (* Signed, 16 bits in TP7, 32 bits in FPC, It costs 7 bytes. *)
    var2: Word;    (* Unsigned 16 bit, works in most cases. *)
    var3: Int64;   (* Signed 64 bits, Only available in FPC. *)
    var4: 0..9;    (* TP7: same as ShortInt (-128..127), FPC: same as Byte (0..255) *)

```

## Use `^J` for line break

```
WriteLn('abc');Write('def');
Write('abc',chr(10),'def');
Write('abc'#10'def');
Write('abc'^J'def');        (* Both in TP7 and FPC *)

```

`^J` is two bytes `^` followed by `J`, not single byte for `Ctrl-J`.

# Answer
> 3 votes
### Numbers before keywords

```
for i:=69 to 420 do writeln(i);
for i:=69to 420do writeln(i);

```

save you 2 byte on for loop

# Answer
> 3 votes
### Variable declaration of same type

```
var i:word;j:word;
var i,j:word;

```

Furthermore, all variables can be declared in one `var` block:

```
var i,j:word;a,b,c:string;x,y:char;

```

# Answer
> 3 votes
## use (already existing) parentheses as token separators

A loop determining the length of `input` without processing it

```
while not EOF do begin get(input);i:=i+1 end

```

can be rearranged into

```
while not EOF do begin i:=i+1;get(input)end

```

Similarly in expressions

```
if ord(c)=32 then

```

is the same as

```
if 32=ord(c)then

```

Since this only saves you one character, it does not make sense to introduce *extra* parentheses.

# Answer
> 3 votes
## use `string` as an `array[1‥n] of 0‥ord(maxChar)`

In Pascal `string` literals may contain arbitrary values from the domain of `char`. Even `chr(0)` is permitted. The only *illegal* component is the value denoting a newline (in ASCII `chr(10)` \[“line feed”\] and/or `chr(13)` \[“carriage return”\]). In other words, multi-line `string` literals are not allowed. Furthermore the string delimiting character `'` (ASCII `chr(39)`) needs to be escaped (conventionally `''`). Example:

```
program stringArrayDemo(output);
begin
    writeLn(ord(('€Bÿ')[3]))
end.

```

Since it’s not properly displayed, the above string literal consists of the following four characters (ordinal value in hexadecimal base):

```
80 42 FF 12

```

Therefore the above `program` will print `255` as it’s the third character’s ordinal value. Obviously in your challenge at hand the constant index `3` will be some *variable* expression and the `string` literal will have different values.

Since the `maxChar` value introduced in ISO standard 10206 “Extended Pascal” documents an implementation characteristic, it is imperative that your solution mentions the processor used. The above `program` will work adequately if compiled with the GNU Pascal Compiler (GPC) or the Free Pascal Compiler (FPC).

# Answer
> 2 votes
## prefer `repeat … until …` loops over `while … do begin … end` loops

Consideration for *guaranteed* iteration count ≥ 1: If the loop body of a `while` loop contains *multiple* statements, i. e. *is surrounded* by a proper `begin … end`, you may consider turning it into a `repeat … until` loop where the `repeat … until` by itself constitutes a `begin … end` frame.

```
while condition do begin statement;statement end

```

becomes

```
repeat statement;statement until not condition

```

Since a `repeat` loop’s body is executed *at least* once, this works fine if it’s *guaranteed* that the `while`’s loop body would be executed at least once, too. If `condition` can legitimately cause *zero* iterations, this tip does not make sense.

# Answer
> 2 votes
### Iterating over the alphabet (or other contiguous ASCII range)

Iterate over the string:

```
var c:char;begin
for c in'abcdefghijklmnopqrstuvwxyz'do writeln(c);

```

Or, use an ASCII range (uppercase alphabet)

```
var j:word;begin
for j:=65to 90do writeln(chr(j));

```

**BUT! Here's the most compact approach**, for 50 bytes:

```
var j:char;begin for j:=#65to#90do writeln(j)end.

```

# Answer
> 1 votes
## Use the short form of `if` and `for`

If your `if` condition/ `for` loop only does one statement, omit `begin` and `end`.

`if <boolean> then begin <statement>;end;`

`if <boolean> then <statement>;`

`for <condition> do begin <statement>;end;`

`for <condition> do <statement>;`

You can also string them together, e.g.

`for <condition> do if <boolean> then <statement>;`

# Answer
> 1 votes
### Prefer `upcase` over `lowercase`

That's 3 whole bytes. Handy for case-insensitive string comparisons.

# Answer
> 0 votes
## use `index` for `in` membership test

**Introduction**: All Pascal variants support at least to some extent the `in` membership operator (in mathematical notation ∊). Extended Pascal, ISO standard 10206, introduces the `index` function. It requires two `char` or `string` arguments (any combination thereof).

```
index(sample, pattern)

```

The `index` function returns the index of the first complete occurrence of `pattern` in `sample`. If no such index exists, `0` is returned (an *invalid* index for any `string`).

**Application**: The `index` function can be utilized to abbreviate `set`-membership operations. For example

```
c in['X','Y','Z']       { `c` is a variable possessing the data type `char` }

```

becomes

```
index('XYZ',c)>0

```

**Synergies**: You can combine this with the `string` as `array[1‥n] of 0‥ord(maxChar)` tip. For example

```
index(')/;CGaek•—§³µãåéïñ', chr(241)) > 0

```

performs a test whether `chr(241)` is a Ramanujan prime less than 256. Note, the `string` literal consists of 23 `char` values and are not properly displayed on this site.

**Dialects**: Delphi users want to use `pos`. The Free Pascal Compiler supports `pos`, too.

---
Tags: code-golf, tips
---


title: Inverse trigonometric functions

text:
# Question
Title: Inverse trigonometric functions
There are 3 (commonly used) trigonometric functions `sin` `cos` and `tan` each of these functions has an inverse function

You goal is to write 3 programs or functions (one for each inverse trigonometric function `asin` `acos` `atan`) that take a (real) number a input and return the result of the corresponding inverse trigonometric function

## Examples/Test-cases (rounded to four decimal places)

```
 x         asin(x)        acos(x)   atan(x)

 0         0              1.5708       0
 1         1.5708         0            0.7854
-1        -1.5708         3.1416      -0.7854
 0.2       0.2014         1.3694       0.1974
 0.4       0.4115         1.1593       0.3805
 0.6       0.6435         0.9273       0.5404
-0.5      -0.5236         2.0944      -0.4636
-0.7      -0.7754         2.3462      -0.6107
// you do not need to support these inputs for asin&acos
2      1.5708-1.317i      -1.317i      1.1071
5      1.5708-2.292i      -2.292i      1.3734
10     1.5708-2.993i      -2.993i      1.4711
15     1.5708-3.400i      -3.400i      1.5042
20     1.5708-3.688i      -3.688i      1.5208
100    1.5708-5.298i      -5.298i      1.5608

```

## Rules

* Please add built-in solutions to the community wiki
* You may declare multiple functions in the same program, if you provide a way to choose which of the trigonometric functions is applied to the argument (e.g function names, a second argument)
* It is allowed to return a tuple containing the results of multiple functions
* You may take a second parameter, to distinguish between different functions
* Your solutions for `asin`/`acos` only have to work for arguments between `-1` and `1` (inclusive)
* Your solution only has to be accurate up to three decimal places
* Your score is the sum of the lengths of your program(s)/function(s)

## Optional additional requirements

* Also support inputs that give a complex result
* Do not use the complex logarithm *(see the Sandbox Post for how the complex logarithm might be useful)*

# Answer
> 8 votes
## Built-in solutions

### APL(Dyalog Unicode), 1 bytes SBCS

Try it on APLgolf!

Left argument chooses function:

```
¯1○⍵ ⍝ asin
¯2○⍵ ⍝ acos
¯3○⍵ ⍝ atan

```

### C, 31 Bytes

```
#include<math.h>
asin
acos
atan

```

### C++, 30 Bytes

```
#include<cmath>
asin
acos
atan

```

### Go

#### 28 bytes (reals only)

```
import."math"
Asin
Acos
Atan

```

Attempt This Online!

#### 34 bytes (includes complex numbers)

```
import."math/cmplx"
Asin
Acos
Atan

```

Attempt This Online!

### JavaScript, 29 bytes

```
Math.asin
Math.acos
Math.atan

```

Attempt This Online!

### Pascal, 6 bytes (only arctan)

```
arctan

```

Unfortunately, there is no built-in function to *inverse* the operations of `sin` and `cos`. See the Pascal submission for a full implementation of the task.

### Python, 32 bytes (reals only)

```
from math import*
asin
acos
atan

```

Attempt This Online!

### Python, 33 bytes (includes complex numbers)

```
from cmath import*
asin
acos
atan

```

Attempt This Online!

### Rust, 29 bytes

```
f64::asin
f64::acos
f64::atan

```

### sclin, 14 bytes

```
sin_
cos_
tan_

```

Try it on scline!

### Thunno 2, 2 bytes each

```
Æs # arcsin
Æc # arccos
Æt # arctan

```

Try it online!

### Vyxal, 2 bytes each

```
∆S # Arcsine
∆C # Arccosine
∆T # Arctangent

```

Try it Online!

### PHP, 14 bytes

```
asin
acos
atan

```

Try it online!

### Zsh, 36 bytes

```
zmodload zsh/mathfunc
asin
acos
atan

```

Try it online!

# Answer
> 8 votes
# , 45 bytes

```
\(x,f,y=0:4e8/1e8)y[match(T,(f(y)-x)^2<1e-7)]

```

Attempt This Online! with slightly reduced precision to enable it to run with ATO's reduced memory allowance.

Single function with arguments `x`=input number, `f`=trigonometric function to inverse (one of `sin`, `cos` or `tan`). Just within the 3rd-decimal place precision limit, but precision can be increased by increasing the `e8` & `e-7` in the code to `e9` & `e-8`.

---

# , 67 bytes

```
\(x,f){while((f(F/T)-x)^2>1e-8)T=`if`(T-1,T+F-(F=F+1),F+(F=1));F/T}

```

Attempt This Online!

Generalized "inverse" function, which, with arguments `x`=input number and `f`=any function, will output a non-negative real number (if it exists) corresponding to the inverse of `f` applied to `x`, within a precision of `1e-4` (in other words, the difference between `f(inv(x,f))` and `x` is less than `1e-4`).

# Answer
> 8 votes
# JavaScript (ES7), 94 bytes

Probably not the golfiest way, especially for edge cases.

Returns `[atan(x), acos(x), asin(x)]`.

```
x=>[(p=1.571,g=x=>1/x?x/(h=k=>k+++k+(k>>9?0:k*k*x*x/h(k)))``:p)(x),c=2*g((1-x*x)**.5/++x),p-c]

```

Try it online!

### Formulas

The arctangent is approximated with the continued fractions:

$$\arctan(x)=\dfrac{x}{1+\dfrac{(1x)^2}{3+\dfrac{(2x)^2}{5+\dfrac{(3x)^2}{7+\ddots}}}}$$

We then use:

$$\arccos(-1)=\pi\\\arccos(x)=2\arctan\left(\frac{\sqrt{1-x^2}}{1+x}\right),\\:-1\<x\le1$$

and:

$$\arcsin(x)=\frac{\pi}{2}-\arccos(x)$$

(source: Wikipedia)

# Answer
> 4 votes
## Pascal, ~~162~~ 194 bytes

“Extended Pascal” (ISO standard 10206) defines that `complex` numbers are part of the language. When calling one of these functions, a `real` argument is automatically promoted to a `complex` value (because the formal parameter list says the `function` requires a `complex` number).

```
const i=cmplx(0,1);type r=complex;function s(x:r):r;begin s:=−i*ln(sqrt(1−x*x)+i*x);end;function c(x:r):r;begin c:=−i*ln(sqrt(x*x−1)+x);end;function t(x:r):r;begin t:=i/2*ln((1−i*x)/(1+i*x));end

```

Ungolfed:

```
    const
        i = cmplx(0, 1);

    function arcsin(protected x: complex): complex;
        begin
            arcsin := −i * ln(sqrt(1 − sqr(x)) + i * x);
        end;

    function arccos(protected x: complex): complex;
        begin
            arccos := −i * ln(sqrt(sqr(x) − 1) + x);
        end;

    function arctan(protected x: complex): complex;
        begin
            arctan := i / 2 * ln((1 − i * x) / (1 + i * x));
        end;

```

Arc tangent is actually already part of the language. Both in ISO standard 7185 (“Standard Pascal”) and ISO standard 10206 (“Extended Pascal”) the built-in function `arctan` is available. Since `complex` numbers are defined by EP, only the latter accepts and can return `complex` values.

# Answer
> 3 votes
# Perl 5, 172 bytes

```
sub asin{n(@_,\&CORE::sin)}
sub acos{n(@_,\&CORE::cos)}
sub atan{n(@_,sub{sin(@_)/cos(pop)})}
sub n{$f=pop;$x=1;$x+=(&$f($x)-$_[0])/((&$f($x-1e-6)-&$f($x))*1e6)for 1..9;$x}

```

Try it online!

Uses Perl's builtin trig functions `sin` and `cos`. Since asin, acos and atan aren't builtin, they're rather found in the core lib Math::Trig, but here they're instead written in a Newton's method-ish solver in `sub n`.

**Or 259 bytes:**

```
sub si{my$x=pop;abs$x<1e-8?$x:2*si($x/2)*co($x/2)}
sub co{my$x=pop;abs$x<1e-8?1:co($x/2)**2-si($x/2)**2}
sub ta{&si/&co}
sub asi{n(@_,'si')}
sub aco{n(@_,'co')}
sub ata{n(@_,'ta')}
sub n{$f=pop;$x=1;$x+=(&$f($x)-$_[0])/((&$f($x-1e-6)-&$f($x))*1e6)for 1..9;$x}

```

Try it online!

...which replaces Perl's `sin` and `cos` with `si` and `co` that uses the property that sin(x) = x and cos(x) = 1 for small x and the formulas for half angles.

# Answer
> 2 votes
# Charcoal, ~~132~~ 125 bytes

```
ＮθＮη⊞υ¹⊞υ∧›⁰ηθ≔⁰ζ≔²εＦ⁵⁰«≔₂⊕Ｘε²δ≔¹ιＦχ«≔⊘⁺ιδι≔₂×ιδδ»≔∨⎇⊕η⁼›⁰§υη⎇η›θ§υ⁰›§υ¹θ›⁰§υ¹±¹δＵＭυ⁺κ×××δε§υ¬λ∨λ±¹≧⁺×∨η¹×δ∕ειζ≧×₂⊕×εεθ≦⊘ε»Ｉζ

```

Try it online! Link is to verbose version of code. Takes the function as the second argument where `-1=atan`, `0=asin` and `1=acos`. Explanation: Uses CORDIC to calculate the inverse functions. Edit: Switched to single-angle CORDIC for `asin` and `acos` to save 7 bytes.

```
Ｎθ

```

Input the real value.

```
Ｎη

```

Input the function code.

```
⊞υ¹

```

Start with `z[0]=1`.

```
⊞υ∧›⁰ηθ

```

Start with `z[1]=0`, except for `atan`, where the input is used.

```
≔⁰ζ

```

Start with a resulting angle of `0`.

```
≔²ε

```

Start with `2` as the first power of `0.5`. This is needed for `acos` to work with negative inputs, but doesn't affect `asin` or `atan`.

```
Ｆ⁵⁰«

```

Loop `50` times, as unfortunately `10` isn't accurate enough.

```
≔₂⊕Ｘε²δ≔¹ιＦχ«≔⊘⁺ιδι≔₂×ιδδ»

```

Start calculating the `atan` of the power of `0.5`. (Yes, I could do the `atan` separately, but that would duplicate code, increasing my byte count.)

```
≔∨⎇⊕η⁼›⁰§υη⎇η›θ§υ⁰›§υ¹θ›⁰§υ¹±¹δ

```

Determine whether we are increasing or decreasing the angle.

```
ＵＭυ⁺κ×××δε§υ¬λ∨λ±¹

```

Rotate `z` by the `atan` of the power of `0.5`.

```
≧⁺×∨η¹×δ∕ειζ

```

Update the angle.

```
≧×₂⊕×εεθ

```

Compensate for rotation's scaling factor (no effect for `atan`). Note that in a real FPGA you would approximate the square root but that doesn't help me here.

```
≦⊘ε

```

Get the next power of `0.5`.

```
»Ｉζ

```

Output the final angle.

---
Tags: code-golf, trigonometry
---


title: Remove leading and trailing zeroes

text:
# Question
Title: Remove leading and trailing zeroes
Given a non-empty list/array containing only non-negative integers like this:

```
[0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0]

```

Output the list with trailing and leading zeroes removed.

The output for this would be:

```
[8, 1, 4, 3, 5, 6, 4, 1, 2]

```

Some other test cases:

```
[0, 4, 1, 2, 0, 1, 2, 4, 0] > [4, 1, 2, 0, 1, 2, 4]
[0, 0, 0, 0, 0, 0] > nothing
[3, 4, 5, 0, 0] > [3, 4, 5]
[6] > [6]

```

Shortest code wins

# Answer
> 24 votes
# Jelly, 2 bytes

Code:

```
t0

```

Explanation:

```
t   # Trim off...
 0  #  zero at both sides

```

Try it online!

# Answer
> 12 votes
# JavaScript (ES6) 43

```
a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a))

```

**Less golfed**

```
a=>{
  f=a=>a.reverse().filter(x=>a|=x) // reverse and remove leading 0
  // leverage js cast rules: operator | cast operands to integer
  // an array casted to integer is 0 unless the array is made of
  // a single integer value (that is ok for me in this case)
  return f(f(a)) // apply 2 times
}

```

**Test**

```
F=a=>(f=a=>a.reverse().filter(x=>a|=x))(f(a))

function test(){
  var l=(I.value.match(/\d+/g)||[]).map(x=>+x)
  O.textContent=F(l)
}

test()
```

```
#I { width:90%}
```

```
<input id=I oninput='test()' value='0 0 1 3 7 11 0 8 23 0 0 0'>
<pre id=O></pre>
```

# Answer
> 6 votes
# Retina, 12 bytes

```
^0 ?

)` 0$

```

The trailing linefeed is significant.

Thanks to @Martin Büttner and @FryAmTheEggman for saving a few bytes.

Try it online

# Answer
> 6 votes
# CJam, 13 bytes

```
l~{_{}#>W%}2*

```

With the array inputted.

Longer version:

```
l~             Puts input on the stack and parse as array
  {       }    Code block
   _           Duplicate the first thing on the stack
    {}#        Finds the index of the first non-0 value in the array, puts it on the stack
       >       Slices the array from that index
        W%     Reverses the array
           2*  Does the code block twice in total

```

# Answer
> 6 votes
# Haskell, 29 bytes

```
t=f.f;f=reverse.dropWhile(<1)

```

# Answer
> 5 votes
## Pyth, 4 bytes

```
.sQ0

```

Demo:

```
llama@llama:~$ pyth -c .sQ0
[0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 5, 0, 0, 0, 0]
[1, 2, 0, 3, 4, 0, 0, 5]

```

From Pyth's `rev-doc.txt`:

```
.s <seq> <any>
    Strip from A maximal prefix and suffix of A consisting of copies of B.

```

# Answer
> 5 votes
# 05AB1E, 4 bytes

Code:

```
0Û0Ü

```

Try it online!

Explanation:

```
0Û    # Trim off leading zeroes
  0Ü  # Trim off trailing zeroes

```

Uses CP-1252 encoding.

# Answer
> 5 votes
## Jelly, 10 bytes

```
Uo\U,o\PTị

```

This doesn't use the builtin.

```
Uo\U            Backward running logical OR
    ,           paired with
     o\         Forward running logical OR
       P        Product
        T       All indices of truthy elements
         ị      Index the input at those values.

```

Try it here.

# Answer
> 5 votes
# R, 43 bytes

```
function(x)x[cummax(x)&rev(cummax(rev(x)))]

```

or as read/write STDIN/STDOUT

```
x=scan();cat(x[cummax(x)&rev(cummax(rev(x)))])

```

---

This finds the cumulative maximum from the beginning and the end (reversed) string. The `&` operator converts these two vectors to logical one of the same size as `x`, (zeroes will always converted to `FALSE` and everything else to `TRUE`), this way it makes it possible to subset from `x` according to the met conditions.

# Answer
> 4 votes
# Mathematica ~~34~~ 27 bytes

```
#//.{0,a___}|{a___,0}:>{a}&

```

This repeatedly applies replacement rules until such action fails to provide a new output. 7 bytes saved thanks to Alephalpha.

The first rule deletes a zero at the beginning; the second rule deletes a zero at the end of the array.

# Answer
> 4 votes
## 05AB1E, 4 bytes

```
0Û0Ü

```

Basically trimming leading then trailing zeroes of the input, given as an array.

Try it online !

# Answer
> 3 votes
## Ruby, ~~49~~ 44 bytes

```
->a{eval ?a+'.drop_while{|i|i<1}.reverse'*2}

```

Thanks to manatwork for chopping off 5 bytes with a completely different method!

This just `drop`s the first element of the array `while` it's 0, reverses the array, repeats, and finally reverses the array to return it to the proper order.

# Answer
> 3 votes
# Perl, 19 + 1 = 20 bytes

```
s/^(0 ?)+|( 0)+$//g

```

Requires `-p` flag:

```
$ perl -pE's/^(0 )+|( 0)+$//g' <<< '0 0 0 1 2 3 4 5 6 0 0 0'
1 2 3 4 5 6

```

# Answer
> 3 votes
# MATL, 9 bytes

```
2:"PtYsg)

```

**Try it online!**

### Explanation

```
2:"     % For loop (do the following twice)
  P     %   Flip array. Implicitly asks for input the first time
  t     %   Duplicate
  Ys    %   Cumulative sum
  g     %   Convert to logical index
  )     %   Apply index
        % Implicitly end for
        % Implicitly display stack contents

```

# Answer
> 3 votes
# Perl, 38 bytes

```
$\.=$_}{$\=~s/^(0\n)*|(0\n)*\n$//gs

```

Run with `perl -p`, (3 bytes added for `-p`).

Accepts numbers on STDIN, one per line; emits numbers on STDOUT, one per line, as a well-behaved unix utility should.

Only treats numbers represented exactly by '0' as zeroes; it would be possible to support other representations with a few more bytes in the regex.

Longer version, still to be run with `-p`:

```
    # append entire line to output record separator
    $\.=$_
}{
    # replace leading and trailng zeroes in output record separator
    $\ =~ s/^(0\n)*|(0\n)*\n$//gs
    # output record separator will be implicitly printed

```

Expanded version, showing interactions with -p flag:

```
# implicit while loop added by -p
while (<>) {
    # append line to output record separator
    $\.=$_
}{ # escape the implicit while loop
    # replace leading and traling
    $\=~s/^(0\n)*|(0\n)*\n$//gs
    # print by default prints $_ followed by
    # the output record separator $\ which contains our answer
    ;print # implicit print added by -p
} # implicit closing brace added by -p

```

# Answer
> 3 votes
## JavaScript (ES6), 47 bytes

```
a=>a.join(a="").replace(/(^0+|0+$)/g,a).split(a)

```

Where `a` is the array.

# Answer
> 3 votes
## Elixir, 77 bytes

```
import Enum
z=fn x->x==0 end
reverse(drop_while(reverse(drop_while(l,z)),z))

```

l is the array.

Edit:wah! copy/pasta fail. of course one has to import Enum, which raises the byte count by 12 (or use Enum.function\_name, which will make it even longer).

# Answer
> 3 votes
# Vitsy, 13 bytes

Vitsy is slowly getting better... (I'm coming for you Jelly. ಠ\_ಠ)

```
1mr1m
D)[X1m]
```

This exits with the array on the stack. For readability, the TryItOnline! link that I have provided below the explanation will output a formatted list.

Explanation:

```
1mr1m
1m      Do the second line of code.
  r     Reverse the stack.
   1m   I'ma let you figure this one out. ;)

D)[X1m]
D       Duplicate the top item of the stack.
 )[   ] If the top item of the stack is zero, do the stuff in brackets.
   X    Remove the top item of the stack.
    1m  Execute the second line of code.
```

Note that this will throw a StackOverflowException for unreasonably large inputs.

TryItOnline!

# Answer
> 3 votes
# JavaScript (ES6), 34 bytes

```
a=>a.replace(/^(0 ?)*|( 0)*$/g,'')

```

Input and output are in the form of a space-delimited list, such as `"0 4 1 2 0 1 2 4 0"`.

# Answer
> 3 votes
# R, 39 bytes

```
function(x)x[min(i<-which(x>0)):max(i)]

```

Four bytes shorter than David Arenburg's R answer. This implementation finds the first and last index in the array which is greater than zero, and returns everything in the array between those two indices.

# Answer
> 3 votes
# Python 3, 48 bytes

```
lambda a:map(int,''.join(map(str,a)).strip('0'))

```

# Answer
> 3 votes
# Brachylog, 12 bytes

```
{↔a₁.h>0∧}ⁱ²

```

Try it online!

The predicate fails in the case of "nothing".

```
  a₁.           Take the longest suffix of
 ↔              the input reversed
     h          the first element of which
      >0        is greater than 0
        ∧       (which is not the output).
{        }ⁱ²    Do it again.

```

If "nothing" has to be some actual value, like an empty list, it's only one more byte:

# Brachylog, 13 bytes

```
{↔a₁.h>0∨Ė}ⁱ²

```

Try it online!

If the input can be assumed to contain only single digits, it's quite a bit shorter:

# Brachylog, 6 bytes

```
c↔↔ℕ₁ẹ

```

Try it online!

# Answer
> 2 votes
## Dyalog APL, 15 bytes

```
{⌽⍵↓⍨+/0=+\⍵}⍣2

               ⍣2     Apply this function twice:
{             }       Monadic function:
           +\⍵        Calculate the running sum.
       +/0=           Compare to zero and sum. Number of leading zeroes.
   ⍵↓⍨               Drop the first that many elements from the array.
 ⌽                   Reverse the result.

```

Try it here.

# Answer
> 2 votes
# Vim 16 Keystrokes

```
i<input><esc>?[1-9]<enter>lD0d/<up><enter>

```

The input is to be typed by the user between `i` and `esc`, and does not count as a keystroke. This assumes that there will be at least one leading and one trailing zero. If that is not a valid assumption, we can use this slightly longer version: (18 Keystrokes)

```
i <input> <esc>?[1-9]<enter>lD0d/<up><enter>

```

# Answer
> 2 votes
## ES6, 51 bytes

```
f=a=>a.map(x=>x?t=++i:f<i++||++f,f=i=0)&&a.slice(f,t)

```

`t` is set to the index after the last non-zero value, while `f` is incremented as long as only zeros have been seen so far.

# Answer
> 2 votes
# Perl 6, 23 bytes

```
{.[.grep(?*):k.minmax]}
{.[minmax .grep(?*):k]}

```

### Usage:

```
# replace the built-in trim subroutine
# with this one in the current lexical scope
my &trim = {.[.grep(?*):k.minmax]}

say trim [0, 0, 0, 8, 1, 4, 3, 5, 6, 4, 1, 2, 0, 0, 0, 0];
# (8 1 4 3 5 6 4 1 2)
say trim [0, 4, 1, 2, 0, 1, 2, 4, 0];
# (4 1 2 0 1 2 4)
say trim [0, 0, 0, 0, 0, 0];
# ()
say trim [3, 4, 5, 0, 0];
# (3 4 5)
say trim [6];
# (6)

```

# Answer
> 2 votes
# Retina, 11 bytes

```
+`^0 ?| 0$
<empty>

```

Quite simple. Recursively replaces zeroes at beginning and end of line.

Try it online!

# Answer
> 2 votes
# PHP, ~~56~~ ~~54~~ 52 bytes

Uses Windows-1252 encoding

String based solution

```
<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));

```

Run like this:

```
echo '<?=preg_replace(~ÜÒ×ßÏÖÔƒ×ßÏÖÔÛÜ,"",join($argv,~ß));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo

```

If your terminal is set to UTF-8, this is the same:

```
echo '<?=preg_replace("#-( 0)+|( 0)+$#","",join($argv," "));' | php -- 0 0 123 234 0 500 0 0 2>/dev/null;echo

```

## Tweaks

* Saved 2 bytes by negating strings and dropping string delimiters
* Saved 2 bytes by using short print tag

# Answer
> 2 votes
**Python, 84 characters**

```
def t(A):
 if set(A)<={0}:return[]
 for i in(0,-1):
  while A[i]==0:del A[i]
 return A

```

# Answer
> 2 votes
# Python 2, ~~69~~ 67 bytes

```
def f(a):
 for i in(0,-1):
  while a and a[i]==0:a.pop(i)
 return a

```

# Answer
> 2 votes
## Javascript (ES6) 40 bytes

```
a=>/^(0,)*(.*?)(,0)*$/.exec(a.join())[2]

```

# Answer
> 2 votes
# ///, 20 bytes

```
/[0 /[// 0]/]//[0]//

```

Try it online!

Input as list of integers separated by spaces and surrounded by square brackets (`[0 1 2 3 4 5 0]`).

# Answer
> 2 votes
# Pari/GP, 27 bytes

```
p->Vecrev(polrecip(Pol(p)))

```

When a list is converted to a polynomial, the leading zeros are removed. Then we can take the reciprocal polynomial, and convert it back to a list, and the trailing zeros are removed.

Try it online!

# Answer
> 2 votes
# MATLAB, ~~38~~ 32 bytes

```
@(x)x((cummax(x))&cummax(x,'r'))

```

Anonymous function, saved to default output variable `Ans`.
Tried different ideas but the simplest stayed the shortest. Also I should note that instead of `cummmax` you can use `cumsum` as well.
Unfortunately, doesn't work with Octave, because its implementation of `cummax` and `cumsum` doesn't allow for reversing the direction. For Octave alternative solution below.

**How does it work?**

* `cummax(x)` takes cumulative maximal value, so everything besides leading zeros is greater than 0.
* `cummax(x,'reverse')` does the same but in reversed direction - everything besides trailing zeros is greater than 0.
* `&` is logical conjunction (AND) on arrays. Both numeric arrays (results of `cummax` functions) are transformed into logical arrays in a way that `0` is `false` and anything else is `true`.
* `cummax(x))&cummax(x,'reverse')` gives thus logical array with `true` for values we need to include and `false` for trailing/leading zeros.
* `x(cummax(x))&cummax(x,'reverse'))` performs logical indexing - only values where corresponding logical value is `true` are selected.
* `'reverse'` can be replaced simply with `'r'`

## Octave, 40 bytes

```
@(x)x((cummax(x))&flip(cummax(flip(x))))

```

Try it online!
Basically the same as MATLAB solution, only `cummax(x,'reverse')` is replaced with `flip(cummax(flip(x)))` \- the `x` is flipped, then `cummax` and then result is flipped.

# Answer
> 2 votes
# Factor, 16 bytes

```
[ [ 0 = ] trim ]

```

Try it online!

Factor has a combinator for this. You just have to supply it with a quotation that returns `t` for the element(s) you want to trim.

# Answer
> 2 votes
# Trilangle, 78 bytes

```
<>?@.#<...#)!j.(,2#_|...><.L/(,\@^_\L\.\.#\S.?S>S(.<)).7),..\._v..._|..._>#('0

```

Try it on the online interpreter! Output is separated by newlines.

This is some of the control flow of all time.

```
           <
          > ?
         @ . #
        < . . .
       # ) ! j .
      ( , 2 # _ |
     . . . > < . L
    / ( , \ @ ^ _ \
   L \ . \ . # \ S .
  ? S > S ( . < ) ) .
 7 ) , . . \ . _ v . .
. _ | . . . _ > # ( ' 0

```

This is definitely the most colors I've had to use in this size of grid. Let's break this down:

The first loop -- red, blue, and yellow -- ignores input until it sees something other than `0`. If it reaches EOF before finding a positive value, the green path terminates the program with no output.

The next loop -- orange and yellow-green -- counts how much input there is after the first positive number.

The third loop -- cyan and brown -- removes zeroes from the end of the array and decreases the counter as it goes.

The final loop -- gray and red-violet -- prints out what's left. The purple branch terminates the program once it's exhausted the list.

# Answer
> 1 votes
## PowerShell, 49 bytes

```
($args[0]-join',').trim(',0').trim('0,')-split','

```

Takes input `$args[0]` and `-join`s them together with commas to form a string. We then use the `.Trim()` function called twice to remove first the trailing and then the leading zeros and commas. We then `-split` the string on commas back into an array.

---

*Alternate version, without using conversion*
**PowerShell, 81 bytes**

```
function f{param($a)$a=$a|%{if($_-or$b){$b=1;$_}};$a[$a.Count..0]}
f(f($args[0]))

```

Since PowerShell doesn't have a function to trim arrays, we define a new function `f` that will do half of this for us. The function takes `$a` as input, then loops through each item with a foreach loop `|%{...}`. Each iteration, we check a conditional for `$_ -or $b`. Since non-zero integers are truthy, but `$null` is falsey (and `$b`, being not previously defined, starts as `$null`), this will only evaluate to `$true` once we hit our first non-zero element in the array. We then set `$b=1` and add the current value `$_` onto the pipeline. That will then continue through to the end of the input array, with zeros in the middle and the end getting added onto the output, since we've set `$b` truthy.

We encapsulate and store the results of the loop all back into `$a`. Then, we index `$a` in reverse order (i.e., reversing the array), which is left on the pipeline and thus is the function's return value.

We call the function twice on the `$args[0]` input to the program in order to "trim" from the front, then the front again (which is the back, since we reversed). The order is preserved since we're reversing twice.

This version plays a *little* loose with the rules for an input array of all zeros, but since ignoring STDERR is accepted practice, the program will spit out two (verbose) `Cannot index into a null array` errors to <sub>(PowerShell's equivalent of)</sub> STDERR and then output nothing.

# Answer
> 1 votes
# Mathematica, 33 bytes

```
#/.{Longest[0...],x__,0...}->{x}&

```

# Answer
> 1 votes
# jq, 48 characters

```
. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]

```

Sample run:

(Command line option `-c` only used in this sample for readability to avoid pretty printing the result.)

```
bash-4.3$ jq -c '. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]' <<< '[0, 4, 1, 2, 0, 1, 2, 4, 0]'
[4,1,2,0,1,2,4]

bash-4.3$ jq -c '. as$a|map(.>0)|indices(1>0)|$a[min:(max//-1)+1]' <<< '[0, 0, 0, 0, 0, 0]'
[]

```

On-line test:

# Answer
> 1 votes
# Groovy, 43 characters

```
{x={it.dropWhile{it<1}.reverse()};x(x(it))}

```

Sample run:

```
groovy:000> ({x={it.dropWhile{it<1}.reverse()};x(x(it))})([0, 4, 1, 2, 0, 1, 2, 4, 0])
===> [4, 1, 2, 0, 1, 2, 4]

groovy:000> ({x={it.dropWhile{it<1}.reverse()};x(x(it))})([0, 0, 0, 0, 0, 0])
===> []

```

# Answer
> 1 votes
# sed, 24 bytes

```
#!/bin/sed -f
:
s/ 0$//
s/^0\b \?//
t

```

Input as space-separated words on stdin.

It cost me five bytes (`\b \?`) to deal with the special case of all zeros.

### Test results

```
$ ./71877.sed <<EOF
0 0 0 8 1 4 3 5 6 4 1 2 0 0 0 0
0 4 1 2 0 1 2 4 0
0 0 0 0 0 0
3 4 5 0 0
6
EOF
8 1 4 3 5 6 4 1 2
4 1 2 0 1 2 4

3 4 5
6

```

# Answer
> 1 votes
## C#, 134 bytes

```
using System.Linq;n=>string.Join(" ",n).Trim('0',' ').Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries).Select(s=>int.Parse(s));

```

If I can return a comma separated string of the return values:

## C#, 36 bytes

```
n=>string.Join(",",n).Trim('0',',');

```

# Answer
> 1 votes
# PHP, 61 bytes

```
<?=preg_replace("^[^_]*_(0_)*(.*)(_0)*$","$2",join(_,$argv));

```

regexp using the underscore as delimiter.

# Answer
> 1 votes
# PHP, 41 Bytes

```
<?="[".trim(join(",",$_GET[a]),",0")."]";

```

If the input as array could be write as `?a=0&b=0` and so on it can be reduce to 38 Bytes

```
<?="[".trim(join(",",$_GET),",0")."]";

```

The longer way working with Regex 65 Bytes

```
<?="[".preg_replace("#^(0,)*|(,0)*$#","",join(",",$_GET[a]))."]";

```

# Answer
> 1 votes
# PHP, 30 bytes

```
<?=trim(join(' ',$argv),' 0');

```

Needs to be saved in a file called '0' (or any number of 0s). Works with all test cases (which are \<10 at time of submission) but if a test case with a final non 0 integer of 10 (or any other integer with a 0 units digit) gets added then it will no longer be valid.

use like:

```
php 0 0 4 1 2 0 1 2 4 0

```

Where the first 0 is the file name and the rest is the input

A bunch of answers got added between me loading the challenge and submitting this. I'd delete it but I never finished the account sign up, would a mod do so please?

# Answer
> 1 votes
# 05AB1E, 2 bytes

Built-in version. :)

Try it online!

# Answer
> 1 votes
# Jellyfish, 22 bytes

```
p
\A2
~R
(#
~*
\
/
+
i

```

Try it online!

## Explanation

```
p   print the result of:
\A2 repeat the following twice:
~R  compose reverse with the below
(#  filter the elements of the input by the following function:
~*  compose sign with:
\   map each prefix to:
/    fold by:
+    addition
i   evaluated input

```

# Answer
> 1 votes
# AWK, 24 bytes

```
gsub(/^(0 )*|( *0)*$/,e)

```

Try it online!

Using a convenient input to awk's default field separator (space). No easy way to define an array here.

This substitutes every match to the regex `/^(0 )*|( *0)*$/` for a null string (variable `e`, not defined). Even if there are no trailing zeros, null matches are found before and after the input, so gsub() always returns a positive number, and the input (modified or not) is printed.

# Answer
> 1 votes
# Python 2/3, 48 bytes

```
lambda x:map(int,''.join(map(str,x)).strip('0'))

```

Try it online!

# Answer
> 1 votes
# Japt `-h`, 6 bytes

```
ã fÎfÌ

```

Try it

```
2Æ=Ôf|

```

Try it

# Answer
> 1 votes
# TypeScript's Type System, 69 bytes

```
type T<R>=R extends[...infer K,0]?T<K>:R extends[0,...infer K]?T<K>:R

```

TypeScript Playground

## Explanation

By using `infer`, we can take out portions of the array that don't start or end in 0 recursively:

```
type T<R> =
    R extends [...infer K, 0] ? T<K> : // take out trailing zeros
    R extends [0, ...infer K] ? T<K> : // and leading zeros
    R; // if none are left, return the final array.

```

Since we use `extends`, we don't need to bind the input parameters to a type (e.g. using `T<"input">` simply returns `"input"`)

# Answer
> 1 votes
# JavaScript (Node.js), 58 bytes

Not the best JS answer, but a different approach not using regexp, replace, nor filter.
(Like other answers, we assume that the array input can only contain integers \<= 9)

```
t=>(r=(g=a=>[...""+a.reverse().join``*1])(g(t)))[0]*1?r:[]

```

Try it online!

---

Converts the array into a number to get rid of the leading zeros.
Then we do this a second time on the reversed array to get rid of the leading (previously trailing) zeros, and reverse back again to get the answer array in the correct order.
The case were the array contains only zeros had to be specifically handled (or else it would have resulted in a `[0]` output), and this part has a **cost of 14 bytes** :(

# Answer
> 0 votes
## Racket 73 bytes

```
(λ(l)(define(g k)(if(= 0(car k))(g(cdr k))k))(reverse(g(reverse(g l)))))

```

Ungolfed:

```
(define f
  (λ(l)
    (define (g k)                     ; fn to remove leading zeros;
        (if(= 0 (first k))
           (g (rest k))
           k))
    (reverse (g (reverse (g l))))))

```

Last line removes leading 0s in original and reversed list. List is re-reversed to get original order.

Testing with different combinations:

```
(f '(0 0   2 5 0 6 8 9   0 0))
(f '(0 0 0 2 5 0 6 8 9   0 0 0))

(f '(0 0 0 2 5 0 6 8 9   0 0))
(f '(0 0   2 5 0 6 8 9   0 0 0))

(f '(0 0   2 5 0 6 8 9))
(f '(0 0 0 2 5 0 6 8 9))

(f '(2 5 0 6 8 9   0 0))
(f '(2 5 0 6 8 9   0 0 0))

(f '(2 5 0 6 8 9))

```

Output:

```
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)
'(2 5 0 6 8 9)

```

# Answer
> 0 votes
# PHP, 144 126 chars

It's a bit longer than the other PHP answers because it's array-based.

```
function e($a){foreach($a as$i=>$v){if($v)break;unset($a[$i]);}return array_reverse($a);}print_r(e(e(explode(",",$argv[1]))));

```

Call like this: `php remove0.php 0,4,2,1,0,1,2,4,0`

Example return:

```
Array
(
    [0] => 4
    [1] => 2
    [2] => 1
    [3] => 0
    [4] => 1
    [5] => 2
    [6] => 4
)

```

# Answer
> 0 votes
# Python 3, ~~48~~ ~~55~~ ~~29~~ 26 bytes

```
print(input().strip('0 '))

```

Input and output is taken as space-separated numbers, eg:

```
0 0 0 1 3 1 4 0 1 3 6 4 5 19 3 1 4 0

```

Alternatively, a 29-byte Python 2 solution:

```
print raw_input().strip('0 ')

```

# Answer
> 0 votes
# JavaScript (V8), 54 bytes

```
s=>(g=a=>a.filter(e=>e^k?k=1:k,k=0).reverse(),g(g(s)))

```

Try it online!

# JavaScript (V8), 52 bytes

```
f=(s,q=f(s,s))=>q.filter(e=>e^k?k=1:k,k=0).reverse()

```

Try it online!

# Answer
> 0 votes
# Vyxal, 2 bytes

```
0P

```

Try it Online!

What it says on the box. Stri`P`s `0`s.

# Answer
> 0 votes
# C (gcc), ~~80~~ 78 bytes

-2 bytes thanks to ceilingcat by using `strlen()` and indexing into the string

```
p;f(char*s){for(;*s&&*s<49;s++);for(p=strlen(s);p&&s[p]<49;s[p--]=0);puts(s);}

```

Try it online!

# Answer
> 0 votes
# Julia 1.0, 15 bytes

```
~x=strip(x,'0')

```

Try it online!

Accepts a `String` input.

# Answer
> 0 votes
# BQN, 10 bytes

```
⌈`∘×⊸/∘⌽⍟2

```

Anonymous tacit function; takes a list, returns a list. Try it at BQN online!

### Explanation

```
⌈`∘×⊸/∘⌽⍟2
      ∘⌽    Reverse the list; then,
    ⊸/      select the elements matching the 1s in the following list:
   ×         Get the sign of each number in the list (0 or 1)
⌈`∘          Scan by maximum: preserves leading 0s, but turns all others into 1s
            All but the leading run of zeros is therefore kept
        ⍟2  Do this twice

```

# Answer
> 0 votes
# Python 3, 101 bytes

```
def f(l,n,a=0):
 while l[a]==0:
  del l[a];a+=1;n-=1
 a=n-1
 while l[a]==0:
  del l[a];a-=1
 return l

```

Try it online!

# Answer
> 0 votes
# ReRegex, 21 bytes

```
\[0,?/[/,?0]/]/#input

```

A very simple solution consisting of two regexes, each stripping 0's from the start and end respectively.

Try it online!

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


title: First odd then even indices

text:
# Question
Title: First odd then even indices
Your task is to find out how often you need to "shuffle" a given list with the following operation until you get back the original list.

```
start with a list:
(1 2 3 4 5 6 7 8 9)
split it into the elements at odd and even indices
(1 3 5 7 9) (2 4 6 8)
concatenate these two list
(1 3 5 7 9 2 4 6 8)

```

Input: A list

Output: The number of iterations it takes until you get back the original list

## Examples

```
(1 2 3) -> (1 3 2) -> (1 2 3)               => 2
(1 2 3 4 3 2 1) -> (1 3 3 1 2 4 2) -> ...   => 3
(1 2 3 4 5 6 7 8 9 10) -> ...               => 6
(1 2 3 4 5 6 7 8 9 10 11) -> ...            => 10
"abab" -> "aabb" -> "abab"                  => 2
"Hello, World!" -> "Hlo ol!el,Wrd" -> ...   => 12
(1 0 1 1 0 0 0 1 1 1) -> ...                => 6
(1 0 0 1 1 1 0 0 0 0 1) -> ...              => 10
(1 1 1 1 1 1 1) -> (1 1 1 1 1 1 1)          => 1

```

## Rules

* You can use lists of any type (that supports at least two distinct values)
* You can assume the the list has at least two elements
* The odd/even indices are determined using 1-based indexing
* You have to apply the operation at least once
* If your language has a built-in for finding fixed points consider adding a non-builtin solution as well
* This is the shortest solution (per language) wins

# Answer
> 8 votes
# K (ngn/k), 12 bytes

```
#{x@<2!!#x}\

```

Try it online!

`{ ... }\` Iterate until reaching the first value again (or a fixed point). Collect intermediate values.
`2!!#x` 2 mod range of length *x*. Sequence of alternating 0s and 1s the same length as *x*.
`x@<` Grade up, then index into *x*. Sorts *x* by that sequence.

`#` Length. Counts the number of intermediate results.

# Answer
> 8 votes
# Thunno 2 `L`, 4 bytes

```
µ¥zS

```

Try it online! or verify all test cases

```
µ¥zḞ

```

Try it online! or verify all test cases

```
µ¥^ḥ

```

Try it online! or verify all test cases

---

> Don't worry, the stack languages with single-byte uninterleave operators are going to be even shorter :P

lol

#### Explanation

```
      # Implicit input

µ¥    # Collect while unique:

  z   #  Uninterleave into two pieces
      #   [1,2,3,4,5,6]  ->  [[1,3,5],[2,4,6]]
   S  #  Then flatten the nested list
      #   [[1,3,5],[2,4,6]]  ->  [1,3,5,2,4,6]
   Ḟ  #  Alternative flatten built-in
      #   [[1,3,5],[2,4,6]]  ->  [1,3,5,2,4,6]

  ^   #  Or, uninterleave and push separately
      #   [1,2,3,4,5,6]  ->  [1,3,5] [2,4,6]
   ḥ  #  Then concatenate the two lists
      #   [1,3,5] [2,4,6]  ->  [1,3,5,2,4,6]

      # Finally, the L flag takes the length
      # Implicit output

```

# Answer
> 7 votes
# , ~~26~~ 24 bytes

```
i.~_:0}(\:2|#\)^:(3<@^#)

```

Try it online!

Accepts numeric lists

The maximum number of iterations until we return to the input is bounded by Landau's function \\$g(n)\\$, and it can be shown that:

$$ {\displaystyle g(n)\leq e^{n/e}} $$

For golf reasons, I simply round that to:

$$ {\displaystyle g(n)\leq 3^{n}} $$

and iterate that many times. Note I could trade bytes for efficiency here and iterate until I see the input again, but this approach was shorter.

* `(\:2|#\)` Apply the needed permutation -- equivalent to sorting down by `1 0 1 0...`
* `^:(3<@^#)` Do that \\$3^n\\$ times, saving results
* `_:0}` Convert the first item on the list, which is the input itself, to infinity, so that match will be skipped.
* `i.~` Index of the input within that list.

# Answer
> 6 votes
# Jelly, 6 bytes

```
ŒœẎ$ƬL

```

Try it online!

Don't worry, the stack languages with single-byte uninterleave operators are going to be even shorter :P

```
    Ƭ     Repeat while unique, collecting all results:
Œœ        Split into odd and even-indexed elements,
  Ẏ$      and concatenate.
     L    How many results are there?

```

# Answer
> 5 votes
# 05AB1E, 8 bytes

```
vDÅ≠})Ùg

```

Try it online or verify all test cases (the test suite uses the faster alternative `ι˜` instead of `Å≠`).

**Explanation:**

Although 05AB1E has an unshuffle builtin `Å≠` (even though `ι˜` does the same and is faster..), it unfortunately lacks a "*Repeat until unique*" builtin..

```
v     # Loop the (implicit) input-length amount of times:
 D    #  Duplicate the current list
      #  (which will be the implicit input-list in the first iteration)
  Å≠  #  Unshuffle it
})    # After the loop: wrap all lists on the stack into a list
  Ù   # Uniquify this list of lists
   g  # Pop and push its length
      # (which is output implicitly as result)

  ι   #  Uninterleave it into a pair of lists
   ˜  #  Flatten it to a single list

```

# Answer
> 5 votes
# Google Sheets, 107 bytes

`=let(d,torow(A:A,3),_,lambda(_,a,n,sort(let(b,torow(wrapcols(a,2),3),if(and(b=d),n,_(_,b,1+n))))),_(_,d,1))`

Put the input in cells `A1:A` and the formula in `B1`.

The formula is self-contained. Uses *singularize(wrap())* like the Excel answer but does not depend on named functions or named ranges.

Try it.

# Answer
> 4 votes
# Python, 65 bytes

```
lambda s,j=1:j*((t:=s[:len(s)-1|1])==(t*2**j)[::2**j])or f(s,j+1)

```

Attempt This Online!

## How?

This is based on the observation that in zero-based indexing the reshuffle can be written as n -\> 2n mod N where N is the largest odd number not greater than the length of the input. (If the length is even the last point is a fixed point, so it can be ignored.)

# Answer
> 4 votes
# Nekomata \+ `-n`, 6 bytes

```
ᶦ{ĭ,ᵖ≠

```

Attempt This Online!

Nekomata has a single-byte uninterleave operator, but still can't beat Jelly, because it doesn't have a "repeat while unique" operator.

```
ᶦ{ĭ,ᵖ≠
ᶦ{          Repeat until failure:
  ĭ             Uniterleave
   ,            Join
    ᵖ≠          Check if the result is unequal to the input

```

`-n` counts the number of iterations.

# Answer
> 4 votes
# Vyxal `l`, 31 bitsv2, 3.875 bytes

```
yJ)↲

```

Try it Online!

> the stack languages with single-byte uninterleave operators are going to be even shorter

~ some jelly answer, probably

# Answer
> 4 votes
# Excel, 93 bytes

Define:

`a` as `=$A$1#` (*7 bytes*)

`z` as `=LAMBDA(p,q,LET(x,TOCOL(WRAPROWS(p,2),2,1),y,q+1,IF(SUM(N(x<>a))=0,y,z(x,y))))` (*79 bytes*)

Within the worksheet: `=z(a,0)` (*7 bytes*)

`$A$1#` is a spilled, *vertical* range comprising the list entries.

# Answer
> 4 votes
# , 70 bytes

```
f=\(x,l=0,y=c(x[!0:1],x[!1:0]),`-`=list)`if`(-y%in%l,0,1+f(y,c(l,-y)))

```

Attempt This Online!

# Answer
> 4 votes
# Ruby, 55 bytes

```
->l{k=*l;1.step.find{w=-2;l==k=k.map{k[w+=2]||k[w=1]}}}

```

Try it online!

# Answer
> 4 votes
# , ~~54~~ ~~52~~ 51 bytes

*Edit: -3 bytes thanks to @Dominic van Essen.*

```
\(x,y=x){while(sd((y[]=matrix(y,2,,T))-x))T=T+1;+T}

```

Attempt This Online!

# Answer
> 3 votes
# Charcoal, 27 bytes

```
⊞υθＷ‹№υθ²⊞υ⭆²Φ§υ±¹﹪⁺κν²Ｉ⊖Ｌυ

```

Try it online! Link is to verbose version of code. Only works on strings. Explanation:

```
⊞υθ

```

Push the string to the predefined empty list.

```
Ｗ‹№υθ²

```

Repeat until a second copy of the string is found.

```
⊞υ⭆²Φ§υ±¹﹪⁺κν²

```

Shuffle the most recent string and push it to the list.

```
Ｉ⊖Ｌυ

```

Output the number of shuffles taken.

28 bytes to work on strings or lists:

```
⊞υθＷ‹№υθ²⊞υΣＥ²Φ§υ±¹﹪⁺κν²Ｉ⊖Ｌυ

```

Attempt This Online! Link is to verbose version of code.

# Answer
> 3 votes
# JavaScript (ES6), 64 bytes

Expects a list of positive integers.

```
a=>(g=a=>(g[a]^=i=-2)&&1+g(a.map(_=>a[!a[i+=2]|i%a.length])))(a)

```

Try it online!

### How?

We can apply the shuffle by doing:

```
a.map((_, i) => a[!a[i * 2] | i * 2 % a.length])

```

This code first collects all values at even (0-based) indices. When `a[i * 2]` is not defined anymore, it starts collecting values at odd indices.

For golfing reasons, we rather start with \\$i=-2\\$ and do:

```
a.map(_ => a[!a[i += 2] | i % a.length])

```

We stop as soon as the same array has been encountered twice and return the number of iterations.

# Answer
> 3 votes
# sclin, 45 bytes

```
=$a $a"2/` tpose flat"itr1dp"$a !=`"tk* len1+

```

Try it here! Takes a list.

For testing purposes:

```
[1 2 3 4 5 6 7 8 9 10 11] ;
=$a $a"2/` tpose flat"itr1dp"$a !=`"tk* len1+

```

NOTE: for string-based inputs, use e.g. `["a" "b" "a" "b"]`.

## Explanation

Prettified code:

```
=$a $a.
( 2/` tpose flat ) itr 1dp ( $a !=` ) tk* len 1+

```
* `=$a $a` Input list *a*
* `(...) itr` generate infinite list from successive modifications of *a*...
    + `2/` tpose flat` chunk into pairs, transpose, flatten
* `1dp` drop first item to prevent `tk*` from exiting early
* `( $a !=` ) tk*` take while not equal to *a*
* `len 1+` length + 1

# Answer
> 3 votes
# Arturo, 49 bytes

```
$->a[1x:a while[i:0arrange'x=>[i%2'i+1]x<>a][1+]]

```

Try it!

```
$->a[                         ; a function taking an input a
    1                         ; push 1 -- this is our output (count)
    x:a                       ; assign a to x
    while[                    ; while...
        i:0                   ; assign 0 to i
        arrange'x=>[i%2'i+1]  ; sort x by its indices' parities
        x<>a                  ; x doesn't equal a...
    ]                         ; end while predicate
    [1+]                      ; ...then increment the output
]                             ; end function

```

# Answer
> 1 votes
# Haskell, 77 bytes

```
o(x:s)=x:e s
o _=[]
e=o.drop 1
a!b|a==b=1|0<1=1+a!(o b++e b)
f a=a!(o a++e a)

```

Try it online!

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


title: Stevin's Notation

text:
# Question
Title: Stevin's Notation
Stevin's Notation is a way to represent decimals in a non-fractional way.

> The Flemish mathematician and engineer Simon Stevin is remembered for his study of decimal fractions. Although he was not the first to use decimal fractions (they are found in the work of the tenth-century Islamic mathematician al-Uqlidisi), it was his tract De Thiende (“The tenth”), published in 1585 and translated into English as Disme: The Art of Tenths, or Decimall Arithmetike Teaching (1608),\[3\] that led to their widespread adoption in Europe. Stevin, however, did not use the notation we use today. He drew circles around the exponents of the powers of one tenth: thus he wrote 7.3486 as 7⓪3①4②8③6④.

For example, the decimal number `32.567` can be expressed as `32 + 5/10 + 6/100 + 7/1000`. In Stevin's Notation, circled numbers representing the denominator of the original decimal fraction were inserted after each number.

In lieu of formatting the output via parenthesis or using any unicode characters, we will simply output the associated power of ten number.

Therefore, the decimal number above would be written as `320516273`.

**Task**

When given a decimal input, output a Stevin's Notation integer equivalent.

**Notes**

* For any input containing trailing `0` after the decimal point, the author can choose whether or not to include the zeroes as part of their output notation. This holds true for multiple trailing zeroes as well.
    + This means for the input `1.0500`, either of the following output would be acceptable: `100152` or `1001520304`
* For any input with no decimal point, or any input containing only zeroes after the decimal point, the author may choose to simply output the integer equivalent.
    + This means for the input `123`, either of the following output would be acceptable: `123`, `1230`.
    + This also means for the input `123.0`, any of the following output would be acceptable: `123`, `1230`, `123001`.
* For this challenge, we can assume the input will be positive.

**Test cases:**

| Input | Output |
| --- | --- |
| `123` | `123` or `1230` |
| `123.0` | `123` or `1230` or `123001` |
| `123.00000` | `123` or `1230` or `12300102030405` |
| `123.456` | `1230415263` |
| `123.456000` | `1230415263` or `1230415263040506` |
| `1.000009` | `10010203040596` |
| `0` | `0` or `00` |
| `0.0` | `0` or `00` or `0001` |
| `0.0001` | `0001020314` |
| `123456789.123456789987654321` | `1234567890112233445566778899910811712613514415316217118` |

This is , so shortest code in bytes wins!

# Answer
> 6 votes
# JavaScript (ES6), 64 bytes

Expects a string as input.

```
s=>s.replace(/\.(.*?)0*$/,(_,s)=>s&&s.replace(/()/g,_=>i++,i=0))

```

Try it online!

## How?

We first look for the fractional part in the input string:

```
  .---------> decimal separator
  |  .------> payload: a non-greedy sequence of digits
  |  |   .--> trailing zeros + end of string
  | _|_  |
  |/   \/ \
/\.(.*?)0*$/

```

If the payload is empty, we remove the fractional part entirely.

Otherwise, we replace the fractional part with the payload transformed as follows:

```
s.replace(  // in the payload,
  /()/g,    // replace each gap (beginning and end included)
  _ => i++, // with the counter i (incremented afterwards)
  i = 0     // starting with i = 0
)           //

```

# Answer
> 4 votes
# Retina, 33 bytes

```
/\./&`\.?0+$

/\..+/_`.
$&$:&
\.

```

Try it online! Link includes test cases. Explanation:

```
/\./&`\.?0+$

```

If the input contains a decimal point, trim any trailing zeros and also the decimal point if there are only trailing zeros (in which case the rest of the script will do nothing).

```
/\..+/_`.
$&$:&

```

Number each character starting at the decimal point.

```
\.

```

Remove the decimal point.

# Answer
> 2 votes
# sclin, 46 bytes

```
99N>d"\."<>"len1>"Q";".' &# c><
0swap $N","zip

```

Try it here!

For testing purposes:

```
7.3486 ;
99N>d"\."<>"len1>"Q";".' &# c><
0swap $N","zip

```

## Explanation

Prettified code:

```
99N>d "\."<> ( len 1> ) Q \;.' &# c><
0swap $N \, zip

```
* `99N>d` convert input to decimal representation
    + necessary to get around sclin's default rational representation, and also to remove trailing zeros (unless spec is more lenient)
* `"\."<>` split by decimal point
* `( len 1> ) Q \;.' &#` if length \> 1 (i.e. decimal values exist), then...
    + `0swap` place zero as "decimal"
    + `$N \, zip` enumerate
* `c><` join
    + NOTE: this might be removable if a jagged list is allowed as an output format - e.g. `[123 0 [ 5 1 6 2 ]]`

# Answer
> 2 votes
# Vyxal `d`, 78 bitsv2, 9.75 bytes

```
\.+\./ḣhfJėR

```

Try it Online!

## Explained

```
\.+\./ḣhfJėR
\.+\./        # Append a "." to the input and split on "."s
      ḣh      # that[0], that[1]
        fJ    # flatten(that[1]) and merge with that[0]
          ėR  # Enumerate and reverse each sublist
# d flag deep sums the list

```

Created with the help of Luminespire.

# Answer
> 2 votes
# Perl 5 (`-p`), 36 bytes

```
s/\.(.*?)0*$/$1&&$1=~s,(),$i++,ger/e

```

Works the same as Arnauld's Javascript answer

Try it online!

# Answer
> 2 votes
# Charcoal, 23 bytes

```
⭆⪪Ｓ.⎇κ⎇Σι⁺0⭆⮌ＩＩ⮌ι⁺λ⊕μωι

```

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

```
  Ｓ                     Input string
 ⪪                      Split on
   .                    Literal string `.`
⭆                       Map over parts and join
     κ                  Current index
    ⎇                   If decimal part then
        ι               Decimal part
       Σ                Digital sum
      ⎇                 If nonzero then
          0             Literal string `0`
         ⁺              Concatenated with
                ι       Decimal part
               ⮌        Reversed
              Ｉ         Cast to integer
             Ｉ          Cast to string
            ⮌           Reversed
           ⭆            Map over characters and join
                  λ     Current character
                 ⁺      Concatenated with
                    μ   Inner index
                   ⊕    Incremented
                     ω  Otherwise empty string
                      ι Otherwise integer part
                        Implicitly print

```

# Answer
> 1 votes
# Python, 77 bytes

```
lambda x,i=0:(s:=x.partition("."))[0]+'0'+''.join(c+str(i:=i+1)for c in s[2])

```

Attempt This Online!

# Answer
> 1 votes
# Thunno 2 `J`, 13 bytes

```
'.+'./2ɱẸsƤŻZ

```

Try it online!

Input as a string.

#### Explanation

```
'.+'./2ɱẸsƤŻZ  # Implicit input
'.+           '# Append a "." in case it isn't there already
   './        '# Then split it on "."s
      2ɱ       # And take the first two items
        Ẹ      # Dump both parts onto the stack
         sƤ    # Split the second part into characters and prepend the first part
           Ż   # Push [0..length] without popping this list
            Z  # And zip these two lists together
               # Implicit output, joined

```

# Answer
> 1 votes
# Nibbles, 8.5 bytes (17 nibbles)

```
`(%$"."+:0!+$,~:

```

Attempt This Online!

Outputs a trailing zero after integers (as permitted), and retains trailing zeros after the decimal point.

---

# Nibbles, 10 bytes (20 nibbles)

```
`(%$"."?,$+:0!+$,~:

```

Attempt This Online!

No trailing zero after integers, but retains trailing zeros after the decimal point.

```
`(%$"."?,$+:0!+$,~:
  %$"."             # split the input string on "."
`(                  # and output the first part
       ?,$          # now, if there's second part
             !+$    # zip it together with
                ,~  # 1..infinity
                  : # by concatenation,
           :0       # prepend a zero
                    # and output it after the first part

```

---

# Nibbles, 14.5 bytes (29 nibbles)

```
:`(%$"."+?,;!\`@~`r\+$,~::0$

```

Attempt This Online!

Outputs according to the initial test cases: no trailing zero for integers, no trailing zeros after the decimal point.

# Answer
> 0 votes
# Scala, 93 bytes

Port of @SuperStormer's Python answer in Scala.

---

Golfed version. Try it online!

```
x=>x.split("\\.").head+"0"+x.split("\\.")(1).zipWithIndex.map{case(c,j)=>c+""+(j+1)}.mkString

```

Ungolfed version. Try it online!

```
object Main {
  def f(x: String, i: Int = 0): String = {
    val parts = x.split("\\.")
    val s = parts(1).toList.zipWithIndex.map { case (c, idx) => c.toString + (i + idx + 1).toString }.mkString
    parts(0) + "0" + s
  }

  def main(args: Array[String]): Unit = {
    println(f("123.456") == "1230415263")
    println(f("0.0001") == "0001020314")
    println(f("123456789.123456789987654321") == "1234567890112233445566778899910811712613514415316217118")
  }
}

```

---
Tags: code-golf
---


# Question
Title: We already have pipes & pattern matching at home!
Inspired by this tweet where a user stated the following:

> it's insane how much code would be cleaned up if JS got pipes and pattern matching
>
> i often do this since it's the best way to make use of TS inference and pattern matching would make it less hacky

```
const result = (() => {
  if (scenario1) {
    return {
      type: 1,
      thing: scenario1.thing
    }
  }
  if (scenario2 && other.foo) {
    return {
      type: 2,
      thing: other.foo
    }
  }
  return {
    type: 3,
    thing: other.foo
  }
})()

```

In the spirit of this statement let's *"simplify"* the above logic to be as concise as possible!

## The Problem

Write a code snippet in the language of your choice which will return the following:

1. When `scenario1` is **Truthy** output: `{ type: 1, thing: scenario1.thing }`
2. Otherwise if `scenario2` & `other.foo` are **Truthy** `{ type: 2, thing: other.foo }`
3. Otherwise output `{ type: 3, thing: other.foo }`

### Constraints

This exercise should be viewed in the context of a program which has already declared `scenario1`, `scenario2` & `other` either above or as globals. Answers should reflect the shortest way to do what the OP was trying to accomplish.

* Variable and property names should be the same as above (or as close as your language will allow) and should be considered global.
* Answers should return an object / struct / class instance containing two properties `type` & `thing`
* Assume these don't have a strict shape (since the OP's example was in JS) and can be any of the following: `null` | `undefined` | `{ thing: "baz" }` | `{ thing: null }` | `{ thing: 123 }`
* Shortest code snippet wins, bonus points if your language can include the `|` operator for example `x || (x | y)` over `x ? x : (x + y)` inspired by the *we already have at home meme*. If two answers are the same number of bytes, the one with more pipes will win.

### Input

To make this problem non-trivial

1. `scenario1`, `scenario2` and `foo` should be considered as globals and already declared
2. The should contain the equivalent properties as the JS example, but don't need to use the `.` syntax

### Output

Output should be an object containing two properties:

```
{
   type: 1 | 2 | 3,
   thing: scenario1.thing | other.foo
}

```

It doesn't have to be JS style object, but it should be an object containing the properties.

### Test Cases

| scenario1 | scenario2 | other | output |
| --- | --- | --- | --- |
| `{thing: true}` | `{thing: false}` | `{foo: 'bar'}` | `{type:1, thing: true}` |
| `{thing: false}` | `{thing: true}` | `{foo: 'bar'}` | `{type:1, thing: false}` |
| `{thing: false}` | `{thing: true}` | `{foo: null}` | `{type:1, thing: false}` |
| `null` | `null` | `{foo: 123}` | `{type:3, thing:123}` |
| `{thing: 0}` | `undefined` | `{foo: 'bar'}` | `{type:1, thing: 0}` |
| `undefined` | `{thing: 0}` | `{foo: 'bar'}` | `{type:2, thing: 'bar'}` |
| `undefined` | `{thing: "js"}` | `{foo: 'bar'}` | `{type:2, thing: 'bar'}` |
| `undefined` | `{thing: "js"}` | `{foo: null }` | `{type:3, thing: null}` |
| etc. | etc. | etc. | etc. |

### Quick Tests

```
function test(scenario1, scenario2, other) {
  if (scenario1) {
    return {
      type: 1,
      thing: scenario1.thing
    }
  }
  if (scenario2 && other.foo) {
    return {
      type: 2,
      thing: other.foo
    }
  }
  return {
    type: 3,
    thing: other.foo
  }
}

console.log([
  test({thing: true}, {thing: false}, {foo: 'bar'}),
  test({thing: false}, {thing: true}, {foo: 'bar'}),
  test({thing: false}, {thing: true}, {foo:  null}),
  test(null, null, {foo: 123}),
  test({thing: 0}, undefined, {foo: 'bar'}),
  test(undefined, {thing: 0}, {foo: 'bar'}),
  test(undefined, {thing: "js"}, {foo: 'bar'}),
  test(undefined, {thing: "js"}, {foo: null }),
  test(undefined, {thing: "js"}, {foo: 'bar' }),
])
```

# Answer
> 2 votes
# JavaScript (ES6), 68 bytes (2 pipes)

```
{type:(v=other.foo,o=scenario1)?1:2|!v|!scenario2,thing:o?o.thing:v}

```

Try it online!

### Commented

```
{                  //
  type: (          // define the 'type' property:
    v = other.foo, //   copy other.foo in v
    o = scenario1  //   copy scenario1 in o
  ) ?              //   if scenario1 is truthy:
    1              //     set the type to 1
  :                //   else:
    2 |            //     set the type to 2 unless
    !v |           //     other.foo is falsy
    !scenario2,    //     or scenario2 is falsy,
                   //     in which case it's set to 3
  thing:           // define the 'thing' property:
    o ?            //   if scenario1 is truthy:
      o.thing      //     use scenario1.thing
    :              //   else:
      v            //     use other.foo
}                  //

```

# Answer
> 4 votes
# Python, 109 bytes

Inspired by Gugu72's comment, and they sure were right about how hard booleans are to golf.

`undefined` doesn't exist, so `None` pulls double duty as its usual analogue of `null` and as that. If I have to explicitly handle a case where the input is the string `"undefined"` I will probably explode

```
{'type':1if(s:=scenario1)else 2|(not((f:=other and other['foo'])and scenario2)),(t:='thing'):s[t]if s else f}

```

Attempt This Online!

# Answer
> 4 votes
# , ~~180~~ ~~150~~ 138 bytes

```
o="other"
s="scenario1"
`+`=\(x)exists(x)&&length(get(x))
list(type=(3-(+"scenario2"&+o))^!+s,thing=`if`(+s,get(s)$thing,if(+o)other$foo))

```

Attempt This Online!

Treats non-empty lists as truthy (not R's default behaviour, but seems to be the intent of this question).
Handles the cases where global variables `scenario1`, `scenario2` or `other` are undefined (=not 'declared').

---

# , ~~116~~ 94 bytes

```
o=other
s=scenario1
`+`=length
list(type=(3-(+scenario2&+o))^!+s,thing=`if`(+s,s$thing,o$foo))

```

Attempt This Online!

Assumes that global variables `scenario1`, `scenario2` and `other` already exist.

# Answer
> 3 votes
# JavaScript (Node.js), 70 bytes

*-4 bytes, thanks to Value Ink*

```
{type:(s=scenario1)?1:2|!((o=other.foo)&&scenario2),thing:s?s.thing:o}

```

Attempt This Online!

Takes Inputs as global variables

---
Tags: code-golf
---


# Question
Title: Perform basic operations on complex numbers in a language without native support for complex numbers
Your code has to provide the following functions:

```
read(x)

```

> Reads a complex number from the standard input. It has to accept and evaluate something in the form of for example `1.42 + 3i`.

```
print(x)

```

> Prints the complex number in the form of, for example `1.23 - 4.32i`

```
add(x,y)
sub(x,y)
mult(x,y)
div(x,y)

```

> Adds, subtracts, multiplies and respectively divides the two complex numbers.

It is enough if your functions are accurate to two digits after the decimal point, of course, it can be more if you so wish. The input will never have more than two digits after the decimal point.

Any language without native support for complex numbers may be used. Similarly, libraries or other language features which deal with complex numbers are **not** permitted. The point is, you have to do all the handling of complex numbers by yourself.

## Scoring

This is a code golf. The score is the sum of the lengths of the function bodies. For example, `int add(int a, int b) {return a+b;}` will have a length of 11 because of `return a+b`. Your solution must have a main program which demonstrates the use of the functions (for easier evaluation of your solution), but it will not be part of the scoring.

You can store the complex numbers in any way you wish, but the functions must have exactly the same amount of parameters as in the above description.

**EDIT**: For languages that support it, you can use operator overloading instead of the `add`, `sub`, etc. functions.

**EDIT 2:** To prohibit the cheap `#define all_your_code_here A`, I'll try to clarify the "only function bodies count" better: every character in the code counts, except for the overhead required to declare and define the functions and the libraries required to do basic I/O. By basic I/O I still mean no language features which directly deal with complex numbers. The `main` or equivalent where you call these functions don't count but you are not allowed to do anything besides using those functions for demonstrative purpose.

# Answer
## APL (33 + 16 + 1 + 1 + 14 + 17 = **82**)

APL does have support for complex numbers if you use it (of the format `5J6`, like Python's `5+6j`), but it is of course not used.

I represent complex numbers as a 2-tuple of regular numbers, (A B) where A is the real part and B is the imaginary part. This means I can use APL's `+` and `-` operators directly, as they can be used on multidimensional types. (i.e. `1+2 3 4` gives `3 4 5` and `1 2+20 10` gives `21 12`).

An APL function is represented as `{body}`. Functions are first-class objects. I have counted the function body without the braces, except for `+` and `-` which I've counted as 1 each.

```
read  ← {⎕ML←3⋄(1,1-2×'-'∊⍵)×⍎¨⍵⊂⍨⍵∊'.',⎕D} ⍝ 33 chars
print ← {⍕(⊃⍵)'+'(⊃⌽⍵)'i'}                   ⍝ 16 chars
add   ← +                                      ⍝ 1 char
sub   ← -                                      ⍝ 1 char
mul   ← {(-/⍺×⍵),+/⍺×⌽⍵}                      ⍝ 14 chars
div   ← {⍺mul 1 ¯1×⍵÷+/⍵*2}                   ⍝ 17 chars

```

Usage: (clarification: APL is evaluated right-to-left so this is actually calculating 8+9i ÷ 5+6i.)

```
      print (read⍞) div (read⍞)
5 + 6i
8 + 9i
1.540983607 + ¯0.04918032787 i

```
> 4 votes

# Answer
## D (205 chars)

```
import stdio;

struct Complex{
  real a,b;

  this(real a,real b){
      this.a=a;
      this.b=b;
  }

  static Complex read(){
      Complex c;
      readf("%f%+fi",&c.a,&c.b);
      return c;
  }

  /** does both addition and substraction */
  Complex opOpBinary(op)(Complex o)if(op=="+"||op=="-"){
    mixin("return Complex(a"~op~"o.a,b"~op~"o.b);");
  }

  Complex opBinary(op)(Complex o)if(op=="*"){
    return Complex(a*o.a-b*o.b,a*o.b+b*o.a);
  }

  Complex opBinary(op)(Complex o)if(op=="/"){
    real z=c**2+d**2
    return this*Complex(o.a/z,-o.b/z);
  }

  void write(){
     writef("%f%+fi",a,b);
  }

}

```

using operator overloading

I didn't count the constructor
> 3 votes

# Answer
## Python, 131 chars

```
add=lambda (a,b),(c,d):(a+c,b+d)
sub=lambda (a,b),(c,d):(a-c,b-d)
mul=lambda (a,b),(c,d):(a*c-b*d,a*d+b*c)
def div(x,(c,d)):z=c**2+d**2;return mul(x,(c/z,-d/z))
def _print(x):print"%f+%fi"%x
read=lambda:tuple(map(float,raw_input()[:-1].split('+')))

x=read()
y=read()
_print(add(x,y))
_print(sub(x,y))
_print(mul(x,y))
_print(div(x,y))

```

Makes lots of use of lambda unpacking, which I'm not including in my "body" count. (I'm counting everything after the first `:`). Kinda cheating, but I'm not really sure how to count it otherwise.
> 1 votes

# Answer
## C# – 369 (I guess)

```
Func<float,float,float[]>C=(x,y)=>new[]{x,y};
Func<float[]>read=()=>{var m=new Regex(@"(\d*(\.\d*)?) *([+-]) *(\d*(\.\d*)?)i").Match(Console.ReadLine()).Groups;return C(float.Parse(m[1].Value),float.Parse(m[2].Value+m[4].Value));};
Action<float[]>print=x=>{Console.WriteLine("{0} {1} {2}i",x[0],x[1]>=0?"+":"-",Math.Abs(x[1]));};
Func<float[],float[],float[]>add=(x,y)=>C(x[0]+y[0],x[1]+y[1]);
Func<float[],float[],float[]>sub=(x,y)=>C(x[0]-y[0],x[1]-y[1]);
Func<float[],float[],float[]>mul=(x,y)=>C(x[0]*y[0]-x[1]*y[1],x[0]*y[1]+x[1]*y[0]);
Func<float[],float[],float[]>div=(x,y)=>mul(x,C(y[0],-y[1])).Select(_=>_/(y[0]*y[0]+y[1]*y[1])).ToArray();

var a = read();
var b = read();
var c = C(3, -7);
var d = C(2, 5);
var e = div(a,c);
var f = mul(b,d);
var g = add(e,f);
print(g);

```

Not sure about the character counting definition, really…
> 1 votes

# Answer
## Haskell 698

Counted everything before `main`. This question struck me as being too straight forward, so I did everything in my power to make my answer more interesting. Also Haskell borks if you redefine `Prelude` functions (div, print, read), so I renamed those.

```
import Control.Arrow
import Control.Monad
import Control.Applicative
import Data.List.Split
a=uncurry(***)
f!g=a(f,g)
j=join(!)
f%b=a$j f b
add=((+)%)
sub=((-)%)
o=join
g#h=(*)<$>g.fst<*>h.snd
c=o.curry
m=add<$>c((fst#fst)!(snd#fst))<*>c((negate.(snd#snd))!(fst#snd))
mul=curry m
b`d1v`c=b`mul`(j (/uncurry(+)(j(^2)c)).second negate$c)
s :: (Show a) => (a, a) -> String
s=uncurry(++).first(++" ").second((++"i").(let g('-':x)="- "++x;g x="+ "++x in g)).j show
pr1nt :: (Show a) => (a, a) -> IO ()
pr1nt=putStrLn.s
t=filter(`notElem`" i")
re4d :: (Read a, Num a) => String -> (a, a)
re4d s|elem '+'s=(\[x,y]->j(read.t)(x,y)).splitOn"+"$s
      |0<1=(\[x,y]->read!(negate.read.t)$(x,y)).splitOn"-"$s

main= do
  let p = pr1nt
  a <- fmap re4d getLine
  b <- fmap re4d getLine
  p $ a `add` b
  p $ a `sub` b
  p $ a `mul` b
  p $ a `d1v` b

```

This spits a "non-exhaustive pattern-match in input" if the input given does not match "a (+|-) bi".
> 1 votes

# Answer
## Pascal, 317 bytes

The simple data type `complex` belongs to Extended Pascal’s vocabulary (ISO standard 10206). However, Standard Pascal – as laid out by ISO standard 7185 – does not support `complex` numbers. Complying with the task specification, the following implementation is restricted to SP.

Note, the routine `read` had to be renamed to `readComplex`, otherwise Pascal’s *built‑in* `read` procedure will become unavailable. Similarly, the word `div` is a *reserved word* (identifies the integer division operator) and had to be renamed, too (for the purposes of scoring a three-letter identifier has been chosen).

```
program basicOperationsOnComplexNumbers(input, output);
    type
        complex = record
                r: real;
                j: real;
            end;
        { In _Standard_ Pascal a `function` can
          only return _simple_ data type values. }
        complexReference = ↑complex;

    var
        { These are used for the test in the main block.
          Standard Pascal has a strict block order
          (`label` → `const` → `type` → `var` → routines → `begin … end`)
          therefore these are “global” variables. }
        x, y: complex;

    { Reads a `complex` in Cartesian (rectangular) format. }
    procedure readComplex(var x: complex);
        begin
            { The `Ln` is necessary so the rest of the line
              (in particular the `'i'`) is consumed, too. }
            readLn(x.r,x.j)
        end;

    { Prints a `complex` in Cartesian (rectangular) format. }
    procedure print(x: complex);
        begin
            { For non-negative `real` values a space (`' '`) is printed.
              Therefore we will need to print the plus sign ourselves. }
            write(x.r);if x.j≥0 then write('+');write(x.j,'i')
        end;

    { Returns the sum of two `complex` numbers. }
    function add(x, y: complex): complexReference;
        var
            { The implicitly defined result variable
              bearing the function’s name (here `'add'`)
              accepts only _complete_ assignments
              (this ensures there are no _partially_ defined results).
              Therefore we will need a temporary result variable. }
            z: complexReference;
        begin
            x.r≔x.r+y.r;x.j≔x.j+y.j;new(z);z↑≔x;add≔z
        end;

    { Returns the difference of two `complex` numbers. }
    function sub(x, y: complex): complexReference;
        var
            z: complexReference;
        begin
            x.r≔x.r−y.r;x.j≔x.j−y.j;new(z);z↑≔x;sub≔z
        end;

    { Returns the product of two `complex` numbers. }
    function mult(x, y: complex): complexReference;
        var
            z: complexReference;
        begin
            new(z);z↑.r≔x.r*y.r−x.j*y.j;z↑.j≔x.r*y.j+x.j*y.r;mult≔z
        end;

    { Returns the quotient of two `complex` numbers.
      CAUTION: DOES NOT CHECK FOR NON-ZERO DIVISOR. }
    function quo(x, y: complex): complexReference;
        var
            z: complexReference;
        begin
            new(z);with z↑do begin
            r≔y.r*y.r+y.j*y.j;j≔r;r≔(x.r*y.r+x.j*y.j)/r;j≔(x.j*y.r−x.r*y.j)/j
            end;quo≔z
        end;

    { === MAIN ========================================================= }
    begin
        readComplex(x);
        readComplex(y);

        write('       sum: '); print( add(x, y)↑); writeLn;
        write('difference: '); print( sub(x, y)↑); writeLn;
        write('   product: '); print(mult(x, y)↑); writeLn;
        write('  quotient: '); print( quo(x, y)↑); writeLn
    end.

```

Example input:

```
-3.00 + 2.00i
-2.72 + 0.00i

```

Example output (subject to implementation-defined behavior):

```
       sum: -5.7200000000000006e+00+ 2.0000000000000000e+00i
difference: -2.7999999999999980e-01+ 2.0000000000000000e+00i
   product:  8.1600000000000001e+00-5.4400000000000004e+00i
  quotient:  1.1029411764705881e+00-7.3529411764705876e-01i

```

RosettaCode │ FreePascal Compiler Wiki │ GNU Pascal Compiler Programmer’s Guide
> 0 votes

---
Tags: code-golf, complex-numbers
---