title: \$n\$-perfect numbers

text:
# Question
Title: \$n\$-perfect numbers
A positive integer \\$x\\$ is an \\$n\\$-perfect number if \\$\sigma(x) = nx\\$, where \\$\sigma(x)\\$ is the divisor sum function. For example, \\$120\\$ is a \\$3\\$-perfect number because its divisors sum to \\$360\\$:

$$360 = 3\times120 = 1+2+3+4+5+6+8+10+12+15+20+24+30+40+60+120$$

and

$$926073336514623897600 = 6\times154345556085770649600 = 1+2+3+4+5+6+7+8+9+10+11+12+\dots+51448518695256883200+77172778042885324800+154345556085770649600$$

so \\$154345556085770649600\\$ is a \\$6\\$-perfect number.

You are to take an integer \\$x\\$ as input and output a value \\$n\\$, such that \\$x\\$ is an \\$n\\$-perfect number. If no such \\$n\\$ exists, you may output any consistent value that isn't a positive integer. You will never receive an input outside the bounds of your language, but your algorithm must work for arbitrarily large \\$x\\$.

This is so the shortest code in bytes wins.

Mini challenge: Beat 5 bytes in Jelly

## Test cases

```
    x -> n
    1 -> 1
    2 -> 0
    3 -> 0
    4 -> 0
    5 -> 0
    6 -> 2
   28 -> 2
  120 -> 3
  496 -> 2
  500 -> 0
  672 -> 3
30240 -> 4
154345556085770649600 -> 6

```

# Answer
# Jelly, 5 bytes

```
R×iÆs

```

Try it online!

### Explanation:

```
      - Explanation (sample for input 6)
R     - Range ([1, 2, 3, 4, 5, 6])
 ×    - Multiply by input ([6, 12, 18, 24, 30, 36])
   Æs - Divisor sum (12)
  i   - Index of divisor sum in list, else 0 (2)

```
> 9 votes

# Answer
# Husk, 4 bytes

```
¦¹ΣḊ

```

Try it online!

The last test case times out.

## Explanation

```
¦¹ΣḊ   Input is a number x.
   Ḋ   List of divisors.
  Σ    Sum.
¦      Division if divisible, 0 if not
 ¹     by x.

```

`¦` is usually just a divisibility test, but here its return value is useful.
> 9 votes

# Answer
# Brachylog, 6 bytes

```
f+;?/ℕ

```

Try it online!

### How it works

```
f+;?/ℕ
f+     the sum of the factors
  ;?/ℕ divided by the input
     ℕ is a natural number

```

Alternative version, I think is cooler, but longer:

```
f+~×[?,.]∧
f+          the sum of the factors
  ~×        unifies with the multiplication of
    [?,.]   the input and the output
         ∧  return the output

```
> 7 votes

# Answer
# 05AB1E, 7 6 bytes

```
Ý*IÑOk

```

Try it online!

Explanation:

```
Ý*IÑOk>
Ý        0-Index inclusive range of input (6 -> [1, 2, 3, 4, 5, 6])
 *       Multiply by input ([6, 12, 18, 24, 30, 36])
  IÑO    Get input -> divisors -> sum (6 -> [1, 2, 3, 6] -> 12)
     k   0-Index of divisor-sum in array or -1 if not found. ([6, >12<, 18, 24, 30, 36] -> 1)

```

I just used Sisyphus' method. This could probably be golfed down or even made more efficient, but I lack the 05AB1E knowledge to do so. Just thought I'd give it a shot to pass the time.

*-1 Byte thanks to ovs*
> 6 votes

# Answer
# C (gcc), 47 bytes

```
s,i;f(x){for(i=s=x;--i;)s+=x%i?0:i;s/=s%x*s+x;}

```

Try it online!

Returns `n` or `0`.
> 5 votes

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

*Thanks to Bubbler for pointing out I can change the output format to save a couple of bytes*

```
⍸×∘⍳⍨=1⊥∘∪⊢∨⍳

```

Try it online!

Outputs a singleton list of `n` when `n` exists, and an empty array otherwise. Finds the index of () where the sum of (`1⊥`) the divisors (`∪⊢∨⍳`) equals (`=`) a multiple of the input (`×∘⍳⍨`). I use  and `=` instead of just  to find the index because it returns an empty list when the element isn't there rather than the length of the list.
> 5 votes

# Answer
# Pyth, 15 bytes

```
&!%Jsf!%QTSQQ/J

```

Try it online!

## Explanation

```
&!%Jsf!%QTSQQ/J
   J              # set J to
    s             # sum of
     f    SQ      # filtering the range [1, input] with
      !%QT        # lambda T: not (input % T)    (divisibility test)
                  # implicit print the
&                 # short-circuiting and of
 !%J        Q     # not (J % input)
             /J   # and J / input

```
> 4 votes

# Answer
# , ~~42~~ ~~41~~ 39 bytes

*Edit: -1 byte (and, inspired by this, -2 more bytes) thanks to Robin Ryder*

```
function(x)(d=sum(1:x*!x%%1:x))/x*!d%%x

```

Try it online!

Commented:

```
perfect_n=
function(x)
 (d=            # d is the divisor sum, calculated as...
  sum(          # sum of...
   1:x*         # the values of 1..x that have...
    !           # zero values for...
     x%%1:x)    # x MOD 1..x
  )
 )/x            # output d/x...
    *!d%%x      # but only if it's an integer
                # (so d MOD x == 0)

```
> 4 votes

# Answer
# Whitespace, 153 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][S N
S _Duplicate_input][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_REACHED_ZERO][S T   S S T   S N
_Copy_0-based_2nd_input][S T    S S T   N
_Copy_0-based_1st_integer][T    S T T   _Modulo][N
T   S T N
_If_0_Jump_to_Label_ADD_TO_SUM][N
S N
N
_Jump_to_Label_LOOP][N
S S T   N
_Create_Label_ADD_TO_SUM][S N
T   _Swap_top_two][S T  S S T   N
_Copy_0-based_1st_integer][T    S S S _Add_top_two][S N
T   _Swap_top_two][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_REACHED_ZERO][S N
N
_Discard_top][S N
S _Duplicate_top][S T   S S T   S N
_Copy_0-based_2nd_input][T  S T T   _Modulo][N
T   S S S N
_If_0_Jump_to_Label_DIVISIBLE][S S S N
_Push_0][N
S N
S T
_Jump_to_Label_OUTPUT][N
S S S S N
_Create_Label_DIVISIBLE][S N
T   _Swap_top_two][T    S T S _Integer_divide_top_two][N
S S S T N
_Create_Label_OUTPUT][T N
S T _Output_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer input = STDIN as input
Integer sum = input
Integer i = input
Start LOOP:
  i = i - 1
  If(i == 0):
    Jump to Label REACHED_ZERO
  If(input % i == 0):
    sum = sum + i
  Go to next iteration of LOOP

Label REACHED_ZERO:
  Integer output
  If(sum % input == 0):
    output = sum integer-divided by input
  Else:
    output = 0

  Print output as integer to STDOUT

```

**Example run: `input = 6`**

```
Command    Explanation                       Stack         Heap   STDIN  STDOUT  STDERR

SSSN       Push 0                            [0]
SNS        Duplicate top (0)                 [0,0]
TNTT       Read STDIN as integer             [0]           {0:6}  6
TTT        Retrieve at address (0)           [6]           {0:6}
SNS        Duplicate top (6)                 [6,6]         {0:6}
SNS        Duplicate top (6)                 [6,6,6]       {0:6}
NSSN       Create Label LOOP                 [6,6,6]       {0:6}
 SSSTN     Push 1                            [6,6,6,1]     {0:6}
 TSST      Subtract top two (6-1)            [6,6,5]       {0:6}
 SNS       Duplicate top (5)                 [6,6,5,5]     {0:6}
 NTSSN     If 0: Jump to Label REACHED_ZERO  [6,6,5]       {0:6}
 STSSTSN   Copy 0-based 2nd (6)              [6,6,5,6]     {0:6}
 STSSTN    Copy 0-based 1st (5)              [6,6,5,6,5]   {0:6}
 TSTT      Modulo top two (6%5)              [6,6,5,1]     {0:6}
 NTSTN     If 0: Jump to Label ADD_TO_SUM    [6,6,5]       {0:6}
 NSNN      Jump to Label LOOP                [6,6,5]       {0:6}

 SSSTN     Push 1                            [6,6,5,1]     {0:6}
 TSST      Subtract top two (5-1)            [6,6,4]       {0:6}
 SNS       Duplicate top (4)                 [6,6,4,4]     {0:6}
 NTSSN     If 0: Jump to Label REACHED_ZERO  [6,6,4]       {0:6}
 STSSTSN   Copy 0-based 2nd (6)              [6,6,4,6]     {0:6}
 STSSTN    Copy 0-based 1st (4)              [6,6,4,6,4]   {0:6}
 TSTT      Modulo top two (6%4)              [6,6,4,2]     {0:6}
 NTSTN     If 0: Jump to Label ADD_TO_SUM    [6,6,4]       {0:6}
 NSNN      Jump to Label LOOP                [6,6,4]       {0:6}

 SSSTN     Push 1                            [6,6,4,1]     {0:6}
 TSST      Subtract top two (4-1)            [6,6,3]       {0:6}
 SNS       Duplicate top (3)                 [6,6,3,3]     {0:6}
 NTSSN     If 0: Jump to Label REACHED_ZERO  [6,6,3]       {0:6}
 STSSTSN   Copy 0-based 2nd (6)              [6,6,3,6]     {0:6}
 STSSTN    Copy 0-based 1st (3)              [6,6,3,6,3]   {0:6}
 TSTT      Modulo top two (6%3)              [6,6,3,0]     {0:6}
 NTSTN     If 0: Jump to Label ADD_TO_SUM    [6,6,3]       {0:6}
 NSSTN     Create Label ADD_TO_SUM           [6,6,3]       {0:6}
  SNT      Swap top two                      [6,3,6]       {0:6}
  STSSTN   Copy 0-based 1st (3)              [6,3,6,3]     {0:6}
  TSSS     Add top two (6+3)                 [6,3,9]       {0:6}
  SNT      Swap top two                      [6,9,3]       {0:6}
  NSNN     Jump to Label LOOP                [6,9,3]       {0:6}

 SSSTN     Push 1                            [6,9,3,1]     {0:6}
 TSST      Subtract top two (3-1)            [6,9,2]       {0:6}
 SNS       Duplicate top (2)                 [6,9,2,2]     {0:6}
 NTSSN     If 0: Jump to Label REACHED_ZERO  [6,9,2]       {0:6}
 STSSTSN   Copy 0-based 2nd (6)              [6,9,2,6]     {0:6}
 STSSTN    Copy 0-based 1st (5)              [6,9,2,6,2]   {0:6}
 TSTT      Modulo top two (6%5)              [6,9,2,0]     {0:6}
 NTSTN     If 0: Jump to Label ADD_TO_SUM    [6,9,2]       {0:6}
  SNT      Swap top two                      [6,2,9]       {0:6}
  STSSTN   Copy 0-based 1st (2)              [6,2,9,2]     {0:6}
  TSSS     Add top two (9+2)                 [6,2,11]      {0:6}
  SNT      Swap top two                      [6,11,2]      {0:6}
  NSNN     Jump to Label LOOP                [6,11,2]      {0:6}

 SSSTN     Push 1                            [6,11,2,1]    {0:6}
 TSST      Subtract top two (2-1)            [6,11,1]      {0:6}
 SNS       Duplicate top (1)                 [6,11,1,1]    {0:6}
 NTSSN     If 0: Jump to Label REACHED_ZERO  [6,11,1]      {0:6}
 STSSTSN   Copy 0-based 2nd (6)              [6,11,1,6]    {0:6}
 STSSTN    Copy 0-based 1st (1)              [6,11,1,6,1]  {0:6}
 TSTT      Modulo top two (6%1)              [6,11,1,0]    {0:6}
 NTSTN     If 0: Jump to Label ADD_TO_SUM    [6,11,1]      {0:6}
  SNT      Swap top two                      [6,1,11]      {0:6}
  STSSTN   Copy 0-based 1st (1)              [6,1,11,1]    {0:6}
  TSSS     Add top two (11+1)                [6,1,12]      {0:6}
  SNT      Swap top two                      [6,12,1]      {0:6}
  NSNN     Jump to Label LOOP                [6,12,1]      {0:6}

 SSSTN     Push 1                            [6,12,1,1]    {0:6}
 TSST      Subtract top two (1-1)            [6,12,0]      {0:6}
 SNS       Duplicate top (1)                 [6,12,0,0]    {0:6}
 NTSSN     If 0: Jump to Label REACHED_ZERO  [6,12,0]      {0:6}
 NSSSN     Create Label REACHED_ZERO         [6,12,0]      {0:6}
  SNN      Discard top (0)                   [6,12]        {0:6}
  SNS      Duplicate top (12)                [6,12,12]     {0:6}
  STSSTSN  Copy 0-based 2nd (6)              [6,12,12,6]   {0:6}
  TSTT     Modulo top two (12%6)             [6,12,0]      {0:6}
  NTSSSN   If 0: Jump to Label DIVISIBLE     [6,12]        {0:6}
  NSSSSN   Create Label DIVISIBLE            [6,12]        {0:6}
   SNT     Swap top two                      [12,6]        {0:6}
   TSTS    Integer-divide top two (12/6)     [2]           {0:6}
   NSSSTN  Create Label OUTPUT               [2]           {0:6}
    TNST   Output top as integer (2)         []            {0:6}         2
                                                                                error

```

Stops with an error after printing the result, because no exit is defined.
> 4 votes

# Answer
# JavaScript (ES6), 41 bytes

Returns **0** if there's no solution.

```
x=>(g=k=>x=k&&k*!(x%k)/x+g(k-1))(x)%1?0:x

```

Try it online!
> 3 votes

# Answer
# Jelly, 6 bytes

```
Æs0:%?

```

A monadic Link accepting a positive integer which yields a non-negative integer.

**Try it online!** Or see the test-suite.

### How?

```
Æs0:%? - Link: x
Æs     - divisor sum
     ? - if...
    %  - ...condition: has a remainder when divided
  0    - ...then: zero
    :  - ...else: integeger divide

```
> 3 votes

# Answer
# Charcoal, ~~23~~ 20 bytes

```
ＮθＩ⌕Ｅ⊕θ×θιΣΦ⊕θ∧ι¬﹪θι

```

Try it online! Link is to verbose version of code. Port of @Sisyphus's algorithm but using @ovs's comment to deal with 0-indexing. Outputs `-1` for nonexistence. Explanation:

```
Ｎθ                      Input `x` as a number
             θ          `x`
            ⊕           Incremented
           Φ            Filter over implicit range
               ι        Current index
              ∧         Logical AND
                  θ     `x`
                 ﹪      Modulo
                   ι    Current index
                ¬       Logical NOT
          Σ             Take the sum
      θ                 `x`
     ⊕                  Incremented
    Ｅ                   Map over implicit range
        θ               `x`
       ×                Multiplied by
         ι              Current index
   ⌕                    Find the index
  Ｉ                     Cast to string
                        Implicitly print

```

Unfortunately for Charcoal the sum of `[]` is not zero, which means that I can't save a byte by removing the two increments of `x` and incrementing the result instead.

Previous 23-byte solution:

```
Ｎθ≔ΣΦ⊕θ∧ι¬﹪θιη¿¬﹪ηθＩ÷ηθ

```

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

```
Ｎθ

```

Input `x`.

```
≔ΣΦ⊕θ∧ι¬﹪θιη

```

Create a list from `1..x`, filter out numbers that don't divide `x`, and take the sum.

```
¿¬﹪ηθＩ÷ηθ

```

If `x` divides the sum then print the quotient.
> 3 votes

# Answer
# Haskell, ~~51~~ 46 bytes

```
a!b=0^mod a b*div a b
f n=sum(map(n!)[1..n])!n

```

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 30 bytes

```
Tr@Divisors@#/#/._Rational->0&

```

Try it online!

-6 bytes from @att
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~19~~ 18 bytes

```
⊢(÷⍨×0=|)1⊥∘⍸0=⍳|⊢

```

Try it online!

Conversion to train by Jo King.(-3 bytes)

-1 more byte from Jo King after changing the check condition.

# Older answer, 22 bytes

```
{(⊢×⌊=⊢)⍵÷⍨+/⍸0=⍵|⍨⍳⍵}

```

## Explanation

```
{(⊢×⌊=⊢)⍵÷⍨+/⍸0=⍵|⍨⍳⍵} ⍵ → input
                   ⍳⍵  range 1-⍵
                ⍵|⍨    mod ⍵
              0=       check which ones are divisors
             ⍸         get the indices (factors)
           +/          sum the factors
        ⍵÷⍨            divide by ⍵
 (⊢×⌊=⊢)               Inner tacit fn:
    ⌊=⊢                Floor equals right? (integer test, returns 0 or 1)
  ⊢×                   times right

```
> 3 votes

# Answer
# Scala, ~~54~~ 53 bytes

```
x=>{val s=1 to x filter(x%_<1)sum;s/x*(1-(s%x).sign)}

```

Try it in Scastie

Sums every divisor of `x` from 1 to x, inclusive. If that sum is divisible by x, it returns that divided by x, otherwise it returns 0.
> 2 votes

# Answer
# Retina, 51 bytes

```
.+
*
|""Lw`^(.+)(?=\1*$)
^
$-1;
L$`^(.+);(\1)+$
$#2

```

Try it online! Link includes less slower test cases. Explanation:

```
.+
*

```

Convert the input to unary.

```
|""Lw`^(.+)(?=\1*$)

```

List all of the factors without delimiting them, thus summing them.

```
^
$-1;

```

Retrieve the original unary value.

```
L$`^(.+);(\1)+$
$#2

```

Count how many times it divides the sum. (Or output nothing if it does not.)
> 2 votes

# Answer
# Octave, ~~36~~ 34 bytes

```
@(x)~mod(s=~mod(x,r=1:x)*r',x)*s/x

```

Anonymous function that takes a floating-point or integer number as input. The last test case fails due to memory limitations.

Try it online! Or verify test cases.

### Explanation

```
@(x)~mod(s=~mod(x,r=1:x)*r',x)*s/x

@(x)                                 % anonymous function with input x
                    1:x              % row vector [1 2 ... x]
                  r=                 % call that r
            mod(x,     )             % x modulo [1 2 ... x]. Gives a row vector
           ~                         % negate each element. Gives 1 for divisors
                         r'          % column vector [1; 2; ... ; x]
                        *            % matrix-multiply. Gives the sum of divisors
         s=                          % call that s
     mod(                  ,x)       % sum of divisors modulo x
    ~                                % negate. Gives 1 if x divides sum of divisors
                               s/x   % sum of divisors divided by x
                              *      % multiply

```
> 2 votes

# Answer
# Python 3.8 (pre-release), 62 bytes

```
lambda x:(a:=sum(x/i*(x%i<1)for i in range(1,x+1)))%x<1and a/x

```

Try it online!
> 2 votes

# Answer
# MathGolf, 7 bytes

```
─Σk‼÷/*

```

Try it online.

**Explanation:**

```
─       # Get the divisors of the (implicit) input-integer
 Σ      # Sum those divisors
  k     # Push the input-integer again
   ‼    # Apply the following two commands separately to the stack:
    ÷   #  Check if the divisor-sum is divisible by the input (1 if truthy; 0 if falsey)
    /   #  Integer-divide the divisor-sum by the input
     *  # Multiply the two together
        # (after which the entire stack joined together is output implicitly as result)

```
> 2 votes

# Answer
# Rockstar, ~~141~~ ~~135~~ 131 bytes

Outputs nothing if no `n` exists.

```
listen to N
X's0
T's0
while N-X
let X be+1
let D be N/X
turn up D
let T be+D is N/X and X

let D be T/N
turn up D
if D is T/N
say D

```

Try it here (Code will need to be pasted in)
> 2 votes

# Answer
# PowerShell, 71 bytes

```
param($x)(1..$x|?{!($x%$_)})|%{$s+=$_};((1..$x)|%{$_*$x}).indexof($s)+1

```

Try it online!

* Get the parameter `x`
* Brute force and calculate divisors
* Sum up the divisors to variable `s`
* Multiply range of `1..x` with `x`
* Return index of `s` in the multiplied range and add 1 to it
> 2 votes

# Answer
# Icon, 67 bytes

```
procedure f(n)
s:=0
n%(i:=1to n)=0&s+:=i&\z
return(0=s%n&s/n)|0
end

```

Try it online!
> 1 votes

# Answer
# Japt , 7 bytes

Outputs `undefined` if no `n` is found.

```
*N¶Îâ x

```

Try it
> 1 votes

# Answer
# Factor, 84 bytes

```
: f ( n -- n ) dup [1,b] [ dupd mod 0 = ] filter sum swap /mod 0 > [ drop 0 ] when ;

```

Try it online!
> 1 votes

# Answer
# Prolog, 117 bytes

```
s(X,D,S):-D<1,!,S is 0;E is D-1,(0 is X mod D,!,s(X,E,T),S is T+D;s(X,E,S)).
f(X,N):-s(X,X,S),0 is S mod X,N is S//X.

```

Try it online! (Please don't modify it directly, it would change my version too)

---

If anyone could figure out why this shorter version (96 bytes) isn't working, I'd be really grateful.

```
s(X,D,S):-D<1,!,S is 0;E is D-1,(0 is X mod D,!,s(X,E,T),S is T+D;s(X,E,S)).
f(X,N):-s(X,X,N*X).

```

Version with print debugging
> 1 votes

# Answer
# GolfScript, 22 bytes

```
~:x),{.x\%!*+}*.x%!*x/

```

Try it online!

```
~:x                     # Store the input in x
   ),                   # Make an array from 0 to x
     {       }*         # For each number in the array, execute this block
      .                 # Copy current number
       x\%!             # The copy becomes 1 if it is a divisor of x and 0 if it isn't
           *+           # Multiply and add
               .        # Copy the sum of the divisors
                x%!     # The copy becomes 1 if it is a divisor of x and 0 if it isn't
                   *    # Multiply
                    x/  # Divide by x

```
> 1 votes

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


title: Package distribution

text:
# Question
Title: Package distribution
While at work I spotted a nice and simple challenge.

The job was to stock products in cargo units with a certain capability. Since an order can have various batches, coming in sequence from the production, we usually make a list of the pieces of those batches distributed in each cargo to make sure nothing is lost during the process.

For example if we had this production sheet:

```
 _____________
|ord: xxx     |
|_____________|
| A | 30 pcs  |
| B | 38 pcs  |
| C | 12 pcs  |
 —————————————

```

and our cargo could contain 12 pieces we would make this list:

```
A | 12 12  6-
B | -6 12 12  8-
C | -4  8//

```

where **x**`-` indicates that **x** pieces will be stocked with `-`**y** pieces of the next line and **z**`//` indicates that after those **z** pieces there's a different order, thus nothing more we can add, and the last cargo is complete.

# Task

In this challenge you have to take a production sheet and a cargo capacity and output the distributed list.

# Specifications

Production sheet is taken in the form of a sequence of numbers representing the batches amounts.

You have to output just the distributed amounts, we don't care about the additional signs `-` `//` mentioned above.

Every batch must be distributed separately, so the output is a list of lists which you can represent in any reasonable format, just specify it and be consistent.

It's guarantee that:

* each batch has at least one piece
* cargo units can contain at least one piece
* an order( input list ) has at least one batch

So you have to handle only positive integers( \>0 ).

## input:

a list of numbers representing the production sheet and a number representing the cargo capacity, each positive integers, in any reasonable method / order.

## output:

the distributed list in form of a list of lists of numbers in any convenient method.

* No extraneous numbers can appear in the output.
* Order of obtained lists must be preserved.

# Test cases

```
 [30, 38, 12], 12 => [[12,12,6],[6,12,12,8],[4,8]]
 [1],1 => [[1]]
 [2],1 => [[1,1]]
 [1],2 => [[1]]
 [1,12,34],20 => [[1],[12],[7,20,7]]
 [5],1 => [[1,1,1,1,1]]
 [5],5 => [[5]]
 [300,120],84 => [[84,84,84,48],[36,84]]
 [1,2,3,4,5],6 => [[1],[2],[3],[4],[2,3]]
 [2,5,16,38,32,38,38,34,8,30,31,9,12],15 => [[2],[5],[8,8],[7,15,15,1],[14,15,3],[12,15,11],[4,15,15,4],[11,15,8],[7,1],[14,15,1],[14,15,2],[9],[4,8]]

```

# Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT, return it as a function result or error message/s.
* Either a full program or a function are acceptable.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

Sandbox

# Answer
# , 36 34 27 24 bytes

```
(]<@(#/.~)/.[:I.#\&:-)I.

```

Try it online!

-3 bytes thanks to Bubbler

Takes capacity as left arg and production sheet as right arg.

## how

Use `12 f 30 38 12` as an example.

* `(...)I.` A dyadic hook which expands the right arg into a mask with 30 `0`s, 38 `1`s, and 12 `2`s:

```
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2

```
* `#\&:-` makes both arguments negative `&:-`. The `_12` on the left means "chunks of size 12" and `#\` will count each:

```
 12 12 12 12 12 12 8

```
* `[:I.` Use the same expansion trick we used before to expand each of those in place into a unique integer:

```
 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6

```
* `].../.` Use the mask from step 1 to group the output of the last step into groups of size 30, 38, and 12:

```
  0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2
  2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5
  5 5 5 5 6 6 6 6 6 6 6 6

```
* `(#/.~)/.` For each of *those* groups, self-group by value, returning a list of the number of items in each group:

```
  _________ 12 ________   ________ 12 _________   ___ 6 ___
 /                     \ /                     \ /         \
 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2

  ___ 6 ___   ________ 12 _________   ________ 12 _________   _____ 8 _____
 /         \ /                     \ /                     \ /             \
 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5

  _ 4 _   _____ 8 _____
 /     \ /             \
 5 5 5 5 6 6 6 6 6 6 6 6

```
* Finally, box each of those results `<@` because J doesn't allow ragged arrays.
> 8 votes

# Answer
# Stax, 19 bytes

```
ÇÑ▄≥Ué(ΘⁿGD$▀X9♦;ûΘ

```

Run and debug it

### Explanation:

Unpacked source:

```
{i]*m$s/{|Rm:f{h}/mMHJ

```
* Implicit input: 12 \[30 38 12\]
* `{i]*m`: Map over array:
    + `i]`: Push singleton array with index, e.g. \[1\]
    + `*`: Repeat by corresponding element, e.g. \[1 1 1 1 1 ... (38 times)\]
* Result: \[\[\<30 times 0\>\] \[\<38 times 1\>\] \[\<12 times 2\>\]\]
* `$`: Flatten: \[\<30 times 0\> \<38 times 1\> \<12 times 2\>\]
* `s/`: Split into groups of maximum package size: \[\[\<12 times 0\>\] \[\<12 times 0\>\] \[\<6 times 0\> \<6 times 1\>\] \[\<12 times 1\>\] \[\<12 times 1\>\] \[\<8 times 1\> \<4 times 2\>\] \[\<8 times 2\>\]
* `{|Rm`: Run-length-encode each element: \[\[\[0 12\]\] \[\[0 12\]\] \[\[0 6\] \[1 6\]\] \[\[1 12\]\] \[\[1 12\]\] \[\[1 8\] \[2 4\]\] \[\[2 8\]\]\]
* `:f`: Flatten: \[\[0 12\] \[0 12\] \[0 6\] \[1 6\] \[1 12\] \[1 12\] \[1 8\] \[2 4\] \[2 8\]\]
* `{h}/`: Split into groups with equal first element: \[\[\[0 12\] \[0 12\] \[0 6\]\] \[\[1 6\] \[1 12\] \[1 12\] \[1 8\]\] \[\[2 4\] \[2 8\]\]\]
* `m`: For each element, e.g. \[\[0 12\] \[0 12\] \[0 6\]\]
    + `M`: Transpose: \[\[0 0 0\] \[12 12 6\]\]
    + `H`: Second element: \[12 12 6\]
    + `J`: Join with spaces: "12 12 6"
    + Implicit print
> 6 votes

# Answer
# JavaScript (ES6), 57 bytes

Expects `(capacity)(list)`.

```
n=>a=>a.map(g=v=>v?[x=v>m?m:v,...g(v-x,m=m-x||n)]:[],m=n)

```

Try it online!

### Commented

```
n => a =>              // n = cargo capacity, a[] = production list
  a.map(g = v =>       // for each quantity v in a[]:
    v ?                //   if v is not equal to 0:
      [                //     build a new array:
        x = v > m ? m  //       append x = min(m, v)
                  : v, //
        ...g(          //       split the result of a recursive call:
          v - x,       //         subtract x from v
          m = m - x    //         subtract x from m; if the result is 0:
              || n     //           restart with a new cargo of capacity n
        )              //       end of recursive call
      ]                //     end of array
    :                  //   else:
      [],              //     stop the recursion
    m = n              //   start with m = n
  )                    // end of map()

```
> 5 votes

# Answer
# Haskell, ~~67~~ 66 bytes

*1 byte saved by xnor*

```
f c|let(a:d)?b|a<=b=[a]:d?(b-a)|x:y<-(a-b:d)?c=(b:x):y;_?_=[]=(?c)

```

Try it online!

I think this takes the cake as the most unreadable Haskell I have written. We have a pattern guard inside a pattern guard which I am actually surprised Haskell can even parse.

Here it is ungolfed:

```
f c
  | let
    (a:d)?b
      | a <= b
        = [a]:d?(b-a)
      | x:y <- (a-b:d)?c
        = (b:x):y
    _?_
     = []
  = (?c)

```
> 5 votes

# Answer
# 05AB1E, 9 bytes

```
OÝI÷¹£εÅγ

```

Try it online or verify all test cases.

**Explanation:**

```
O          # Sum the first (implicit) input-list
 Ý         # Push a list in the range [0,sum]
  I÷       # Integer-divide each by the second input-integer
    ¹£     # Split it into groups of the first input-list amount of values
      ε    # Map over each group:
       Åγ  #  And run-length encode it, which will put the values and counts as two
           #  separated lists to the stack, and since we're using a large map `ε`, it
           #  will only leave the top one with the counts
           # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Charcoal, 31 bytes

```
ＵＭθ…Ｅι⊞Ｏυκ⁰Ｆ⪪υηＦ…·⌊ι⌈ι⊞§θκ№ικＩθ

```

Try it online! Link is to verbose version of code. Outputs each entry on its own line with batches double-spaced. Explanation:

```
ＵＭθ…Ｅι⊞Ｏυκ⁰

```

For each element of the input array, push its index `n` times to the predefined empty list, and then replace it with an empty array, thereby creating a master batch list.

```
Ｆ⪪υη

```

Split the list of indices into batches of the given capacity and loop over each batch.

```
Ｆ…·⌊ι⌈ι

```

Loop over each value in the current batch.

```
⊞§θκ№ικ

```

Push the value's frequency to the master batch list.

```
Ｉθ

```

Print the resulting list.
> 3 votes

# Answer
# , ~~123~~ ~~80~~ 78 bytes

*Edit: -43 bytes by ~~stealing tricks from~~ blatantly copying Kevin Cruijssen's 05AB1E answer (please upvote that one!)*

```
function(s,c)sapply(lapply(split((1:sum(s)-1)%/%c,rep(seq(a=s),s)),rle),`[`,1)

```

Try it online!
> 2 votes

# Answer
# C (clang), ~~93~~ 75 bytes

* Original answer setting the Bounty score required under 93.

```
p,u;f(*l,c,z){for(p=u=0;++u,++p,z;u*=u!=c)--*l&&u-c||printf("%d%c",p,!*l?++l,z--,10:32,p=0);}
```

Try it online!

* 75 bytes after some golfing.
* stolen from @Arnaulds the 0 terminated list input.

```
p,u;f(*l,c){for(p=u=1;*l||*++l;++p)u++%c*--*l||printf("%d%c",p,9+!*l,p=0);}

```

Try it online!

* `u` is the total counter of pieces.
* `p` is the partial counter.
* `c` is cargo capacity
* when u%c == 0 or current batch (\*l) is 0 we print the partial and reset it.
> 2 votes

# Answer
# Perl 5, 116 bytes

```
sub{$c=pop;map[map y///c,/x+|y+|X+|Y+/g],join('',map[X,Y]->[$n++%2]x$_,@_)=~s/(.{$c})(.{1,$c})/$1\L$2/gr=~/x+|y+/gi}

```

Try it online!

```
sub{
  $c=pop;                           #capacity from last input
  map [map y///c,/x+|y+|X+|Y+/g],   #split into same letters case-sensitive
                                    #...and convert into lengths as numbers
  join('',map[X,Y]->[$n++%2]x$_,@_) #stringify order into XXXYYYXX of given sizes
  =~ s/(.{$c})(.{1,$c})/$1\L$2/gr   #lower case every other capacity
  =~ /x+|y+/gi                      #split into same letters case-insensitive
}

```
> 1 votes

# Answer
# C (clang),  ~~91 87 86~~  83 bytes

*Saved 4 bytes by switching to clang and using TABs, as suggested by @AZTECCO*
*Saved 3 bytes thanks to @ceilingcat*

Expects a zero-terminated list of quantities.

```
m,x;f(int*a,n){for(m=n;*a?printf("%d%c",x=*a>m?m:*a,(m=m-x?:n,*a-=x)?9:13):*++a;);}

```

Try it online!
> 1 votes

# Answer
# Jelly, 9 bytes

```
SḶṁẋ@:Œɠ€

```

Try it online!

Port of @KevinCruijssen's 05AB1E answer.

## Explanation

```
SḶṁẋ@:Œɠ€   Main dyadic link
S           Sum
 Ḷ          Lowered range [0..n-1]
  ṁ         Reshape like
   ẋ@         a list consisting of lists of the second argument repeated each first argument times
     :      Integer divide by the second argument
      Œɠ    Run lengths
        €     of each

```
> 1 votes

# Answer
# Clojure, 111 bytes

```
#(let[p partition-by](for[k(p last(for[i(partition-all %2(mapcat repeat %1(range)))j(p + i)]j))](map count k)))

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: *Overwrit*labels

text:
# Question
Title: *Overwrit*labels
If you've ever tried adding labels to a really dense plot, then you'll realise that sometimes labels will overlap one another, making them hard to read. We're going to do something similar but in 1D.

Input will be a sequence of `(label, x-coordinate)` pairs, and output will be the result of drawing each point and label, in the given order. An asterisk `*` representing the point should be placed at the given x-coordinate and the label should follow. Any existing characters will be overwritten.

For instance, if the input was

```
Hello  0
World  8
Fizz   3
Buzz   5
PPCG   16
X      9

```

Then the following would happen:

```
*Hello
*Hello  *World
*He*Fizz*World
*He*F*Buzzorld
*He*F*Buzzorld  *PPCG
*He*F*Buz*Xrld  *PPCG

```

The final line should then be outputted.

## I/O rules

* Input may consist of any number of pairs. Each label will only consist of uppercase and lowercase letters, and label lengths will be at most 127 chars. Each x-coordinate will be between 0 and 127 inclusive.
* Input may be in any convenient list or string format such that the pairs are unambiguous and labels/x-coordinates alternate in the input. For example, a format like `[("Hello", 0), ("World", 8) ...]` or `[0 "Hello" 8 "World" ...]` is fine. However, you may not assume two separate lists of labels and x-coordinates.
* Functions and full programs are both okay.
* Any spots not covered by a label should be represented with a space. However, there may not be any extraneous leading or trailing whitespace aside from a single optional trailing newline.

## Examples

**Input:**

```
OneLabel   10

```

**Output:**

```
          *OneLabel

```

**Input:**

```
Heathrow   0
Edinburgh  2
London     4
Liverpool  6
Oxford     8

```

**Output:**

```
*H*E*L*L*Oxfordl

```

**Input:**

```
alpha     20
beta       4
gamma     57
delta      3
epsilon   22
zeta      32
eta       53
theta     27

```

**Output:**

```
   *delta           *a*epsi*thetazeta                *eta*gamma

```

**Input:**

```
abc  5
d    5
abc  10
ABCDEFGHIJKLMNOPQRSTUVWXYZ 127

```

**Output:**

```
     *dbc *abc                                                                                *ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

Note that labels and/or x-coordinates may be repeated.

# Answer
# CJam, ~~24~~ ~~23~~ 19 bytes

```
l~Sf.*'*f*:.{S^+1=}

```

This reads the input as a CJam array of coordinate-label pairs.

Try this fiddle in the CJam interpreter or verify all test cases at once.

*Thanks to @MartinBüttner for helping me save 4 bytes!*

### How it works

```
l~                   Read a line from STDIN and evaluate it.
  Sf                 For each pair, push the pair and " "; then:
    .*                 Perform vectorized repetition.
                         [X "label"] " " .* -> [(X spaces) "label"]
      '*f*           Join each resulting pair, using '*' as separator.
          :.{     }  Reduce by the following vectorized operator:
                       Push two characters (A and B).
             S^        Compute the symmetric difference of B and " ".
                       This pushes "B " for a non-space B and "" otherwise.
                +1=    Append and select the second character (with wrap).
                       This selects B for "AB " and A for "A".

```
> 7 votes

# Answer
## Python 2, 67 bytes

```
z=''
for a,b in input():z=(z+' '*b)[:b]+'*'+a+z[len(a)-~b:]
print z

```

Takes input like `[('Heathrow', 0), ('Edinburgh', 2), ('London', 4), ('Liverpool', 6), ('Oxford', 8)]` and prints the result.

Python doesn't allow strings to be modified, and converting to and from a list is expensive. So, this recreates the string `z` to add in a new word. We take the `b` characters before the word, padding with spaces if needed, then the new text with an asterisk, then the part of `z` after the new word. Note that trailing spaces are never added.

The `reduce` version is 3 chars longer (70):

```
lambda I:reduce(lambda z,(a,b):(z+' '*b)[:b]+'*'+a+z[len(a)-~b:],I,"")

```
> 5 votes

# Answer
# Pyth, 20 bytes

```
V.Tmrj" *"d9Qpe+d-Nd

```

Try it online: Demonstration or Test Suite

### Explanation

```
V.Tmrj" *"d9Qpe+d-Nd
   m        Q         map each pair d of the input to:
     j" *"d             join d by the string " *"
    r      9            range-length encode
                        (this gives x-coordinate spaces, a star and the label)
 .T                   transpose this table
V                     for N in ^:
                 -Nd    remove spaces from N
               +d       add a space at the beginning
              e         take the last character
             p          and print it (without newline)

```
> 4 votes

# Answer
# JavaScript ES6, 104 bytes

```
c=>(a=Array(255).fill(" "))&&c.map(([u,v])=>a.splice(u,v.length+1,..."*"+v))&&a.join``.replace(/ +$/,"")

```

## Example Usage

Input into a compliant console:

```
t = [[0,"Hello"],[8,"World"],[3,"Fizz"],[5,"Buzz"],[16,"PPCG"],[9,"X"]];
(c=>(a=Array(255).fill(" "))&&c.map(([u,v])=>a.splice(u,v.length+1,..."*"+v))&&a.join``.replace(/ +$/,""))(t);

```

Output from the last statement:

```
"*He*F*Buz*Xrld  *PPCG"

```

## Explanation

This creates an anonymous function from `c` to three expressions that have been logically-ANDed together. The first two statements are always truthy, and the JS short-circuit rules say that whenever the first is truthy, return the entire value on the right hand side (without coercing to boolean): so this is formally equivalent to

```
(function (c) {
    a = Array(255).fill(" ");                    // global variable `a` overwritten
    c.map(function (x) {                         // only side-effects are used here.
       var u = x[0], v = x[1];                   // ES6 destructuring
       a.splice(u, v.length + 1, ..."*" + v));   // main logic
    });
    return a.join("").replace(/ +$/, "");        // postprocessing and trim
})

```

The first statement has to be wrapped in parentheses above because the assignment operator `=` has lower precedence than the logical-AND operator `&&`.

The "rest parameter" assembly `..."*"+v` is also part of ES6; it concatenates a leading `*` to the string and then interprets it as a list-like parameter, splitting it into a bunch of arguments which are provided to `Array.prototype.splice`, which takes `(m, n, ...rest)` and modifies its array at position `m` to remove `n` elements and then insert all of the `rest` arguments. To accomplish this before ES6 you would use the more cumbersome:

```
[].slice.apply(a, [u, v.length + 1].concat(("*" + v).split("")))

```

The array then gets concatenated with the empty string and trailing whitespace is deleted.
> 4 votes

# Answer
# Ruby, ~~94~~ ~~81~~ 75 bytes

Golfed:

```
s=" "*128;$<.map{|l|w,p=l.split;p=p.to_i;s[p..w.size+p]="*"+w};$><<s.rstrip

```

Here's the ungolfed code:

```
s = " "*128
$<.map{|l|                 # for each line entered via stdin, ctrl+D to stop
  w,p = l.split            # had to move the chomp down here
  p = p.to_i               # there's no 'to_i!'...
  s[p..w.size+p] = "*"+w   # in the range of *foobar, replace the string
}
$><<s.rstrip               # output suggested by w0lf

```

Thanks @w0lf for the suggestions on mapping the input!

Thanks @w0lf and @Not that Charles for the thought on removing a variable.
> 3 votes

# Answer
# Javascript 121 chars

Using non-standard features, works on Firefox.
`x=Array(255).fill(" ");eval(prompt()).map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"});x=x.join``.trimRight()`

Older version: `x=Array(255).fill(" ");eval(prompt()).map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"});x=x.join``.replace(/ +$/,"")`

```
x=Array(255).fill(" ");      //Creates an array with spaces
eval(prompt())               //Gets some input, has to look like [["Hello",4],["Hi",14],["Oi",0]]
.map(s=>{s[0].split``.map((n,i)=>x[s[1]+i+1]=n);x[s[1]]="*"}); //Main "logic"
x=x.join``.replace(/ +$/,"") //Gets rid of the trailing spaces

```
> 3 votes

# Answer
# Jelly, 14 bytes

```
0x;”*;µ/€Ṛo/o⁶

```

Try it online!

Takes input as a list of pairs `[coordinate, label]`. The last test case does work, TIO simply has wrapping

## How it works

```
0x;”*;µ/€Ṛo/o⁶ - Main link. Takes a list of pairs I
        €      - Over each pair P in I:
      µ        -   Run the following, using:
       /       -     C (coord) as the left argument and L (label) as the right:
0x             -       Repeat 0 C times
  ;”*          -       Concatenate "*"
     ;         -       Append L
         Ṛ     - Reverse I
          o/   - Reduce columnwise by logical OR
                 This replaces 0s with the next non-zero element
            o⁶ - Replace the remaining zeros with spaces

```
> 3 votes

# Answer
## Python, 85 bytes

```
def g(p):
 z=[' ']*256
 for a,b in p:z[b:b+len(a)+1]='*'+a
 return''.join(z).rstrip()

```

Try it online
> 2 votes

# Answer
## Perl, 66 bytes

**63 bytes script + 3 bytes for `-p`**

```
$}||=$"x128;/\s+/,substr$},$',1+length$`,"*$`"}{$_=$};s/\s+$/
/

```

Nothing too special, utilising the variables `$`` and `$'` which are 'before the match' and 'after the match' respectively, instead of splitting the string. I used a `$}` for the string variable as originally it was saving me a byte, but isn't any more!

### Example run:

```
$perl -p overwritlabels.pl <<< 'Hello  0
World  8
Fizz   3
Buzz   5
PPCG   16
X      9'
*He*F*Buz*Xrld  *PPCG

```

---

## Perl, 65 bytes

**62 bytes script + 3 bytes for `-p`**

Another version that prints out each line (for one less byte!). (Yes, I made this because I didn't read the question properly...)

```
$}||=$"x128;/\s+/;substr$},$',1+length$`,"*$`";$_=$};s/\s+$/
/

```

### Example run:

```
$perl -p overwritlabels.pl <<< 'Hello  0
World  8
Fizz   3
Buzz   5
PPCG   16
X      9'
*Hello
*Hello  *World
*He*Fizz*World
*He*F*Buzzorld
*He*F*Buzzorld  *PPCG
*He*F*Buz*Xrld  *PPCG

```
> 2 votes

# Answer
# PHP -- 84 bytes

```
<? foreach(array_chunk(array_slice($argv,1),2) as $p) echo "␣[".($p[1]+1)."G*$p[0]";
                                                            ^ ESC character (\x1b)

```

Uses ANSI escape codes to position the cursor (`\x1b[XG`, featuring the Escape character and X being the 1-based coordinate), followed by the `*` then the input string for that row. Accepts input on the command line of the form:

```
php filename.php Heathrow 0 Edinburgh 2 London 4 Liverpool 6 Oxford 8
php filename.php abc 5 d 5 abc 10 ABCDEFGHIJKLMNOPQRSTUVWXYZ 127

```

Accepts multi-word entries if they're in quotes, since they're command line arguments.
> 2 votes

# Answer
# C++11, 95 bytes

Why not?

As a function, receive input as a `map<int, string>` named `v` containing the position and the string.

```
string t(255,' ');for(auto&m:v){int i=m.first;t[i++]='*';for(auto&c:m.second)t[i++]=c;}cout<<t;

```

Usage

```
#include <iostream>
#include <map>
using namespace std;
int main(){
    map<int,string> v{{0,"Heathrow"},{2,"Edinburgh"},{4,"London"},{6,"Liverpool"},{8,"Oxford"}};
    string t(255,' ');for(auto&m:v){int i=m.first;t[i++]='*';for(auto&c:m.second)t[i++]=c;}cout<<t;
}

```

Check it Running Here
> 1 votes

# Answer
# Husk, 13 bytes

```
Fż|mF(J'*eR'

```

Try it online!

Takes a list of pairs (coordinate, label) as input. N.B.: there is a space character at the end of the code.

### Explanation

```
Fż|mF(J'*eR'
   m             For each pair in the input
    F            apply the following function using the pair members as arguments
          R'     Repeat a space (coord) time
         e       put this in a list with the label
      J'*        and join the strings in the list with "*"
F                Fold over the resulting list
 ż               by zipping strings together
                   (keeping extra characters in the longer string unchanged)
  |              with OR (Second argument if truthy else first. Spaces in Husk are falsy)

```
> 1 votes

# Answer
# Japt, 18 bytes

```
rÈh'*+YÎYÌ}Sp#ÿ)x1

```

Try it online!

Takes input as an array of `[label, x-coordinate]`

Explanation:

```
rÈh'*+YÎYÌ}Sp#ÿ)x1    #
           Sp#ÿ       # Store 255 spaces as X
r         }    )      # Do this for each pair in order:
 Èh                   #  Overwrite part of X:
        YÌ            #   Starting at index equal to the second item of the pair
   '*                 #   Write "*"
     +YÎ              #   Write the first item of the pair
                x1    # Remove any remaining whitespace on the right side

```
> 1 votes

# Answer
# Stax, <sup>~~11~~</sup> 8 bytes

```
┤6╧ß╡⌠░$

```

Run and debug it

Takes input as a list of pairs `[coordinate, label]`. Thanks to caird coinheringaahing for the testcases.

## Explanation

```
zsFE'*s+|%
zs            push empty list and swap with the input
  F           for each element,
   E          push each item onto stack
    '*s+      add asterisk to label
              Stack: [index,label]
        |%    embed in the array

```
> 0 votes

# Answer
# Canvas, 9 bytes

```
Ｈ｛｝０┘*；＋╋

```

Try it here!

Same as my Stax answer, except canvas is better at grid overlaps.
> 0 votes

# Answer
# GolfScript, 29 bytes

```
~""\{~." "*3$\+<"*"+\+.,@>+}/

```

Try it online!
> 0 votes

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


title: Is it zero- or one- indexed?

text:
# Question
Title: Is it zero- or one- indexed?
Your task is to determine whether some arbitrary programming language has zero-indexed or one-indexed arrays based on sample inputs and outputs

### Inputs

* An array of integers with at least 2 elements
* A positive integer index
* The value of the array at that index

### Output

One of four distinct values representing:

* **One-indexed** if the language unambiguously has one-indexed arrays
* **Zero-indexed** if the language unambiguously has zero-indexed arrays
* **Unknown** if the given inputs aren't enough to determine whether the language is zero- or one- indexed because it is ambiguous.
* **Neither** if the language is not zero- or one-indexed because it is something else that may or may not make any sense.

## Example Test Cases

Formatted as `[array, elements][index] == value_at_index => output`

```
[2, 3][1] == 2  ==>  one-indexed
[2, 3][1] == 3  ==>  zero-indexed
[1, 2, 2, 3][2] == 2  ==>  unknown
[4, 5][1] == 17  ==>  neither
[-3, 5, 2][2] == 5  ==>  one-indexed
[-744, 1337, 420, -69][3] == -69  ==>  zero-indexed
[-744, 1337, 420, -69][3] == 420  ==>  one-indexed
[-744, 1337, 420, -69][3] == -744  ==>  neither
[42, 42, 42, 42, 42][2] == 42  ==>  unknown
[42, 42, 42, 42, 42][1] == 56  ==>  neither

```

## Rules and Scoring

* Use any convenient I/O methods
* Use any convenient representation for each of the four distinct categories as long as it is consistent and each possible category is mapped to exactly one value.
* You may assume that all array values are between \\$-2^{31}\\$ and \\$2^{31} - 1\\$, inclusive (i.e. the signed int32 range.)
* You may assume that arrays are no longer than \\$65535\\$ elements.
* You may assume that the index is in-bounds for both zero- and one-indexed semantics.

Shortest code wins. Happy golfing!

# Answer
> 15 votes
# convey, 47 bytes

Returns 0 for neither, 1 for one-based, 2 for zero-based and 3 for unknown.

```
{2+~`0
?;\2:!2[
v^<]`
?;\?+2
v^< v*+}
!>>>=?^
2

```

Try it online!

Run for `1 2 2 3` with index `2` and value `2`:

On the left we split the input lines with `;\ ^<` into the three paths. The first one pushes two zeroes after `length of path + index` time steps into the `+`. The second one path tries to push the array into `+` – if there are values waiting (the two zeroes), they get passed through unaltered. Otherwise, they get deleted `?]`. The two values then get pushed into `=`, where they are compared to the third input. The result are two boolean bits. The second one gets multiplied by 2, then they get added together.

# Answer
> 12 votes
# Brainfuck, 43 bytes

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

Arguments are taken in this order: value\_at\_index, index, array values.

Outputs are: 0-unknown, 1-zero indexed, 2-one indexed, 3-neither.

## How it works

```
,               read value_at_index into first cell
>,              read index into second cell
[->,<]          read the array till the one indexed element is found and store it into third cell
,               store the zero indexed element into second cell
<[->->-<<]      substract value_at_index from both saved elements
>[[-]>>++<<]    if the zero indexed element isn't equal to zero then add 2 to result
>[[-]>+<]       if the one indexed element isn't equal to zero then add 1 to result
>.              print the result

```

# Answer
> 7 votes
# Haskell, 27 bytes

```
(l%i)n=[l!!j==n|j<-[i,i-1]]

```

Try it online!

Outputs a two-element list like `True/False`.

**28 bytes**

```
(l%i)n=[l!!i==n,l!!(i-1)==n]

```

Try it online!

**28 bytes**

```
(l%i)n=(==n).(l!!)<$>[i,i-1]

```

Try it online!

**29 bytes**

```
n?i=map(==n).take 2.drop(i-1)

```

Try it online!

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

Returns **0** for *neither*, **1** for *0-indexed*, **2** for *1-indexed* or **3** for *unknown*.

```
(a,i,v)=>a[i]==v|2*(a[i-1]==v)

```

Try it online!

or **28 bytes** by outputting a pair of Boolean values:

```
(a,i,v)=>[a[i]==v,a[i-1]==v]

```

Try it online!

# Answer
> 6 votes
# Jelly, 5 bytes

```
+.ịẹ⁵

```

Try it online! or see the test cases (slightly modified to run as a function)

Full program, takes input as `index`, `array`, `value` on the command line.

Outputs `[1]` for one-indexed, `[2]` for zero-indexes `[1, 2]` for unknown and `[]` for neither

## How it works

```
+.ịẹ⁵ - Main link. Takes index on left and array on right
 .    - Yield 0.5
+     - Add to index
  ị   - Yield [array[index], array[index+1]]
   ẹ⁵ - Return the indices of the value in that array

```

# Answer
> 5 votes
# x86 (with MMX) machine code, 9 bytes

(Same machine code works in 64-bit and 32-bit modes; 16-bit mode doesn't have scaled-index addressing modes.)

2 boolean compare results from `array[index-1] == element` and `array[index] == element` can be concatenated to produce a 2-bit return value: one or the other set means we can tell that it's 0 (first) or 1 (second) indexed. Neither set means "neither", both set means "unknown". Apparently we don't consider it ambiguous if the expected element is also present somewhere else in the array; "neither" is only a fallback that we don't have to consider if 0-indexed or 1-indexed explains the observation.

So we only need to look at 2 elements at `index-1` and `index`, e.g. with a packed-compare of those 2 elements in parallel. That's exactly what MMX `pcmpeqd mm1, mm2/m64` does.

Array pointer in EDI/RDI, index in EDI/RSI, expected element in mm0 (in the low 32-bit element), retval in mm0

```
  line  offset   machine            NASM source
    #             code
     1                         compare_at_index:
     2 00000000 0F62C0             punpckldq   mm0, mm0                 ; broadcast expected
     3 00000003 0F7644B7FC         pcmpeqd     mm0, [rdi + rsi*4 - 4]   ; compare integers at array[i-1, i]
     4 00000008 C3                 ret
  size = 9 bytes

```

Return values, as a SIMD vector of 2 32-bit dword elements `[low, high]` (shown in memory order, not Intel's usual notation of highest element first):

* `[-1, 0]` means 0-indexed, only the first matched
* `[0, -1]` means 1-indexed
* `[-1, -1]` means "unknown"; both matched
* `[0, 0]` means "neither"; neither matched

(Untested but I'm confident this works, and writing a test harness would be significantly more work for asm. SIMD packed compares are a pretty normal thing to work with.)

If you wanted to compact that return value into a scalar integer bitmap, that costs 3 bytes for `pmovmskb eax, mm0` (`0F D7 C0`) which would give you a `0x0F` / `0xF0` / `0xFF` / `0x00` result in EAX.

(If this was an XMM register, we could use `movmskps` to get 1 bit from each 4-byte element, instead of 4. Or `movmskpd` to get 2 bits total from a 16-byte vector. But SSE2 instructions on XMM registers are 1 byte longer than MMX, so even using 64-bit array elements wouldn't let us keep the code-size the same. Also, SSE2 would require a 16-byte memory operand to be aligned unless you use a separate `movups` load instruction, although AVX allows `vpcmpeqq xmm0, xmm0, [rdi+rsi*8-8]` with no alignment requirement.)

Most standard calling conventions expect you to use `emms` after using MMX registers, but I'm considering a hypothetical system where it's normal to pass around integers in MMX registers, never returning the FPU to x87 mode.

If you wanted the expected-element to arrive in an integer register, say EDX, you could use `0F 6E C2` `movd mm0, edx` before punpckldq. Unfortunately, `vpbroadcastd xmm0, edx` requires AVX512 with its longer EVEX encoding, and only works for 16-byte XMM registers not 8-byte MMX. If we took the element as a stack arg, `pshufw mm0, [rsp+8], 0b0100_0100` is 6 bytes total, same as movd+punpckldq. 2 register args with the rest on the stack is a pretty normal calling convention, especially for 32-bit mode (e.g. `__fastcall`, but that would want `ret 4` callee pops. So maybe `gcc -m32 -mregparm=2` with `[esp+4]`). Not that we need to justify our calling convention as being a standard one.

# Answer
> 4 votes
# , 26 bytes

```
function(a,i,n)a[0:1+i]==n

```

Try it online!

Inputs array `a`, index `i`, value `n`.

Outputs a boolean pair: `F T = 0`, `T F = 1`, `T T = unknown`, `F F = either`.

Full program for the same byte count, inputs in the order of `i n a` merged into a single vector:

## , 26 bytes

```
a=scan();a[2:3+a[1]]==a[2]

```

Try it online!

# Answer
> 4 votes
# Pyth, 11 bytes

```
xE,@QJE@QtJ

```

Test suite

---

Takes input in the form:

```
list
value
index

```

Translation of caird coinheringaahing's Jelly answer.

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~15~~ 13 bytes

Saved 2 bytes thanks to Kamil Drakari

```
{⍵=⍺⍺[⍺,⍺+1]}

```

Try it online!

Call it with `index (array f) value)`. Returns `0 1` if it's zero-indexed, `1 0` if it's one-indexed, `1 1` if it's unknown, and `0 0` if it's neither.

```
{⍵=⍺⍺[⍺,⍺+1]}
      [     ]   ⍝ Index into
    ⍺⍺          ⍝ the array (the left operand)
       ⍺        ⍝ at the given index (the left argument) (one-indexed)
        ,       ⍝ and (parentheses would have been better, but , saves a byte)
         ⍺+1    ⍝ index+1 (zero-indexed)
 ⍵=             ⍝ Compare the value (right argument) to this 2-element vector

```

# Answer
> 3 votes
# MATL, 5 bytes

```
tQh)=

```

Inputs are: index, array, value. Outputs are `1 0` for one-indexed, `0 1` for zero-indexed, `1 1` for unknown, `0 0` for neither.

Try it online! Or verify all test cases

(Also for 5 bytes: `FT+)=`).

### Explanation

```
t    % Implicit input: index. Duplicate
Q    % Add 1
h    % Concatenate
)    % Implicit input: array. Apply index
=    % Implicit input: value. Test for equality. Implicit display

```

# Answer
> 3 votes
# Perl 5 -`apl`, 40 bytes

```
$_=1*($F[$i=<>]!=($t=<>)).($F[$i-1]==$t)

```

Try it online!

Input is on three lines:

```
Space separated list of numbers
index
target value

```

| Output | Meaning |
| --- | --- |
| 0 | Zero-indexed |
| 11 | One-indexed |
| 01 | Unknown |
| 1 | Neither |

# Answer
> 3 votes
# C (gcc), ~~42~~ 40 bytes

Saved 2 bytes thanks to att!!!

```
f(l,i,e)int*l;{e=l[i]==e|2*(l[i-1]==e);}

```

Try it online!

Inputs a pointer to the array, the index, and the test element.
Returns \\$2\\$ for \\$1\\$-indexed, \\$1\\$ for \\$0\\$-indexed, \\$3\\$ for unknown, and \\$0\\$ for neither.

# Answer
> 3 votes
# Japt, 8 bytes

```
gVôJ)®¥W

```

Try it online! or check all test cases

Outputs `[true, false]` for one-indexed, `[false, true]` for zero-indexed, `[true, true]` for unknown, and `[false, false]` for neither. Takes inputs in the order `array, index, value`.

Explanation:

```
gVôJ)®¥W
 Vô         # Create an array starting at input 2...
   J)       # ...And ending -1 integers later
g           # Get the values from input 1 at those indices (0-indexed)
     ®      # Replace each value with:
      ¥W    #  Is it equal to input 3?

```

# Answer
> 2 votes
# Java, 44 bytes

```
a->i->v->a[i]==v?a[i-1]==v?1:2:a[i-1]==v?3:4

```

Returns:

* 1, if unknown
* 2, if zero-indexed
* 3, if one-indexed
* 4, if neither

Try it online!

# Answer
> 2 votes
# PowerShell, 38 36 35 bytes

Takes three arguments: the array to index into, the index to test, and the number to test for. Outputs 0 or 1 for 0 or 1 based indexing, respectively, outputs 0 and 1 for unknown, and outputs nothing for neither.

```
param($a,$b,$c)0,1|?{$a[$b--]-eq$c}

```

Try it online!

# PowerShell, 33 bytes

This version has completely unintuitive output, but still works. Outputs 1 for 0-based, 0 for 1-based, 0 and 1 for neither, and nothing for unknown

```
param($a,$b,$c)0,1|?{$c-$a[$b--]}

```

Try it online!

# Answer
> 2 votes
# Charcoal, 9 bytes

```
Ｅ²⁼ζ§θ⁻ηι

```

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

```
Neither  0-indexed   1-indexed   Unknown
         -                       -
                     -           -

```

Explanation:

```
 ²          Literal `2`
Ｅ           Map over implicit range (i.e. `0`, `1`)
       η    Second input
      ⁻     Subtract
        ι   Current value
    §       Indexed into
     θ      First input
  ⁼         Equals
   ζ        Third input
            Implicitly print

```

# Answer
> 2 votes
# , 13 bytes

```
1 :'=u{~],<:'

```

Try it online!

Thanks to user's APL answer for suggesting the idea of using a J adverb to emulate a 3-argument function

The solution is an adverb `f` that operates like this:

```
<expected value> (<array> f) <index>

```

Return value key:

```
1 0 = zero-indexed
0 1 = one-indexed
1 1 = can't tell
0 0 = neither

```
* `=` Does the expected value equal...
* `],<:` The index, catted with "index - 1"
* `u{~` Both taken from the given array? (In J, within an adverb definition, `u` is the canonical name given to "the noun or verb being modified")

# Answer
> 1 votes
# Python 2, 32 bytes

```
lambda l,i,n:[l[i]==n,l[i-1]==n]

```

Try it online!

Outputs a two-element list of Booleans for whether 0-indexing and 1-indexing are consistent with the input.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~25~~ 24 bytes

```
Sign[#2[[#;;#+1]]-#3]^2&

```

Try it online!

Input `[index, array, value]`. Returns `{0,1}` for 1-indexed, `{1,0}` for 0-indexed, `{0,0}` for both, and `{1,1}` for neither.

# Answer
> 1 votes
# jq, 22 bytes

Inputs as: `[index, array, value]`.

Output key: `true,false` for 1-indexed, `false,true` for 0-indexed, `true,true` for unknown, `false,false` for 0-indexed.

```
.[1][.[0]|.-1,.]==.[2]

```

Try it online! or Try all testcases!

## Explanation

```
.[1]                    # Index the array by the indices:
    [.[0]               #    * The index
         |.-1,.]        #    * Prepended with the index - 1
                ==      # Vectorizing equality:
                  .[2]  # With the value

```

# Answer
> 1 votes
# Rust, 31 bytes

```
|a:&[_],i,v|(a[i]==v,a[i-1]==v)

```

Try it online!

Port of Arnauld's JavaScript answer. Returns

```
(false, false) => "neither"
(false, true) => "one-indexed"
(true, false) => "zero-indexed"
(true, true) => "unknown"

```

I had to include the `:&[_]` part for the code to compile, but I have the feeling that it can be optimized somehow.

# Answer
> 0 votes
# Julia, 18 bytes

```
l*i*r=l[i:i+1].==r

```

Try it online!

overloads the `*` operator, expecting `array*index*result`

Outputs `[1,0]` for one-indexed, `[0,1]` for zero-indexed, `[0,0]` for neither and `[1,1]` for unknown

# Answer
> 0 votes
# GolfScript, 11 bytes

```
~].~==\~(==

```

Try it online!

# Answer
> 0 votes
# Ruby, 30 bytes

```
->(a,i,v){[a[i]==v,a[i-1]==v]}

```

returns:

* `[true, false]`, if zero-indexed
* `[false, true]`, if one-indexed
* `[true, true]`, if unknown
* `[false, false]`, if neither

Try it online!

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


title: Tips for golfing in Lua

text:
# Question
Title: Tips for golfing in Lua
What general tips do you have for golfing in Lua? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Lua (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
In addition to the ones already posted, here are some tricks I've gathered over time, in no specific order...

* For the function calls that only have one parameter delimited by a symbol (`"` for strings, `{` for tables), the parameter doesn't need to be wrapped around parentheses.
For example, instead of doing `print("hello")`, you can simply do : `print"hello"`
* Remove as much whitespace as possible - this is especially easy to do after a symbol that closes strings (or before one opening), function calls, tables...
Instead of `print(42) a=1` you can do `print(42)a=1`. Other example: `print(a and-1 or-2)`.
* Use the ternary operator when you can! Instead of `if a>0 then print("hello") else print("goodbye") end`, prefer `print(a>0 and "hello" or "goodbye")`. More info here.
*(This can actually get even better : `print(a>0 and"hello"or"goodbye")`)*
* Use the colon-call syntactic sugar when you can : instead of `string.rep(str,12)`, do `str:rep(12)`. That also works on non-variables this way (and only this way) : `("a"):rep(5)`
* Instead of doing `tonumber(str)` just do `str+0`
* For functions with no parameters, instead of defining them the usual way (`function tick() blabla() end`), you can do : `ticks=loadstring"blabla()"`, which saves 1 or more bytes, depending on the content. Also, if you define multiple functions, localize `loadstring` to a 1-char variable before and you'll save a lot of bytes ;). *Credits to Jim Bauwens for this trick.*
* Lua considers empty string (and `0` too unlike other languages) as *true* in conditional tests, so, for example, instead of doing `while 1 do ... end`, save 1 byte by writing `while''do ... end`
* `({""})[i]or"s"` is 1 char shorter than `i==1 and""or"s"` and can be written without a whitespace at the beggining, which may save one more byte.
> 13 votes

# Answer
**Shorten your infinite loop**

When you have to use an infinite loop, you may think of using a `while`, but using a label instead is shorter by 2 byte:

```
while''do end
::a::goto a

```

**Use the less space as possible**

There's a simple thing you could (ab)use to remove even more spaces from your code. Lua's specs are clear about the name you give to variables: They have to start with a letter. It imply that, sometimes, you can skip on spaces between numbers and functions/variables

```
x=0>1 and 0or 1print(x)

```

The possibility of removing the space depends on the letter following the number, here's the letter that won't allow you to do this:

```
a,b,c,d,e,f            -- They would be interpreted as hexadecimal
x                      -- only fail when after a 0, other number are fine
                       -- (0x indicates the following is an hexadecimal number)

```

By using this, and paying attention to how you call your variables, you can make most of your source codes space-free.

Picking up an example already here, and using this advice, here's one more byte you could shaved off :).

```
print(a and-1 or-2)
print(a and-1or-2)

```

**Use the right input method**

If we look at the boilerplate and cost for each *major* type of input, here's what we have:

```
function f(x)x end
io.read()
arg[1]

```

Each one of this method allow us to take 1 input, with the function being the one with the heaviest cost (but allows us to take a table as input)

We can now see that using command-line argument is the way-to-go if you want to golf, but be aware: it can be even shorter

```
arg[1]
...

```

The `...` are a bit special in lua, it's a variable containing the unpacked content of `arg`, or the unpacked parameters in case of a variadic function.

When you will have to get more than one input, and use each of them, it can be good to do save them in a variable. Here's some ways to save 2 inputs in variables

```
a=arg[1]b=arg[2]    -- highly un-efficient, costs 8 bytes by variable
a,b=unpack(arg)     -- costs 15, but at least doesn't depends on the number of argument
a,b=...             -- only costs 7

```

and here are the shortest call you could have done without the variables:

```
...     -- using a allow a gain of 1-2 bytes at each use
arg[2]  -- using b allow a gain of 4-5 bytes at each use

```

From the point where you have 3 argument, or when you use 2 arguments, with one used twice, you're already gaining bytes due to `a,b=...`! :)

**Almost never use if!**

There's near no cases where using a if/elseif/if statement will cost less than a ternary. the boilerplate for such a statement is really heavy:

```
-- exemple with dumb values
if 1>0then v=1 else v=0 end
v=1>0 and 1or 0

```

With a simple example, you already save 12 bytes, when you have to do some elseifs, it become more and more important, so be aware of that!

Also, ternaries in lua are *special*, there's some condition in how they work, for those interested, I'll explain it below:

Ternaries in lua are of the form `<condition> and <case true: have to be a true value> or <case false: can be anything>`

First of all, let's see the truth table of the `or`. A `or` can be considered as a function: it always return a value, here's the value it returns:

```
x | y ||x or y
------||-------
0 | 0 ||   y
0 | 1 ||   y
1 | 0 ||   x
1 | 1 ||   x

```

That's what allow us to construct our ternary.

The `and` is what allow us to evaluate the condition, it will always return `y` if `x and y` evaluates to true.

The problem with it is that it will fail if we want a `nil` or `false` to be return when the condition is `false`. For instance, the following will always return 5, despite the condition being true.

```
v = true and false or 5

```

Here's a step by step evaluation of a ternary to explain how it works (it will be useful for when you have to nest them :))

```
-- let's use our dumb ternary
= true and false or 5
-- and statement will be evaluated first, leading to
= false or 5
-- and we saw how the or works
= 5

```
> 7 votes

# Answer
I have already thought of one. I don't know if it works in some other languages, but Lua is the only one I know what allows you to store functions in variables. So if e.g. `string.sub`is used multiple times in your program, use e.g. `s=string.sub`.
> 5 votes

# Answer
It's a pretty verbose language for golfing... but some general tips that come to mind are:

* Try to avoid conditionals, since `if`...`then`...`else`...`end` is a major waste.
* Instead, try to focus on language constructs that are shorter, e.g. `for i=1,5 do`.
* The `#` operator is pretty great for golfing (and in general).
> 5 votes

# Answer
## Variadic Functions

The main variadic function that will trouble you is `print()`. For instance, when you're using it along `String.gsub()` it will print the string you modified AND the number of times `gsub` triggered.

To supress that second output, encapsulate your `gsub` in parens to force it to return only one value

```
print(("").gsub("aa",".","!"))    -- outputs "!!    2\n"
print((("").gsub("aa",".","!")))  -- outputs "!!\n"

```
> 5 votes

# Answer
I have compiled several tips as well. I'm sure some of mine will overlap with ones already stated, but I'll include them anyhow in the vein of creating a more complete answer.

---

**Assign repeated functions to variables**

Lua allows you to assign functions to variables. Even one character variables. This means if you repeat the function `string.sub(x, y)` more than twice, you will get a benefit from assigning it to a variable.

Without assigning to a variable (69 characters):

```
print(string.sub(x, y))
print(string.sub(x, y))
print(string.sub(x, y))

```

Assigning to a variable (51 characters):

```
s=string.sub
print(s(x,y))
print(s(x,y))
print(s(x,y))

```

There's cases where you can take this yet a step further. Lua allows an OOP to string manipulation, like so: `str:sub(x, y)` or `str.sub(x, y)` This opens up new options for our code. You can assign a variable to the function by it's reference as shown (46 characters.)

```
s=z.sub
print(s(x, y))
print(s(x, y))
print(s(x, y))

```

---

**Use the most efficient way to parse strings**

You may find yourself using a `for` loop and `string.sub` to iterate character by character in Lua. Sometimes this may work best, depending on your needs, but other times, string.gmatch will work in fewer characters. Here's an example of both:

```
s=io.read()
for a = 1, s:len() do
    print(s:sub(a, a))
end

for i in io.read():gmatch('.') do
    print(i)
end

```

And when golfed, the difference is more notable:

```
s=io.read()for a=1,s:len()do print(s:sub(a, a))end

for i in io.read():gmatch'.'do print(i)end

```

---

**Restructure Assignations To Optimize Whitespace**

In Lua, you do not have to put a space character between a closed parentheses or a end quotation mark and the next character. So far, I've found two cases where restructuring with this in mind will cut characters.

* Assigning variables:

```
 x,y=io.read(),0 print(x)
 vs.
 y,x=0,io.read()print(x)

```
* If Statements:

```
 if x:sub(1,1)==1 then
 vs
 if 1==x:sub(1,1)then

```

---

**Return the fewest characters possible**

If you must return a true or false value, then it seems you must necessarily use at least 5 characters for the return value. In reality the following works just as well:

```
return true
return false
vs
return 1>0
return 0>1

```
> 4 votes

# Answer
The expression `a==1 and 1or 0` can be shortened to `#{[a]=0}`.

This works because the array length operator `#` is actually measuring the number of consecutive integer array indices starting at 1. (Arrays in Lua are 1-based, but they allow assignment at other indices, even those that are negative or floating point.) If there no element at index 1, it will always report a length of zero. And `{[a]=0}` is an anonymous array with an element of value `0` at index `a`.

How many bytes this will save depends on the circumstance. For example, if you're already using `n%i<1` as a shorthand for `n%i==0` to test divisibility, then changing `n%i<1 and z or 0` to `z*#{[n%i+1]=0}` saves 2 or 3 bytes, depending on whether it's followed by a symbol or a keyword/identifier.
> 4 votes

# Answer
These are Lua only (I think) optimizations:

Strings are automatically converted into numbers when doing arithmetic operations on them. Just watch out for conditional statements, they do not automatically convert. This is great for taking user input as numbers while saving space.

Switching the contents of two variables does not require a temporary variable. `a,b=b,a` will swap the values of a and b.

Also, to extend upon what was said above, any alphanumeric character can touch a non alphanumeric character. So `a,b=io.read():match"(.+)/(.+)"u,v=a,b` is a perfect, working script, even with the lack of whitespace.
> 3 votes

# Answer
### Combine Local Variable Assignments

Instead of:

```
local a=42
local b=17
local c=99

```

Use parallel assignment:

```
local a,b,c=42,17,19

```

6 bytes saved for each variable!

### Declare Local Variables via Unused Function Parameters

Instead of:

```
function foo(a,b) local c,d ... end
function bar(a,b) local c,d=42,17 ... end

```

Use

```
function foo(a,b,c,d) ... end
function bar(a,b,c,d) c,d=42,17 ... end

```

6 bytes saved (minus 1-2 bytes for each variable that might be duplicated).
> 2 votes

# Answer
## Know how to output

There's two main method of outputting in lua

```
io.write()    -- outputs without trailing newline
print()       -- outputs with trailing new line and shorter by 3 bytes

```

When you have to concatenate multiple times, you could shorten that by using `io.write()` assigned to a one letter variable instead of the standard concatenation operator `..`

```
i(a)    -- i was defined as io.write
s=s..a

```

You gain 2 bytes at each call while paying some upfront

```
i=io.write  -- longer by 6 bytes
s=""

```

You're even on the third concatenation, and start gaining byte on the fourth.
> 2 votes

# Answer
A bunch of tips in no particular order:

* `string` is pretty long name. Efficiently, `('').char` is same as `string.char`. Even better results can be achieved if you use it together with a semicolon on variables: `a=...; print(a:sub(1, 5))`, but some `string` functions don't take strings as input.
* Lua has automatic conversions between strings and numbers for most cases, so `tonumber` and `+0` often only waste bytes.
* Always use `load'your function code here'` instead of `function()your function code here end`. Access function arguments using `...` inside.
* Some string functions in Lua can be used in unintended ways! For example, `a:gsub('.',load'my function')` seems to be the shortest way to iterate over chars in a string
* While the string engine is powerful, beware of its power when using user input as patterns! Because of that, you might have to use `a:find('.',1,1)` (to test for this issue, try including `%` at various places in your input and check out results). Countless ideas broke because of Lua trying to parse input as pattern.
* `nil` is three bytes, `_` is one (it is just random name which most likely doesn't exist). Also, any digit will work as truthy value.
* Know your logic behind `x and i or o`. It isn't just a ternary operator - it is a complete logical expression. In fact, it means the following: "if `x` is truthy, try `i`. If either x or i is falsy, return o". So if `i` is not truthy, result is `o`. Also, both `and` or `or` parts can be omitted (`x and i`, `x or o`).
* Use integer division by one instead of `math.floor`: `5.3//1==5.0`. Please note that the resulting number always follows the type of input one (integer/float).
> 2 votes

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


title: Match the permutations!

text:
# Question
Title: Match the permutations!
Your challenge is to create a regex that matches every string permutation of itself, and nothing else. The match must also be case-sensitive.

So, for example, if your regex is:

```
ABC

```

It should match (and only match) these strings:

```
ABC
ACB
BAC
BCA
CAB
CBA

```

It shouldn't match things like:

```
AABC (contains an extra A)
ABCD (contains an extra D)
AC   (no B)
AAA  (no B and C, extra 2 A's)
abc  (case-sensitive)

```

## Rules:

* You are allowed to use any flavour of regex you like.
* Standard loopholes apply.
* You must have at least two different characters in your code. That means solutions like `1` are invalid.
* The regex should contain only printable ASCII, and nothing else.

# Answer
# JavaScript, ~~64~~ 57 bytes

4 bytes removed thanks to Martin Ender.

```
^(?!.*([^])(.*\1){3}]?)[$$[-^?!!.'''-*11{33}5577\\-]{57}$

```

Try it here.

### Explanations (outdated)

```
^                                  # Beginning of the string.
(?!.*                              # Match only the strings that don't contain...
  (.)(.*\1){4}                     #     5 occurrences of the same character.
  [^1]?[^1]?                       #     Something that doesn't matter.
)
[]zzz^(?!!!.**[)\\1{{44}}666]{64}  # 64 occurrences of these 16 characters.
                                   # Some are duplicated to make sure the regex
                                   # contains 4 occurrences of each character.
\z                                 # End of the string.

```
> 14 votes

# Answer
# JavaScript, 50 bytes

```
^(?!([^])+.*\1.*\1)[?!ZZ-__==''-22+,,//{50}$]{50}$

```

Try it on regex101

The key to beating jimmy23013's solution was to reduce the number of repetitions of each character from 3 to 2.

### Explanation

`^(?!([^])+.*\1.*\1)` \- assert that no character in the string is repeated at least 3 times

`([^])+` is equivalent to `.*([^])`.

`[^]` works because JavaScript allows empty character classes (unlike most other regex engines, at least by default). It is equivalent to `[\W\w]` or `.` with the `/s` flag, i.e. it matches any character including newlines. For our purposes here, newlines don't matter, so it's equivalent to `.`.

Using `^(?!([^])+.*\1.*\1)` instead of `(?!.*([^])(.*\1){2})` or `^(?!(.)+.*\1.*\1)` eliminates the need for a third `(`, `)`, or `.`, and this is the key to reducing the number of repetitions of every character from 3 to 2.

`^`...`[?!ZZ-__==''-22+,,//{50}$]{50}$` \- assert that the entire string consists of the 25 characters `?` `!` `Z` `[` `\` `]` `^` `_` `=` `'` `(` `)` `*` `+` `,` `-` `.` `/` `0` `1` `2` `{` `5` `}` `$` and is 50 characters in length. Combined with the first assertion this guarantees that every character occurs exactly twice (due to the generalized pigeonhole principle, if any character occurred only once, some other character would have to occur three times).

`Z-_` is the range `Z[\]^_`. It's essential, because we already used `[`, `\`, `]`, and `^` twice each. We need to double the `Z` and `_`, because they aren't used elsewhere.

`'-2` is the range `'()*+,-./012`. It's essential, because we already used `(`, `)`, `*`, `.`, and `1` twice each. We need to double the `'`, `,`, `/`, and `2`, because they aren't used elsewhere.

There is no other way besides ranges to include the above in our character class, because octal or hexadecimal escape codes would require using `\`, and a negative character class would require using `^`.

`==` is extra padding to get us to 50 characters. It could be any arbitrary doubled character. We need it because if we went for `{48}`, we'd need to include two `0` somewhere, which would bring our 48 back up to 50.

Note that this can be trivially rearranged to include the delimiters:

```
/^(?!([^])+.*\1.*\1)[?!ZZ-__==''-22+,,{50}$]{50}$/

```

Try it on regex101

# Perl / PCRE, 57 bytes

I'm pretty sure it's impossible to do 2 repetitions in Perl/PCRE, because `[^]` is not available (except with the PCRE2\_ALLOW\_EMPTY\_CLASS flag), and the only other alternatives use `\` – for example `\C`, `\N`, `\X`, `\S`, and `[^\0]`. So, with 3 repetitions:

```
^(?!(.)*(.*\1){3})[[[-\]\]^^??!!'''-*.11{335577}$$-]{57}$

```

Try it on regex101

This is very similar to jimmy23013's JavaScript solution. It doesn't work under JavaScript however, because `^(?!(.)*(.*\1){3})` can always match on any string; it would capture an unset `\1` by doing zero repetitions on `(.)*`, and then `\1` would match an empty string 3 times.

Making it portable to both JavaScript and Perl/PCRE by using `(.)+` instead of `(.)*` would end up making it 60 bytes, due to adding the `+` character.

Alternatively:

```
((.)+(.*\2){3})?+^[[[-\]\]^^??+'''-**.22{335577}$$-]{57}$

```

Try it on regex101

This uses the possessive quantifier `?+` to atomically try to match a character repeated 4 times. If such a match is not found, it will be forced to do zero repeats (instead of one) and the `^` will match. Otherwise it will match something non-empty, and the `^` won't match.
> 6 votes

# Answer
# Perl and PCRE regex, 280 bytes

```
^(?=(.*z){2})(?=(.*\(){43})(?=(.*\)){43})(?=(.*\*){22})(?=(.*\.){23})(?=(.*0){2})(?=(.*1){6})(?=(.*2){16})(?=(.*3){7})(?=(.*4){4})(?=(.*5){1})(?=(.*6){3})(?=(.*7){2})(?=(.*8){2})(?=(.*9){1})(?=(.*=){22})(?=(.*\?){22})(?=(.*\\){11})(?=(.*\^){2})(?=(.*\{){23})(?=(.*\}){23}).{280}\z

```

(Slightly) more readable:

```
^
(?=(.*z){2})
(?=(.*\(){43})
(?=(.*\)){43})
(?=(.*\*){22})
(?=(.*\.){23})
(?=(.*0){2})
(?=(.*1){6})
(?=(.*2){16})
(?=(.*3){7})
(?=(.*4){4})
(?=(.*5){1})
(?=(.*6){3})
(?=(.*7){2})
(?=(.*8){2})
(?=(.*9){1})
(?=(.*=){22})
(?=(.*\?){22})
(?=(.*\\){11})
(?=(.*\^){2})
(?=(.*\{){23})
(?=(.*\}){23})
.{280}\z

```

This runs in O(2^n) time as written, so is incredibly inefficient. The easiest way to test it is to replace every occurrence of `.*` with `.*?`, which causes the case where it matches to be checked first (meaning that it matches in linear time, but still takes exponential time if it fails to match).

The basic idea is that we enforce the length of the regex to equal 280, and use lookahead assertions to force each character in the regex to appear at least a certain number of times, e.g. `(?=(.*z){2})` forces the `z` character to appear at least twice. `2+43+43+22+23+2+6+16+7+4+1+3+2+2+1+22+22+11+2+23+23` is 280, so we can't have any "extra" occurrences of any characters.

This is a programming example of an autogram, a sentence that describes itself by listing the number of each character it contains (and, in this case, also the total length). I got fairly lucky in constructing it (normally you have to use brute force but I stumbled across this solution while testing my brute-force program before I'd fully finished writing it).

# Perl and PCRE regex, 253 bytes, in collaboration with Martin Ender

I hypothesized that there might be shorter solutions which omit some digits (most likely 9, 8, or 7). Martin Ender found one, shown below:

```
^(?=(.*z){2})(?=(.*\(){39})(?=(.*\)){39})(?=(.*\*){20})(?=(.*\.){21})(?=(.*0){4})(?=(.*1){6})(?=(.*2){11})(?=(.*3){6})(?=(.*4){3})(?=(.*5){2})(?=(.*6){3})(?=(.*9){4})(?=(.*=){20})(?=(.*\?){20})(?=(.*\\){9})(?=(.*\^){2})(?=(.*{){21})(?=(.*}){21}).{253}\z

```

Readable version:

```
^
(?=(.*z){2})
(?=(.*\(){39})
(?=(.*\)){39})
(?=(.*\*){20})
(?=(.*\.){21})
(?=(.*0){4})
(?=(.*1){6})
(?=(.*2){11})
(?=(.*3){6})
(?=(.*4){3})
(?=(.*5){2})
(?=(.*6){3})
(?=(.*9){4})
(?=(.*=){20})
(?=(.*\?){20})
(?=(.*\\){9})
(?=(.*\^){2})
(?=(.*{){21})
(?=(.*}){21})
.{253}\z

```
> 3 votes

---
Tags: code-golf, quine, permutations, regular-expression, decision-problem
---


# Question
Title: Draw This ASCII art In The Least Amount Of Bytes(edited)
your challenge is to draw this ASCII art:

```
|     |  |- - - -  |       |       - - -
|     |  |         |       |       |   |
|- - -|  |- - -    |       |       |   |
|     |  |         |       |       |   |
|     |  |- - - -  |- - -  |- - -  - - -

```

remember this is `code golf` meaning you have to answer in the least amount of bytes possible. EDIT: spacing between letters is two spaces. the only symbols used are | and -. NO underscores. i added spaces between the dashes to make it easier to see how many there are

# Answer
# 05AB1E, 52 bytes

```
•C"¹Ò∞ʒÓŸ2ýŸ¦ÙLŒðd4Í}‡éλPÓãžãš±àýEŽª™§M₆2•… |-ÅвJ5ä»

```

Try it online!

```
•...•… |-ÅвJ5ä»  # full program
              »  # join...
           J     # joined...
         Åв      # characters in...
     … |-        # literal...
         Åв      # with indices in digits of...
•...•            # 88667318995411980279046696478254356886483104218636819581201379955454517801745112819324119476267...
         Åв      # in base length of...
     … |-        # literal...
             ä   # split into...
            5    # literal...
             ä   # equal sized pieces...
              »  # by newlines
                 # implicit output

```
> 1 votes

# Answer
# PHP, 63 bytes

```
<?=gzinflate('«Q  ÒU€@&`a^®¸J4Èt
P%XÂL<*‰7‹;Ñh0');

```

**WARNING**: this code contains many non-printable chars and a function that is disabled in most online code testers. It is either impossible to enter the correct code on their sites or run the function. Here is the php file I uploaded to gitHub so that you can test (I recommend using `<pre><code>` tags to see it as intended in a browser, because of spaces being narrower than , and new lines ignored in HTML):

Try it OFFline!

Well this is a one-time trick that is becoming recurrent, and quite boring, as all I need to do is reuse the script I made to generate the file, replace the string and run it. So this is the last time I'll use this trick, and I post it as a demonstration of why these challenges are not that much interesting IMO.

EDIT: updated the answer and the file with edited question (the string is shorter, so from 94 bytes originally to 63)
> 1 votes

# Answer
# Charcoal, 54 bytes

```
≔…- ⁵θ↓³↗→θ↑³Ｍχ¹←…- ⁷↓³↗→θＭ²⁰→Ｐ↑²Ｍ⁴→↑²←θ‖Ｏ↓Ｆ²«←←←θＰ↑⁵←

```

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

```
≔…- ⁵θ

```

Construct the string `- - -` as it gets used a lot.

```
↓³↗→θ↑³

```

Draw the top half of the `H`.

```
Ｍχ¹←…- ⁷↓³↗→θ

```

Draw the top half of the `E`.

```
Ｍ²⁰→Ｐ↑²Ｍ⁴→↑²←θ

```

Draw the top half of the `O`.

```
‖Ｏ↓

```

Reflect to complete the `HE O`.

```
Ｆ²«←←←θＰ↑⁵←

```

Draw two `L`s.

Or I could just do boring string compression for 51 bytes:

```
”~∨CθＯÀ·y←B～⊟⧴n^；δＳ3E⊖⎇✂↶0¶KZ7≦%⊕wG4Ｈ⁻φ｜eＰυυ[qπ<Φ⊙›

```

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

If there were no spaces in the horizontal lines, it would be only 44 bytes:

```
↓³↗→⁵↑³Ｍχ¹←⁷↓³↗→⁵Ｍ²⁴→↑²←⁴Ｐ↓³←¹‖Ｏ↓Ｆ²«←←←⁵Ｐ↑⁵←

```

Try it online! Link is to verbose version of code.
> 1 votes

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