# Question
Title: Многочлены Чебышёва (Chebyshev Polynomials)
Chebyshev Polynomials are a family of orthogonal polynomials that pop up in all kinds of places in math, and they have a lot of quite interesting properties. One characterization of them is that they are the unique polynomials that satisfy \\$T\_n(\cos(x)) = \cos(nx)\\$.

### Challenge

Given an nonnegative integer \\$n\\$, you should output the \\$n\\$-th Chebyshev Polynomial. \\$T\_n(x)\\$.

### Definition

The \\$n\\$-th Chebyshev Polynomial is given by following three term recursion:

$$\begin{align} T\_0(x) & = 1 \\ T\_1(x) & = x \\ T\_{n+1}(x) & = 2xT\_n(x) - T\_{n-1}(x) \end{align}$$

### Details

If your language has a native polynomial type, you can use that one as an output, otherwise you should output a list of coefficients in ascending- or descending order, or as a string representing a polynomial.

This is so the shortest code in bytes wins

### Examples

```
T<sub>0</sub>(x) = 1
T<sub>1</sub>(x) = x
T<sub>2</sub>(x) = 2x^2 - 1
T<sub>3</sub>(x) = 4x^3 - 3 x
T<sub>4</sub>(x) = 8x^4 - 8x^2 + 1
T<sub>5</sub>(x) = 16x^5 - 20x^3 + 5x
T<sub>10</sub>(x) = 512x^10 - 1280x^8 + 1120x^6 - 400x^4 + 50x^2 - 1

```

In the descending degree list format we'd get `T<sub>3</sub>(x) = [4,0,-3,0]` and in the ascending degree format we'd get `T<sub>3</sub>(x) = [0,-3,0,4]`

# Answer
> 17 votes
# Mathematica, 15 bytes

```
#~ChebyshevT~x&

```

Of course, Mathematica has a builtin.

If an alternative input form is allowed (10 bytes):

```
ChebyshevT

```

takes an integer `n` and a variable.

# Answer
> 14 votes
# Octave, 39 bytes

```
@(n)round(2^n/2*poly(cos((.5:n)/n*pi)))

```

Try it online!

### Explanation

`cos((.5:n)/n*pi)` builds a vector with the roots of the polynomial, given by

`poly` gives the monic polynomial with those roots. Multiplying by `2^n/2` scales the coefficients as required. `round` makes sure that results are integer in spite of numerical precision.

# Answer
> 11 votes
# Pari/GP, 12 bytes

Yes, a builtin. Shorter than Mathematica.

```
polchebyshev

```

Try it online!

---

Without builtin:

# Pari/GP, 34 bytes

```
f(n)=if(n<2,x^n,2*x*f(n-1)-f(n-2))

```

Try it online!

# Answer
> 10 votes
# Haskell, 62 bytes

```
t n|n<2=1:[0|n>0]|x<-(*2)<$>t(n-1)++[0]=zipWith(-)x$0:0:t(n-2)

```

Try it online!

flawr saved a byte.

# Answer
> 7 votes
## CJam (21 bytes)

```
1a2,qi{0X$+2f*@.-}*;`

```

This is a full program: the equivalent as an anonymous block is the same length:

```
{1a2,@{0X$+2f*@.-}*;}

```

Online demo

# Answer
> 6 votes
# Python + SymPy, 66 bytes

```
from sympy.abc import*
T=lambda n:n<2and x**n or 2*x*T(n-1)-T(n-2)

```

Try it online!

### With descending coefficients representation

```
from sympy import*
x=symbols('x')
T=lambda n:n<2and x**n or expand(2*x*T(n-1)-T(n-2))

```

Try it online!

# Answer
> 6 votes
# MATL, 17 bytes

```
lFTi:"0yhEbFFh-]x

```

Coefficients are output in increasing order of degree.

Try it online! Or verify all test cases.

## Explanation

For input *n*, the code applies the recursive relation *n* times. The two most recent polynomials are always kept on the stack. When a new polynomial is computed, the oldest is removed.

At the end, the second-last polynomial is displayed (the last polynomial is deleted), as we have done one too many iterations.

```
l        % Push 1
FT       % Push [0 1]. These are the first two polynomials
i:"      % Input n. Do the following n times
  0      %   Push 0
  y      %   Duplicate most recent polynomial
  h      %   Concatenate: prepends 0 to that polynomial
  E      %   Multiply coefficients by 2
  b      %   Bubble up. This moves second-most recent polynomial to top
  FF     %   Push [0 0]
  h      %   Concatenate: appends [0 0] to that polynomial
  -      %   Subtract coefficients
]        % End
x        % Delete. Implicitly display

```

# Answer
> 5 votes
## SageMath, 25 bytes

```
lambda n:chebyshev_T(n,x)

```

Try it online

# Answer
> 5 votes
# Jelly, 18 bytes

```
Cr1µ’ßḤ0;_’’$ß$µỊ?

```

Try it online!

Returns a list of coefficients in ascending order.

There is another solution for **17 bytes** with floating-point inaccuracies.

```
RḤ’÷Ḥ-*ḞÆṛæ«’µ1Ṡ?

```

Try it online!

## Explanation

```
Cr1µ’ßḤ0;_’’$ß$µỊ?  Input: integer n
                Ị   Insignificant - abs(n) <= 1
                    If true, n = 0 or n = 1
   µ                  Monadic chain
C                       Complement, 1-x
 r1                     Range to 1
                    Else
               µ      Monadic chain
    ’                   Decrement
     ß                  Call itself recursively
      Ḥ                 Double
       0;               Prepend 0
         _              Subtract with
            $             Monadic chain
          ’’                Decrement twice
              $           Monadic chain
             ß              Call itself recursively

```

# Answer
> 3 votes
# , 33 bytes

```
(0>.<:)2&*1:p.@;9:o._1^+:%~1+2*i.

```

Try it online!

Assumes that floating-point inaccuracies are acceptable and creates the emoji `(0>.<:)`

For **41 bytes**, there is another solution that avoids floats.

```
(0&,1:)`(-&2((-,&0 0)~2*0&,)&$:<:)@.(>&1)

```

Try it online!

# Answer
> 2 votes
# Ruby + polynomial, ~~59~~ 58+13 = ~~72~~ 71 bytes

Uses the `-rpolynomial` flag.

```
f=->n{x=Polynomial.new 0,1;n<2?[1,x][n]:2*x*f[n-1]-f[n-2]}

```

# Answer
> 2 votes
# Python 2, 79 bytes

```
f=lambda n:n>1and[2*a-b for a,b in zip([0]+f(n-1),f(n-2)+[0,0])]or range(1-n,2)

```

Try it online!

# Answer
> 2 votes
# Axiom, 40 bytes

```
f(n,x)==(n<2=>x^n;2*x*f(n-1,x)-f(n-2,x))

```

results

```
(9) -> for i in [0,1,2,3,4,5,10] repeat output ["f(y)",i,"=", f(i,y)]
   ["f(y)",0,"=",1]
   ["f(y)",1,"=",y]
                   2
   ["f(y)",2,"=",2y  - 1]
                   3
   ["f(y)",3,"=",4y  - 3y]
                   4     2
   ["f(y)",4,"=",8y  - 8y  + 1]
                    5      3
   ["f(y)",5,"=",16y  - 20y  + 5y]
                      10        8        6       4      2
   ["f(y)",10,"=",512y   - 1280y  + 1120y  - 400y  + 50y  - 1]
                                                               Type: Void

```

it is possible define one substitution law for formula in Axiom use above f() function for expansion of cos(n\*x) where n is one integer

```
(9) -> o:=rule cos(n*%y)==f(n,cos(%y))
   (9)  cos(%y n) == 'f(n,cos(%y))
                    Type: RewriteRule(Integer,Integer,Expression Integer)
                                                              Time: 0 sec
(10) -> b:=o cos(20*x)
   (10)
                 20                18                16                14
     524288cos(x)   - 2621440cos(x)   + 5570560cos(x)   - 6553600cos(x)
   +
                  12                10               8              6
     4659200cos(x)   - 2050048cos(x)   + 549120cos(x)  - 84480cos(x)
   +
               4            2
     6600cos(x)  - 200cos(x)  + 1
                                                 Type: Expression Integer
                       Time: 0.48 (EV) + 0.02 (OT) + 0.10 (GC) = 0.60 sec

```

# Answer
> 1 votes
# C# (.NET Core), 126 bytes

```
f=n=>n==0?new[]{1}:n==1?new[]{0,1}:new[]{0}.Concat(f(n-1)).Select((a,i)=>2*a-(i<n-1?f(n-2)[i]:0)).ToArray();

```

Byte count also includes:

```
using System.Linq;

```

Try it online!

The function returns polynomial as an array of coefficients in ascending order (from `x^0` to `x^n`)

Explanation:

```
f = n =>                          // Create a function taking one parameter (int)
    n == 0 ? new[] { 1 } :        // If it's 0, return collection [1]
    n == 1 ? new[] { 0, 1 } :     // If it's 1, return collection [0,1] (so x + 0)
    new[] { 0 }                   // Else create new collection, starting with 0
        .Concat(f(n - 1))         // Concatenate with f(n-1), effectively multiplying polynomial by x
        .Select((a, i) => 2 * a - (i < n - 1 ? f(n - 2)[i] : 0))
                                  // Multiply everything by 2 and if possible, subtract f(n-2)
        .ToArray();               // Change collection to array so we have a nice short [] operator
                                  // Actually omitting this and using .ElementAt(i) is the same length, but this is my personal preference

```

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

```
f=n=>n?n>1?[0,...f(n-1)].map((e,i)=>e+e-(f(n-2)[i]||0)):[0,1]:[1]

```

Inefficient for large `n`. Interesting but sadly also inefficient:

```
n=>[...Array(n+1)].map(g=(m=n,i)=>i<0|i>m?0:m<2?i^m^1:g(m-1,i-1)*2-g(m-2,i))

```

Very efficient for 68 bytes:

```
f=(n,a=[1],b=[0,1])=>n?f(n-1,b,[0,...b].map((e,i)=>e+e-(a[i]||0))):a

```

Returns an array of coefficients in ascending order.

# Answer
> 0 votes
# Stax, 19 bytes

```
╛5%Ö←Äⁿ¿æ╔Dë!é╔J╗yì

```

Run and debug it

zipping takes a lot of bytes.

---
Tags: code-golf, math, sequence, polynomials, recursion
---


title: Determine the degree of a polynomial

text:
# Question
Title: Determine the degree of a polynomial
**Background:**

For this challenge, a polynomial looks like this:

$$P(x)=a\_nx^n+a\_{n-1}x^{n-1}+\dots+a\_2x^2+a\_1x+a\_0$$

The degree, \\$n\\$, is the highest power \\$x\\$ is raised to. An example of a degree 7 polynomial would be:

$$P(x)=4x^7+2x^6-7x^4+x^2-6x+17$$

All powers are integers \\$n\ge0\\$. This means \\$x\\$, \\$-2\\$, and \\$0\\$ could all be considered polynomials, but not \\$\frac{1}{x}\\$ or \\$\sqrt{x}\\$.

**Challenge:**

Write a program or functions which takes a number of pairs \\$(x, P(x))\\$, and finds the smallest possible degree of \\$P(x)\\$. The values of \\$x\\$ will be incrementing; \\$\\{(0, 1), (1, 0), (2, 1)\\}\\$ is a valid input, but \\$\\{(0, 2), (10, 20), (11, 22)\\}\\$ is not.

Given \\$\\{(0, 1), (1, 0), (2, 1)\\}\\$, for example, the degree is \\$2\\$ (and \\$P(x)=x^2-2x+1\\$).

**Input:**

Input will consist of at least \\$n+1\\$ pairs of integer values, and at least \\$2\\$, representing \\$x\\$ and \\$P(x)\\$. The \\$x\\$ values will all be one higher than the previous one.

Input can be taken in any reasonable format. Invalid inputs do not need to be handled. Optionally, you can input only the \\$P(x)\\$ values (and ignore \\$x\\$ altogether).

**Output:**

Output will be an integer \\$n\ge0\\$, representing the degree of \\$P(x)\\$.

As with the input, any reasonable format is valid.

**Tip:**

A simple way to find the degree of a polynomial function (like \\$P(x)\\$) when you have a list of inputs with incrementing \\$x\\$ values is to create a list of the \\$P(x)\\$ values, then repeatedly find the difference between adjacent items. For example, given the inputs \\$\\{(-3, 14), (-2, 4), (-1, -2), (0, -4), (1, -2)\\}\\$:

$$\\{14, 4, -2, -4, -2\\}$$ $$\\{10, 6, 2, -2\\}$$ $$\\{4, 4, 4\\}$$

After some number of iterations, \\$2\\$ in this case, all of the items will be the same number. That number of iterations is \\$n\\$.

**Test cases:**

```
(-1, 8), (0, 8), (1, 8)                                    0
(0, 0), (1, 0), (2, 0)                                     0
(1, 0), (2, 1)                                             1
(0, 0), (1, 2), (2, 4), (3, 6), (4, 8)                     1
(-4, -20), (-3, -12), (-2, -6)                             2
(6, 1296), (7, 2401), (8, 4096), (9, 6561), (10, 10000)    4

```

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

# Answer
> 6 votes
# Husk, ~~8~~ 6 bytes

```
←VE¡Ẋ-

```

Try it online!

-2 bytes from Leo.

## Explanation

```
←VE¡Ẋ- Input: list of P(x)
   ¡Ẋ- repeatedly take deltas and put in infinite list
 V     First index where
  E    all elements are equal
←      decrement

```

# Answer
> 6 votes
# , 26 18 17 bytes

```
-~@}.i.~#\-/\~&2]

```

Try it online!

Thanks to Bubbler for -1 byte and for catching a bug!

* `-/\~&2` Apply "successive deltas" verb iteratively "left arg" times to the right arg.
* `#\ ... ]` Where the left arg is the lengths of input prefixes (ie, `1 2 3 ... <input length>`) and the right arg is the input. Eg, with the input `14 4 _2 _4 _2` this gives us the matrix:

```
 10 6 2 _2
 4 4 4  0
 0 0 0  0
 0 0 0  0
 0 0 0  0

```
* `-~@}.` Subtract the original input from itself after killing the first element `}.`. The gives a row of all zeros:

```
 0 0 0 0

```
* `i.~` Return index of the first row in the matrix above matching that all zeros row.

# Answer
> 5 votes
# Pyth, 9 bytes

```
tl.u@.+QY

```

Try it online!

Input taken as a list of \\$P(x)\\$.

Translation of Razetime's Husk answer.

# Answer
> 5 votes
# , ~~50~~ 39 bytes

```
x=scan();while(any(x<-diff(x)))F=F+1;+F

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~13~~ 7 bytes

```
[DËD–#¥

```

Try it online!

*-6 thanks to ovs!*

# Answer
> 4 votes
# Jelly, 6 bytes

```
IƬE€ċ0

```

Try it online!

## How it works

```
IƬE€ċ0 - Main link. Takes P on the left
 Ƭ     - Until reaching a fixed point:
I      -   Take deltas
   €   - For each:
  E    -   All equal?
    ċ0 - Count the number of 0s

```

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

```
f=p=>(q=p.map(x=>p-(p=x))).some(x=>x)&&f(q)+1

```

Try it online!

`NaN` is falsy, let's propagate it.

---

As the tip shown in question. We iterate one more step as:

$$ \begin{matrix} \\{& 14 & 4 & −2 & −4 & −2 & \\} \\ \\{& 10 & 6 & 2 & −2 & & \\} \\ \\{& 4 & 4 & 4 & & & \\} \\ \\{& 0 & 0 & & & &\\} \\ \end{matrix} $$

We check the finish of iteration by looking if all elements are \\$0\\$.

Reducing array size when iterate cost to many bytes. So we simply fill `NaN` instead.

$$ \begin{matrix} \\{& 14 & 4 & −2 & −4 & −2 & \\} \\ \\{& 10 & 6 & 2 & −2 & \text{NaN} & \\} \\ \\{& 4 & 4 & 4 & \text{NaN} & \text{NaN} & \\} \\ \\{& 0 & 0 & \text{NaN} & \text{NaN} & \text{NaN} &\\} \\ \end{matrix} $$

And check if everything is *falsy*.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 39 bytes

```
Exponent[InterpolatingPolynomial[#,],]&

```

Try it online!

Takes input as the list of `y`-values only. Spits some syntax errors because it uses `Null` as the variable (after each comma) to save two bytes.

If anyone knows how to translate this into Sledgehammer, I bet it would be really short.

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~32~~ 34 bytes

```
f@{a_..}=0
f@a_:=f@Differences@a+1

```

Try it online!

Perhaps less interesting than Greg's answer. Implements the differences algorithm.

# Answer
> 2 votes
# Vyxal, `l`, 6 bytes

```
‡≈¬⁽¯ẋ

```

Try it Online!

I'm very proud with how this turned out. It looks and works exactly how I hoped Vyxal would eventually look like.

## Explained

```
‡≈¬

```

Push a two character lambda to the stack, which returns the logical not of whether or not every element in the list is equal.

```
⁽¯

```

Push a function reference of the detlas built-in

Repeat the deltas function on the input until the first lambda returns true for the current iteration (generate while condition true). Push and implicitly print the length of the resulting list (done by the `-l` flag)

# Answer
> 2 votes
# JavaScript (V8), 59 bytes

*-9 bytes thanks to @Neil*

```
f=p=>p.some(x=>x-p[0])?f(p.slice(1).map((x,j)=>x-p[j]))+1:0

```

\[Can't add TIO link on school internet\]

## Old, 68 bytes

```
f=(p,i=0)=>!p.some(x=>x-p[0])?i:f(p.slice(1).map((x,j)=>x-p[j]),i+1)

```

Try it online!

# Answer
> 2 votes
# Python 3, ~~59~~ 56 bytes

```
from numpy import*
f=lambda x:len({*x})-1and-~f(diff(x))

```

Try it online!

Takes a tuple of P(x) values as input.

*-3 bytes thanks to Danis*

# Answer
> 2 votes
# Java, 153 bytes

```
int s(int[]y){return java.util.Arrays.stream(y).distinct().count()!=1?s(java.util.stream.IntStream.range(1,y.length).map(i->y[i]-y[i-1]).toArray())+1:0;}

```

Takes an array of `P(x)` values as input.

Try it online!

## Explanation

```
int s(int[] y){
   return java.util.Arrays.stream(y).distinct().count() != 1 //if not all elements are equal
       ?
        s(
           java.util.stream.IntStream.range(1,y.length).map(i->y[i]-y[i-1]).toArray()
           //get difference of adjacent elements as new array
        ) + 1 //get result of recursive call plus 1
       :  0; //otherwise, we are done
}

```

# Answer
> 2 votes
# Ruby, 45 bytes

```
f=->a{(a|(r,*a=a))[1]?f[a.map{|c|r-r=c}]+1:0}

```

Try it online!

### Some explanation please?

Basically, a recursive function checking if all elements in the array are equals, and then calculating the differences and increasing by 1 at every step.

```
f=->a{

    (a|(r,*a=a))[1]?

```

Check if the array has at least 2 different elements, and split it into head and tail. `r,*a=a` does the split, putting the first element of a into the variable r. The second step is equivalent to `(a|a)[1]`, or `a.uniq[1]`. If the array has at least 2 unique elements, this is a truthy value, and if it doesn't, then the result is `nil`.

```
    f[a.map{|c|r-r=c}]+1

```

If the array has at least 2 different values, then calculate the difference between consecutive elements of the array, and increase the final result by 1.

```
    :0}

```

If the array only contains one unique value, then the degree of the polynomial is 0.

It took me some time to come up with this solution, so I'm a little late to the party, but I didn't want to post anything above 50 bytes.

# Answer
> 1 votes
# Stax, ~~9~~ 8 bytes

```
▓>ⁿⁿ∟╔♪╒

```

Run and debug it

Same idea as my Husk answer. Takes input as P(x) alone.

## Explanation

```
{uD}{:-gf%
       g   generate values till:
        f  a value fails the filter
{  }       filter:
 u         uniquify the list
  D        and delete first element
    {  g   generator:
     :-    take deltas of the previous iteration
         % take the length of the generated list

```

# Answer
> 1 votes
# Charcoal, 24 bytes

```
Ｗ⁻⌈θ⌊θ«ＵＭθ⁻§θ⊕λκ⊞υ⊟θ»ＩＬυ

```

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

```
Ｗ⁻⌈θ⌊θ«

```

Repeat until the maximum and minimum of the array are equal...

```
ＵＭθ⁻§θ⊕λκ

```

... calculate the cyclic differences of the elements...

```
⊞υ⊟θ

```

... and remove the last one (which is meaningless) and push it to the predefined empty list (which thereby keeps track of the number of iterations).

```
»ＩＬυ

```

Print the final number of iterations.

# Answer
> 1 votes
# Julia, 25 bytes

```
~n=any(n'.<n)&&1+~diff(n)

```

Try it online!

# Answer
> 1 votes
# Scala, 72 bytes

```
def g(a:Int*):Int=if(a.min<a.max)1+g(a.lazyZip(a.tail)map(_-_):_*)else 0

```

For once, recursion is shorter!

## Without recursion, 74 bytes

```
Stream.iterate(_){a=>a.lazyZip(a.tail)map(_-_)}indexWhere(a=>a.min==a.max)

```

Try them both in Scastie!

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


title: Constrained integer partition

text:
# Question
Title: Constrained integer partition
# Challenge

**In this challenge**, all numbers are in \\$\mathbb{N}\_0\\$.

Create a function or program that, when given a number \\$N\\$ and a tuple of \\$k\\$ numbers \\$(n\_i)\\$ (all ≤ \\$N\\$), returns the number of ways \\$N\\$ can be written as a sum of \\$k\\$ integers (\\$x\_1 + x\_2 + ... + x\_k\\$) such that \\$n\_i \le x\_i \le N\\$.

The input format is not fixed. You can read and parse strings, take two parameters as int and int\[\], etc.

This is a variation of the classical **Integer Partition** problem.

# Test Cases

\\$N=4, n=(0, 0, 2) \implies 6\\$ `(2+0+2, 1+1+2, 0+2+2, 1+0+3, 0+1+3, 0+0+4)`

\\$N=121, n=(7, 16, 21, 36, 21, 20) \implies 1\\$ `(7+16+21+36+21+20)`

This is , so the lowest byte count for each language wins!

# Answer
# Jelly, 5 bytes

```
rŒp§ċ

```

A dyadic Link accepting the lower bound tuple on the left and the total on the right which yields the count.

**Try it online!**

### How?

```
rŒp§ċ - Link: T, N       e.g. [2,1,3], 5
r     - inclusive range       [[2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
 Œp   - Cartesian product     [[2,1,1],[2,1,2],[2,1,3],[2,1,4],[2,1,5],[2,2,1],...,[5,5,4],[5,5,5]]
   §  - sums                  [ 4,      5,      6,      7,      8,      5,     ..., 14,     15]
    ċ - count (Ns)            2

```
> 8 votes

# Answer
# Haskell, 35 bytes

```
n%(x:t)=sum$map(%t)[0..n-x]
n%_=0^n

```

Try it online!
> 7 votes

# Answer
# Husk, ~~9~~ 7 bytes

*Edit: -2 bytes thanks to user*

```
#¹mΣΠm…

```

Try it online!

```
#¹         # number of times that arg 1 appears in the list of
  mΣ       # sums of
    Π      # cartesian product of
     m     # mapping
      …    # range up to arg 1
           # for each element of arg 2

```
> 5 votes

# Answer
# Python 3.8+, 62 bytes

```
import math
f=lambda S,N:math.comb(S-sum(N)+len(N)-1,len(N)-1)

```

The result can be found using the formula:

$$R = \binom{N-(\Sigma x\_i)+k-1}{k-1}$$
> 3 votes

# Answer
# Ruby, ~~62~~ 51 bytes

```
->n,k{[*1..n-k.sum+z=k.size-1].combination(z).size}

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 65 bytes

Expects `(n)(list)`. Uses the formula provided by the OP.

```
n=>a=>(n-=eval(a.join`-1+`),g=k=>!k||g(--k)*(k-n)/~k)(a.length-1)

```

Try it online!

### How?

The expression `eval(a.join('-1+'))` subtracts 1 from all entries in `a[]` except the last one and sums everything. For instance:

```
[ 2, 3, 4 ] --> "2-1+3-1+4" --> 7

```

So, this is equivalent to: $$\sum\_{i=1}^{k} x\_i-k+1$$

We could also use `eval(a.join('+~-'))` which subtracts 1 from all entries but the first one, leading to the same result.

The helper function `g` computes the combination.
> 2 votes

# Answer
# , 46 bytes

**(using n\_choose\_k)**

```
function(x,y)choose(x-sum(y)+(z=sum(y|1)-1),z)

```

Try it online!

# , 58 bytes

**(by enumeration)**

```
function(x,y)sum(rowSums(z<-expand.grid(Map(`:`,y,x)))==x)

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 38 bytes

port of xnor's answer

```
n>N=n==[]?0^N:sum([n[2:end]].>0:N-n[])

```

Try it online!

### alternative answer, 38 bytes too

```
!N=0^N;!(N,x,t...)=sum(.!(0:N-x,t...))

```

Try it online!

a few more bytes with julia 1.0+
> 1 votes

# Answer
# Pyth, 14 bytes

```
.c+-hAQsHJtlHJ

```

Try it online!

Translation of zdimension's Python 3 answer.

# 14 bytes

```
/sMsM*F}RGeAQG

```

Try it online!

Translation of Jonathan Allan's Jelly answer.
> 1 votes

# Answer
# JavaScript (ES2020), 59 bytes

```
f=(n,[h,...t],s=0)=>eval('for(;n>=h;)s+=f(n-h++,t)')??!n&!h

```

```
f=(n,[h,...t],s=0)=>eval('for(;n>=h;)s+=f(n-h++,t)')??!n&!h

console.log(f(4, [0,0,2]));
console.log(f(121, [7,16,21,36,21,20]));
```

Firefox 72+, Chrome 80+, IE no. TIO currently out of date.

Simple brute force, literally.

* `eval()` return *completion value* of given statement(s).
    + Completion value of `for` statement is completion value of its execute body in last iteration.
    + Completion value of assignment is the value assigned.
    + In case the control flow does not goes into for loop due to the looping condition, `for` statement has no completion value.
    + As the result, `eval(for(;n>=h;)...)` returns the value of `s` (an integer) if once `n>=h`, and return `undefined` if `n>=h` never happened.
* `??` is nullish coalescing operator which is introduced in ES2020.
    + If left side of `??` is null or undefined, it equals to right side. Otherwise, it returns left side (short circuit evaluation). (Similar as what `??` in C# do.)
    + If `n>=h` is falsy, it may due to `n<h` or `h` is undefined.
    + We found a valid integer partition as long as `n == 0` and `h` is undefined (undefined value of `h` means the array is empty.).
    + `!n&!h` check both `n` and `h` are falsy. As `n` may only be integers, it would be `0`. `h` may be integers or undefined. But if `h === 0`, `n >= h` is true, the `??` operator short circuit current expression. As the result, we know `h` is undefined.
> 1 votes

# Answer
# Charcoal, 17 bytes

```
≔…¹ＬηζＩ÷Π⁺ζ⁻θΣηΠζ

```

Try it online! Link is to verbose version of code. Explanation: Based on the OP's formula.

```
≔…¹Ｌηζ

```

Get the exclusive range from `1` to `k`.

```
Ｉ÷Π⁺ζ⁻θΣηΠζ

```

Subtract the sum of `xᵢ` from `N`, add it element-wise to the the range, take the product, and divide by the product of the range. This is equivalent to calculating the number of combinations.
> 0 votes

---
Tags: code-golf, combinatorics, integer-partitions
---


title: Loading Forever... Windows style

text:
# Question
Title: Loading Forever... Windows style
Make a Windows style Loading bar by the following instructions.

(notice that this is different than Loading... Forever)

Your output should start by `[.... ]`.

Every tick, you should wait 100 ms, then move each dots by one character right. if the dot is on the tenth character, move it to the first. Notice that you should clear the screen before outputting again. The output is ordered as the following:

```
[....      ]
[ ....     ]
[  ....    ]
[   ....   ]
[    ....  ]
[     .... ]
[      ....]
[.      ...]
[..      ..]
[...      .]

```

..Then it loops forever.

# Rules

* This is , so the shortest answer wins I doubt I would even accept a winning answer tho
* Please provide a gif file of the loading bar in action if possible.

# Answer
# V, ~~17~~ ~~16~~ 15 bytes

```
i[´.¶ ]<esc>ògó$X|p

```

`<esc>` is `0x1b`.

And the hexdump:

```
00000000: 695b b42e b620 5d1b f267 f324 587c 70    i[... ]..g.$X|p

```

### Explanation

```
i                       " Insert
[                       " a [
´.                      " 4 .s
¶<space>                " 6 spaces
]<esc>                  " and a ]. Then return to normal mode
ò                       " Recursively do:
 gó                     "  Sleep for 100 milliseconds
 $                      "  Go to the ]
 X                      "  Delete the character to the left of the ]
 |                      "  Go to the [
 p                      "  And paste the deleted character right after the [
                        " Implicit ending ò

```
> 19 votes

# Answer
## CSS/HTML, ~~202~~ ~~190~~ 186 + 45 = ~~247~~ ~~235~~ 231 bytes

```
pre{position:relative}x{position:absolute;display:inline-block;width:10ch;height:1em;overflow:hidden}x>x{width:14ch;left:-10ch;animation:1s steps(10,end)infinite l}@keyframes l{to{left:0
```

```
<pre>[<x><x>....      ....</x></x>          ]
```

Edit: Saved ~~12~~ 14 bytes thanks to @Luke.
> 19 votes

# Answer
# PowerShell, ~~67~~ 66 Bytes

```
for($s='.'*4+' '*6;$s=-join($s[,9+0..8])){cls;"[$s]";sleep -m 100}

```

-1 by using shortened constructor thanks to Beatcracker

replaces the string with a copy of the string where the last char is put in front of the remaining chars, clears the screen, prints it, and then sleeps for 100 ms.

saved a lot of bytes by using the for loop constructor rather than wrap the logic inside the string.
> 12 votes

# Answer
# Python 3, ~~99~~ ~~93~~ ~~85~~ 83+2 (-u flag) bytes

-12 bytes thanks to ovs
-2 bytes thanks to totallyhuman

```
import time
s=4*'.'+6*' '
while 1:print(end='\r[%s]'%s);time.sleep(.1);s=s[9]+s[:9]

```

Try it online!
> 10 votes

# Answer
# Windows batch , ~~201~~ 181 bytes

*Turns out using the old-school method actually saves bytes!*

```
@for %%p in ("....      " " ....     " "  ....    " "   ....   " "    ....  " "     .... " "      ...." ".      ..." "..      .." "...      .")do @echo [%%~p]&timeout 0 >nul&cls
@%0

```

---

Note:

```
get-screenrecorder.level
- low grade

get-gpu.level
- horrible

if get-screenrecorder.level == low grade || get-gpu.level == horrible {
     say("GIF may not be accurate");
}

```

Please note that my GIF recorder skipped a few frames, making the loading bar jumps `:(`
> 10 votes

# Answer
## Mathematica, ~~67~~ 77 Bytes

+10 Bytes as I forgot the square brackets.

```
Animate["["<>"....      "~StringRotateRight~n<>"]",{n,1,10,1},RefreshRate->10]

```
> 8 votes

# Answer
# C (gcc), ~~126~~ ~~125~~ ~~124~~ ~~123~~ ~~122~~ ~~121~~ ~~119~~ ~~118~~ ~~117~~ ~~114~~ 115 bytes

This one uses a bitmask to keep track of where the dots are.

I had to add another byte as I was only outputting 5 spaces before.

```
m=30;f(i){usleep(3<<15);system("clear");for(i=1;i<1920;i*=2)putchar(i^1?i&m?46:32:91);m+=m&512?m+1:m;f(puts("]"));}

```

Try it online!
> 8 votes

# Answer
# Javascript (ES6), 86 bytes

```
setInterval('with(console)clear(),log(`[${x=x[9]+x.slice(0,9)}]`)',100,x='...      .')
```
> 8 votes

# Answer
# JavaScript (ES6) + HTML, ~~104~~ ~~85~~ 83 bytes

```
f=(s="....      ")=>setTimeout(f,100,s[9]+s.slice(0,9),o.value=`[${s}]`)
<input id=o

```
* Saved 2 bytes thanks to Johan's suggestion that I use an `input` instead of a `pre`.

---

## Try It

Requires a closing `>` on the `input` tag in order to function in a Snippet.

```
(f=(s="....      ")=>setTimeout(f,100,s[9]+s.slice(0,9),o.value=`[${s}]`))()
```

```
<input id=o>
```
> 5 votes

# Answer
# Noodel, ~~16~~ ~~15~~ ~~14~~ 13 bytes

~~\[ CỤ‘Ṁ~ððÐ\]ʠḷẸḍt~~

~~\]ʠ\[Ð.×4¤×6⁺ḷẸḍt~~

~~\]ʠ⁶¤⁴.ȧ\[ėÐḷẸḍt~~

Try it:)

---

## How it works

```
]ʠ⁶¤⁴.ȧ[ėÐḷẸḍt

]ʠ⁶¤⁴.ȧ[ėÐ     # Set up for the animation.
]              # Pushes the literal string "]" onto the stack.
 ʠ             # Move the top of the stack down by one such that the "]" will remain on top.
  ⁶¤           # Pushes the string "¤" six times onto the stack where "¤" represents a space.
    ⁴.         # Pushes the string "." four times onto the stack.
      ȧ        # Take everything on the stack and create an array.
       [       # Pushes on the string literal "[".
        ė      # Take what is on the top of the stack and place it at the bottom (moves the "[" to the bottom).
         Ð     # Pushes the stack to the screen which in Noodel means by reference.

          ḷẸḍt # The main animation loop.
          ḷ    # Loop endlessly the following code.
           Ẹ   # Take the last character of the array and move it to the front.
            ḍt # Delay for a tenth of a second.
               # Implicit end of loop.

```

---

## Update

```
[Ð]ıʠ⁶¤⁴.ḷėḍt

```

Try it:)

Don’t know why this took me a while to think of. Anyways, this places it at **13 bytes**.

```
[Ð]ıʠ⁶¤⁴.ḷėḍt

[Ð]ıʠ⁶¤⁴.     # Sets up the animation.
[             # Push on the character "["
 Ð            # Push the stack as an array (which is by reference) to the screen.
  ]           # Push on the character "]"
   ı          # Jump into a new stack placing the "[" on top.
    ʠ         # Move the top of the stack down one.
     ⁶¤       # Push on six spaces.
       ⁴.     # Push on four dots.

         ḷėḍt # The main loop that does the animation.
         ḷ    # Loop the following code endlessly.
          ė   # Take the top of the stack and put it at the bottom.
           ḍt # Delay for a tenth of a second.

```

```
<div id="noodel" code="[Ð]ıʠ⁶¤⁴.ḷėḍt" input="" cols="12" rows="2"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 5 votes

# Answer
# MATL, 24 bytes

```
`1&Xx'['897B@YS46*93hhDT

```

Try it at **MATL Online!** Or see a gif from the offline compiler:

### Explanation

```
`        % Do...while
  1&Xx   %   Pause for 0.1 s and clear screen
  '['    %   Push this character
  897B   %   Push [1 1 1 0 0 0 0 0 0 1]
  @      %   Push current iteration index, 1-based
  YS     %   Circularly shift the array by that amount
  46*    %   Multiply by 46 (code point of '.')
  93     %   Push 93 (code point of ']')
  hh     %   Concatenate horizontally twice. Numbers are interpreted as chars
         %   with the corresponding code points
  D      %   Display
  T      %   Push true. Used as loop condition. Results in an infinite loop
         % End (implicit)

```
> 4 votes

# Answer
# PHP, 67 bytes

```
for($s="...      .";$s=substr($s.$s,9,10);usleep(1e5))echo"\r[$s]";

```

no comment
> 4 votes

# Answer
# C#, 162 157 bytes

```
()=>{for(string o="[....      ]";;){o=o.Insert(1,o[10]+"").Remove(11,1);System.Console.Write(o);System.Threading.Thread.Sleep(100);System.Console.Clear();}};

```

or as whole program for 177 bytes

```
namespace System{class P{static void Main(){for(string o="[....      ]";;){o=o.Insert(1,o[10]+"").Remove(11,1);Console.Write(o);Threading.Thread.Sleep(100);Console.Clear();}}}}

```
> 4 votes

# Answer
# Jelly, ~~28~~ 27 bytes

```
ṙ©-j@⁾[]ṭ”ÆȮœS.1®ß
897ṃ⁾. Ç

```

### How?

```
ṙ©-j@⁾[]ṭ”ÆȮœS.1®ß - Link 1, the infinite loop: list of characters s
ṙ                  - rotate s left by:
  -                -   -1 (e.g. "...      ." -> "....      ")
 ©                 -   copy to the register and yield
     ⁾[]           - literal ['[',']']
   j@              - join with reversed @rguments
         ”Æ        - literal '\r'
        ṭ          - tack (append the display text to the '\r')
           Ȯ       - print with no newline ending
              .1   - literal 0.1
            œS     - sleep for 0.1 seconds then yield the printed text (unused)
                ®  - recall the value from the register
                 ß - call this link (1) again with the same arity

897ṃ⁾. Ç - Main link: no arguments
897      - literal 897
    ⁾.   - literal ['.',' ']
   ṃ     - base decompression: convert 897 to base ['.',' '] = "...      ."

```
> 4 votes

# Answer
# Pure bash, 68

```
s=${1:-....      }
printf "[$s]\r"
sleep .1
exec $0 "${s: -1}${s%?}"

```
> 4 votes

# Answer
# C (gcc), ~~202~~ ~~198~~ ~~196~~ ~~189~~ ~~96~~ ~~99~~ ~~88~~ ~~86~~ ~~79~~ ~~77~~ ~~75~~ ~~74~~ 73 bytes

Saved ~~7~~ 8 bytes thanks to Digital Trauma.

```
f(i){usleep(dprintf(2,"\r[%-10.10s]","....      ...."+i%10)<<13);f(i+9);}

```

Or, if your system's `stdout` doesn't need to be flushed after every write without a newline:

# C (gcc), 70 bytes

```
f(i){usleep(printf("\r[%-10.10s]","....      ...."+i%10)<<13);f(i+9);}

```

### How it works

* `usleep(` sleeps for the next return value in microseconds.
* `dprintf(2,` prints to file descriptor 2, or `stderr`. This is necessary because while `stdout` is line-buffered (meaning output will not show until it prints a newline), `stderr` is character-buffered (all output is shown immediately).
* `"\r` prints a carriage return (clears the current line).
* `[%-10.10s]"` is the `printf` format specifier for a string with exact length 10 (no matter what string provided the output will always be a string with length 10), padded with spaces to the right if necessary. This will be enclosed with brackets.
* `".... ...."` is the loading bar.
* `+i%10` offsets the loading bar by the current index modulo 10. For example, if `i == 3`, `i % 10` is equal to 3. Offsetting the loading bar by 3 makes it equal to `". ...."`.
* When the offset-ed string is passed to the `printf` format specifier, it limits to a length of 10 if necessary and adds spaces to the end if necessary. Therefore, the loading bar will always be between `[.... ]` and `[. ...]`.
> 4 votes

# Answer
# Python 2, ~~81~~ 78 bytes

-1 byte (noticing I missed use of `%s` when Rod submitted an almost identical Python 3 version at the same time!)
-2 bytes (using totallyhuman's idea \- replace `s[-1]+s[:-1]` with `s[9]+s[:9]`)

```
import time
s='.'*4+' '*6
while s:print'\r[%s]'%s,;s=s[9]+s[:9];time.sleep(.1)

```
> 3 votes

# Answer
# Java 7, ~~139~~ 124 bytes

```
String s="....      ";void c()throws Exception{System.out.print("["+s+"]\r");s=(s+s).substring(9,19);Thread.sleep(100);c();}

```
* Mentioning of `\r` thanks to *@Phoenix*.

The carriage return `\r` resets the 'cursor' back to the begin of the line, which can then be overwritten. Unfortunately, online compilers nor the Eclipse IDE doesn't support this, so I've added a gif at the end of this answer to show it from Windows Command Prompt.

Try it here. (Slightly modified so you won't have to wait for the time-out before viewing the result. Also, the TIO doesn't support carriage returns, so every line is printed without overwriting the previous line.)

**Explanation:**

```
String s="....      ";            // Starting String "....      " on class level
void c()                          // Method without parameter nor return-type
 throws Exception{                // throws-clause/try-catch is mandatory for Thread.sleep
  System.out.print("["+s+"]\r");  //  Print the String between square-brackets,
                                  //  and reset the 'cursor' to the start of the line
  s=(s+s).substring(9,19);        //  Set `s` to the next String in line
  Thread.sleep(100);              //  Wait 100 ms
  c();                            //  Recursive call to same method
}                                 // End of method

```

**Output gif:**
> 3 votes

# Answer
# Go, ~~150~~ ~~145~~ ~~132~~ ~~129~~ 124 bytes

*-5 bytes thanks to sudee.*

I feel like I don't see enough Go here... But my answer is topping C so... pls halp golf?

```
package main
import(."fmt"
."time")
func main(){s:="....      ";for{Print("\r["+s+"]");Sleep(Duration(1e8));s=(s+s)[9:19];}}

```

Try it online!
> 3 votes

# Answer
# VBA 32-bit, ~~159~~ ~~157~~ ~~143~~ ~~141~~ 134 Bytes

VBA does not have a built in function that allows for waiting for time periods less than one second so we must declare a function from `kernel32.dll`

**32 Bit Declare Statement (41 Bytes)**

```
Declare Sub Sleep Lib"kernel32"(ByVal M&)

```

**64 Bit Declare Statement (49 Bytes)**

```
Declare PtrSafe Sub Sleep Lib"kernel32"(ByVal M&)

```

Additionally, we must include a `DoEvents` flag to avoid the infinite loop from making Excel appear as non-responsive. The final function is then a subroutine which takes no input and outputs to the VBE immediate window.

**Immediate Window function, 93 Bytes**

Anonymous VBE immediate window function that takes no input and outputs to the range `A1` on the ActiveSheet

```
s="...      ....      .":Do:DoEvents:Sleep 100:[A1]="["&Mid(s,10-i,10)&"]":i=(i+1)Mod 10:Loop

```

### Old Version, 109 Bytes

Immediate window function that takes no input and outputs to the VBE immediate window.

```
s="...      ....      .":i=0:Do:DoEvents:Sleep 100:Debug.?"["&Mid(s,10-i,10)&"]":i=(i+1) Mod 10:Loop

```

**Ungolfted and formatted**

```
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal M&)
Sub a()
    Dim i As Integer, s As String
    s = "...      ....      ."
    i = 0
    Do
        Debug.Print [REPT(CHAR(10),99]; "["; Mid(s, 10 - i, 10); "]"
        DoEvents
        Sleep 100
        i = (i + 1) Mod 10
    Loop
End Sub

```

*-2 Bytes for removing whitespace*

*-30 Bytes for counting correctly*

*-14 Bytes for converting to immediate window function*

**Output**

*The gif below uses the full subroutine version because I was too lazy to rerecord this with the immediate window function.*
> 3 votes

# Answer
# Perl, 69 bytes

*-3 bytes thanks to @Dom Hastings.*

```
$_="....".$"x6;{print"\ec[$_]
";select$a,$a,!s/(.*)(.)/$2$1/,.1;redo}

```

That `select undef,undef,undef,.1` is the shortest way to sleep less than 1 second in Perl, and it takes a lot of bytes...

---

Slightly longer (79 bytes), there is:

```
@F=((".")x4,($")x6);{print"\ec[",@F,"]\n";@F=@F[9,0..8];select$a,$a,$a,.1;redo}

```
> 2 votes

# Answer
# 05AB1E, 23 bytes

```
'.4×ð6×J[D…[ÿ],Á¶т×,т.W

```

Try it online!

**Explanation**

```
'.4×ð6×J                  # push the string "....      "
        [                 # forever do:
         D                # duplicate
          …[ÿ],           # interpolate the copy between brackets and print
               Á          # rotate the remaining copy right
                ¶т×,      # print 100 newlines
                    т.W   # wait 100ms

```
> 2 votes

# Answer
# Bash, ~~93~~ ~~90~~ 96 bytes

```
s="...      ....      ."
for((;;)){ for i in {0..9};do printf "\r[${s:10-i:10}]";sleep .1;done;}

```

view here

couldn't get nested { } in for syntax
> 2 votes

# Answer
# Ruby, ~~57~~ 56 bytes

```
s=?.*4+' '*6;loop{$><<"[%s]\r"%s=s[-1]+s.chop;sleep 0.1}

```

Heavily influenced by other answers here.

Saved a byte thanks to @manatwork. Also apparently I have trouble counting characters -- I use ST3 and apparently it will include newlines in the count of characters in the line if you're not attentive.
> 2 votes

# Answer
# Batch, ~~99~~ 98 bytes

*Saved 1 byte thanks to SteveFest!*

(I could remove `\r` from the code, but in the spirit of batch golfing, I won't.)

```
@SET s=....
:g
@CLS
@ECHO [%s%]
@SET s=%s:~-1%%s:~,-1%
@ping 0 -n 1 -w 100>nul
@GOTO g

```

There are four spaces after the first line.

The main logic is modifying the string. `%s:~-1%` is the last character of `%s%` and `%s:~0,-1%` is all but the last character of `%s%`. Thus, we are moving the last character to the front of the string, which rotates the string.
> 2 votes

# Answer
# Groovy, 72 bytes

```
s="*"*4+" "*6
for(;;){print("["+s+"]"+"\n"*20);s=s[9]+s[0..8];sleep 100}

```

**Explaination**

```
s="*"*4+" "*6 //creates the string "****      "
for(;;){ //classic infinite loop
    print("["+s+"]"+"\n"*20) //prints the string with [ at the beginning and ] at the end. After that some newlines
    s=s[9]+s[0..8] //appends the final char of the string to beginning, creating a cycling illusion
    sleep 100 //100 ms delay
}

```
> 1 votes

# Answer
# Haskell (Windows), 159 bytes

```
import System.Process
import Control.Concurrent
main=mapM id[do system"cls";putStrLn('[':["....      "!!mod(i-n)10|i<-[0..9]]++"]");threadDelay(10^5)|n<-[0..]]

```

Explanation

```
mapM id             sequentially perform each IO action in the following list
[                   start a list comprehension where each element is...
  do                  an IO operation where
    system "cls";       we clear the screen by calling the windows builtin "cls"
    putStrLn(           then display the string...
      '[':                with '[' appended to
      [                   a list comprehension where each character is...
        "....      "!!       the character in literal string "....      " at the index
        mod(i-n)10          (i - n) % 10
      |i<-[0..9]]         where i goes from 0 to 9
      ++"]"             and that ends with ']'
    );
    threadDelay(10^5)   then sleep for 100,000 microseconds (100 ms)
|n<-[0..]]          where n starts at 0 and increments without bound

```

Haskell's purity made generating the cycling dot pattern somewhat complex. I ended up creating a nested list comprehension that generated an infinite list of strings in the order they should be output, then went back added the appropriate IO operations.
> 1 votes

# Answer
# Ruby, 61 bytes

If the spec were for the dots to scroll left instead of right, it would save 1 byte because `rotate!` with no arguments shifts the array once to the left.

```
s=[?.]*4+[' ']*6
loop{print ?[,*s,"]\r";s.rotate!9;sleep 0.1}

```
> 1 votes

# Answer
# GNU sed (with exec extension), 64

Score includes +1 for `-r` flag.

```
s/^/[....      ]/
:
esleep .1
s/[^. ]*(.+)(.)].*/\c[c[\2\1]/p
b

```
> 1 votes

# Answer
# c, 100

```
char *s="....      ....     ";main(i){for(i=0;;i=(i+9)%10)dprintf(2,"[%.10s]\r",s+i),usleep(3<<15);}

```
> 1 votes

# Answer
# S.I.L.O.S, 282 bytes

```
canvas # #
def # 1000 ! Obj N new M move > 10
newObj 0 # #
pen 255 255 255
N! 0 > >0
M! 1 > >
N! 0 > >0
M! 2 560 >
x=8
lblx
x-1
N! 0 > >
if x x
M! 3 20 >
M! 4 20 >0
M! 5 550 >
M! 6 550 >0
lbla
x=4
lbly
A=6+x
B=60+50*(((x-1)+a)%>)
M! A B 50
x-1
if x y
refresh
a+1
a%>
wait >0
GOTO a

```

TIO currently does not support graphical output, but the official interpreter does. I think this is the first time I have gotten a chance to test out the graphical output functionality of SILOS.
> 1 votes

# Answer
# shortC, ~~85~~ ~~72~~ ~~71~~ ~~66~~ ~~65~~ 64 bytes

```
f(i){Udprintf(2,"\r[%-10.10s]","....      ...."+i%10)<<13);f(i+9

```

Explanation:

```
f(i){                                                           function that takes integer
     U                                                          sleep
      dprintf(2,                                                print unbuffered
                "\r[%-10.10s]",                                 string with exactly 10 characters, wrapped with spaces
                               "....    ...."                   a string that, when printed with exactly 10 characters, will always have output that is in the loading screen
                                             +i%10              scroll through the string
                                                  )<<13);       sleep 10<<13 microseconds
                                                         f(i+9  recursion :D

```
> 1 votes

# Answer
# Japt, ~~31~~ 22 bytes

*Saved 9 bytes thanks to @obakaron*

```
Li@O¬OpT=T?Té :'.²²+6î

```

Try it online!
> 1 votes

# Answer
# TI-Basic (TI-84 Plus CE), 58 bytes

```
"....      (6 spaces)
Ans+Ans
While 1
For(X,11,2,-1
ClrHome
Disp "["+sub(Ans,X,10)+"]
Wait .1
End
End

```
> 1 votes

# Answer
# APL (Dyalog), 44 bytes

```
{∇r⊣⎕DL.1⊣⎕←⎕TC[20⍴2],1⌽'][',r←¯1⌽⍵}10↑4⍴'.'

```

Try it online with a slightly modified version: `⎕←` replaced by `∆_` which outputs with timestamps.

`4⍴'.'` four periods

`10↑` take the first ten characters of that (pads with spaces)

`{``}` apply the following function

`¯1⌽` rotate one character from the tail to the head

`r←` assign that to *r*

`'][',` prepend the brackets

`1⌽` rotate one character from the head to the tail

`⎕TC[``]` index the list of **T**erminal **C**ontrol characters with

`20⍴2` twenty repetitions of the number two (the second element is the newline)

`⎕←` output that

`.1⊣` discard that in favour of the number 0.1

`⎕DL`**D**e**l**ay that many seconds (returns elapsed time)

`r⊣` discard that in favour of *r* (which is then returned by the function)

recurse (tail calls do not work up a stack, and can thus be repeated forever)
> 1 votes

# Answer
# Haskell, 132 bytes

```
import Control.Concurrent
main=mapM_(\x->putStrLn("\27[H\27[J["++x++"]")>>threadDelay(10^5))$iterate(\x->last x:init x)"....      "

```

First, we define a function `r` to rotate a string to the right. We begin with `".... "` and construct an infinite list of its right-rotations, then for each `x` of these, print:

* An ANSI escape sequence to clear the screen,
* A left-bracket,
* `x` itself,
* A right-bracket,
* And a newline character so the terminal will flush.

Then `threadDelay` waits 100000 microseconds before continuing onto the next element.

Since we are applying these operations to an infinite list, it will continue forever.
> 1 votes

# Answer
# VBA (Excel), 109 bytes

Using Immediate Window and `Cell A1` as output

```
a="...      .":Do:b=Right(a,1):a=b &Left(a,9):[A1]="["& a &"]":c=Timer+.1:Do While Timer<c:DoEvents:Loop:Loop

```
> 1 votes

# Answer
# CJam, 39 bytes

```
'.4*S6*+{_a`'"-oDcoes{es1$m100<}g;1m>}h

```

Can't make a GIF right now...

**How it works**

```
'.4*S6*+       e# Push a string containing 4 dots and 6 spaces
{              e# Do:
 _             e#  Copy the string
 a`            e#  Wrap it in an array and take its string representation: ["....      "]
 '"-           e#  Remove quote characters from it: [....      ]
 o             e#  Print it
 Dco           e#  Print a carriage return (ASCII 13), moving the cursor back to the start
 es            e#  Push the current time in milliseconds
 {es1$m100<}g  e#  Loop until the current time is at least 100 more than that time
 ;             e#  Delete the old time
 1m>           e#  Rotate the string 1 space to the right
}h             e# Repeat while the TOS is truthy. The string being printed is non-empty, so
               e#   it is always truthy, and will repeat forever.

```
> 0 votes

# Answer
# Pyth, 28 bytes

```
J+*4\.*6d#.d.1p"\r"pj=.>J1`Y

```
> 0 votes

# Answer
# Perl 6, 61 bytes

```
$_='....      ';loop {"^M[$_]".print;s/(.*)(.)/$1$0/;sleep .1}

```

(That `^M` is a single carriage return character.)

I really tried to base the output on a lazy infinite list, but couldn't nearly approach the terseness of this solution.
> 0 votes

# Answer
## C, ~~74~~ 73 bytes

```
i;f(){usleep(printf("\r[%-10.10s]","....      ...."+i%10)*7692);f(i+=9);}

```

Modified and improved version of https://codegolf.stackexchange.com/a/120321.

Displays correct output on MinGW.
> 0 votes

# Answer
## C, ~~98~~ 93 Bytes

```
main(){char b[]="x...      .";for(;;)*b=b[10],usleep(12<<printf("\r[%s]",memcpy(b+1,b,10)));}

```

View Video
> 0 votes

# Answer
# Octave, 71 bytes

```
s="...       ."';do;printf('[%s]\r',s=circshift(s,1));pause(.1);until 0

```

For once my Octave answer is not MATLAB compatible. Specifically this solution uses

* Both `"` and `'` for quotes, to transpose a string
    + MATLAB: `('asd')'`
    + Octave: `"asd"'`
* Octave specific `do ... until 0` structure, one char shorter than `while 1 ... end`
* Octave's `printf`,one char shorter than the `fprintf` in MATLAB
> 0 votes

# Answer
# C, 91 bytes

```
main(i){for(char*s="....      ....    ";;i+=9)usleep(dprintf(2,"[%.10s]\r",s+i%10-1)<<13);}

```

If it doesn't have to begin at the left: (89 bytes)

```
main(i){for(char*s="....      ....    ";;i+=9)usleep(dprintf(2,"[%.10s]\r",s+i%10)<<13);}

```
> 0 votes

# Answer
## R, 100 bytes

```
z="....      "
repeat{flush.console()
cat("\r[",z,"]",sep="")
z=sub("(.)(.+)(.)","\\3\\1\\2",z)
Sys.sleep(.1)}

```
> 0 votes

# Answer
# F# (Mono), ~~122~~ ~~114~~ ~~118~~ 110 bytes

```
let rec t s=printf"[%s]\r"s;System.Threading.Thread.Sleep(100);t((string s.[8])+s.Substring(0,8))
t"      ..."

```

Try it online!
> 0 votes

# Answer
# JS (ES6), 179 bytes

```
x=`[....      ]
[ ....     ]
[  ....    ]
[   ....   ]
[    ....  ]
[     .... ]
[      ....]
[.      ...]
[..      ..]
[...      .]`.split`
`;c=0;setTimeout(y=>alert(x[++c]),100)

```
> 0 votes

# Answer
# Powershell, 64 bytes

```
for(){cls;"[$('...      .'*2|% s*g(9-$i++%10)10)]";sleep -m 100}

```

Where `$string|% s*g $From $Length` is a shortcut to summon `$string.SubString($From,$Length)`

This solution has one small disadvantage:

* there will be an overflow exception after the Windows style Loading bar has worked for 988 million years.

# Powershell, 65 bytes

```
for(){9..0|%{cls;"[$('...      .'*2|% s*g $_ 10)]";sleep -m 100}}

```

This Windows style Loading bar is an Immortal Eldar from Valinor.
> 0 votes

# Answer
# Japt, 22 bytes

```
Oq"[{'.²²úA éU°}]"Lt@ß

```

Test it
> 0 votes

# Answer
# Stax, 18 bytes

```
Θo░a↑▐»xr←9hV╣ä&N╞

```

Run and debug it
> 0 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity, animation
---


title: The sea in your terminal

text:
# Question
Title: The sea in your terminal
### Background

Summer is well over in the Northern Hemisphere, and a lot of us miss the sun, the beaches, the waves of the ocean... This challenge aims at cheering them up by reminding them of the sea.

### The challenge

Here is the sea :

```
             **              **              **              **              **
         ****            ****            ****            ****            ****
      *****           *****           *****           *****           *****
    **   **         **   **         **   **         **   **         **   **
  **      **      **      **      **      **      **      **      **      **
**          ******          ******          ******          ******          ****

```

The sea is made of 5 times this wave pattern :

```
            **
        ****
     *****
   **   **
 **      **
*          *****

```

Note that the pattern is 16 characters long, and the sea is 5 times this pattern = 80 characters long.

Which you can print into a terminal using this command-line :

```
perl -e 'print "            **  \n        ****    \n     *****      \n   **   **      \n **      **     \n*          *****\n"'

```

Or this one :

```
perl -e 'print " "x12, "*"x2, " "x2, "\n", " "x8, "*"x4, " "x4, "\n", " "x5, "*"x5, " "x6, "\n", " "x3, "*"x2, " "x3, "*"x2, " "x6, "\n", " "x1, "*"x2, " "x6, "*"x2, " "x5, "\n", "*"x1, " "x10, "*"x5, "\n"'

```

(The second one should make it easier for you to get the exact pattern)

Your task is to display the sea in a terminal, and make look like the waves are moving toward the right : it needs to shift to the right at a speed of 1 character each 100ms (= 10 times each seconds). No character should be printed after the 80th column, but as the rightmost wave disappears, a new one appears on the left.
Here is an example of output :

time = 0.0s

```
             **              **              **              **              **
         ****            ****            ****            ****            ****
      *****           *****           *****           *****           *****
    **   **         **   **         **   **         **   **         **   **
  **      **      **      **      **      **      **      **      **      **
**          ******          ******          ******          ******          ****

```

time = 0.1s

```
              **              **              **              **              **
          ****            ****            ****            ****            ****
       *****           *****           *****           *****           *****
     **   **         **   **         **   **         **   **         **   **
   **      **      **      **      **      **      **      **      **      **
***          ******          ******          ******          ******          ***

```

time = 0.2s

```
*              **              **              **              **              *
           ****            ****            ****            ****            ****
        *****           *****           *****           *****           *****
      **   **         **   **         **   **         **   **         **   **
    **      **      **      **      **      **      **      **      **      **
****          ******          ******          ******          ******          **

```

time = 0.3s

```
**              **              **              **              **
            ****            ****            ****            ****            ****
         *****           *****           *****           *****           *****
       **   **         **   **         **   **         **   **         **   **
     **      **      **      **      **      **      **      **      **      **
*****          ******          ******          ******          ******          *

```

time = 0.4s

```
 **              **              **              **              **
*            ****            ****            ****            ****            ***
          *****           *****           *****           *****           *****
        **   **         **   **         **   **         **   **         **   **
      **      **      **      **      **      **      **      **      **      **
******          ******          ******          ******          ******

```

Of course, each output should replace the previous one.

You can run this code into a unix terminal to see how it should look with the animation:

```
perl -M5.010 -MTime::HiRes=sleep -E '@arr=([($")x12,($n="*")x2,($")x3],[($")x8,($n)x4,($")x4],[($")x5,($n)x5,($")x6],[($")x3,($n)x2,($")x3,($n)x2,($")x6],[($")x1,($n)x2,($")x6,($n)x2,($")x5],[($n)x1,($")x10,($n)x5]);while(++$j){for$i(0..5){for$k(0..15) {$out[$i][16*$_+$k]=$arr[$i][($k-$j)%16]for 0..4}}say"\e[H",$/,join$/,map{join"",@$_}@out;sleep 0.1}'

```

(Note that this code isn't very well golfed: I just made it compact enough to be convenient to run in a terminal.)

### Winning criterion

This is codegolf, so shortest code in byte wins.

# Answer
# MATL, ~~41~~ 40 bytes

```
`'3SJp/B@Tc`@+ara'F'* 'Za6el&Xx80:@-Z)DT

```

Example run:

Or try it at **MATL Online!** (the actual speed may depend on server load).

### How it works

```
`                    % Do...while
  '3SJp/B@Tc`@+ara'  %   Compressed string (actually it's just a change of base)
  F                  %   Push false. Indicates base-95 input alphabet for decompression
  '* '               %   Push this string, which defines output alphabet
  Za                 %   Base conversion. This decompresses the string
  6e                 %   Reshape as a 6-row char array. This gives the basic pattern
  l&Xx               %   Pause 0.1 seconds and clear screen
  80:                %   Push array [1 2 ... 80]
  @-                 %   Subtract iteration index to each element of that array. This
                     %    will produce the rotation via modular indexing
  Z)                 %   Use as column index. Indexing is modular, so this repeats
                     %   (and rotates) the pattern
  D                  %   Display
  T                  %   True. Loop condition for infinite loop
                     % Implicit end

```
> 17 votes

# Answer
## JavaScript (ES6) + HTML, ~~151~~ 143 + 10 = ~~161~~ 153 bytes

```
a=[48,15,57347,6147,1542,504];setInterval("a=a.map(n=>{for(x=-1;++x<80;)s+=' *'[n>>x%16&1];s+=`\n`;return n>>>15|n<<1},s='');O.innerHTML=s",99)
```

```
<pre id=O>
```
> 17 votes

# Answer
# HTML + CSS, 70 + ~~181~~ 175 = 245 bytes

Makes use of `text-shadow`, `rtl` text and CSS keyframe animations.

```
a{display:flex;overflow:hidden;width:80ch}pre{text-shadow:16ch 0,32ch 0,48ch 0,64ch 0,80ch 0;direction:rtl;animation:w steps(16)1.6s infinite}@keyframes w{0%{margin-left:-16ch
```

```
<a><pre>**
  ****
    *****
    **   **
   **      **
***          ***
```
> 16 votes

# Answer
# C# 450 444 425 417 Bytes

*399 without `using System.Linq;` but I'm sure that would be cheating...*

*Edit: Saved 25 Bytes thanks to @Cyoce*

Golfed:

```
void S(){Func<string,string>r=a=>string.Concat(Enumerable.Repeat(a,5));Func<string,int,string>s=(b,i)=>(b.Substring(16-i)+b).Substring(0,80);int p=0;for(;;){Console.Clear();Console.WriteLine(string.Join("\r\n",new string[]{s(r("            **  "),p),s(r("        ****    "),p),s(r("     *****      "),p),s(r(" **      **     "),p),s(r("*          *****"),p),}));Thread.Sleep(100);p++;if(p==16)p=0;}}

```

Ungolfed:

```
public void S()
{
  Func<string, string> r = a => string.Concat(Enumerable.Repeat(a, 5));
  Func<string, int, string> s = (b, i) => (b.Substring(16 - i) + b).Substring(0, 80);

  int p = 0;
  for(;;)
  {
    Console.Clear();
    Console.WriteLine(
      string.Join("\r\n", new string[]
    {
      s(r("            **  "), p),
      s(r("        ****    "), p),
      s(r("     *****      "), p),
      s(r(" **      **     "), p),
      s(r("*          *****"), p),})
      );
    Thread.Sleep(100);
    p++;

    if (p == 16)
      p = 0;
  }
}

```
> 9 votes

# Answer
# V, ~~98~~ ~~97~~ 73 bytes

*Thanks to @nmjcman101 for saving 24 bytes!*

```
i¹ ³ **
¸ ´*´
µ µ*¶
³ **³ **¶
 **¶ **µ
*± µ*<ESC>{<C-v>}y4pò:sl100m
$<C-v>}x|Pò

```

This contains a lot of unprintables, so here's an xxd hexdump:

```
0000000: 69c2 b920 c2b3 202a 2a20 200a c2b8 20c2  i.. .. **  ... .
0000010: b42a c2b4 200a c2b5 20c2 b52a c2b6 200a  .*.. ... ..*.. .
0000020: c2b3 202a 2ac2 b320 2a2a c2b6 200a 202a  .. **.. **.. . *
0000030: 2ac2 b620 2a2a c2b5 200a 2ac2 b120 c2b5  *.. **.. .*.. ..
0000040: 2a1b 7b16 7d79 3470 c3b2 3a73 6c31 3030  *.{.}y4p..:sl100
0000050: 6d0a 2416 7d78 7c50 c3b2 0a              m.$.}x|P...

```

### Edit

1. Used `y$` instead of `<C-v>$y`
2. A lot of changes

* Instead of copying each line and pasting them 4 times, I first generate the wave and then copy the whole thing and paste it 4 times
    * Used `{` and `}` to save few bytes
    * Used `ò` instead of registers to create the infinite loop (for some reason I have to include a `ò` at the end for it to work)
    * fixed the static `*` at the bottom

### Mini-Explanation

I'm using `<alt-n>` to create copies of strings. For example, `<alt-5>*` (this looks like `µ5`) makes `5` copies of `*` in insert mode. This I found to be shorter than copying the string and using a regex to do the necessary replacements. After creating one wave, I paste it to create the other waves. Finally, I loop recursively using `ò` to create the infinite loop (with a delay of `100ms`).

### Gif

Most of the code is dedicated towards creating the wave, so I'm still trying to golf this. Note that this code will not work on TIO since TIO only outputs the output after the code has finished execution. So here's a gif (sorry for the low quality, I had to use a website to convert a `.mov` to a `.gif`, also the `>_` that keeps popping up in the right is the Terminal icon on my mac's dock):
> 7 votes

# Answer
## Batch, 424 bytes

```
@echo off
set f=
set a=%f%%f%  **
set b=%f%   ****
set c=%f%***** %f%
set d=   **   ** %f%
set e= **%f% **%f%
set f=*%f%%f%*****
set a=%a%%a%%a%%a%%a%%b%%b%%b%%b%%b%%c%%c%%c%%c%%c%%d%%d%%d%%d%%d%%e%%e%%e%%e%%e%%f%%f%%f%%f%%f%
:l
cls
echo %a%
set a=%a:~79,1%%a:~0,79%%a:~159,1%%a:~80,79%%a:~249,1%%a:~160,79%%a:~319,1%%a:~240,79%%a:~399,1%%a:~320,79%%a:~-1%%a:~-80,79%
ping>nul 1.1 -n 1 -w 100
goto l

```

Some lines have trailing spaces. Requires a standard 80-column terminal. The timing isn't very accurate, but it's the best you can do in Batch.
> 6 votes

# Answer
# Racket 395 374 373 367 364 351 bytes

Uses an external library for screen clearing
Edit: Saved 21 bytes by not defining `w` and inlining the function.
Edit2: Saved 1 byte by removing a space.
Edit3: Saved 6 bytes by renaming `loop` to `p`, thanks @rnso!
Edit4: Putting substring in the let saving 3 bytes.
Edit5: Remove `#lang racket`, which isn't needed in the interpreter.

Golfed: 351 bytes

```
[require[planet neil/charterm:3:0]][let p([n 1])[with-charterm[void[charterm-clear-screen]]][for([i'["            **  ""        ****    ""     *****      ""   **   **      "" **      **     ""*          *****"]])[let([g substring][x[string-join[make-list 5 i]""]])[displayln[string-append[g x[- 16 n]][g x 0[- 16 n]]]]]][sleep .1][p[modulo[+ n 1]16]]]

```

Scrolling (no clear): 272 bytes

```
[let p([n 1])[for([i'["            **  ""        ****    ""     *****      ""   **   **      "" **      **     ""*          *****"]])[let([g substring][x[string-join[make-list 5 i]""]])[displayln[string-append[g x[- 16 n]][g x 0[- 16 n]]]]]][sleep .1][p[modulo[+ n 1]16]]]

```

Ungolfed:

```
#lang racket
[require [planet neil/charterm:3:0]]
[define w
'[
"            **  "
"        ****    "
"     *****      "
"   **   **      "
" **      **     "
"*          *****"]]
[define (rotmul count)
  [for ([i w])
    [let ([x [string-join [make-list 5 i] ""]])
      [displayln [string-append [substring x count]
                                [substring x 0 count]]]]]]

[let loop ([n 1])
  [with-charterm
   [void [charterm-clear-screen]]]
  [rotmul [- 16 n]]
  [sleep .1]
  [loop [modulo [+ n 1] 16]]]

```
> 6 votes

# Answer
# PowerShell 3.0, ~~183~~ ~~182~~ 173 bytes

Requires PS 3.0 for binary shift operators. Slimmed to 173 bytes with AdmBorkBork's help!

```
$w=12,240,1984,6336,24672,32799
for(){0..5|%{'{0:D16}'-f+[Convert]::ToString(([uint16]$o=$w[$_]),2)*5-replace0,' '-replace1,'*'
$w[$_]=$o-shr1-bor$o-shl15}
sleep -m 100
cls}

```
> 4 votes

# Answer
# Bash+coreutils, 172 148 bytes

*24 bytes saved thanks to @zeppelin, many thanks*

```
while :
do clear
cut -c$[i=i%16+1]-$[79+i] <(base64 -d<<<4AJFACddABVgf2dnw+CvmeyOkhIoUJOPLK6oKkljh0+Peqi5BfrbbnDyuVkr+AA==|xz -qdFraw)
sleep .1
done

```

The first line decompresses the following pattern made of 6 consecutive waves:

```
**              **              **              **              **              **
            ****            ****            ****            ****            ****            ****
         *****           *****           *****           *****           *****           *****
       **   **         **   **         **   **         **   **         **   **         **   **
     **      **      **      **      **      **      **      **      **      **      **      **
*****          ******          ******          ******          ******          ******          *

```

Then, the loop slides an 80-bytes-wide window through that pattern.
> 3 votes

# Answer
# \*\>\<\>, ~~251~~ ~~250~~ 251 bytes (non-competing)

```
" **             "e1C0["   ****         "e1C0["     *****      "e1C0["     **   **    "e1C0["    **      **  "e1C0["****          **"e1C0[06.
52Cl2,[52C52C]R
<v0&:l
$>:@=?v1+{:}&l1-[:&$@
?!v]1->:
~R>
vDDDDDD"H;0["ooooo
>l?u1S06.O{52Cl2,[a}48C]I
ol?!R

```

Note: `"H;0["` is supposed to have ascii `27` after `[`.

Try it here! (set delay to 0ms)

I can't believe I ended up sucessfully making this. This uses the `I` and `D` instructions, which increments or decrements the selected stack. This is demonstrates that it's probably possible to do this in pure \>\<\> (minus the sleep) or a competetive \*\>\<\> answer, though probably a lot harder to do.

The online interpreter version is different simply to clear the output using a carriage return.

This is non-competing because the `I`, `D`, `C`, and `R` instructions are younger than the challenge. This is probably possible to do without those instructions, but it'd be very hard/long.

Edit: I actually managed to remove a byte, but I also noticed I measured the size wrong, so I actually gained a byte.

---

I'll do my best to break down the steps and explain what's happening here...

# Explanation

```
" **             "e2C0["   ****         "e2C0["     *****      "e2C0["     **   **    "e2C0["    **      **  "e2C0["****          **"e2C0[09.
# Copy current stack 4 times
54Cl2,[54C54C]R
# Copy stack
<v0&:l
$>:@=?v1+{:}&l1-[:&$@
?!v]1->:
~R>
# Main loop
vDDDDDD"H;0["ooooo
>l?u1S09.O{54Cl2,[a}4cC]I
# Output stack
ol?!R

```

## Table of Contents

```
Line 1 - Initialization
e2C    - Call "copy current stack 4 times"
54C    - Call "copy stack"
09.    - Jump to "main loop"
4cC    - Call "output stack" (not explained, is very simple)

```

## Initialization

Here we build the 6 lines which construct the waves. We need to repeat each string 5 times to be the correct length.

We start with 6 of these, one for each line of the wave:

```
 " **             "       push " **             " to the stack
                   e2C    call "copy current stack 4 times"
                      0[  create a new stack

```

And we enter the main loop after initialization through `09.`.

## Copy Current Stack 4 Times

This is a simple function which simply takes the current stack, and copies it 4 times. So "a" would become "aaaaa".

```
54C              call "copy stack"
   l2,[          copy half the current stack to a new stack
       54C54C    call "copy stack" twice
             ]   close the current stack, moving values to the one below
              R  return from the function

```

## Copy Stack

This copies the current stack, appending the copy to the current stack.

### Setup

Going to skip the initial `<` and invert the first line to become `l:&0v` as that's the order it gets executed in after the `<` changes the IP's direction.

```
l      push the stack length to the stack
 :&    copy the length to the register
   0   push 0 to the stack
    v  move the IP downwards, entering the loop

```

From here on out the length will be referred to as `n` and the `0` as `i`.

### Loop

```
>                        move the IP to the right
 :                       copy i
  @=?v                   pop i from the stack, if n == i, proceed to cleanup
      1+                 add 1 to i
        {:}              copy the first value of the stack to the end of the stack
           &             place n on the stack
            l1-[         open a new stack moving all values but index 0 to the new one
                :&       copy n and place it on the register
                  $@     swap i with the value on its right
                     $   swap i with n

```

### Cleanup

```
>                        move the IP to the right
 :?!v                    if i == 0 then ...
  ~R>                      remove i from the stack and return
     ]                   close the stack, appending all values to the stack below
      1-                 subtract 1 from i

```

## Main Loop

Here is where the code runs forever, constantly redrawing the waves in-between 100ms sleeps.

### Setup

```
DDDDDD                 select the 6th stack down
      "H;0[x"ooooo     move the cursor to the top-left of the term (x == ascii 27)
                  v    move the IP downwards, entering the loop

```

### Loop

```
>                          move the IP to the right
 l?u     O                 if the stack is empty ...
    1S                       sleep for 100ms
      09.                    jump to main loop initialisation
          {                shift the stack left
           54Cl2,[         copy the current stack to a new stack
                  a        append a newline to the stack
                   }       shift the stack to the right
                    4cC    call "output stack"
                       ]   close the stack
                        I  select one stack higher

```
> 3 votes

# Answer
# PHP, 128 bytes

```
for($a=[3,60,496,1584,6168,57351];;usleep(1e5))foreach($a as&$x)for($x=$x/2|$x%2<<15,$i=80;$i--;)echo" *"[$x>>$i%16&1],"\n"[$i];

```

Cannot animate more than one line, but it scrolls.
Add `,0` to the array for an empty line between iterations. Run with `-r`.
> 2 votes

# Answer
# Ruby 269 217 189 185 Bytes

*-28 Bytes thanks to @manatwork*

*-5 Bytes thanks to @ropata*

**Normal**

```
p=0
loop do
  system 'clear'
  [' '*12+'**  ', ' '*8+'****    ','     *****      ','   **   **      ',' **      **     ','*          *****'].each {|i| puts ((i*5)[16-p..-1]+i)[0..79]}
  p=-~p%16
  sleep 0.1
end

```

**Golfed**

```
p=0
b=' '
loop{system'clear'
[b*12+'**  ',b*8+'****    ',b*5+'*****'+b*6,'   **   **'+b*6,' **      **     ',"*#{b*10}*****"].map{|i|puts ((i*5)[16-p..-1]+i)[0,79]}
p=-~p%16
sleep 0.1}

```
> 2 votes

# Answer
## Mathematica, 213 bytes

```
i=0;RunScheduledTask[i++,0.1];Dynamic[RotateRight[#,i]&/@Characters/@(StringRepeat[#,5]&)/@{"            **  ","        ****    ","     *****      ","   **   **      "," **      **     ","*          *****"}//Grid]

```

I don't see any way of golfing the wave pattern in Mathematica other than just starting with a list of strings for each line. I initialize `i` to be `0` and schedule a task to increment it every `0.1` seconds. I `Dynamic`ally display the result of the following:

1. `StringRepeat` each line 5 times.
2. Convert each line into a list of its `Characters`.
3. `RotateRight` each list of characters by `i`.
4. Display the resulting array of characters as a `Grid`.
> 2 votes

# Answer
# C (unix), ~~231~~ 191 bytes

This will only work on unix environments. Also, please excuse the fact that sleep accepts only integers... so it actually delays 1second between frames.

Ungolfed version:

```
#include <stdio.h>
int main() {
    int x=0,l,i,a[6]={32799,24672,6336,1984,240,12};
    while(l=6,++x) {
        printf("\033[2J");
        while(i=128,l--) {
            while(i--) putchar(a[l]&1<<(i+x)%16 ? 42 :32);
            puts("");
        }
        sleep(1);
    }
}

```

Golfed version:

```
#include <stdio.h>
int main(){int x=0,l,i,a[6]={32799,24672,6336,1984,240,12};while(l=6,++x){printf("\033[2J");while(i=128,l--){while(i--)putchar(a[l]&1<<(i+x)%16?42:32);puts("");}sleep(1);}}

```
> 2 votes

# Answer
# Javascript (ES6), ~~152~~ ~~147~~ 145 bytes

```
x=0,c=console;setInterval(a=>{for(c.clear();f="",i=128,++x,a--;c.log(f))for(;i--;)f+=" *"[[32799,24672,6336,1984,240,12][a]>>(i+x)%16&1]},100,6);

```
> 2 votes

# Answer
## Perl 6, ~~140~~ ~~138~~ ~~137~~ ~~123~~ 120 bytes

```
for ^Inf ->\i{print "\e[H";for 12,240,1984,6336,24672,32799 ->\j{say [~] map {j+>((i-$_)%16)%2??'*'!!' '},^80};sleep .1}

```

Old solutions:

```
for ^Inf ->\i {print "\e[H";for 12,240,1984,6336,24672,32799 ->\j {say [~] map {j+>((i-$_)%16)%2??'*'!!' '},^80};sleep .1;}
my @a=12,240,1984,6336,24672,32799;for ^Inf ->\i {print "\e[H";for @a ->\j {for ^80 {print j+>((i-$_)%16)%2??'*'!!' '};say ""};sleep .1;}
my @a=12,240,1984,6336,24672,32799;for ^Inf {print "\e[H";for @a ->\j {for ^80 ->\k {print j+>(($_- k)%16)%2??'*'!!' '};say ""};sleep .1;}
my @a=12,240,1984,6336,24672,32799;for ^Inf {print "\e[H";for @a ->\j {for ^80 ->\k {print j+>(($_+15*k)%16)%2??'*'!!' '};say ""};sleep .1;}

```
> 2 votes

# Answer
# Python 3, ~~240~~ ~~239~~ 230 bytes

*-1 byte thanks to @redstarcoder*

*-9 bytes thanks to @PascalvKooten*

```
import time
def p():print("\x1b[0;H")
i=0;p();s=[' '*13+'**',' '*9+'****  ','      *****    ','    **   **    ','  **      **   ','**          ***']
while True:
 for x in s:x*=5;c=i%80;print(x[-c:]+x[:-c])
 i+=1;p();time.sleep(.1)

```
> 1 votes

# Answer
## Racket 295 bytes

```
(let*((g string-append)(h substring)(d displayln)(j(λ(l)(map(λ(x)(g(h x 1)(h x 0 1)))l))))(let p((l(map(λ(x)(apply g(for/list((i 5))x)))'("            **  ""         ****   ""      *****     ""    **   **     ""  **      **    ""*          *****"))))(for((i l))(d i))(d"")(sleep .1)(p(j l))))

```

Ungolfed:

```
(define(f)
 (define (lf l)
    (map (λ (x) (string-append (substring x 1) (substring x 0 1)))
         l))
  (let loop ((l (map (λ (x) (apply string-append (for/list ((i 5)) x)) )
                     (list
                      "            **  "
                      "         ****   "
                      "      *****     "
                      "    **   **     "
                      "  **      **    "
                      "*          *****"))))
    (for ((i l))
      (displayln i))
    (displayln "")
    (sleep 0.1)
    (loop (lf l))))

```

Testing:

```
(f)

```

Output:

(This gif file display is slower than actual output).
> 1 votes

# Answer
## Python 2, ~~207~~ 202 bytes

Usually I'm a C# developer, so this might not be completely golfed yet...

```
import time;i=0
while 5:
    print"\033[;H"
    for l in[" "*12+"**  "," "*8+"*"*4+" "*4," "*5+"*"*5+" "*6,"   **   **"+" "*6," **     "*2,"*"+" "*10+"*"*5]:print(l[16-i:]+l*5)[:80]
    time.sleep(.1);i=(i+1)%16

```
> 1 votes

# Answer
## C#, 327 bytes

More or less a ported version of my solution in Python...

```
_=>{Func<string,int,string>t=(s,j)=>(s.Substring(16-j)+string.Concat(Enumerable.Repeat(s,5))).Substring(0,80);for(var i=0;;i=++i%16){Console.Clear();foreach(var q in "            **  ,        ****    ,     *****      ,   **   **      , **      **     ,*          *****".Split(','))Console.WriteLine(t(q,i));Thread.Sleep(100);}}

```
> 1 votes

# Answer
## Perl, 110 bytes

**Requires `-E` at no extra cost. This contains unprintable characters.**

```
$_=unpack"B*","x?`00?";s!.{16}!$&x5 .$/!ge;y/01/ */;{say"\ec$_";select!s/(.+)(.)$/$2$1/mg,$a,$a,.1;redo}"

```

Create the above data using the below reversible hexdump. Run `xxd -d > sea.pl` in a linux or compatible terminal, paste the below and press `Ctrl`+`d`, then run `perl -E "$(cat sea.pl)"`.

```
0000000: 245f 3d75 6e70 6163 6b22 422a 222c 2200  $_=unpack"B*",".
0000010: 0600 7803 e00c 6030 30c0 0f22 3b73 212e  ..x...`00..";s!.
0000020: 7b31 367d 2124 2678 3520 2e24 2f21 6765  {16}!$&x5 .$/!ge
0000030: 3b79 2f30 312f 202a 2f3b 7b73 6179 225c  ;y/01/ */;{say"\
0000040: 6563 245f 223b 7365 6c65 6374 2173 2f28  ec$_";select!s/(
0000050: 2e2b 2928 2e29 242f 2432 2431 2f6d 672c  .+)(.)$/$2$1/mg,
0000060: 2461 2c24 612c 2e31 3b72 6564 6f7d       $a,$a,.1;redo}

```

### Usage

For easy copy/pasting, please use the below:

```
perl -E '$_=unpack"B*","\x00\x06\x00\x78\x03\xe0\x0c\x60\x30\x30\xc0\x0f";s!.{16}!$&x5 .$/!ge;y/01/ */;{say"\ec$_";select!s/(.+)(.)$/$2$1/mg,$a,$a,.1;redo}'

```

### Explanation

A fairly straightforward solution that stores the wave as a string at the beginning, which is `unpack`ed to binary, each section is quintuplicated, `0`s are converted to spaces and `1`s are converted to `*`s. Now we have the whole string so we enter a `redo` loop which prints out the whole string, then we wait for .1 seconds and for each line in the string, we move the last character to the beginning of the string.
> 1 votes

# Answer
## Mathematica 171 Bytes

The wave itself is data, so I'm storing a compressed version of the whole wave in my code. I can store a single wave much more compactly as `\fð߀ᣀ恠耟` using it's binary representation, but the character count overhead of uncompressing is too high\*.

Here is the code:

```
w=Uncompress@"1:eJxTTMoPSmNjYGAoZgESPpnFJcEBQIYCEtDSUlCglI9iqJYWqhJy+QhDtdCUUMCHGQrmIymiiA8xFMajEg02FMkXWmi+IosPAJNuSHg=";
Dynamic[Pause[.1];Column[w=StringRotateRight/@w]]

```

Here is the code I used to create the compressed version of the wave data:

```
s={"            **  ","        ****    ","     *****      ","   **   **      "," **      **     ","*          *****"};
s//TableForm
StringRepeat[#,5]&/@s
Compress[%]

```

Here is the code I would have preferred to use to store compressed repeating binary data like this wave:

```
StringJoin /@ (PadLeft[(IntegerDigits[#1, 2] & ) /@ ToCharacterCode["\fð߀ᣀ恠耟"]] /. {0 -> " ", 1 -> "*"})

```

As you can see, the overhead to turn the compressed data back into a string is too expensive for this particular problem, although a single wave can be stored this way with 7 UTF characters and 15 bytes.

Here was the code to determine the UTF character sequence to store a single wave (s as above).

```
StringReplace[#,{" "->"0","*"->"1"}]&/@s
ToExpression/@%
IntegerDigits/@%
FromDigits[#,2]&/@%
FromCharacterCode/@%
StringJoin@%

```
> 1 votes

# Answer
# Stax, 38 bytes

```
ç²kτ,e7rà♠Çƒ╜?║í▬u╬wπ■&Jµⁿj↨▄!=╢╡═+ZWu

```

Run and debug it

Took some shuffling around and `:B` to beat the MATL score.

## Explanation

```
. *9*"!1$'YKaK968"%13|E:B16/WcM|)Ms{|,}6*|:m5*
. *                                            " *"
   9*                                          repeat 9 times
     "!1$'YKaK968"%13|E                        compressed run lengths of wave
                       :B                      run length decode using the two arrays
                         16/                   split in groups of 16
                            W                  loop forever
                             c                 copy the wave
                              M|)M             shift right
                                  s            swap
                                   {|,}6*      wait 6 frames(0.1s at 60fps)
                                         m5*   pop, repeat each line 5 times and display

```
> 1 votes

# Answer
# HTML + JS + jQuery, 10 + 233 = 243 bytes

```
b="            **  q        ****    q     *****      q   **   **      q **      **     q*          *****".split`q`.map(x=>x.repeat(5).split``)
setInterval(a=>$("#a").text(b.map(f=>f.join``).join`\n`)+b.map(e=>e.unshift(e.pop())),100)
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- start -->
<pre id=a>
```

The JavaScript just shifts each row by 1 and changes the text every 100 ms.
> 0 votes

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


title: Tips for golfing in Whispers

text:
# Question
Title: Tips for golfing in Whispers
Whispers is February 2021's Language of the Month, so what tips do you have for golfing in it? Tips do not have to be specific to , so long as they apply to other types of challenges on the site. Tips should be at least somewhat specific to Whispers (e.g. "remove ignored code" is not an answer). Please post one tip per answer.

# Answer
> 4 votes
# Order is important

Swap lines that are referenced more frequently than other lines with less referenced lines that are referenced by a small digit number.

**Example:**

```
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> Input
>> #10
>> [10]
>> Output 11 12

```

The input is referenced twice and the line number is `10`. If this line is moved up to *line 1*. Both `10`s are replaced by `1`s. In this example 2 bytes were saved.

```
> Input
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
>> #1
>> [1]
>> Output 11 12

```

Moving *line 11* and *12* up saves another 2 bytes.

```
> Input
>> #1
>> [1]
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
>> Output 2 3

```

I wrote a script that takes a Whispers program as input and prints the optimized re-ordered program.

TIO | Github

# Answer
> 2 votes
# Use `Then` to group values into an array

`Then` is a command which takes an indefinite number of arguments and puts them in an array:

```
> "hello"
> "world"
>> Then 1 2

```

The last line here returns `['hello', 'world']`.

This can then be used with `Each` or `Select` to output things or modify them for something else.

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