title: Implement bag operations

text:
# Question
Title: Implement bag operations
A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.

# Operations

The specified operations may not be conventional.

* **addition** combines two bags into one, conserving the total number of each value
`[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]`
* **difference** removes from a bag each element of another bag, or does nothing if no such element
`[1,2,2,4] - [1,2] = [2,4]` `[1,2,3] - [2,4] = [1,3]`
* **multiplication** multiplies each element in the bag.
`[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]` `2 * [1,3] = [1,1,3,3]`
* **division** is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.
`[1,1,2,2,2] / 2 = [1,2]` `[1,2,2,3,3,3] / 3 = [3]`
* **counting** counts how many divisor bags can be produced from the dividend bag
`[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2`
* **equality test** checks if two bags have the same numbers of each element
`[1,2,2,3] == [3,2,1,2] = truthy` `[1,2,3] == [1,2,2,3] = falsy` (can also use `=` for this)

If you are using your own symbols for the operators, please specify.

# Formats

Bags will be displayed as lists of the form `[1,1,2,3,4]`. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily `int`) for the purpose of this question. Bags do not have to be sorted.

The **input format** will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.

The **output format** should be a single bag of the same format.

# Rules

* you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)
* standard loopholes apply
* shortest answer wins

# Test cases

```
[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy

```

# Answer
> 3 votes
## 05AB1E, ~~92~~ ~~87~~ ~~83~~ ~~82~~ 77 bytes

```
>i‚˜,}¹iÐ¸˜Qis}GD})˜,}¹<i³v²y¢O}){0è,}¹Íi{s{Q,}¹Í<iÙv²y¢O³‹_iy}}),}svy†¬yQi¦}}

```

**Split by operation**

```
>i                      # if 0
  ‚˜,}                  # addition
¹i                      # if 1
  Ð¸˜Qis}GD})˜,}        # multiplication
¹<i                     # if 2
   ³v²y¢O}){0è,}        # count
¹Íi                     # if 3
   {s{Q,}               # equality
¹Í<i                    # if 4
   Ùv²y¢O³÷Fy}}),}      # division
                        # else
   svy†¬yQi¦}}          # difference

```

**Explanation**

*Addition*

```
‚˜,}

```

Put one bag in other and flatten them to one bag.

*Multiplication*

```
Ð¸˜Qis}

```

Make sure the number is on the top of the stack. Call this X.

```
GD})˜,}

```

Duplicate the bag X times and join to one bag.

*Count*

```
³v²y¢O}){0è,}

```

For each element in the divisor bag, count number of occurences in dividend bag.
The minimum count will be the number of bags we can make.

*Equality*

```
 {s{Q,}

```

Sort both bags and check if they're equal.

*Division*

```
Ùv²y¢O³÷Fy}}),}

```

Count how many times each unique element occurs in the bag.
If it occurs at least as many times as the divisor. Keep (nr\_of\_copies\_total // divisor) copies in the bag.

*Difference*

```
svy†¬yQi¦}}

```

For each element in the subtrahend, sort it to the front of the minuend.
If the current subtrahend if equal to the first element in the minuend, remove it from the minuend.

# Answer
> 9 votes
# APL (155)

```
∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕

```

This defines an operator  'bag', which defines bag operations for given functions. I.e. `+∆` would be addition. It then reads a line from the keyboard and evaluates it as an APL expression.

The functions are:

* `+∆`, addition
* `-∆`, subtraction
* `×∆`, multiplication
* `÷∆`, division
* `⊂∆`, counting
* `≡∆`, equivalence (though due to golfing any unrecognized function will do equivalence)

Explanation:

* `∆←{`...`}`: define an operator :

+ `O←⍺⍺`: store the given function in `O` (`⎕CR` won't work with `⍺⍺` directly)
    + `O←⎕CR'O'`: get the string representation of that function
    + `'+'=O`...`:`: for addition,
        - `⍺,⍵`: join the two lists together
        - `R[⍋R←`...`]`: and sort the result
    + `'-'=O:`: for subtraction,
        - `⍺{`...`}⍵`: run the following recursive function:
            * `⍵≡⍬:⍺`: if the subtrahend is empty, return the minuend
            * `⍺/⍨(⍳⍴⍺)≢⍺⍳⊃⍵∇1↓⍵`: otherwise, remove the first element of the subtrahend from both the subtrahend and the minuend and try again
    + `(⍬=⍴⍵)∧K←'×'=O:` for multiplication, and if the right argument is not a bag:
        - `⍵/⍺`: replicate each element in the left argument by the right argument
    + `K:`: ...and if the right argument *is* a bag:
        - `⍺/⍵`: replicate each element in the right argument by the left argument (this is so that multiplication is commutative)
    + `'÷'=O:`: for division,
        - `⍵≤⍺∘.+⍺`: see which elements in ⍺ occur at least ⍵ times,
        - `⍺/⍨`: select those from ⍺,
        - : and remove all duplicates from that list
    + `'⊂'=O:`: for counting,
        - `⍵{`...`}⍺`: run the following recursive function:
            * `(∪⍺)≢∪⍵:0`: if one list contains elements the other doesn't, the result is 0
            * `1+⍺∇⍵-∆⍺`: otherwise, subtract the dividend from the divisor, try again, and increment the result.
    + : if none of the above, do the equivalence test:
        - `⍺[⍋⍺]≡⍵[⍋⍵]`: sort both lists and see if they are equal
* : read an expression from the keyboard, evaluate it, and output the result.

Test cases:

```
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 3 +∆ 1 2 4
1 1 2 2 2 3 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 4 -∆ 1 2
2 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 -∆ 2 4
1 3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 3 4 ×∆ 3
1 1 1 2 2 2 3 3 3 3 3 3 4 4 4
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      2 ×∆ 1 3
1 1 3 3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 1 2 2 2 ÷∆ 2
1 2
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 2 3 3 3 ÷∆ 3
3
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 1 2 2 2 2 3 3 3 ⊂∆ 1 2 3
2
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      3 2 1 2 ≡∆ 1 2 2 3
1
      ∆←{O←⍺⍺⋄'+'=O←⎕CR'O':R[⍋R←⍺,⍵]⋄'-'=O:⍺{⍵≡⍬:⍺⋄(⍺/⍨(⍳⍴⍺)≠⍺⍳⊃⍵)∇1↓⍵}⍵⋄(⍬≡⍴⍵)∧K←'×'=O:⍵/⍺⋄K:⍺/⍵⋄'÷'=O:∪⍺⌿⍨⍵≤+/⍺∘.=⍺⋄'⊂'=O:⍵{(∪⍺)≢∪⍵:0⋄1+⍺∇⍵-∆⍺}⍺⋄⍺[⍋⍺]≡⍵[⍋⍵]}⋄⎕
⎕:
      1 2 3 ≡∆ 1 2 2 3
0

```

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

```
(x,o,y,a=a=>a.reduce((r,e,i)=>[...r,...Array(e).fill(i)],[]),b=(a,r=[])=>a.map(e=>r[e]=-~r[e])&&r)=>[z=>a(b(y,z)),z=>y.map(e=>z[e]&&z[e]--)&&a(z),z=>a(z.map(e=>e*y)),z=>a(z.map(i=>i/y|0)),z=>b(y).map((e,i)=>r=Math.min(r,z[i]/e),r=1/0)|r,z=>``+z==b(y)][o](b(x))

```

Takes 3 parameters. The first parameter is an array, the second is an operator, the third depends on the operator. Bags are required to hold non-negative integers.

```
[...] 0 [...] -> addition
[...] 1 [...] -> difference
[...] 2 <n> -> multiplication
[...] 3 <n> -> division
[...] 4 [...] -> counting
[...] 5 [...] -> equality

```

Ungolfed:

```
function do_bag_op(lhs, op, rhs) {
    function bag2array(bag) {
        return bag.reduce(function (result, entry, index) {
            return result.concat(Array(entry).fill(index));
        }, []);
    }
    function array2bag(array, bag) {
        if (!bag) bag = [];
        array.forEach(function (entry) {
            if (bag[entry]) bag[entry]++;
            else bag[entry] = 1;
        }
        return bag;
    }
    var bag = array2bag(lhs);
    switch (o) {
    case 0: // addition
        return bag2array(array2bag(rhs, bag));
    case 1: // difference
        rhs.forEach(function(entry) {
            if (bag[entry]) bag[entry]--;
        });
        return bag2array(bag);
    case 2: // multiplication
        return bag2array(bag.map(function (entry) {
            return entry * rhs;
        }));
    case 3: // division
        return bag2array(bag.map(function (entry) {
            return Math.floor(entry / rhs);
        }));
    case 4: // counting
        return Math.floor(array2bag(rhs).reduce(function (count, entry, index) {
            return Math.min(count, bag[index] / entry);
        }, Infinity));
    case 5: // equality
        return String(bag) == String(array2bag(rhs));
    }
}

```

# Answer
> 6 votes
# Octave, ~~253~~ ~~244~~ 226 bytes

```
function r=f(a,b,o)
u=union(a,b);p=hist(a,u);q=hist(b,u);m=d=0;if(numel(b)==1)m=p.*b;d=p/b;elseif(numel(a)==1)m=a.*q;end
r={p+q,p-q,m,d,min(fix(p./q)),isequal(p,q)}{o};if(o<5)r=[arrayfun(@(x,y)repmat(y,1,x),r,u,'un',0){:}];end

```

This function must be in a file. To write the function in the command window you must use `endfunction` or `end`.

Thanks to Luis Mendo for saving 18 bytes.

The operations are:

```
1 = addition
2 = difference
3 = multiplication
4 = division
5 = counting
6 = equality test

```

Usage example:

```
>> f([1,2,2,3], [1,2,4], 1)
ans = 1   1   2   2   2   3   4

>> f([1,2,2,4], [1,2], 2)
ans = 2   4

>> f([1,2,3], [2,4], 2)
ans = 1   3

>> f([1,2,3,3,4], 3, 3)
ans = 1   1   1   2   2   2   3   3   3   3   3   3   4   4   4

>> f(2, [1,3], 3)
ans = 1   1   3   3

>> f([1,1,2,2,2], 2, 4)
ans = 1   2

>> f([1,2,2,3,3,3], 3, 4)
ans =  3

>> f([1,1,2,2,2,2,3,3,3], [1,2,3], 5)
ans =  2

>> f([3,2,1,2], [1,2,2,3], 6)
ans =  1

>> f([1,2,3], [1,2,2,3], 6)
ans = 0

```

Ungolfed:

```
function r = f(a,b,o)
    u = union(a,b);
    p = hist(a,u);
    q = hist(b,u);
    m = d = 0;
    if (numel(b)==1)
        m = p.*b;
        d = p/b;
    elseif (numel(a)==1)
        m = a.*q;
    end
    r = {p+q, p-q, m, d, min(fix(p./q)), isequal(p,q)}{o};
    if (o<5)
        r = [arrayfun(@(x,y) repmat(y, 1, x), r, u, 'un', 0){:}];
    end
end

```

# Answer
> 5 votes
## Mathematica, ~~387~~ ~~347~~ ~~300~~ 284 bytes

```
k=KeyValueMap[Table,#]&;j=b@@Join@@#&;l=List;q=Counts
b~SetAttributes~Orderless
a_b+c_b^:=j@{a,c}
c_b-a_b^:=j@k@Merge[q/@(l@@@{a+c,2a}),-Min[0,+##2-#]&@@#&]
a_b*n_Integer/;n>0^:=a+a*(n-1)
a_Rational c_b^:=j@k[⌊a#⌋&/@q@*l@@c]
a_b==d_b^:=l@@a==l@@d
c_b/a_b^:=If[(c-a)+a==c,1+(c-a)/a,0]

```

Slightly degolfed (a.k.a old version), didn't have full support for equality tests (returned truthy values, but left unevaluated for non-matching bags).

```
SetAttributes[b,Orderless]
b/:-a_b:=d@@a
b/:a_b+c_b:=Join[a,c]
d/:a_b+c_d:=b@@Join@@KeyValueMap[Table,Merge[Counts/@(List@@@{a+b@@c,b@@c+b@@c}),Max[0,#-(+##2)]&@@#&]]
b/:Rational[1,a_]c_b:=b@@Join@@KeyValueMap[Table,Floor[#/a]&/@Counts@*List@@c]
b/:(a_b)^-1:=c@@a
c/:a_b d_c:=Min@Merge[Counts/@(List@@@{a,d}),If[+##2==0,\[Infinity],#/+##2]&@@#&]
b/:a_b*n_Integer:=a+a*(n-1)

```

Implements the required data type with head `b`.

First `b` is defined to be `Orderless`. Any object passed to the kernel with head `b` will autosort its arguments. So even if `b[3,2,1]` is typed in, the evaluator will never see anything other than `b[1,2,3]`.

Addition is trivially defined as joining the elements.

A special rule for the difference of two bags is defined (explained below). Previous version had an auxiliary symbol for expressions of form `-bag`.

Then multiplication (as long as `n` is a positive integer) is recursively defined as `n*b[...] = b[...] + (n-1)*b[...]` which will eventually reduce to a simple sum.

The special rule for `b[...] - b[...]` counts the number of distinct elements in the sum of the bags and subtracts the bag to be subtracted twice from that result. Easier explained:

```
b[1,2,3,4,5] - b[2,3,6]
Element counts in sum of bags: <|1->1, 2->2, 3->2, 4->1, 5->1, 6->1|>
Element counts in 2x second bag:     <|2->2, 3->2, 6->2|>
Subtracting the corresponding values:
                               <|1->1, 2->0, 3->0, 4->1, 5->1, 6->-1|>

```

Above is a list of `Keys->Values`. `KeyValueMap` with `Table` creates lists of each `Key` `Value` times. (there's also a `Max[...,0]` there to not attempt creation of negative length tables). This comes out as:

```
{{1},{},{},{4},{5},{}}

```

which is flattened and head `List` is replaced with `b`.

Division by integers is somewhat similar in functions used, it is simply the floored division of the element counts by the integer.

Division by sets or counting I've changed since the original implementation. It is now recursively done as follows. Say, we divide bag `b1` by `b2` (which in the golfed code are `c` and `a` respectively. If `(b1-b2) + b2 == b1`, then add 1 and add to that the result of dividing `(b1-b2)/b2`. If not, return 0 and exit the recursion.

If bags match, built-in `==` gives `True`. The last line forces a `False` if they don't.

Test cases:

```
Input:
b[1, 2, 2, 3] + b[1, 2, 4]
b[1, 2, 2, 4] - b[1, 2]
b[1, 2, 3] - b[2, 4]
b[1, 2, 3, 3, 4]*3
2*b[1, 3]
b[1, 1, 2, 2, 2]/2
b[1, 2, 2, 3, 3, 3]/3
b[1, 1, 2, 2, 2, 2, 3, 3, 3] /b[1, 2, 3]
b[3, 2, 1, 2] == b[1, 2, 2, 3]
b[1, 2, 3] == b[1, 2, 2, 3]

Output:
b[1, 1, 2, 2, 2, 3, 4]
b[2, 4]
b[1, 3]
b[1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4]
b[1, 1, 3, 3]
b[1, 2]
b[3]
2
True
False

```

# Answer
> 2 votes
# Ruby, class definition answer, ~~323~~ 291 bytes

Mostly just wanted to make the `Bag` an actual class because of Ruby's flexibility with classes. In this case, it inherits from `Array` because it's shorter than having to initialize an internal array and dealing with the other stuff.

I'll probably do a more-serious golfing answer that uses a function to deal with the operations tomorrow. I'm very tired and I had too much fun with this ~~even though I had to wrangle with the numerics class definition to get `Number * Bag` working properly~~ PRAISE THE COERCE FUNCTION FOR MAKING IT SO I DIDN'T NEED TO MESS UP THE NUMERICS CLASS DEFINITIONS

Try it online! (Whitespace doesn't matter in Ruby, so the code is slightly ungolfed there.)

```
class B<Array
def == o
sort==o.sort
end
def + o
B.new super
end
def - o
r=to_a
o.map{|i|r[r.index(i)||size]=p}
B.new r-[p]
end
def * i
B.new super
end
def / i
B.new uniq.map{|o|[o]*(count(o)/i)}.flatten
end
def c o
o.map{|i|count i}.min
end
def inspect
sort
end
def coerce o
[self,o]
end
end

```

# Answer
> 2 votes
## Q - 219 characters

```
a:(,)
s:{[x;y]x((!:)(#:)x)except(,/)({.[(#);x]}')flip(7h$(({(+/)x=y}[y]')(?:)y);(({where x=y}[x]')y))}
m:{(,/)$[0>(@:)x;(#[x]')y;(#[y]')x]}
d:{(?:)x(&:)({y<=(+/)x=z}[x;y]')x}
c:{min({(+/)x=y}[x]')y}
e:{(asc x)~asc y}

```

`a` for addition, `s` for difference (subtraction), `m` for multiplication, `d` for division, `c` for counting, `e` for equality.

The addition algorithm is the obvious one, just joining the bags.

The subtraction function indexes in input bag (represented as an array) with the entire index range, except for the first `n` indices of each equivalence class formed by equality to each element in `y`, where `n` is the number of copies of that representative in `y`. Handling possible duplicates in `y` makes this a real monster of a function.

The multiplication function takes `x` values from each `y`, in the case that `y` is a single value, instead of an array, it just replicates them.

The division function produces the values whose count in the array is greater than `y`, and then removes duplicates.

The counting function calculates the counts of each element in `y`, and then returns the minimum.

Two bags are equal if their sorted array representations are equal.

# Answer
> 1 votes
# C++, ~~555~~ 551 bytes

(line breaks added for readability - only the first newline is required and counted)

```
#include<map>
struct B:std::map<int,int>{
B(std::initializer_list<int>l){for(auto i:l)++(*this)[i];}};
B operator+(B a,B b){for(auto m:b)a[m.first]+=m.second;return a;}
B operator-(B a,B b){for(auto m:b){int&x=a[m.first];x-=x>m.second?m.second:x;if(!x)a.erase(m.first);};return a;}
B operator*(B b,int n){for(auto m:b)b[m.first]*=n;return b;}
B operator*(int n,B b){return b*n;}
B operator/(B b,int n){for(auto m:b)if(!(b[m.first]/=n))b.erase(m.first);return b;}
int operator/(B a,B b){auto r=~0u;for(auto m:b){int x=a[m.first]/m.second;r=r>x?x:r;}return r;}

```

# Explanation

We implement our bag as a map of (value, count). The basic operations can be implemented by manipulating the counts; subtraction and integer division also need to remove any elements whose count reaches zero, so that `std::map::operator==` will work as the equality test.

The following expanded code is a generic version of the above, much less golfed: we use a separate `s()` to squeeze out any zero-count values, and we implement `const` operations in terms of assignment operators in the idiomatic C++ way. We also use `s()` to make multiplication by `0` return a truly empty bag (tested by adding `(B{1}*0 != B{})` to `main()`); the original fails this test, and it's not clear whether it's a requirement.

```
template<class T>
struct Bag{
    std::map<T,int>b;
    Bag(const std::initializer_list<T>& l){for(auto i:l)++b[i];}
    Bag&s(){for(auto i=b.begin();i!=b.end();i=i->second?++i:b.erase(i));return*this;}
    Bag&operator+=(const Bag& o){for(auto m:o.b)b[m.first]+=m.second;return*this;}
    Bag&operator-=(const Bag& o){for(auto m:o.b){auto&x=b[m.first];x-=x>m.second?m.second:x;}return s();}
    Bag&operator*=(int n){for(auto m:b)b[m.first]*=n;return s();}
    Bag&operator/=(int n){for(auto m:b)b[m.first]/=n;return s();}
    auto operator/=(const Bag& o){auto r=~0u;for(auto m:o.b){int x=b[m.first]/m.second;r=r>x?x:r;}return r;}
    bool operator==(const Bag& o)const{return b==o.b;}

    Bag operator+(Bag o)const{return o+=*this;}
    Bag operator-(const Bag& o)const{Bag t=*this;return t-=o;}
    Bag operator*(int n)const{Bag t=*this;return t*=n;}
    friend Bag operator*(int n,const Bag& b){return b*n;}
    auto operator/(auto n)const{Bag t=*this;return t/=n;}
    bool operator!=(const Bag& o)const{return b!=o.b;}
};

using B = Bag<int>;

```

## Tests

```
bool operator!=(B a,B b){return!(a==b);}
int main()
{
    return 0
        + (B{1,2,2,3}+B{1,2,4}  !=  B{1,1,2,2,2,3,4})
        + (B{1,2,2,4}-B{1,2}  !=  B{2,4})
        + (B{1,2,3}-B{2,4}  !=  B{1,3})
        + (B{1,2,3,3,4}*3  !=  B{1,1,1,2,2,2,3,3,3,3,3,3,4,4,4})
        + (2*B{1,3}  !=  B{1,1,3,3})
        + (B{1,1,2,2,2}/2  !=  B{1,2})
        + (B{1,2,2,3,3,3}/3  !=  B{3})
        + (B{1,1,2,2,2,2,3,3,3}/B{1,2,3} != 2)
        + (B{3,2,1,2}  !=  B{1,2,2,3})
        + (B{1,2,3}  ==  B{1,2,2,3})
        ;
}

```

# Answer
> 1 votes
# Ruby, 201 bytes

As promised in my other answer, here's one that uses functions instead of building a new class. I'm so close to breaching the 200 byte mark... Try it online

This uses the same opcodes as @Neil in his JavaScript answer, and the same order of arguments (lhs, opcode, rhs)

```
0: Addition
1: Difference
2: Multiplication
3: Division
4: Counting
5: Equality

```

---

The code:

```
->x,o,y{[->{(x+y).sort},->r=[*x]{y.map{|i|r[r.index(i)||x.size]=p};r-[p]},->{(x==[*x]?x*y :y*x).sort},->{x.uniq.map{|i|[i]*(x.count(i)/y)}.flatten},->{y.map{|i|x.count i}.min},->{x.sort==y.sort}][o][]}

```

# Answer
> 1 votes
**Python 2.7 - 447B (filesize)**

This is my first try at Codegolf, I hope it satisfies. I needed 2h. (But I'm still a beginner at Python)

Edit: Thanks to "Kevin Lau - not Kenny" for pointing out these:

* pythons self argument in a class can be replaced by anything
* indentation only has to be a single space
* the builtin sorted - funktion (I **knew** I had seen it, but I thought it to be a method in lists)
* \__ radd \__ is not needed (I only support adding B-objects(Bag-type) anyways)

Edit: Additionally I saved space by replacing functions with lambdas and new lines and indentations with more semicolons.

Code:

```
class B:
 def __init__(S,L=[]):S.L=sorted(list(L));S.p=lambda:[[i]*S.L.count(i)for k,i in enumerate(S.L)if i!=S.L[k-1]];S.__eq__=lambda o:S.L==o.L;S.__rmul__=S.__mul__=lambda o:B(S.L*o);S.__add__=lambda o:B(S.L+o.L);S.__sub__=lambda o:B([i for k in S.p()for i in k[:max(0,S.L.count(k[0])-o.L.count(k[0]))]]);S.__div__=lambda o:B([i for k in S.p()for i in k[::o][:[-1,None][len(k)%o==0]]]);S.c=lambda o:min([S.L.count(i)//o.L.count(i)for i in o.L])

```

checks:

```
print B([1,2,2,3]) + B([1,2,4]) == B([1,1,2,2,2,3,4]) # Add

print B([1,2,2,4]) - B([1,2]) == B([2,4]) #Substract
print B([1,2,3])   - B([2,4]) == B([1,3]) #Substract

print B([1,2,3,3,4]) * 3 == B([1,1,1,2,2,2,3,3,3,3,3,3,4,4,4])#Multiply
print 2 * B([1,3]) == B([1,1,3,3])                            #

print B([1,1,2,2,2])   /2 == B([1,2]) #Divide
print B([1,2,2,3,3,3]) /3 == B([3])   #

print B([1,1,2,2,2,2,3,3,3]).c(B([1,2,3]))==2 #Contained n times

print B([3,2,1,2]) == B([1,2,2,3]) # Equal
print B([1,2,3])   == B([1,2,2,3]) # Unequal

```

Output:

```
True
True
True
True
True
True
True
True
True
False

```

I might try it an other time with set as basis some time. Edit: Maybe I'll even try with functions only.

# Answer
> 1 votes
# Go, 642 bytes

```
type B struct{C map[int]int}
func N(c...int)B{b:=B{make(map[int]int)};for _,d:=range c{b.C[d]+=1};return b}
func(b B)L()(o[]int){for k,v:=range b.C{for i:=0;i<v;i++{o=append(o,k)}};return}
func(b*B)A(O B)B{for k,v:=range O.C{b.C[k]+=v};return*b}
func(b*B)S(O B)B{for k,v:=range O.C{if _,o:=b.C[k];o{b.C[k]-=v}};return*b}
func(b*B)M(n int)B{for k:=range b.C{b.C[k]*=n};return*b}
func(b*B)D(n int)B{for k:=range b.C{b.C[k]/=n;if b.C[k]==0{delete(b.C,k)}};return*b}
func(b B)O(O B)int{i:=0;for;len(b.L())>len(O.L());i++{b=b.S(O)};return i}
func(b B)E(O B)bool{for k,v:=range b.C{if V,o:=O.C[k];o{if V!=v{return 0>1}}else{return 0>1}};return 0<1}

```

Attempt This Online!

Methods `ASMDOE` are the methods described in-order in the OP. `N` is the constructor, taking a list of ints, and `L` is a utility function that turns a bag into a list of ints.

## Go, generic, 712 bytes

```
type B[T comparable]struct{C map[T]int}
func N[T comparable](c...T)B[T]{b:=B[T]{make(map[T]int)};for _,d:=range c{b.C[d]+=1};return b}
func(b B[T])L()(o[]T){for k,v:=range b.C{for i:=0;i<v;i++{o=append(o,k)}};return}
func(b*B[T])A(O B[T])B[T]{for k,v:=range O.C{b.C[k]+=v};return*b}
func(b*B[T])S(O B[T])B[T]{for k,v:=range O.C{if _,o:=b.C[k];o{b.C[k]-=v}};return*b}
func(b*B[T])M(n int)B[T]{for k:=range b.C{b.C[k]*=n};return*b}
func(b*B[T])D(n int)B[T]{for k:=range b.C{b.C[k]/=n;if b.C[k]==0{delete(b.C,k)}};return*b}
func(b B[T])O(O B[T])int{i:=0;for;len(b.L())>len(O.L());i++{b=b.S(O)};return i}
func(b B[T])E(O B[T])bool{for k,v:=range b.C{if V,o:=O.C[k];o{if V!=v{return 0>1}}else{return 0>1}};return 0<1}

```

Attempt This Online!

---
Tags: code-golf, data-structures
---


title: Remove excessive occurrences

text:
# Question
Title: Remove excessive occurrences
Given an array \\$A\\$ of positive integers between \\$1\\$ and \\$9\\$ inclusive and a positive integer \\$n\\$, remove all integers in \\$A\\$ which appear more than \\$n\\$ times.

For example:

```
             [1,2,3,2,3,2,4,1,2], n = 2
Occurrence:   1 1 1 2 2 3 1 2 4
Keep?         1 1 1 1 1 0 1 1 0
Kept values: [1,2,3,2,3,  4,1  ]

```

so the output is `[1,2,3,2,3,4,1]`

You can assume that:

* At least one element will always appear more than \\$n\\$ times
* At least one element will appear fewer than \\$n\\$ times
* \\$A\\$ will have a minimum of 2 distinct elements
* \\$n\\$ and the length of \\$A\\$ are within the integer bounds of your language.

You may take input and output in any convenient method. As the elements of \\$A\\$ are digits, you may also take input as an integer, or a single string, if that suits you.

This is so the shortest code in bytes wins

## Test cases

```
A, n -> out
[7,3,3,9], 1 -> [7,3,9]
[4,1,7,7,4,2,1], 1 -> [4,1,7,2]
[6,9,7,6,7,9,9], 2 -> [6,9,7,6,7,9]
[6,5,3,9,4,9,6,9], 2 -> [6,5,3,9,4,9,6]
[4,8,9,7,3,1,7,5,4,6], 1 -> [4,8,9,7,3,1,5,6]
[5,6,7,8,1,7,3,3,6,4], 1 -> [5,6,7,8,1,3,4]
[2,3,8,1,6,4,8,2,8,3], 2 -> [2,3,8,1,6,4,8,2,3]
[4,1,4,4,2,4,4,5,7,1,3], 1 -> [4,1,2,5,7,3]
[1,5,5,2,5,1,4,1,6,7,7,6,9,8,8,1,7,8,1,3,1,1,7,4], 3 -> [1,5,5,2,5,1,4,1,6,7,7,6,9,8,8,7,8,3,4]
[8,8,6,2,9,6,4,7,1,2,9,5,5,6,6,2,5,8,9,1,2,8,4,4,7,2,1,1], 3 -> [8,8,6,2,9,6,4,7,1,2,9,5,5,6,2,5,8,9,1,4,4,7,1]
[8,8,4,9,7,1,2,9,8,8,5,2,2,9,1,7,4,6,6,8,6,6,1,6,1,9,2,8,5,1,2,6,1,7,6,4,7,9], 4 -> [8,8,4,9,7,1,2,9,8,8,5,2,2,9,1,7,4,6,6,6,6,1,1,9,2,5,7,4,7]
[8,8,9,2,7,4,7,5,6,9,7,2,7,7,6,2,6,9,6,3,5,1,1,6,2,8,7,4,2,4,5,9,3,3,3,3,7,4,8,7,5,4,1,4,7,8], 2 -> [8,8,9,2,7,4,7,5,6,9,2,6,3,5,1,1,4,3]
[6,8,1,8,6,9,2,2,5,8,7,6,2,5,4,3,3,1,4,2,7,1,6,3,9,8,9,5,2,6,8,8,7,7,5,2,5,1,4,7,5,5,3,7,6,3,7,6,3,6,7], 4 -> [6,8,1,8,6,9,2,2,5,8,7,6,2,5,4,3,3,1,4,2,7,1,6,3,9,8,9,5,7,7,5,1,4,3]
[1,3,5,6,1,2,8,8,8,4,4,4,5,8,9,9,6,4,5,3,8,7,9,7,8,6,1,6,1,6,4,5,5,3,9,3,5,4,2,1,6,6,5,4,2,6,2,1,1,1,5,5], 2 -> [1,3,5,6,1,2,8,8,4,4,5,9,9,6,3,7,7,2]
[9,9,9,4,6,1,5,4,5,3,7,9,8,9,8,2,9,1,3,4,9,5,8,7,8,6,1,9,9,5,1,3,1,9,5,7,3,5,9,6,6,2,2,4,1,4,2,1,7,5,3,7,9,8,2,3,1,6], 9 -> [9,9,9,4,6,1,5,4,5,3,7,9,8,9,8,2,9,1,3,4,9,5,8,7,8,6,1,9,9,5,1,3,1,5,7,3,5,6,6,2,2,4,1,4,2,1,7,5,3,7,8,2,3,1,6]
[9,6,3,5,5,2,8,2,9,6,7,9,5,3,1,1,1,3,6,9,4,3,6,9,2,2,3,7,5,3,9,5,2,1,1,1,1,6,2,2,4,6,1,5,7,3,7,9,5,3,1,2,6,4,3,1,7,9,3,8,5,2,4,2,8,2,6,7,3,9,1,7,9,4,7,4], 5 -> [9,6,3,5,5,2,8,2,9,6,7,9,5,3,1,1,1,3,6,9,4,3,6,9,2,2,3,7,5,5,2,1,1,6,4,7,7,4,7,8,4,8,4]
[7,1,8,2,2,1,4,9,8,6,5,1,9,7,5,5,8,1,7,8,6,8,5,9,3,2,7,9,4,3,9,1,5,2,5,7,8,5,2,6,6,2,7,6,2,9,3,3,5,3,7,9,8,7,3,6,7,4,6,1,4,5,8,9,8,6,9,1,1,1,8,2,4,2,9,3,4,2,9,6], 8 -> [7,1,8,2,2,1,4,9,8,6,5,1,9,7,5,5,8,1,7,8,6,8,5,9,3,2,7,9,4,3,9,1,5,2,5,7,8,5,2,6,6,2,7,6,2,9,3,3,5,3,7,9,8,7,3,6,4,6,1,4,8,9,6,1,1,2,4,3,4]
[7,2,8,9,7,5,1,4,6,8,6,9,1,8,6,2,2,6,1,1,6,8,4,5,2,6,5,5,4,5,5,3,6,8,3,7,9,3,9,8,4,9,6,7,2,7,9,2,4,8,3,3,2,5,9,1,4,6,4,8,2,5,8,6,8,1,8,3,3,9,4,8,1,1,2,9,1,9,3,3,7], 11 -> [7,2,8,9,7,5,1,4,6,8,6,9,1,8,6,2,2,6,1,1,6,8,4,5,2,6,5,5,4,5,5,3,6,8,3,7,9,3,9,8,4,9,6,7,2,7,9,2,4,8,3,3,2,5,9,1,4,6,4,8,2,5,8,6,8,1,8,3,3,9,4,1,1,2,9,1,9,3,3,7]
[7,7,6,5,9,7,2,6,1,4,4,5,4,3,1,7,5,5,8,1,6,3,9,3,3,9,5,9,1,2,4,3,8,2,6,6,5,2,8,7,5,6,5,7,3,2,5,3,5,8,6,1,9,7,4,3,9,8,2,4,5,7,8,8,2,8,1,8,7,8,7,6,3,8,6,7,9,4,6,1,6,1,2,5,6,7,7,2,8,3,2,1,7], 11 -> [7,7,6,5,9,7,2,6,1,4,4,5,4,3,1,7,5,5,8,1,6,3,9,3,3,9,5,9,1,2,4,3,8,2,6,6,5,2,8,7,5,6,5,7,3,2,5,3,5,8,6,1,9,7,4,3,9,8,2,4,5,7,8,8,2,8,1,8,7,8,7,6,3,8,6,7,9,4,6,1,6,1,2,2,3,2,1]
[3,4,1,1,2,4,4,8,4,9,1,1,7,7,6,8,6,2,9,4,2,9,9,7,5,7,6,5,3,7,6,6,1,9,1,5,2,4,9,6,1,5,4,1,7,2,4,3,8,5,1,9,5,9,1,7,4,7,3,1,2,1,3,8,7,9,2,5,1,6,2,4,5,9,1,5,5,5,2,6,3,7,2,2,5,7,6,8,3,7,5,9,3,3,9], 7 -> [3,4,1,1,2,4,4,8,4,9,1,1,7,7,6,8,6,2,9,4,2,9,9,7,5,7,6,5,3,7,6,6,1,9,1,5,2,4,9,6,1,5,4,7,2,3,8,5,9,5,7,3,2,3,8,2,5,6,3,8,3]

```

Test case generator. Run with no arguments to have a max length of 100 for \\$A\\$. For a different max length (no larger than \\$891\\$), run with that as an argument.

# Answer
> 16 votes
# AWK -vn=, 9

```
a[$1]++<n

```

This is so competitive with the golfing-language answers, I feel like I might have misunderstood the question - did I?

The limit n is passed as a variable at the command line with `-vn=<value>`. The array is read from STDIN.

Try it online!

# Answer
> 9 votes
# JavaScript (ES6), 35 bytes

Expects `(A)(n)`, where `A` is an array of digit characters.

```
a=>n=>a.filter(v=>!(a[~v]+=v)[n+9])

```

Try it online!

### How?

We use the underlying object of `a[]` to keep track of the number of times each digit has appeared in the string.

By using `~v`, we make sure that we use a *property* of the object (a negative value as a string) rather than an *index* of the array (which is already filled with the input values).

The first time we append `v` to `a[~v]`, we get *undefined* coerced to a string followed by the digit character. Because `"undefined"` is 9 characters long, we know that we've reached `n+1` occurrences of `v` by testing `a[~v][n+9]`.

---

# JavaScript (ES6), 37 bytes

Expects `(A)(n)`, where `A` is an array of integers.

```
a=>n=>a.filter(v=>(a[~v]=-~a[~v])<=n)

```

Try it online!

# Answer
> 9 votes
# Husk, 4 bytes

```
n¹*u

```

Try it online!

I've tried a few different ways, but Razetime's approach turned out to be very concise in Husk.

### Explanation

```
n¹*u    Function of two arguments: A=[6,9,7,6,7,9,9], n=2
   u    Unique values of A: [6,9,7]
  *     Repeated n times: [6,9,7,6,9,7]
n¹      Intersected with A: [6,9,7,6,7,9]

```

# Answer
> 8 votes
# Stax, <sup>~~6~~</sup> 5 bytes

```
°º☻¿_

```

Run and debug it

Output as a string of codepoints(since stax prints all numeric arrays as strings). Verifiable version

## Explanation

```
cua*|b
c       copy the list
 u      uniquify
  a     bring the count to the top
   *    repeat the elements n times
    |b  multiset intersect

```

# Answer
> 7 votes
# MATL, 9 bytes

```
t&=Rsi>~)

```

Inputs `A`, then `n`. Try it online!

Or verify all test cases. For each case this takes a third input containing the desired output. The footer code checks if the program output equals the desired output, and prints `Correct` or `Incorrect` accordingly.

### How it works

Consider inputs `[1 2 3 2 3 2 4 1 2]` and `2` as an example.

```
t    % Implicit input: array A. Duplicate
     % STACK: [1 2 3 2 3 2 4 1 2], [1 2 3 2 3 2 4 1 2]
&=   % Matrix of pairwise comparisons
     % STACK: [1 2 3 2 3 2 4 1 2], [1 0 0 0 0 0 0 1 0
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 1 0 1 0 0 0 0;
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 1 0 1 0 0 0 0;
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 0 0 0 0 1 0 0;
                                    1 0 0 0 0 0 0 1 0;
                                    0 1 0 1 0 1 0 0 1]
R    % Upper triangular part: sets entries below the diagonal to 0
     % STACK: [1 2 3 2 3 2 4 1 2], [1 0 0 0 0 0 0 1 0;
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 1 0 1 0 0 0 0;
                                    0 0 0 1 0 1 0 0 1;
                                    0 0 0 0 1 0 0 0 0;
                                    0 0 0 0 0 1 0 0 1;
                                    0 0 0 0 0 0 1 0 0;
                                    0 0 0 0 0 0 0 1 0;
                                    0 0 0 0 0 0 0 0 1]
s    % Sum of each column. For each entry of A this gives the number
     % of repetitions up to that point
     % STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 2 2 3 1 2 4]
i    % Input: number a
     % STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 2 2 3 1 2 4], 2
>~   % Less than or equal? Element-wise
     % STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 1 1 0 1 1 0]
)    % Apply as an index (logical mask)
     % STACK: [1 2 3 2 3 4 1]
     % Implicit display

```

# Answer
> 6 votes
# , 13 bytes

```
(>:1#.]=]\)#]

```

Try it online!

# Answer
> 4 votes
# Husk, 9 bytes

```
fm≤⁰Sz#ḣ³

```

Try it online!

```
f           # filter input to retain only elements at positions of truthy values of
 m≤⁰        # elements less-than-or-equal to arg 2 of
    Sz#     # count the occurrences of each element of arg1
       ḣ³   # in the list of prefixes of arg1

```

# Answer
> 4 votes
# , 17 bytes

```
0-.~]-1&(]*(-~:))

```

Try it online!

Apparently, this is shorter than a solution using Self-classify `=` or self equality `=/~`.

### How it works

```
0-.~]-1&(]*(-~:))  NB. left: n, right: A
      1&(       )  NB. Apply this function on A, n times...
      1    (-~:)   NB.   Negation of Nub Sieve (mark first occurrence of each number)
         ]*        NB.   Multiply to A so that each first occurrence becomes 0
    ]-             NB. Kill (change to 0) survivors of ^ from the original A
0-.~               NB. Erase zeros by set difference

```

Illustration:

```
n = 2, A = 2 3 8 1 6 4 8 2 8 3
First iteration:
Nub sieve of A = 1 1 1 1 1 1 0 0 0 0
Kill them      = 0 0 0 0 0 0 8 2 8 3

Second iteration:
Nub sieve of ^ = 1 0 0 0 0 0 1 1 0 1
Kill them      = 0 0 0 0 0 0 0 0 8 0

Kill the survivors of ^ = 2 3 8 1 6 4 8 2 0 3
Erase zeros by set diff = 2 3 8 1 6 4 8 2 3

```

# Answer
> 4 votes
# Python 3, 57 bytes

```
lambda a,n:[e for i,e in enumerate(a)if a[:i].count(e)<n]

```

Try it online!

# Answer
> 4 votes
# Python 2, 50 bytes

```
lambda s,n:reduce(lambda r,x:r+x*(r.count(x)<n),s)

```

Try it online!

*-2 bytes from Leo by taking input and output as a string of digits, which is also used in the answers below*

---

# Python 3.8 (pre-release), 53 bytes

```
lambda s,n,r='':[x for x in s if(r:=r+x).count(x)<=n]

```

Try it online!

Input and output as list of characters.

---

**55 bytes**

```
f=lambda s,n:s and f(s[:-1],n)+s[-1][s.count(s[-1])>n:]

```

Try it online!

Repeatedly takes and removes the last element of the list, keeping it if it appears a maximum of `n` times in the current list.

It feels like there should be a better way to express this, but I'm not seeing it. Python is clumsy at dealing with the end of a list. While `l[-k:]` usually takes the last `k` elements from the end, for `k=0` it instead takes the whole list. So, I didn't find a nice single slice that conditionally takes 0 or 1 elements from the end of a list. Also, doing `l.pop()` has the trouble that the recursive function call comes before the expression where we want the last element.

# Answer
> 4 votes
# Haskell, 44 bytes

```
f n=foldl(\r x->r++[x|sum[1|y<-r,y==x]<n])[]

```

Try it online!

# Answer
> 4 votes
# PowerShell Core, ~~38~~ 37 bytes

```
$a,$b=$args
$t=@{}
$a|?{++$t.$_-le$b}

```

-1 byte thanks to *mazzy*!

Try it online!

# Answer
> 4 votes
# , 48 bytes

```
function(x,n)x[diag(diffinv(outer(x,x,"=="))<n)]

```

Try it online!

Test harness taken from Dominic's answer.

Closely related to Luis Mendo's answer, though implementing it in MATL is longer. Rather than zeroing out the lower triangle of the matrix and computing the column sums, this calculates the cumulative sum of each column, then takes the diagonal of the resulting matrix as the filtering criterion -- for some element \\$a\_i\\$ this tells the number of occurrences of \\$a\_i\\$ before index \\$i\\$.

So for instance, using `[6,9,7,6,7,9,9]`:

```
Pairwise equality check:
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    1    0    0    0
[2,]    0    1    0    0    0    1    1
[3,]    0    0    1    0    1    0    0
[4,]    1    0    0    1    0    0    0
[5,]    0    0    1    0    1    0    0
[6,]    0    1    0    0    0    1    1
[7,]    0    1    0    0    0    1    1

Column-wise cumulative sum (with an initial condition of 0):
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0    0    0    0    0    0    0
[2,]    1    0    0    1    0    0    0
[3,]    1    1    0    1    0    1    1
[4,]    1    1    1    1    1    1    1
[5,]    2    1    1    2    1    1    1
[6,]    2    1    2    2    2    1    1
[7,]    2    2    2    2    2    2    2
[8,]    2    3    2    2    2    3    3
The diagonal:
[1] 0 0 0 1 1 1 2

```

# Answer
> 4 votes
# K (ngn/k), ~~18~~ 16 bytes

```
{x@&~y<+/'x=,\x}

```

Try it online!

Adapted from @rak1507's message in the APL Orchard. Takes the list as `x` and the number of occurrences as `y`.

* `+/'x=,\x` get the running totals of the counts of each number in the input
* `&~y<` get indices of the first `y` instances of each value
* `x@` index back into the input

# Answer
> 3 votes
# , 62 bytes

```
function(x,n)x[sapply(seq(x),function(i)sum(x[1:i]==x[i]))<=n]

```

Try it online!

---

...although a port of Luis Mendo's answer is shorter at ~~59~~ 58 bytes (*Thanks to Giuseppe*)

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~23~~ 19 bytes

Saved a couple bytes by looking at Bubbler how negated the mask in their answer.

```
{⍺/⍨(⊢∨(≠⍺×~))⍣⍵⊢0}

```

Don't try it online! because TIO has an older version of Dyalog APL without Unique Mask.

Takes the array on the left and n on the right.

This takes advantage of monadic , which gives a mask to obtain unique elements. While `≠A` lets you keep unique elements in `A`, the mask `1-≠A` inverts it and lets you keep only repeated elements in `A`. Then `A×1-≠A` replaces unique elements with zeroes (this is safe because as the question states, `A` only contains numbers 1-9). The mask `≠A×1-≠A` gives us only unique elements from this new array, but since we replaced unique elements, it lets us keep duplicates (and the first element, but that is always kept no matter what anyway). `(≠A)∨≠A×1-≠A` now gives us a mask for unique elements and duplicates, but not triplicates, etc. By repeating this process `n` times, we get a mask for keeping only n-plicates, and then we just apply that mask to `A` to get the result.

# Answer
> 3 votes
# Jelly, 5 bytes

```
œ&Qx¥

```

Try it online!

Accidental translation of Razetime's Stax answer based on his comment.

```
œ&       Multiset intersection of A with
  Q ¥    the unique elements of A
   x     repeated n times.

```

# Jelly, 7 bytes

```
xċṪ$Ƥ<¥

```

Try it online!

I was going to hold off on posting until I tied caird's 6 bytes, but I feel like I'm so far off the mark that it's worth documenting anyhow.

```
x     ¥    Repeat each element of A by the corresponding elements of:
    Ƥ      for each prefix of A,
 ċ         how many times it contains
  Ṫ$       its last element (which is then not considered).
     <     Is each count less than n?

```

# Answer
> 3 votes
# Java, 157 bytes

```
l->n->java.util.stream.IntStream.range(0,l.length).filter(i->java.util.stream.IntStream.range(0,i+1).filter(j->l[j]==l[i]).count()<=n).map(i->l[i]).toArray()

```

Takes a `int[]` and the integer `n` as input and returns a `int[]`.

Try it online!

# Answer
> 3 votes
# **T-SQL**, 114 bytes

`SELECT C FROM (SELECT B,C,row_number() OVER (PARTITION BY C ORDER BY B) AS D FROM @A) E WHERE D <= @n ORDER BY B;`

Example:

```
DECLARE @A TABLE(B INT IDENTITY(1,1), C INT);
DECLARE @n INT;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3),(2),(3),(2),(4),(1),(2)) AS A(C);
SET @n = 2;

SELECT C --4.Finally select the filtered rows
FROM (SELECT B
            ,C
            ,row_number() OVER (PARTITION BY C ORDER BY B) AS D --1.Create an ordinal for each repetition that increments in ascending order of B
      FROM @A
      ) E
WHERE D <= @n --2.Filter on the windowed function in subquery, removing rows with more than n repetitions
ORDER BY B; --3. Preserve original order of table variable @A (Can't order by in subquery)

```

Returns:

|  | C |
| --- | --- |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 2 |
| 5 | 3 |
| 6 | 4 |
| 7 | 1 |

Only way I could simulate an 'array' was by making a table with an identity on insert to store the insertion order.

# Answer
> 2 votes
# Retina 0.8.2, 52 bytes

```
\d+$
$*
(.)(?=.*,(.)+)(?<=(?(2)$)(?<-2>\1.*)+.)|,.+

```

Try it online! Link includes test cases. Takes `A` as a string of digits and `n` as a positive integer separated by a comma. Explanation:

```
\d+$
$*

```

Convert `n` to unary.

```
(.)(?=.*,(.)+)(?<=(?(2)$)(?<-2>\1.*)+.)|,.+

```

Delete any digit of `A` that is preceded by at least `n` identical digits and also delete `n` from the result.

# Answer
> 2 votes
# Perl 5 `-al`, 28 bytes

```
$l=<>;map$k{$_}++<$l&&say,@F

```

Try it online!

# Answer
> 2 votes
# Ruby, 38 bytes

```
->a,n{w=[0]*10;a.reject{|x|n<w[x]+=1}}

```

Try it online!

# Answer
> 2 votes
# Japt, 8 bytes

```
fVÆâÃc 2

```

Try it online! or Check all test cases

Very similar to the Jelly, Stax, and Husk answers.

Explanation:

```
            # Implicitly store the input array as U and the input number as V
 VÆ         # Create an array of length V
   âÃ       #  Each item in the array is the unique elements of U
     c      # Flatten that array
f           # Only keep elements of U that are in that array...
       2    # ... up to the number of times it appears in that array

```

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 56 bytes

```
(a,n)=>{var b=new int[10];return a.Where(c=>b[c]++<n);}

```

Try it online!

Or 66 bytes if output should explicitly be an array vs an enumerable:

```
(a,n)=>{var b=new int[10];return a.Where(c=>b[c]++<n).ToArray();}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 11 bytes

```
ＮθΦη‹№…ηκιθ

```

Try it online! Link is to verbose version of code. Takes input `n` as an integer and `A` as a string of digits. Explanation:

```
Ｎθ          Input `n` as an integer
   η        Input `A`
  Φ         Filtered where
     №      Count of
         ι  Current character in
      …ηκ   Prefix so far
    ‹       Is less than
          θ Input `n`
            Implicitly print

```

# Answer
> 1 votes
# Julia 1.0, ~~46~~ 43 bytes

```
l$n=(j=0;!i=sum(l[1:(j+=1)].==i)<=n;l[.!l])

```

Try it online!

# Answer
> 1 votes
# C (clang), 62 bytes

```
f(*l,n){for(int m[10]={0};*l;++l)m[*l]++<n&&printf("%d ",*l);}

```

Try it online!

* Expects a 0 terminated array as input

If tacking a 0 filled array as an additional input is valid:

# C (clang), 58 bytes

```
f(*l,n,*o){for(int m[10]={0};*l;++l)m[*l]++<n&&(*o++=*l);}

```

Try it online!

# Answer
> 1 votes
# Haskell, 54 bytes

```
f n|let a?x|sum[1|y<-a,y==x]<n=a++[x]|1>0=a=foldl(?)[]

```

Try it online!

* I was on the right track, one big step behind @xnor answer which cost me 10 bytes!

# Answer
> 1 votes
# Clojure, 76 bytes

```
#(for[[i v](map vector(range)%1):when(<(count(filter #{v}(take i %1)))%2)]v)

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~31~~ 28 bytes

```
nFold[#||Count@##<n&&#2&]

```

Try it online!

Returns an `Or` of digits. Input `[n][A]`.

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 87 bytes

```
	N =INPUT
	T =TABLE()
R	I =INPUT	:F(END)
	T<I> =T<I> + 1
	OUTPUT =I LE(T<I>,N)	:(R)
END

```

Try it online!

Takes input as `N`, then `A`, each element separated by newlines.

```
	N =INPUT			;* Read in N, number to keep
	T =TABLE()			;* create an empty table
R	I =INPUT	:F(END)		;* read in the next input; if none exists, exit
	T<I> =T<I> + 1			;* increment the value at index I (initially 0)
	OUTPUT =I LE(T<I>,N)	:(R)	;* if T<I> is LEQ to N, then output I. Goto R.
END

```

# Answer
> 1 votes
# **Python3, 66 Bytes**

```
def f(A,n):[A.pop(-A[::-1].index(i)-1) for i in A if A.count(i)>n]

```

There are already superior Python answers to this, but thought it's worth a mention as it only uses list methods.

# Answer
> 1 votes
# Java (JDK), 101 bytes

```
l->n->{for(int i=0,j,c;i++<9;)for(j=c=0;j<l.size();)j+=l.get(j)==i?++c>n?l.remove(j)*0:1:1;return l;}

```

Try it online!

Input: `ArrayList<Integer>`

Output: `ArrayList<Integer>`

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
ʒˆ¯¤¢@

```

Try it online or verify all test cases.

**Explanation:**

```
ʒ       # Filter the (implicit) input-list by:
 ˆ      #  Pop and push the current value to the global array
  ¯     #  Push the global array
   ¤    #  Get its last item (without popping the list itself)
    ¢   #  Count how many times it occurs in the global array
     @  #  And check if the (implicit) input-integer is >= this count
        # (after which the filtered list is output implicitly)

```

# Answer
> 1 votes
# Factor, 46 bytes

```
[ '[ [ dup inc get _ > ] reject ] with-scope ]

```

Attempt This Online!

* `'[ ... _ ]` A fried quotation. Slot the top value on the data stack (\\$n\\$) into the `_`.
* `[ ... ] with-scope` Variables set in this quotation get cleared afterward. Without this, the function is not idempotent.
* `[ ... ] reject` Remove values from a sequence for which `[ ... ]` returns true.
* `dup inc get` Increment the value at the current sequence element. In other words, uses the current element as a variable (key) to store and increment its count.
* `>` Is it greater than \\$n\\$?

# Answer
> 1 votes
# Desmos, 57 bytes

```
f(l,n)=l[[l[1...i][l=l[i]].lengthfori=[1...l.length]]<=n]

```

The double `.length` is really bugging me but I can't think of a way to circumvent that at the moment...

Try It On Desmos!

Try It On Desmos! - Prettified

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


title: Implement a zipwith function

text:
# Question
Title: Implement a zipwith function
`zipwith` is a functional construct that takes three arguments: one binary function and two lists of the same length, and returns a single list where each element is constructed by applying the binary function to each pair of elements from the two lists:

```
zipwith (a+b) [1,2,3] [4,5,6] = [5,7,9]

```

You are to take a black-box function which takes exactly two arguments and two non-empty arrays of the same length consisting of positive integers, and output the result of applying `zipwith` to this function and arrays.

For the sake of simplicity, you can assume that the black-box function will always input and output integers within your language's integer domain.

If your answer consists solely of a builtin which does this (for example Haskell's `zipWith`), please edit into this Community Wiki answer. You may input and output in any convenient method.

This is so the shortest code in bytes wins

### Test Cases

```
function, array, array -> output
a = b, [1, 2, 3], [3, 2, 1] -> [0, 1, 0]
a - b, [8, 3], [3, 8] -> [5, -5]
a² + b/2, [6, 8, 1, 3], [5, 3, 6, 2] -> [38, 65, 4, 10]
a × φ(b), [4, 2, 5, 8, 3], [7, 6, 10, 2, 1] -> [24, 4, 20, 8, 3]

```

The third test case uses integer (floor) division. The fourth uses the Euler Totient function

# Answer
> 14 votes
# Haskell, 22 bytes

```
(.zip).(.).map.uncurry

```

Try it online!

Not particularly interesting, just a reimplementation of `zipWith` converted to pointfree form:

```
\f x y -> map (uncurry f) (zip x y)
\f x -> map (uncurry f) . zip x
\f x -> (map (uncurry f) .) zip x
\f -> (map (uncurry f) .) . zip
\f -> (. zip) (map (uncurry f) .)
\f -> (. zip) ((.) (map (uncurry f)))
\f -> (. zip) ((.) ((map . uncurry) f))
\f -> (. zip) ((.) . (map . uncurry) $ f)
\f -> (. zip) . ((.) . (map . uncurry)) $ f
(. zip) . ((.) . (map . uncurry))

```

# Answer
> 11 votes
# Trivial builtin answers

Edit your answer into this post if it consists of a builtin which does the entire task by itself

---

# HBL, 0.5 bytes

```
2

```

(Not implemented in the online version at the time of this writing.)

# Fig, \\$1\log\_{256}(96)\approx\\$ 0.823 bytes

```
z

```

Try it online!

Same as Husk.

# APL (Dyalog Unicode), 1 byte

```
¨

```

Try it online!

# BQN, 1 byte

```
¨

```

Same as APL. Try it at BQN online!

# Husk, 1 byte

```
z

```

Try it online!

# Jelly, 1 byte

```
"

```

Try it online!

# , 2 bytes

```
"0

```

Try it online!

Not technically a builtin, but close enough.

# C#, 3 bytes

```
Zip

```

Try it online!

# Julia, 3 bytes

```
map

```

Try it online!

# Python 2, 3 bytes

```
map

```

Try it online!

# , 3 bytes

```
Map

```

Try it online!

The canonical  built-in function is mapply (6 bytes).
However, the  documentation for `Map` reads *"Map is a simple wrapper to mapply which does not attempt to simplify the result"* (meaning that `Map` leaves its output as a list, rather than a vector, of results), so this seems to be a perfectly-acceptable 3-byte alternative here.

# Factor, 4 bytes

```
2map

```

Try it online!

# Raku, 4 bytes

```
&zip

```

Try it online!

# Haskell, 7 bytes

```
zipWith

```

Try it online!

# Prolog (SWI), 7 bytes

```
maplist

```

Try it online!

# MATLAB / Octave, 8 bytes

```
arrayfun

```

Try it online!

# Elm, 9 bytes

```
List.map2

```

# PHP, 9 bytes

```
array_map

```

Try it online! (PHP's `array_map` can take any number of array arguments)

# Wolfram Language (Mathematica), 9 bytes

```
MapThread

```

Try it online!

# tinylisp, 18 bytes

Not exactly a builtin, but a library function:

```
map*

```

4 bytes for the function, 14 bytes for `(load library)`. Try it online!

# Answer
> 8 votes
# C (gcc), 49 bytes

```
z(f,a,b,n)int*a,*b,(*f)();{for(;n--;f(a++,b++));}

```

Try it online!

Loops for `0-n`, applying `f` on `&a[i], &b[i]`. Fairly simple.

Ungolfed signature:

```
void zipwith(void (*blackbox)(int *, int *), int *a, int *b, int length);

```

This version expects a function like this:

```
void func(int *a, int *b)
{
    *a = *a OP *b;
}

```

It overwrites the contents in `a`.

Since this is a pretty loose interpretation of the rules, I have also provided a more strict version which acts like a normal `zipwith`.

# C (gcc) strict, ~~61~~ 54 bytes

```
z(f,a,b,n)int*a,*b,(*f)();{for(;n--;*a++=f(*a,*b++));}

```

Try it online!

Loops for `0-n`, storing the result of `f` on `a[i], b[i]` to `a[i]`. Fairly simple.

Degolfed signature:

```
void zipwith(int (*blackbox)(int, int), int *a, int *b, int length);

```

Thanks to @att for reminding me I don't need a separate output array, saving 7 bytes.

# Answer
> 7 votes
# Husk, 2 bytes

```
δm

```

Try it online! (Implement the function in the footer, the header passes it to the main code)

Sure, Husk has a trivial builtin solution for this (`z`), but here's the shortest interesting solution :)

`δ` is a higher order function that turns something using an unary function on elements of one list into one using a binary function on elements from two lists.

Here, we turn the map function `m` that applies the (unary) input function to each element of the input list into one that applies the (binary) input function to each pair of elements from the two input lists: exactly what zipWith should do!

# Answer
> 7 votes
# x86-16 machine code, ~~15~~ 14 bytes

Saved 1 byte thanks to @Joshua!

```
AD 50 87 F3 AD 50 87 F3-FF D2 AB E2 F3 C3

```

Callable function.

Inputs:

* `CX` = lengths of both lists
* `[SI]` = address of first list
* `[BX]` = address of second list
* `[DX]` = address of function

Outputs towards `[DI]` = address of output list (buffer needs to be large enough).

Disassembly:

```
       LoopTop:
AD            LODSW           ; AX = [SI], SI+=2
50            PUSH    AX      ; push AX onto stack
87 F3         XCHG    SI, BX  ; swap SI and BX
AD            LODSW           ; AX = [SI], SI+=2
50            PUSH    AX      ; push AX onto stack
87 F3         XCHG    SI, BX  ; swap SI and BX
FF D2         CALL    DX      ; call function at [DX]
                              ; the function should take two items on the stack
                              ; and AX = the return value (stock calling convention)
AB            STOSW           ; [DI] = AX, DI+=2
E2 F3         LOOP    LoopTop ; --CX; jump to top of loop while CX >= 0
C3            RET             ; return to caller

```

## Example run

Tested with DOS debug:

```
-r
AX=0000  BX=0040  CX=0003  DX=0060  SP=FFFE  BP=0000  SI=0030  DI=0050
DS=1000  ES=1000  SS=0B17  CS=1000  IP=0000   NV UP EI PL NZ NA PO NC
1000:0000 AD            LODSW
-u1000:0060
1000:0060 58            POP     AX
1000:0061 A37600        MOV     [0076],AX
1000:0064 58            POP     AX
1000:0065 A37800        MOV     [0078],AX
1000:0068 58            POP     AX
1000:0069 01067800      ADD     [0078],AX
1000:006D A17600        MOV     AX,[0076]
1000:0070 50            PUSH    AX
1000:0071 A17800        MOV     AX,[0078]
1000:0074 C3            RET
-t
AX=0004  BX=0030  CX=0003  DX=0060  SP=FFFF  BP=0000  SI=0042  DI=0050
DS=1000  ES=1000  SS=0B17  CS=1000  IP=0001   NV UP EI PL NZ NA PO NC
1000:0001 50            PUSH    AX
-t
AX=0004  BX=0030  CX=0003  DX=0060  SP=FFFD  BP=0000  SI=0042  DI=0050
DS=1000  ES=1000  SS=0B17  CS=1000  IP=0002   NV UP EI PL NZ NA PO NC
1000:0002 87F3          XCHG    SI,BX
...
-t
AX=0009  BX=0036  CX=0000  DX=0060  SP=FFFF  BP=0000  SI=0046  DI=0056
DS=1000  ES=1000  SS=0B17  CS=1000  IP=000D   NV UP EI PL NZ NA PE NC
1000:000D C3            RET
-d1000:0000
1000:0000  AD 50 87 F3 AD 50 87 F3-FF D2 AB E2 F3 C3 00 19   .P...P..........
1000:0010  00 00 00 00 00 00 00 20-20 20 20 20 20 20 20 20   .......
1000:0020  20 20 20 20 20 20 20 20-20 20 00 00 00 00 00 00             ......
1000:0030  01 00 02 00 03 00 00 00-00 00 00 00 00 00 00 00   ................
1000:0040  04 00 05 00 06 00 00 00-00 00 00 00 00 00 00 00   ................
1000:0050  05 00 07 00 09 00 00 00-00 00 00 00 00 00 00 00   ................
1000:0060  58 A3 76 00 58 A3 78 00-58 01 06 78 00 A1 76 00   X.v.X.x.X..x..v.
1000:0070  50 A1 78 00 C3 00 0A 00-09 00 00 00 00 00 00 00   P.x.............

```

# Answer
> 6 votes
# , 32 bytes

```
function(f,x,y)Vectorize(f)(x,y)

```

Try it online!

If  *didn't* already have a built-in (`mapply`/`Map`) for zipwith, here's how one could implement it in 32 bytes...
(...and if  *didn't* have `Vectorize`, we'd need to implement it the 'hard' way for 54 bytes: `function(f,x,y){for(i in seq(a=x))T[i]=f(x[i],y[i]);T}`)

# Answer
> 6 votes
# Rust, 34 bytes

```
|f,a,b|a.into_iter().zip(b).map(f)

```

Try it online!

Rust doesn't have a `zipwith` function but it does have a `zip` and a `map` function. Returns an iterator over the values.

# Answer
> 6 votes
## **GNU-C-Preprocessor, 90 + O(48\*n) Bytes**

There should be code golf challenges for C preprocessor only, my idea:

```
#define T(x,...) x
#define D(x,y...) y
#define A(f,x,y) f(x,y)
#define Z5(f,x,y) A(f,T x,T y),Z4(f,(D x),(D y))
#define Z4(f,x,y) A(f,T x,T y),Z3(f,(D x),(D y))
#define Z3(f,x,y) A(f,T x,T y),Z2(f,(D x),(D y))
#define Z2(f,x,y) A(f,T x,T y),Z1(f,(D x),(D y))
#define Z1(f,x,y) A(f,T x,T y)

```

This example works for input lists of length \<= 5. You can call the function like this:

```
#define C(x,y) x##y
(Z5(C,(h,e,l,l,o),(w,o,r,l,d)))

```

which results in

```
(hw,eo,lr,ll,od)

```

The "n" is the maximum list length to process and output. Of course you could use single characters instead of "Z" as name but using a digit allows for more flexibility and easier maintenance. For example you could add a parameter for "Z" to specify the bounds which is concatenated as `Z##n` and used as nested macro call.

The C Preprocessor opens a new realm of languages for code golf and is a rather minimal pure-functional primitive-recursive programming language which only features macro substitutions (which look like function calls, '(', ')', ',' and '#' are the only characters with special meaning), stringification, character concatenation (must be result in valid C tokens) and no direct recursion (each call must be defined with different macro name). Primitive-recursive means, it uses inputs of strictly bounded or fixed lengths and the program always terminates for all inputs. If you want a program for unbounded length, you would need an infinite program but program inputs are always bounded in practice. Literally any strictly limited output for strictly limited input values can be programmed by a primitive-recursive program and thus the C preprocessor. The program only must be big enough to compute it. It can become quite memory-inefficient though.

---

## GNU-C Preprocessor, 238 + O(32\*log3(n)) Bytes

A more optimal program size with O(log(n)) program growth is possible but requires hacky additional macro definitions and will only pay off starting with slightly larger input lists. This example purposefully does not add commas between elements in the output to allow for higher flexibility in output.

```
#define L4(p) L3(p) L3(p) L3(p)
#define L3(p) L2(p) L2(p) L2(p)
#define L2(p) L1(p) L1(p) L1(p)
#define L1(p) p() p() p()

#define T(x,...) x
#define D(x,y...) y
#define I(x...) x
#define W(r,f,a,b,x,y) (I r f(a,b)),f,x,y
#define X(r,f,x,y) W(r,f,T x,T y,(D x),(D y))
#define Y(x...) X(x)
#define C() )
#define O() (
#define U(x...) T(x)
#define Z(f,x,y) U(U(L4(Y O)(),f,x,y L4(C)))

```

Explanation:

* `L<x>` is the loop and `<x>` is the exponent of how often to loop.
* `T,U` = take first element from comma-separated list
* `D` = drop first element from comma-separated list
* `I` = identity function (evaluates arguments and can remove parens)
* `A` = applies a function but **without lazy argument-evaluation**
* `X,Y,Z` = the actual zipWith function
* `C` = closing parenthesis, needed for code generation
* `O` = opening parenthesis, needed for code generation (prevents unclosed macro call errors)

The main idea is to code-generate a long nested expression in a loop so that `Z(args)` evaluates to literally `Y ( Y ( Y ( ... args' ...) ) )` and `Y` reduces the arguments by one step when evaluated in `U(U(...))` (it does not work with only one `U`).

This example can process up to 3^4 = 243 elements of two lists. If you want to multiply the processing limit by 3, add a new loop line on the top of the code. You need about 20 loop lines to handle unsigned 32-bit of elements. But keep in mind that each element is evaluated, even if does not exist! This is an example which zip-concatenates elements of two lists and places a comma between elements *iff* the concatenation is not empty:

```
#define V2(x...) ,##x
#define V(x...) V2(x)
#define CONC(x,y...) y##x
#define CONC1(x,y) V(CONC(y,x))
#define D2(x) (D x)
D2(Z(CONC1,(h,e,l,l,o),(w,o,r,l,d)))

```

The result is `(hw ,eo ,lr ,ll ,od)` . It works with any lists with any number of elements but will output at most 243 elements. Tested on godbolt.org.

If you find improvements which aren't only shorter macro names, please feel free to update this answer and leave a comment.

# Answer
> 5 votes
# Husk, 5 bytes

```
mF₁Te

```

Try it online!

Takes the two arrays as arguments, and the function in the footer. You can use any binary function which operates on two `TNum`s from Husk's Commands page.

## Explanation

```
mF₁Te Main program: accepts two arrays
    e two element list from the arrays
   T  transpose
m     map each pair to
 F    itself folded by
  ₁   the black box function

```

# Answer
> 5 votes
# Factor, 24 bytes

```
[ zip swap f assoc>map ]

```

Try it online!

Avoids the obvious built-in `2map` and its trivial generalizations `nmap` and `2map-as`, and uses `zip` and `assoc>map` instead (so it works like e.g. the Rust answer). Takes the input from the stack in the order of `func arr1 arr2`.

Small golfing tip: when using a function that takes an "exemplar" (which specifies the type of the output container), supplying `f` has the same effect as supplying `{ }` (a plain array).

## Factor, using `nmap`, 10 bytes

```
[ 2 nmap ]

```

Try it online!

`nmap` is a generalized version of `map`-family of functions that works with `n` input arrays and `n`-ary functions. Obviously, `2 nmap` works on two input arrays and binary functions.

## Factor, using `2map-as`, 13 bytes

```
[ f 2map-as ]

```

Try it online!

`2map-as` is a simple variation of `2map` that takes an exemplar.

`2map` itself is already listed in the trivial built-in catalogue.

# Answer
> 5 votes
# GNU sed, 55 + 1(r flag) = 56 bytes

GNU sed doesn't even have integers, not to mention functions, lists / arrays, etc. In order to participate, I used the following assumptions for the I/O methods, which hopefully respect the consensus regarding sed:

1. each input list / array is given on a separate input line, with the integers separated by space.
2. the black-box function is predefined under the label `f`.
3. the black-box function arguments are two space separated integers read from the first pattern space line (generated there at runtime during each iteration).
4. the return value of the black-box function is placed on the first pattern space line
5. the output list / array is given as one integer per line.

```
1N                                            # read the 2nd input list
s:([^ ]+) ?(.*\n)([^ ]+) ?(.*):\1 \3\n\2\4:   # put list1[i] and list2[i] on first line
tf;:                                          # call the black-box function `f`
P                                             # print the function return value
D                                             # delete return value, start new iteration

```

Try it online with sed 4.2.2!

The implemented black-box function in the link above is `a == b`. The other test functions are significantly harder to implement in sed, but possible since the language is Turing complete.

# Answer
> 4 votes
# JavaScript (ES6), 32 bytes

```
(F,a,b)=>a.map((x,i)=>F(x,b[i]))

```

Try it online!

# Answer
> 4 votes
# Zsh, 24 bytes

```
for 1 2 (`paste $@`)f $@

```

Try it online!

Uses a black-box function named `f`, with input from two files specified in command line arguments.

However, `paste` alone is really just a `zip`, and this brings up some interesting debate depending on your interpretation of what counts as a "function" under the Unix philosophy of "everything should be a text stream":

```
#!/bin/zsh

# using a predefined function F
z1() { paste $1 $2 | F }
# using a function named in the arguments
z2() { paste $1 $2 | $3 }

F() { while read line; do rev <<< line; done }
z1 input1 input
z2 input1 input2 F
paste input1 input2 | F
paste input1 input2 | rev

# so maybe paste is just a point-free function?
paste

```

So maybe this is a trivial built-in solution:

**Unix shell (?), 5 bytes (?)**

```
paste

```

# Answer
> 4 votes
# Java 8, 52 bytes

```
A->B->{for(int l=A.length;l-->0;)A[l]=f(A[l],B[l]);}

```

Puts the result in the first argument instead of returning a new integer-array (to save 25 bytes).

Try it online.

**Explanation:**

```
A->B->{                     // Method with two integer-array parameters & no return-type
  for(int l=A.length;l-->0;)//  Loop `l` in the range (length,0]:
    A[l]=                   //   Change the `l`'th item in the first array to:
      f(                    //    Call the black-box function `f`
        A[l],B[l]);}        //    with the `l`'th items of both arrays as parameters

```

**Black box input format:**

Assumes a named function `Object f(Object a,Object b)` is present, which is allowed according to this meta answer.

I have an abstract class `Test` containing the default function `f(a,b)`, as well as the lambda above:

```
abstract class Test{
  Object f(Object a,Object b){
    return(int)a+(int)b;
  }

  public java.util.function.Function<Object[], java.util.function.Consumer<Object[]>>c=
    A->B->{for(int l=A.length;l-->0;)A[l]=f(A[l],B[l]);}
  ;
}

```

For the test cases, I overwrite this function `f`. For example, the third test case (which is responsible for the black-box having `Object` as parameters/return-type instead of `int`) is called like this:

```
Object[] a = new Object[]{1,2,3};
new Test(){
  @Override
  Object f(Object a,Object b){
    return a==b;
  }
}.c.apply(a).accept(new Object[]{3,2,1});
System.out.println(java.util.Arrays.toString(a));

```

# Answer
> 4 votes
# Nim, 71 70 bytes

```
iterator z[I](f:proc(x,y:I):I;a,b:seq):I=
 for i,x in a:yield x.f b[i]

```

Try it online!

# Answer
> 4 votes
# Idris \- 77 bytes

```
z:(a->b->c)->List a->List b->List c
z f(x::v)(y::w)=f x y::z f v w
z _ _ _=[]

```

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

```
Inner[##,]&

```

Try it online!

Returns a `Null` of results.

`Inner` *almost* does zipwith - except, by default, it returns the sum of the results.

---

### Also 11 bytes

```
#@@@In@@#2&

```

Try it online!

`In` (among others) is as short as a built-in `Listable` function gets, and remains unevaluated with \>1 argument.

# Answer
> 3 votes
## Stax, 6 bytes invocable, or 3 bytes toplevel

Does not make sense to compress functions in stax so I didn't.

The two arrays are passed on the stack, and the black-box function is passed in the x register.

```
|\{x!m

```

Explained:

```
|\                Zip input arrays
  {
   x              push contents of x register
    !             invoke top of stack
  m               map

```

Program head version: two arrays are passed to it on the stack; body of blackbox program follows

```
|\m

```

Explained:

```
|\                Zip input arrays
  m               map array with rest of program

```

# Answer
> 2 votes
# Red, 69 bytes

```
func[a b f][collect[repeat i length? a[keep compose[(f a/:i b/:i)]]]]

```

Try it online!

## Printing the result instead of returning it:

## 61 bytes

```
func[a b f][repeat i length? a[print compose[(f a/:i b/:i)]]]

```

Try it online!

# Answer
> 2 votes
# Racket, 41 bytes

```
(λ(x y f)(for/list([i x][j y])(f i j))))

```

Try it online!

`for/list` is almost the necessary builtin, just needs some additional syntax.

# Answer
> 2 votes
# Scala 3 (compile time), 87 bytes

```
type Z[F[_,_],A<:Tuple,B]<:Tuple=(A,B)match{case(a*:b,c*:d)=>F[a,c]*:Z[F,b,d]case _=>A}

```

Try it online!

Takes tuples instead of lists.

This isn't particulary interesting or complicated, but here's an explanation:

```
type Z[                //Declare a type Z taking these arguments
  F[_,_],              //A type F that itself takes two arguments
  A <: Tuple,          //The first list, a tuple
  B                    //The second list (actually also a tuple)
] <: Tuple =           //The returned type is also a tuple
  (A, B) match {       //Make a tuple (A, B) and match it:
  //`h*:t` represents a tuple with head `h` and tail `t` (like :: or :)
  case (a *: b, c *: d) => //If A is of the form a*:b and B is of the form c*:d
    F[a, c]         //Call F on the heads
      *:            //And prepend that to
      Z[F, b, d]    //The result of zipping the rest of the tuples
  case _ => A //Otherwise, both tuples are empty, so we return an empty tuple
  }

```

# Answer
> 2 votes
# Pure Zsh, 31 bytes

```
b=($=3)
for 2 3 (${${=2}:^b})$@

```

Try it online!

Takes parameters `function name, space-delimited list, space-delimited list`

With `-o shwordsplit`, one byte is saved with `b=($3)` instead.

```
b=($=3)                  # =split $3 and save as array $b
#        ${${=2}:^b}     # Zip $=2 and $b together
for 2 3 (${${=2}:^b})    # Loop over 2 at a time as $2 and $3 (argv[2], argv[3])
    $@                   # $1 $2 $3

```

# Answer
> 2 votes
# Python 3, ~~37~~ 35 bytes

```
lambda f,*a:[f(*t)for t in zip(*a)]

```

Try it online!

# Answer
> 2 votes
# Groovy, 36 bytes

```
{f,a,b->[a,b].transpose().collect f}

```

Try it online!

# Answer
> 2 votes
# PowerShell, 93 bytes

```
function Z($F,$S,$R={,$args}){[Linq.Enumerable]::Zip($F,$S,[Func[Object,Object,Object[]]]$R)}

```

**Example**

```
Z (1,2,3) (4,5,6) {param($a, $b) ($a+$b)}
'-'
Z (8,3) (3,8) {param($a, $b) ($a-$b)}
'-'
Z (6,8,1,3) (5,3,6,2) {param($a, $b) ([math]::pow($a,2)+$b/2)}
'-'
Z (1,2,3) (3,2,1) {param($a, $b) ([int]($a-eq$b))}

```

Try it online!

It is a zip function which can take map expression as its third parameter to know how to pass it then see the demo in the Try it online "Footer" section how to use it.

# Answer
> 2 votes
# Python 3, 19 bytes

```
lambda*l:[*map(*l)]

```

Try it online!

# Answer
> 2 votes
# Vyxal, 5 bytes

```
£Zƛ¥R

```

Try it Online!

I don't know how to input functions properly in Vyxal, so the Vyxal interpreter link just has the function stuffed with the code.

```
£Zƛ¥R
£     Set the register to the blackbox function
 Z    Zip the two lists
  ƛ   For each element of that
    R Reduce using
   ¥  The function in the register

```

# Answer
> 2 votes
# Pip `-xp`, 5 bytes

```
aMZbc

```

Try It Online!

### Explanation

This is essentially a built-in, the ternary `MZ` (map-zip) operator. However, I'm pretty sure a bare operator isn't a valid solution, so I've made it a full program. The `-x` flag allows functions and lists to be evaluated as such when passed as command-line arguments, and the `-p` flag means lists will be output in list format rather than concatenated together.

# Answer
> 1 votes
# Icon, 52 bytes

```
procedure z(a,b,f)
write(f(a[i:=1to*a],b[i]))&\y
end

```

Try it online!

# Answer
> 1 votes
# CJam, 8 bytes

```
l'.l++~p

```

Try it online! Or verify the first three cases: , , .

Input is a line with (the string representation of) two arrays, and then a line with (the string representation of) the function, defined as a CJam block.

### How it works

```
l    e# Read line containing the two arrays
'.   e# Push character "." (which will do the actual job)
l    e# Read line containing a code block
++   e# Concatenate twice
~    e# Evaluate as CJam code
p    e# Print

```

# Answer
> 1 votes
# Perl 5, ~~46~~ bytes, 37 bytes

-9 bytes thanks to Kjetil S.

```
sub{map$_[0](@_[$_,$_+@_/2]),1..@_/2}

```

Try it online!

# Answer
> 1 votes
# Lua, 63 bytes

```
load'o,f,a,b={},...for i=1,#a do o[i]=f(a[i],b[i])end return o'

```

Try it online!

Functions are 1st-class values in Lua, so this is pretty simple (if a bit long because of it's need to iterate).

# Answer
> 1 votes
## Batch, 99 bytes

```
@set/pf=
@set/ps=
@call:c %s%
@exit/b
:c
@set/ps=
@for %%i in (%s%)do @call %f% %%1 %%i&shift

```

Takes three lines of input, the command or batch function to execute, followed by two space or comma separated lists. Works fine with numbers but anything needing quoting is likely to crash and burn. Explanation:

```
@set/pf=

```

Input the command or function to execute.

```
@set/ps=

```

Input the first list.

```
@call:c %s%

```

Call the subroutine, expanding the list into separate parameters.

```
@exit/b

```

Exit the program.

```
:c

```

Declare the subroutine.

```
@set/ps=

```

Input the second list.

```
@for %%i in (%s%)do

```

Expand the list, looping over each element.

```
@call %f% %%1 %%i&shift

```

Call the command or function, passing in the current element from both the first and current list, then shift the element from the first list. The use of `call` here both allows the function to be a batch script but also allows the expansion of `%1` to be delayed using an extra `%` so that it uses the most recently shifted value.

# Answer
> 1 votes
# Io, 37 bytes

```
method(f,a,b,a map(i,x,f(x,b at(i))))

```

Try it online!

# Answer
> 1 votes
# Ruby, 34 bytes

```
def z(f,b)zip(b).map{|p|f.(*p)}end

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
øε`I.V

```

Try it online or verify all test cases.

05AB1E lacks functions, but strings can be used with an eval builtin to mimic the behavior of functions (which I've also used pretty often for recursive `[ragged-list]` challenges).

**Explanation:**

```
ø       # Zip the first two (implicit) input-lists
 ε      # Map over each pair:
  `     #  Pop and push the contents of the pair separated to the stack
   I    #  Push the third input function-string
    .V  #  Evaluate and execute it as 05AB1E code
        # (after which the resulting list is output implicitly)

```

# Answer
> 1 votes
# Go, ~~90~~ 89 bytes

```
func z[T any](f func(T,T)T,l,r[]T)(o[]T){for i:=range l{o=append(o,f(l[i],r[i]))}
return}

```

Attempt This Online!

In a strange reversal, this answer is 1 byte *shorter* if made generic. Usually the generic version is more verbose.

### Old answer, `int`s only, 90 bytes

```
func(f func(int,int)int,l,r[]int)(o[]int){for i:=range l{o=append(o,f(l[i],r[i]))}
return}

```

Attempt This Online!

The fun thing about Go is that you have to implement things like the functional programming functions "from scratch" every single time.

# Answer
> 0 votes
# Ruby, 26 bytes

Like Donat’s answer, just tighter syntax and doesn’t have to monkey-patch Array.

```
->(f,a,b){a.zip(b).map &f}

```

Attempt This Online!

# Answer
> 0 votes
# QBasic, 59 bytes

```
SUB z(a(),b(),n)
FOR i=1TO n
a(i)=f(a(i),b(i))
NEXT
END SUB

```

Defines a subprogram `z` that takes two arrays and their length, calls a predefined function `f` on pairs of elements, and stores the results back into the first array. It can be invoked either as `CALL z(a(), b(), n)` or as `z a(), b(), n`.

### Explanation

The tricky part was figuring out a way to do this at all in QBasic, since it doesn't have first-class functions, function pointers, or the ability to return arrays from functions. Once I found a combination of technically allowed approaches that would work, the code itself was pretty straightforward: loop over each index `i` and set `a(i)` to `f(a(i), b(i))`.

### Testing instructions

You can run QBasic code at Archive.org. Here's a full program that runs the third test case:

```
CLS
CONST LENGTH = 4
DIM a(LENGTH), b(LENGTH)

DATA 6, 8, 1, 3
DATA 5, 3, 6, 2

FOR i = 1 TO LENGTH
  READ a(i)
NEXT i
FOR i = 1 TO LENGTH
  READ b(i)
NEXT i

CALL z(a(), b(), LENGTH)

FOR i = 1 TO LENGTH
  PRINT a(i);
NEXT i
PRINT

FUNCTION f(x, y)
f = x ^ 2 + y \ 2
END FUNCTION

SUB z(a(),b(),n)
FOR i=1TO n
a(i)=f(a(i),b(i))
NEXT
END SUB

```

Note: as soon as you type the `FUNCTION` or `SUB` line, the editor will automatically add the corresponding `END FUNCTION` or `END SUB` and put the new function/subprogram in its own window. To add the sub after entering the function, position your cursor below the `END FUNCTION` line and start typing from `SUB z(...`. Once you've entered both the function and the sub, you can run the program using Run \> Start (or press F5). You can also switch between the sub, function, and main program using View \> SUBs (or press F2).

# Answer
> 0 votes
# Arturo, 37 bytes

```
$[f a b][map combine a b'x->f x\0x\1]

```

Try it

# Answer
> 0 votes
# Japt, 3 bytes

The same byte count as using the interleave built-in.

Takes the arrays as input as a single, 2D array. Black box function is pre-assigned to variable `V`.

```
yrV

```

Try it

---
Tags: code-golf, array, integer, functional-programming
---


title: Calculate the value of \$\zeta(s)\$

text:
# Question
Title: Calculate the value of \$\zeta(s)\$
## Challenge

Given an integer, \\$s\\$, as input where \\$s\geq 1\\$ output the value of \\$\zeta(s)\\$ (Where \\$\zeta(x)\\$ represents the Riemann Zeta Function).

## Further information

\\$\zeta(s)\\$ is defined as:

$$\zeta(s) = \sum\limits^\infty\_{n=1}\frac{1}{n^s}$$

You should output your answer to 5 decimal places (no more, no less). If the answer comes out to be infinity, you should output \\$\infty\\$ or equivalent in your language.

Riemann Zeta built-ins are allowed, but it's less fun to do it that way ;)

## Examples

***Outputs must be exactly as shown below***

```
Input -> Output
1 -> ∞ or inf etc.
2 -> 1.64493
3 -> 1.20206
4 -> 1.08232
8 -> 1.00408
19 -> 1.00000

```

## Bounty

As consolation for allowing built-ins, I will offer a 100-rep bounty to the shortest answer which **does not** use built-in zeta functions. (The green checkmark will still go to the shortest solution overall)

## Winning

The shortest code in bytes wins.

# Answer
> 13 votes
# Mathematica, ~~9~~ ~~7~~ 11 bytes

```
Zeta@#~N~6&

```

Explanation:

```
Zeta@#       (* Zeta performed on input *)
      ~N     (* Piped into the N function *)
        ~6   (* With 6 digits (5 decimals) *)
          &  (* Make into function *)

```

Without builtin:

# Mathematica, 23 UTF-8 bytes

```
Sum[1/n^#,{n,∞}]~N~6&

```

Thanks to Kelly Lowder

# Answer
> 9 votes
# Javascript, ~~81~~ ~~70~~ ~~66~~ 65 bytes

```
s=>s-1?new Int8Array(1e6).reduce((a,b,i)=>a+i**-s).toFixed(5):1/0

```

## Runnable examples:

```
ζ=s=>s-1?new Int8Array(1e6).reduce((a,b,i)=>a+i**-s).toFixed(5):1/0

const values = [ 1, 2, 3, 4, 8, 19 ];
document.write('<pre>');
for(let s of values) {
  document.write('ζ(' + s + ') = ' + ζ(s) + '\n')
}
```

# Answer
> 7 votes
# APL (Dyalog), ~~22~~ 21 bytes

Look ma, no built-ins! -1 thanks to ngn.

Since Dyalog APL does not have infinities, I use Iverson's proposed notation.

```
{1=⍵:'¯'⋄5⍕+/÷⍵*⍨⍳!9}

```

Try it online!

`{` anonymous function:

`1=⍵:` if the argument is one, then:

`'¯'` return a macron

else

`!9` factorial of nine (362880)

first that many integers **i**ntegers

`⍵*⍨` raise them to the power of the argument

`÷` reciprocal values

`+/` sum

`5⍕` format with five decimals

`}` \[end of anonymous function\]

# Answer
> 5 votes
# C (gcc), ~~112~~ ~~101~~ ~~94~~ 84 bytes

Thanks for the golfing tips from ceilingcat.

```
n;f(s){float r;for(n=98;n;r+=pow(n--,-s));printf("%.5f",r+pow(99,-s)*(.5+99./--s));}

```

Try it online!

# Answer
> 5 votes
## C, ~~74~~ ~~70~~ 69 bytes

```
n;f(s){double z=n=0;for(;++n>0;)z+=pow(n,-s);printf("%.5f",z/=s!=1);}

```

Compile with `-fwrapv`. It will take some time to produce an output.

See it work here. The part `++n>0` is replaced with `++n<999999`, so you don't have to wait. This keeps identical functionality and output.

# Answer
> 5 votes
# TI-Basic, 16 bytes (no builtins)

```
Fix 5:Σ(X^~Ans,X,1,99

```

# Answer
> 3 votes
# Julia, 36 bytes

```
x->x!=1?@sprintf("%.5f",zeta(x)):Inf

```

# Answer
> 3 votes
# C,~~129 130~~ 128 bytes

```
#include<math.h>
f(s,n){double r=0;for(n=1;n<999;++n)r+=(n&1?1:-1)*pow(n,-s);s-1?printf("%.5f\n",r/(1-pow(2,1-s))):puts("oo");}

```

it uses the following formula

test and results

```
main(){f(2,0);f(1,0);f(3,0);f(4,0);f(8,0);f(19,0);}

1.64493
+oo
1.20206
1.08232
1.00408
1.00000

```

# Answer
> 3 votes
# Rust, ~~133 129 120~~ 117 bytes

```
fn f(s:f64){let mut y@mut n=0.;while n<999.{n+=1.;y-=f64::powf(-1.,n)/n.powf(s)}print!("{:.5}",y/(1.-(1.-s).exp2()))}

```

Try it online!

Thanks to @Steffan for -9.

Slightly golfed less

```
fn f(s:f64){
  let mut y@mut n=0.;
  while n<999.{
    n+=1.;
    y-=f64::powf(-1.,n)/n.powf(s)
  }
  print!("{:.5}",y/(1.-(1.-s).exp2()))
}

```

# Answer
> 2 votes
# MATL, 21 bytes

```
q?'%.5f'2e5:G_^sYD}YY

```

Try it online!

### Explanation

Input `1` is special-cased to output `inf`, which is how MATL displays infinity.

For inputs other than `1`, summing the first `2e5` terms suffices to achieve a precision of 5 decimal places. The reason is that, from direct computation, this number of terms suffices for input `2`, and for greater exponents the tail of the series is smaller.

```
q         % Input (implicit) minus 1
?         % If non-zero
  '%.5f'  %   Push string: format specifier
  2e5:    %   Push [1 2 ... 2e5]
  G       %   Push input again
  _       %   Negate
  ^       %   Power. element-wise
  s       %   Sum of array
  YD      %   Format string with sprintf
}         % Else
YY        %   Push infinity
          % End (implicit)
          % Display (implicit)

```

# Answer
> 2 votes
# R, 54 bytes

```
function(a){round(ifelse(a==1,Inf,sum((1:9^6)^-a)),5)}

```

Finds the sum directly and formats as desired, outputs `Inf` if a is 1. Summing out to `9^6` appears to be enough to get five-place accuracy while still being testable; `9^9` would get better accuracy in the same length of code. I could get this shorter if R had a proper ternary operator.

# Answer
> 2 votes
# Python 3: 67 bytes (no built-ins)

```
f=lambda a:"∞"if a<2else"%.5f"%sum([m**-a for m in range(1,10**6)])

```

Nothing fancy, only uses python **3** because of the implicit utf-8 encoding.

Try it online with test cases.

# Answer
> 1 votes
# Python 3 \+ SciPy, 52 bytes

```
lambda n:'%.5f'%zeta(n,1)
from scipy.special import*

```

Try it online!

# Answer
> 1 votes
# Jelly, 23 bytes

```
ȷ6Rİ*⁸S÷Ị¬$ær5;ḷỊ?”0ẋ4¤

```

**Try it online!**

### How?

* Sums the first million terms
* Divides by `0` when `abs(input)<=1` to yield `inf` (rather than `14.392726722864989`) for `1`
* Rounds to 5 decimal places
* Appends four zeros if `abs(result)<=1` to format the `1.0` as `1.00000`
* Prints the result

```
ȷ6Rİ*⁸S÷Ị¬$ær5;ḷỊ?”0ẋ4¤ - Main link: s
ȷ6                      - literal one million
  R                     - range: [1,2,...,1000000]
   İ                    - inverse (vectorises)
     ⁸                  - link's left argument, s
    *                   - exponentiate
      S                 - sum
          $             - last two links as a monad:
        Ị               -   insignificant? (absolute value of s less than or equal to 1?)
         ¬              -   not (0 when s=1, 1 when s>1)
       ÷                - divide (yielding inf when s=1, no effect when s>1)
           ær5          - round to 10^-5
                      ¤ - nilad followed by link(s) as a nilad:
                  ”0    -   literal '0'
                    ẋ4  -   repeated four times
                Ị?      - if insignificant (absolute value less than or equal to 1?)
              ;         -       concatenate the "0000" (which displays as "1.00000")
               ḷ        - else: left argument
                        - implicit print

```

# Answer
> 1 votes
# Perl 6, 50 bytes

```
{$_-1??(1..1e6).map(* **-$_).sum.fmt('%.5f')!!∞}

```

# Answer
> 1 votes
# PARI/GP, ~~27~~ 26 bytes

```
\p 6
s->trap(,inf,zeta(s))

```

# Answer
> 1 votes
# MathGolf, 14 bytes (no builtins)

```
┴¿Å'∞{◄╒▬∩Σ░7<

```

Note that in the TIO link, I have substituted  for , which pushed \\$10^6\\$ instead of \\$10^7\\$. This is because the version submitted here timeouts for all test cases. This results in the answers for 3 and 8 to be off by 1 decimal place. However, there are way bigger 1-byte numerical literals in MathGolf, allowing for arbitrary decimal precision.

Try it online!

## Explanation

```
┴                check if equal to 1
 ¿               if/else (uses one of the next two characters/blocks in the code)
  Å              start block of length 2
   '∞            push single character "∞"
     {           start block or arbitrary length
      ◄          push 10000000
       ╒         range(1,n+1)
        ▬        pop a, b : push(b**a)
         ∩       pop a : push 1/a (implicit map)
          Σ      sum(list), digit sum(int)
           ░     convert to string (implicit map)
            7    push 7
             <   pop(a, b), push(a<b), slicing for lists/strings

```

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

```
s=>[...Array(1e6)].reduce((a,b,i)=>s>1>i?a:i**-s+a,0).toFixed(5)

```

Try it online!

Pointed in Frxstrem's

# Answer
> 1 votes
# Vyxal, 19 bytes

```
ċ[₆(n⁰eĖ⅛)¾∑øḋ7Ẏ|\∞

```

Try it Online!

No builtins used, used 4 bytes on the decimal places

# Answer
> 0 votes
# Jelly, 26 bytes

```
⁵*5İH+µŒṘḣ7
⁴!Rİ*³SÇµ’İµ’?

```

Don't try it online with this link! (Since this uses 16!~20 trillion terms, running on TIO produces a MemoryError)

Try it online with this link instead. (Uses 1 million terms instead. Much more manageable but takes one more byte)

Returns `inf` for input 1.

**Explanation**

```
⁵*5İH+µŒṘḣ7    - format the output number
⁵*5İH+         - add 0.000005
      µŒṘ      - get a string representation
         ḣ7    - trim after the fifth decimal.

⁴!Rİ*³SÇµ’İµ’? - main link, input s
           µ’? - if input minus 1 is not 0...
⁴!R            -   [1,2,3,...,16!] provides enough terms.
   İ           -   take the inverse of each term
    *³         -   raise each term to the power of s
      S        -   sum all terms
       Ç       -   format with the above link
               - else:
        µ’İ    -   return the reciprocal of the input minus 1 (evaluates to inf)

```

Out of the 26, bytes, 7 are used for computation, 12 are for formatting, and 7 are for producing `inf` on zero. There has to be a better golf for this.

# Answer
> 0 votes
# , 33 bytes (no built-ins)

```
_:^:('*'&e.)7j5":1#.1%[^~1+i.@1e6

```

Attempt This Online!

```
_:^:('*'&e.)7j5":1#.1%[^~1+i.@1e6
                           i.@1e6  NB. integers up to 1e6
                         1+        NB. add one
                      [^~          NB. nʸ for each in 1..1e6
                    1%             NB. reciprocal of each
                 1#.               NB. sum the result
            7j5":                  NB. format each result, width of 7, 5 decimal places
  ^:                               NB. if
    ('*'&e.)                       NB. '*' is in the formatted result
                                   NB. (": fills with *'s if the width is too small)
_:                                 NB. return an infinity

```

# Answer
> 0 votes
# 05AB1E, 20 bytes

```
i'∞ë6°LImzO5.ò¾4×«7£

```

4 bytes are used to account for edge case \\$n=1\\$, and 9 bytes to round to five decimal places (6 of which for edge case `1.00000`)..

Try it online or verify all test cases.

**Explanation:**

```
i          # If the (implicit) input-integer is 1:
 '∞       '#  Push "∞"
ë          # Else:
 6°        #  Push 10 to the power 6: 1,000,000
   L       #  Pop and push a list in the range [1,1000000]
    Im     #  Get the power of the input on each integer
      z    #  Calculate 1/value for each
       O   #  Sum everything together
 5.ò       #  Round to 5 decimal places
    ¾4×    #  Push a string of 4 zeros: "0000"
       «   #  Append it to the result
        7£ #  Pop and leave just the first 7 characters: "1.abcde"
           # (after which the result is output implicitly as result)

```

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