# Question
Title: The number of ways a number is a sum of consecutive primes
Given an integer greater than 1, output the number of ways it can be expressed as the sum of one or more consecutive primes.

Order of summands doesn't matter. A sum can consist of a single number (so the output for any prime will be at least 1.)

This is . Standard rules apply.

See this OEIS wiki for related information and sequences, including the sequence itself OEIS A054845.

### Test cases

```
2 => 1
3 => 1
4 => 0
5 => 2
6 => 0
7 => 1
8 => 1
10 => 1
36 => 2
41 => 3
42 => 1
43 => 1
44 => 0
311 => 5
1151 => 4
34421 => 6

```

# Answer
# Jelly,  ~~6~~  5 bytes

-1 thanks to dylnan

```
ÆRẆ§ċ

```

A monadic link

**Try it online!** Or see the test-suite (note the final test case would time out at 60s at TIO).

### How?

```
ÆRẆ§ċ - Link: integer, n
ÆR    - primes from 2 to n inclusive
  Ẇ   - all contiguous substrings
   §  - sum each
    ċ - count occurrences of n

```
> 9 votes

# Answer
# , 95 bytes

```
function(x,P=2){for(i in 2:x)P=c(P,i[all(i%%P)])
for(i in 1:x){F=F+sum(cumsum(P)==x)
P[i]=0}
F}

```

Try it online!

* -24 bytes thanks to @Giuseppe who has basically revolutionized my solution supporting 34421 as well !
> 8 votes

# Answer
# 05AB1E, 6 bytes

### Code

```
ÅPŒOQO

```

Uses the **05AB1E** encoding. Try it online!
> 5 votes

# Answer
# Brachylog, ~~14~~ 9 bytes

```
{⟦ṗˢs+?}ᶜ

```

Try it online!
Multiple test cases

*(-5 whole bytes, thanks to @Kroppeb!)*

### Explanation:

```
{⟦ṗˢs+?}ᶜ
{      }ᶜ     Count the number of ways this predicate can succeed:
 ⟦            Range from 0 to input
  ṗˢ          Select only the prime numbers
    s         The list of prime numbers has a substring (contiguous subset)
     +        Whose sum
      ?       Is the input

```
> 4 votes

# Answer
# JavaScript (ES6), 92 bytes

```
n=>(a=[],k=1,g=s=>k>n?0:!s+g(s>0?s-(p=d=>k%--d?p(d):d<2&&a.push(k)&&k)(++k):s+a.shift()))(n)

```

Try it online!

### Commented

```
n => (                          // n = input
  a = [],                       // a[] = array holding the list of consecutive primes
  k = 1,                        // k = current number to test
  g = s =>                      // g = recursive function taking s = n - sum(a)
    k > n ?                     //   if k is greater than n:
      0                         //     stop recursion
    :                           //   else:
      !s +                      //     increment the final result if s = 0
      g(                        //     add the result of a recursive call to g():
        s > 0 ?                 //       if s is positive:
          s - (                 //         subtract from s the result of p():
            p = d => k % --d ?  //           p() = recursive helper function looking
              p(d)              //                 for the highest divisor d of k,
            :                   //                 starting with d = k - 1
              d < 2 &&          //           if d is less than 2 (i.e. k is prime):
              a.push(k) &&      //             append k to a[]
              k                 //             and return k (else: return false)
          )(++k)                //         increment k and call p(k)
        :                       //       else:
          s + a.shift()         //         remove the first entry from a[]
                                //         and add it to s
      )                         //     end of recursive call
  )(n)                          // initial call to g() with s = n

```
> 4 votes

# Answer
# MATL, ~~15~~ 12 bytes

```
EZqPYTRYsG=z

```

Try it on MATL Online

The initial `E` (multiply by 2) makes sure that, for prime input, the result of the later `Ys` (`cumsum`) does not have the input prime repeating itself in the zeroed part of the matrix (thus messing with the count).

### Explanation:

```
                % Implicit input, say 5
E               % Double the input
 Zq             % Get list of primes upto (and including) that
                %  Stack: [2 3 5 7]
   P            % Reverse that list
    YT          % Toeplitz matrix of that
                %  Stack: [7 5 3 2
                           5 7 5 3
                           3 5 7 5
                           2 3 5 7]
      R         % `triu` - upper triangular portion of matrix
                %  Stack: [7 5 3 2
                           0 7 5 3
                           0 0 7 5
                           0 0 0 7]
       Ys       % Cumulative sum along each column
                %  Stack: [7  5  3  2
                           7 12  8  5
                           7 12 15 10
                           7 12 15 17]

         G=     % Compare against input - 1s where equal, 0s where not
           z    % Count the number of non-zeros

```
> 4 votes

# Answer
# MATL, 16 bytes

```
:"GZq@:g2&Y+G=vs

```

Try it at MATL Online!

### Explanation

```
:"        % Input (implicit): n. For each k in [1 2 ... n]
  G       %   Push n
  Zq      %   Primes up to that
  @:g     %   Push vector of k ones
  2&Y+    %   Convolution, removing the edges
  G=      %   True for entries that equal n
  v       %   Concatenate vertically with previous results
  s       %   Sum
          % End (implicit). Display (implicit)

```
> 3 votes

# Answer
# Husk, ~~9~~ 8 bytes

<sup>-1 byte thanks to Mr.Xcoder (use named argument `¹` instead of `S`)!</sup>

```
#¹ṁ∫ṫ↑İp

```

Try it online!

### Explanation

```
#¹ṁ∫ṫ↑İp  -- example input: 3
#¹        -- count the occurrences of 3 in
      İp  -- | primes: [2,3,5,7..]
     ↑    -- | take 3: [2,3,5]
    ṫ     -- | tails: [[2,3,5],[3,5],[5]]
  ṁ       -- | map and flatten
   ∫      -- | | cumulative sums
          -- | : [2,5,10,3,8,5]
          -- : 1

```
> 3 votes

# Answer
# Retina 0.8.2, 68 bytes

```
.+
$*_$&$*
_
$`__¶
A`^(__+)\1+$
m)&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1)

```

Try it online! Link includes faster test cases. Explanation:

```
m)

```

Run the whole script in multiline mode where `^` and `$` match on every line.

```
.+
$*_$&$*

```

Convert to unary twice, first using `_`s, then using `1`s.

```
_
$`__¶

```

Generate all the prefixes of the `_`s and add two to each, thus counting from \\$2\\$ to \\$n + 1\\$.

```
A`^(__+)\1+$

```

Delete all the composite numbers in the range.

```
&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1)

```

Match any number of `_`s and newlines (starting and ending at the end of a line) then compare the number of `_`s with the number of `1`s. Count the number of sums of consecutive prime numbers which add up to \\$n\\$.
> 3 votes

# Answer
# Clean, ~~100~~ 98 bytes

```
import StdEnv,StdLib
$n=sum[1\\z<-inits[i\\i<-[2..n]|all(\j=i/j*j<i)[2..i-1]],s<-tails z|sum s==n]

```

Try it online!

Defines the function `$ :: Int -> Int` which works as explained below:

```
$ n                              // the function $ of n is
    = sum [                      // the sum of
        1                        // 1, for every
        \\ z <- inits [          // prefix z of
            i                    // i, for every
            \\ i <- [2..n]       // integer i between 2 and n
            | and [              // where every
                i/j*j < i        // j does not divide i
                \\ j <- [2..i-1] // for every j between 2 and i-1
            ]
        ]
        , s <- tails z           // ... and suffix s of the prefix z
        | sum s == n             // where the sum of the suffix is equal to n
    ]

```

(Explanation is for an older but logically identical version)
> 2 votes

# Answer
# Java 10, ~~195~~ ~~194~~ ~~184~~ 182 bytes

```
n->{var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}for(x=L.size(),i=0;i<x;)for(k=i++,s=0;k<x;r+=s==n?1:0)s+=(int)L.get(k++);return r;}

```

-1 byte thanks to *@ceilingcat*.
-10 bytes thanks to *@SaraJ*.

Try it online.

**Explanation:**

```
n->{                // Method with integer as both parameter and return-type
  var L=new java.util.Stack();
                    //  List of primes, starting empty
  int i=1,k,x,s,    //  Temp integers
      r=0;          //  Result-counter, starting at 0
  for(;i++<n;){     //  Loop `i` in the range [2, `n`]
    for(k=1;        //   Set `k` to 1
        i%++k>0;);  //   Inner loop which increases `k` by 1 before every iteration,
                    //   and continues as long as `i` is not divisible by `k`
    if(k==i)        //   If `k` is now still the same as `i`; a.k.a. if `i` is a prime:
      L.add(i);}    //    Add the prime to the List
  for(x=L.size(),   //  Get the amount of primes in the List
      i=0;i<x;)     //  Loop `i` in the range [0, amount_of_primes)
    for(s=0,        //   (Re)set the sum to 0
        k=i++;k<x;  //   Inner loop `k` in the range [`i`, amount_of_primes)
        r+=s==n?    //     After every iteration, if the sum is equal to the input:
            1       //      Increase the result-counter by 1
           :        //     Else:
            0)      //      Leave the result-counter the same by adding 0
      s+=(int)L.get(k++);
                    //    Add the next prime (at index `k`) to the sum
  return r;}        //  And finally return the result-counter

```

---

It's basically similar as the Jelly or 05AB1E answers, just 190 bytes more.. XD
Here a comparison for each of the parts, added just for fun (and to see why Java is so verbose, and these golfing languages are so powerful):

1. Take the input: (Jelly: 0 bytes) *implicitly*; (05AB1E: 0 bytes) *implicitly*; (Java 10: 5 bytes) `n->{}`
2. Create a list of primes in the range `[2, n]`: (Jelly: 2 bytes) `ÆR`; (05AB1E: 2 bytes) `ÅP`; (Java 10: 95 bytes) `var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}`
3. Get all continuous sub-lists: (Jelly: 1 byte) ; (05AB1E: 1 byte) `Œ`; (Java 10: 55 bytes) `for(x=L.size(),i=0;i<x;)for(k=i++;k<x;)` and `(int)L.get(k++);`
4. Sum each sub-list: (Jelly: 1 byte) `§`; (05AB1E: 1 byte) `O`; (Java 10: 9 bytes) `,s` and `,s=0` and `s+=`
5. Count those equal to the input: (Jelly: 1 byte) `ċ`; (05AB1E: 2 bytes) `QO`; (Java 10: 15 bytes) `,r=0` and `r+=s==n?1:0`
6. Output the result: (Jelly: 0 bytes) *implicitly*; (05AB1E: 0 bytes) *implicitly*; (Java 10: 9 bytes) `return r;`
> 2 votes

# Answer
# Japt, 17 bytes

There's gotta be a shorter way than this!

Craps out on the last test case.

```
õ fj x@ZãYÄ x@¶Xx

```

Try it or run all test cases

---

## Explanation

```
                      :Implicit input of integer U
õ                     :Range [1,U]
  fj                  :Filter primes
      @               :Map each integer at 0-based index Y in array Z
         YÄ           :  Y+1
       Zã             :  Subsections of Z of that length
             @        :  Map each array X
               Xx     :    Reduce by addition
              ¶       :    Check for equality with U
            x         :  Reduce by addition
     x                :Reduce by addition

```
> 2 votes

# Answer
# Python 2, ~~106~~ 104 bytes

```
P=k=o=1
p=[]
i=input()
exec'o+=P%k*sum(p)==i;P*=k*k;k+=1;p+=P%k*[k];exec"p=p[i<sum(p):];"*k;'*i
print~-o

```

Try it online!
> 2 votes

# Answer
# Perl 6, 53 bytes

```
{+grep $_,map {|[\+] $_},[\R,] grep *.is-prime,2..$_}

```

Try it online!

Uses the triangle reduction operator twice. The last test case is too slow for TIO.

### Explanation

```
{                                                   } # Anonymous block
                               grep *.is-prime,2..$_  # List of primes up to n
                         [\R,]  # All sublists (2) (3 2) (5 3 2) (7 5 3 2) ...
          map {|[\+] $_},  # Partial sums for each, flattened
 +grep $_,  # Count number of occurrences

```
> 2 votes

# Answer
# Physica, 41 bytes

```
->x:Count[Sum@Sublists[PrimeQ$$[…x]];x]

```

Try it online!

### How it works

```
->x:Count[Sum@Sublists[PrimeQ$$[…x]];x] // Full program.
->x:            // Define an anonymous function with parameter x.
    […x]        // Range [0 ... x] (inclusive).
        $$      // Filter-keep those that...
  PrimeQ        // Are prime.
 Sublists[...]  // Get all their sublists.
Sum@            // Then sum each sublist.
Count[...;x]    // Count the number of times x occurs in the result.

```
> 1 votes

# Answer
# Haskell, 89 bytes

```
g n=sum[1|a<-[0..n],_<-filter(n==).scanl1(+)$drop a[p|p<-[2..n],all((>0).mod p)[2..p-1]]]

```

Try it online!

### Alternative, 89 bytes

```
f n=length$do a<-[0..n];filter(n==).scanl1(+)$drop a[p|p<-[2..n],all((>0).mod p)[2..p-1]]

```

Try it online!
> 1 votes

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


title: Indentation-based Sort

text:
# Question
Title: Indentation-based Sort
Given an ordered list of same-case letter strings (a-z XOR A-Z) where each string is preceded by 0 or more space ( ) characters, output the same list but with the strings sorted at each level of indentation. Indentation depths under different parents count as distinct lists for sorting purposes.

## Example

If your input is:

```
bdellium
  fox
  hound
  alien
aisle
  wasabi
    elf
    alien
  horseradish
    xeno
irk
wren
tsunami
djinn
      zebra

```

your output should be

```
aisle
  horseradish
    xeno
  wasabi
    alien
    elf
bdellium
  alien
  fox
  hound
djinn
      zebra
irk
tsunami
wren

```

If you like, think of it like a directory listing, and you need to sort the names within each directory.

## Minutiae

* An item may be indented by any number of spaces. If it is indented by the same number of spaces as the previous item it belongs in the same sort hierarchy as the previous item. If it is indented by more spaces it is the start of a new sub-hierarchy.
* If a line is indented by *fewer* spaces than the line above it, it links up to the closest sub group above it with the same # or fewer spaces before it (like horseradish in the above example, which links onto the wasabi group above it because wasabi is the first item above it to not have more spaces than horseradish)
* You must preserve the indenting level of each input item in your output
* Tabs in the output are disallowed
* The first line of the input will never be indented
* Your program must handle at least one of all-uppercase and all-lowercase strings; it doesn't have to handle both.

## Scoring

This is a , so the answer which uses the fewest bytes wins.

# Answer
# Pyth, 23 bytes

```
jeMtSuaG+f</Td/HdeGHQ]Y

```

Try it here!
> 1 votes

# Answer
# Python 2, 117 bytes

```
lambda S:[s[-1]for s in sorted(reduce(lambda t,s:t+[[v for v in t[-1]if v.count(' ')<s.count(' ')]+[s]],S,[[]]))[1:]]

```

Try it online!

Takes as input a list of strings; and outputs a list of strings, sorted as required.

The idea is to turn each element into a list which contains the "absolute path" as a list; and then let Python handle the sorting. E.g. if the input is:

```
[
 'a',
 ' c',
 '  d',
 ' b'
]

```

Then via the `reduce()`, we convert to a list of lists:

```
[
 ['a'],
 ['a',' c'],
 ['a',' c', '  d'],
 ['a',' b']
]

```

which gets sorted as:

```
[
 ['a'],
 ['a',' b']
 ['a',' c'],
 ['a',' c', '  d'],
]

```

and then output the last element of each list in the list-of-lists to get:

```
[
 'a',
 ' b'
 ' c',
 '  d',
]

```
> 14 votes

# Answer
# APL (Dyalog Unicode), 31 bytesSBCS

Anonymous prefix lambda, takes and returns list of strings.

```
{⍵[⍋{1=≢⍵:⍺⋄⍵}⍀↑' '(,⊂⍨⊣=,)¨⍵]}

```

Try it online!

`{``}` "dfn";  is argument

`⍵[``]` index the argument with the following indices:

`' '(``)¨⍵` apply the following tacit function to each string with space as left argument:

`,` concatenate the space to the string

`⊣=` Boolean list indicating where the space is equal to each character that

`,⊂⍨` use that to partition (begin part where true) the concatenation of space and string

mix list of lists of strings into matrix of strings

`{``}⍀` vertical cumulative reduction by this "dfn";  and  are upper and lower args:

`≢⍵` the length of the lower string

`1=` is that equal to 1? (i.e. is there nothing but the single space there?)

`:⍺` if so, return the upper argument

`⋄⍵` else, return the lower argument

grade up (find indices which will sort that)
> 7 votes

# Answer
# Retina, 47 bytes

```
+-1m`(?<=^\2(\S+).*?¶( *))
$1
O$`
$L$&
\S+

```

Try it online! Note: Several lines have trailing spaces. Explanation:

```
+-1m`(?<=^\2(\S+).*?¶( *))
$1

```

The first step is to insert each word into following lines at the same indentation. For example, with the lines `aisle`,  `wasabi` and  `elf` the resulting lines are `aisle`, `aisle wasabi` and `aisle wasabi elf`. I discovered this regex by trial and error so there may be edge cases with it.

```
O$`
$L$&

```

We can now sort the lines case-insensitively.

```
\S+

```

Delete all of the inserted words.
> 7 votes

# Answer
# Perl 6, ~~120 83 81 63 54 37 47~~ 42 bytes

*-5 bytes thanks to nwellnhof*

```
{my@a;.sort:{@a[+.comb(' ')..*+1]=$_;~@a}}

```

Try it online!

This uses Chas Brown's method. An anonymous code block that takes a list of lines and returns a list of lines.

### Explanation:

```
{                                        }  # Anonymous code block
 my@a;  # Declare a local list
      .sort # Sort the given list of lines
           :{                           }  # By converting each line to:
             @a[+.comb(' ')..*+1]=$_;      # Set the element at that indentation level onwards to that line
                                     ~@a   # And return the list coerced to a string

```
> 4 votes

# Answer
# Clean, ~~112~~ 101 bytes

```
import StdEnv
f=flatten
?e=[0\\' '<-e]
$[h:t]#(a,b)=span(\u= ?u> ?h)t
=sort[[h:f($a)]: $b]
$e=[]

```

#

```
f o$

```

Try it online!

Anonymous function `:: [[Char]] -> [[Char]]` which wraps `$ :: [[Char]] -> [[[Char]]]` into the right output format. `$` groups the strings into "more spaces than" and "everything else afterwards", recurses over each group and sorts when they're adjoined. At each step, the list being sorted looks like:

```
[[head-of-group-1,child-1,child-2..],[head-of-group-2,child-1,child-2..]..]

```

# Clean, 127 bytes

```
import StdEnv
$l=[x++y\\z<- ?(map(span((>)'!'))l),(x,y)<-z]
?[h:t]#(a,b)=span(\(u,_)=u>fst h)t
=sort[[h:flatten(?a)]: ?b]
?e=[]

```

Try it online!

Defines the function `$ :: [[Char]] -> [[Char]]` which separates the strings into tuples in the form `(spaces, letters)` which are recursively sorted by the helper function `? :: [([Char],[Char])] -> [[([Char],[Char])]]`.

Explained:

```
$ list                                  // the function $ of the list
    = [                                 // is
        spaces ++ letters               // the spaces joined with the letters
        \\ sublist <- ? (               // from each sublist in the application of ? to
            map (                       // the application of
                span ((>)'!')           // a function separating spaces and letters
            ) list                      // to every element in the list
        )
        , (spaces, letters) <- sublist  // the spaces and letters from the sublist
    ]

? [head: tail]                              // in the function ? of the head and tail of the input
    # (group, others)                       // let the current group and the others equal
        = span (                            // the result of separating until ... is false
            \(u, _) = u >                   // only elements where there are more spaces
                          fst head          // than in the head of the input
        ) tail                              // the tail of the input
    = sort [
        [head                               // prepend the head of the input to
             : flatten (?group)             // the flat application of ? to the first group
                               ]            // and prepend this to
                                : ?others   // the application of ? to the other group(s)
    ]

? empty = [] // match the empty list

```
> 3 votes

# Answer
# JavaScript (Node.js), ~~114~~ ~~100~~ ~~92~~ 88 bytes

```
x=>x.map(y=>a=a.split(/ */.exec(y)[0]||a)[0]+y,a="_").sort().map(x=>/ *\w+$/.exec(x)[0])

```

Try it online!

Similar approach to Chas Brown's Python answer, but using regular expressions instead.

## Explanation

```
x => x.map(                         //
 y => a = a.split(                  // Renders the indentation paths
  / */.exec(y)[0]                   //  Checks the indentation level
  || a                              //  If this is the top level, go to root
 )[0] + y,                          //  Appends the child to the parent
 a = "_"                            // At first the cursor is at the root
)                                   //
.sort()                             // Sorts the indentation paths
.map(                               //
 x => / *\w+$/.exec(x)[0]           // Extracts only the last level of the path
)                                   //

```
> 1 votes

# Answer
# K4, 51 bytes

**Solution:**

```
{,/(1#'r),'.z.s@'1_'r:(w_x)@<x@w:&s=&/s:+/'" "=/:x}

```

**Example:**

```
q)k){,/(1#'r),'.z.s@'1_'r:(w_x)@<x@w:&s=&/s:+/'" "=/:x}("bdellium";"  fox";"  hound";"  alien";"aisle";"  wasabi";"    elf";"    alien";"  horseradish";"    xeno";"irk";"wren";"tsunami";"djinn";"      zebra")
"aisle"
"  horseradish"
"    xeno"
"  wasabi"
"    alien"
"    elf"
"bdellium"
"  alien"
"  fox"
"  hound"
"djinn"
"      zebra"
"irk"
"tsunami"
"wren"

```

**Assumptions:**

a. That each hierarchy will start with the lowest level, i.e. you will not get:

```
bdellium
      fox
    hound
    alien

```

**Explanation:**

```
{,/(1#'r),'.z.s@'1_'r:(w_x)@<x@w:&s=&/s:+/'" "=/:x} / the solution
{                                                 } / lambda function, implicit x
                                           " "=/:x  / " " equal to each right (/:) x
                                        +/'         / sum up each
                                      s:            / save as s
                                    &/              / find the minimum (ie highest level)
                                  s=                / is s equal to the minimum?
                                 &                  / indices where true
                               w:                   / save as w
                             x@                     / index into x at these indices
                            <                       / return indices to sort ascending
                           @                        / index into
                      (   )                         / do this together
                       w_x                          / cut x at indices w
                    r:                              / save as r
                 1_'                                / drop first from each r
            .z.s@                                   / apply recurse (.z.s)
          ,'                                        / join each both
    (    )                                          / do this together
     1#'r                                           / take first from each r
  ,/                                                / flatten

```
> 0 votes

# Answer
# Perl 5, 166 bytes

```
sub f{my$p=shift;my@r;while(@i){$i[0]=~/\S/;$c=$-[0];if($p<$c){$r[-1].=$_ for f($c)}elsif($p>$c){last}else{push@r,shift@i}}sort@r}push@i,$_ while<>;print sort@{[f 0]}

```

Ungolfed (sort of):

```
sub f {
    my $p = shift;
    my @r;
    while(@i) {
        $i[0] =~ /\S/;
        $c = $-[0];
        if($p < $c) {
            $r[-1] .= $_ for f($c)
        } elsif ($p > $c) {
            last
        } else {
            push @r, shift @i
        }
    }
    sort @r
}

push @i, $_ while <>;
print sort@{[f 0]}

```

It's a pretty straightforward recursive implementation. We check the indentation level by searching for the first non-space character (`/\S/`) and getting its index (`$-[0]`). Unfortunately, we actually have to *declare* a handful of variables that are used in the recursion, or else they'll be implicitly global and the recursion won't work correctly.
> 0 votes

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


title: Let's Play some ProSet!

text:
# Question
Title: Let's Play some ProSet!
ProSet is a classic card game that is played normally with 63 cards. One card has 6 colored dots on it, like below

The rest of the cards are missing some of these 6 dots, but each card has at least 1 dot. Every card in the deck is different. Below are some example valid cards.

A **ProSet** is a **nonempty** set of cards such that the total number of each color of dot is even. For example, the above set of 4 cards are a **ProSet** since there are 2 reds, 4 oranges, 2 greens, 2 blues, 0 yellows, and 2 purples.

Interestingly, any set of 7 cards will contain at least 1 **ProSet**. Hence, in the actual card game, a set of 7 cards are presented, and the player who finds a **ProSet** first wins. You can try the game out for yourself here.

# Challenge

Given a set of cards, each **ProSet** card can be assigned a value from 1 to 63 in the following manner: a red dot is worth 1 point, an orange 2 points, yellow 4, green 8, blue 16, purple 32. The sum of the values of each dot on the card is the value of the card.

**Input**: A list of integers from 1-63, i.e.,

```
[11,26,35,50]

```

This list represents the above 4 cards.

**Output**: The number of valid **ProSets**, which in this example is `1`.

# Rules

* This is a challenge.
* This is also a challenge, as all valid solutions **must** be in polynomial time or less in the number of dots (in this case 6) **and** in the number of cards.

# Test Cases

I've created an exponential algorithm to find the correct output for every input here. Again, exponential solutions are **not** valid submissions. But, you can use this to validate your findings.

# Edit

I will address the comments in a bit. But for now, none of the answers have been in polynomial time. It is indeed possible, so here's a hint: **binary** representation and two s complement.

Moreover, I made a mistake earlier when I said polynomial in solely dots. It needs to be polynomial in dots and cards.

# Answer
# Python 2, 60 bytes

```
p=[0]
for i in input():p+=[n^i for n in p]
print~-p.count(0)

```

Try it online!
This generate the powerset from the input (based on this answer), reducing each subset by `xor`.
The output will be the amount of `0`s (0 = all bytes/dots appear an even number of times).
In fact the xoring is done instead of the "powerset appending", but the result is the same
> 4 votes

# Answer
# Japt, 8 bytes

```
à x@!Xr^

```

Try it here
> 1 votes

# Answer
# Clojure, 182 166 149 127 bytes

```
(defn f[k]((frequencies(map(fn[x](reduce #(bit-xor % %2)0 x))(reduce(fn[c n](concat(map #(concat %[n])c)[(list n)]c))'()k)))0))

```

If I had barfed on the screen, it would've looked better than this

Try it online!
> 0 votes

# Answer
## JavaScript (ES6), 53 bytes

```
f=
a=>a.map(i=>p.map(j=>n+=p.push(j^=i)&&!j),p=[n=0])&&n
```

```
<input oninput=o.textContent=f(this.value.split`,`)><pre id=o>
```

Loosely based on @Rod's Python answer.
> 0 votes

# Answer
# Jelly, 8 bytes

```
ŒPḊ^/€¬S

```

A monadic Link. 9 bytes if the empty set is considered a ProSet - `ŒPḊ^/€¬S‘` (since reducing an empty list errors).

**Try it online!**

### How?

```
ŒPḊ^/€¬S - Link: list of integers, L
ŒP       - powerset (of cards)
  Ḋ      - dequeue (remove the empty list)
    /€   - reduce €ach with:
   ^     -   XOR
      ¬  - NOT (vectorises)
       S - sum

```
> 0 votes

# Answer
# Python 2, 88 bytes

```
lambda l:~-sum(x<1for x in f(l))
f=lambda l:l and[n^l[0]for n in f(l[1:])]+f(l[1:])or[0]

```

Try it online!
> -1 votes

---
Tags: code-golf, card-games, restricted-complexity
---


title: Indent your code according to Fibonacci

text:
# Question
Title: Indent your code according to Fibonacci
Okay, so I saw this in a meme and decided it'd be the perfect code golf challenge:

I prefer to increase the side of my indents according to the Fibonacci sequence:

```
class Kls
 def method
  t = Time.now
  if t.hour >= 12
    puts "It's afternoon"
    if t.hour == 18
       puts "It's time for your meal of:"
       %w(bread sausage brocolli milk).each do |food|
            "Some #{food}"
       end
    end
  else
    puts "It's not afternoon"
  end
 end
end

```

This means each line is indented by the sum of the spaces indented in the previous indentation-level. The first indention-level is indented by one space, then subsequent indention-levels are indented by 1, 2, 3, 5, 8, 13, 21, etc ***additional*** spaces.

## The challenge

Given a multi-line string with multiples of 2 spaces as indentation, convert it to a Fibonacci indented multi-line string instead.
This means every line with 0 indented spaces will remain 0 spaces; every line with 2 indented spaces will become 1 instead (sum of the first two Fibonacci numbers `0+1 = 1`); every line with 4 indented spaces will becomes 2 instead (sum of the first three Fibonacci numbers `0+1+1 = 2`); etc. So the number of indentations can be calculated as follows:

* Get the current amount of leading spaces (guaranteed to be a multiple of 2, so `[0,2,4,6,8,...]`)
* Divide this by 2, so we have our 0-indexed numbers (let's call it `n`)
* Get the first `[0,n]` (0-indexed) Fibonacci numbers
* Sum that sub-sequence together, and use that amount of leading spaces instead in the output

For example, for the output above, the input would have been:

```
class Kls
  def method
    t = Time.now
    if t.hour >= 12
      puts "It's afternoon"
      if t.hour == 18
        puts "It's time for your meal of:"
        %w(bread sausage brocolli milk).each do |food|
          "Some #{food}"
        end
      end
    else
      puts "It's not afternoon"
    end
  end
end

```

If we take a look at the line containing `"Some #{food}"`:

In the input it has 10 amount of leading spaces, so `n` will be `10/2 = 5`. The first `[0,5]` Fibonacci numbers are: `[0,1,1,2,3,5]`. When we take the sum of that list (`0+1+1+2+3+5`) the new amount of leading spaces in the output would be 12.

The amount of indented spaces in the output for every 2 indented spaces in the input will be `[0, 1, 2, 4, 7, 12, 20, 33, 54, 88, ...]` A000071 on oeis.org (except for the first 0).

## Challenge rules:

* The space-indentation of the input is guaranteed to be multiples of 2 (`[0,2,4,6,8,...]`)
* The input is guaranteed to not contain more than 1 consecutive space elsewhere (except for the leading indentation of course)
* Use whatever language you like
* Please include a link to an online interpreter
* Input should be a multi-line string (so no, string-lists/arrays aren't allowed)
* Output should also be a multi-line string (either printed or returned as string)
* Your method should work for deeper-indented Fibonacci indented multi-line strings than the example
* This is , so try to do it in the fewest bytes possible.

## Additional test cases:

Input:

```
this
  is
    one
      of
        the
          tests
            !

```

Output:

```
this
 is
  one
    of
       the
            tests
                    !

```

Input:

```
      And
  how
               about
        this ?

```

Output:

```
    And
 how
                                 about
       this ?

```

Input:

```
                    20 spaces?

```

Output:

```
                                                                                20 spaces?

```

# Answer
> 4 votes
# 05AB1E (legacy), ~~22~~ 21 bytes

```
|εDgsðÛ©g-;LÅfOð*®J}»

```

Try it online.

**21 bytes alternative using the formula \\$Fib(\frac{n}{2}+2)-1\\$ instead of \\$\sum\_{i=1}^{i=\frac{n}{2}}{Fib(i)}\\$ :**
(Credit to *@JonathanAllan*'s Jelly answer for this formula.)

```
|εDgsðÛ©g-;ÌÅf<ð*®J}»

```

Try it online.

**Explanation:**

```
|                        # Take the input split by newlines
 ε                  }    # Map each line to:
  Dg                     #  Duplicate the line and take its length
    s                    #  Swap so the duplicated line is at the top of the stack again
     ðÛ                  #  Remove all leading spaces
       ©                 #  Store the result in the register (without popping)
        g                #  Take its length as well
         -               #  Subtract both lengths from each other
          ;              #  Halve it, because they are multiples of 2 indented spaces
           L             #  Create a list in the range [1, n]
            Åf           #  Get the i'th Fibonacci number for each
              O          #  And sum them together
               ð*        #  Have that many space characters
                 ®J      #  And join them with the saved string from the register
                    »    # And finally print the mapped list with new-lines

```

# Answer
> 3 votes
# Jelly, 20 bytes

```
Ỵµ=⁶i0‘H‘ÆḞ’⁶ẋ;t⁶$)Y

```

Try it online!

---

# Explanation

Let \\$x\\$ be the 1-indexing index of the first non-whitespace character (\\$1,3,5,7,\dots\\$).

Then the new indent is

$$F\_{(x+1)/2+1}-1$$

where \\$F\\$ is the Fibonacci function.

# Answer
> 3 votes
# Python 2, ~~111~~ ~~109~~ ~~100~~ 95 bytes

```
g=lambda n:n<1or g(n-2)+g(n-4)
def f(I):
 for l in I:L=l.lstrip();print~-g(len(l)-len(L))*' '+L

```

Try it online!

---

Saved:

* -5 bytes, thanks to ovs.

# Answer
> 3 votes
# Husk, 23 bytes

```
mȯF+M(R' !∫Θİf→½L)↕=' ¶

```

Try it online!

### Explanation

```
m(F+M(R' !∫Θİf→½L)↕=' )¶  -- full program
                       ¶  -- lines
m(                    )   -- map
                  ↕='     -- | split on first non-space
    M(           )        -- | with the spaces
                L         -- | | length
               ½          -- | | halve
              →           -- | | increment
            İf            -- | | Fibonacci numbers: [1,1,2,3,5..]
           Θ              -- | | prepend 0: [0,1,1,2,3,5..]
          ∫               -- | | cumulative sums: [0,1,2,4,7,12..]
         !                -- | | 1-based index
      R'                  -- | | replicate that many spaces
  F+                      -- | join

```

# Answer
> 2 votes
# Retina 0.8.2, 37 bytes

```
m`^

+`( +	)( +)
$2$1$1
 	 *

```

Try it online! Warning: Lots of white space. Explanation:

```
m`^

```

Prefix each line with space tab space tab. These keep track of the previous and current Fibonacci number.

```
+`( +   )( +)
$2$1$1

```

For each two spaces of the original indentation, compute the next Fibonacci number by summing the previous two.

```
 	 *

```

Subtract 1 from the result and delete the previous Fibonacci number.

# Answer
> 2 votes
# Japt v2.0a0, ~~20~~ 19 bytes

```
r/^ +/m@ÓMgXÊz ÄÄ)ç

```

Try it

---

## Explanation

```
r                        :Replace
 /^ +/m                  :Global, multiline regular expression matching one or more spaces at the start of each line
       _                 :Pass each match through a function
        Ê                :  Length
         z               :  (Floor) divide by 2
           õ             :  Range [0,result]
              @          :  Map each X
               MgX       :    Xth Fibonacci number
                  Ã      :  End mapping
             x           :  Reduce by addition
                   ç     :  Repeat <space> that many times

```

# Answer
> 2 votes
# Jelly, 17 bytes

```
Ỵµwt©⁶$HÆḞ€⁶ẋ;®)Y

```

A full program which prints the result.

**Try it online!**

### How?

The indentations required for a line of the output is \\$Fib(\frac{s}{2}+2)-1\\$ where \\$s\\$ is the number of spaces in the line of the input, and:

$$Fib(\frac{s}{2}+2)-1=\sum\_{i=1}^{i=\frac{s}{2}}{Fib(i)}$$

(\\$i\\$ could also start at \\$0\\$ since \\$Fib(0)=0\\$)

```
Ỵµwt©⁶$HÆḞ€⁶ẋ;®)Y - Main Link: list of characters
Ỵ                 - split at newlines
 µ             )  - for each line:
      $           -   last 2 links as a monad:
     ⁶            -     literal space character
   t              -     trim from both sides
    ©             -     (copy to register)
  w               -   first index of that substring in the line
       H          -   halve (this is (s+1)/2)
        ÆḞ€       -   Fibonacci of €ach (using an implicit range [1,2,...,s/2]
                  -                      where the (s+1)/2 is floored to s/2)
           ⁶      -   literal space character
            ẋ     -   repeat (vectorises) (e.g. [1,1,2,3,5] -> [[' '],[' '],[' ',' '],[' ',' ',' '],[' ',' ',' ',' ',' ']]
              ®   -   recall from register
             ;    -   concatenate
                Y - join with newline characters
                  - implicit print
                  -  ...smashes, so e.g. [[' '],[' '],[' ',' '],['x']] is just "    x"

```

# Answer
> 2 votes
# Java 11, 150 bytes

```
s->{for(var l:s.split("\n"))System.out.println(" ".repeat(f(l.length()-(l=l.stripLeading()).length())-1)+l);};int f(int n){return n<1?1:f(n-2)+f(n-4);}

```

Try it online (NOTE: Both `String.repeat(int)` and `String.stripLeading()` are emulated as `repeat(String,int)` and `stripLeadingE(String)` respectively, because Java 11 isn't on TIO yet.)

**Explanation:**

```
s->{                   // Method with String parameter and no return-type
  for(var l:s.split("\n"))
                       //  Loop over the lines of the input:
    System.out.println(//   Print with trailing new-line:
      " ".repeat(      //    Repeat a space this many times:
           f(          //     Call the separated (recursive) method `f` with the parameter:
             l.length()//      The length of the line,
             -(l=l.stripLeading()).length()
                       //      minus the length of the line without leading spaces
           )-1         //     minus 1
      )+l);};          //    And append the line without leading spaces

int f(int n){          // Separated method with integer as both parameter and return-type
  return n<1?          //  If the input is 0 or lower:
          1            //   Return 1
         :             //  Else:
          f(n-2)+f(n-4);}
                       //   Return a recursive call to `n-2` plus a recursive call to `n-4`

```

# Answer
> 1 votes
# JavaScript (Node.js), ~~87~~ 81 bytes

```
x=>x.replace(/^ */gm,s=>" ".repeat((g=(n,a=b=1)=>n?g(n-2,b,b+=a):b-1)(s.length)))

```

Try it online!

## For small indent levels (up to 15), 61 bytes using approximation:

```
x=>x.replace(/^ */gm,s=>" ".repeat(1.272**s.length*1.171-.5))

```

Use `1.27202 ** s.length * 1.17082 - .5` for indents up to 21 levels

# Answer
> 1 votes
# Perl 6, 62 bytes

```
*.trans(/[\n|^]' '+/=>{"\n"~' 'x(1,1,*+*...*)[$/.ords/2+1]-1})

```

Try it online!

---
Tags: code-golf, string, fibonacci, subsequence
---


title: Seven Segment Scrolling

text:
# Question
Title: Seven Segment Scrolling
Sandbox Post

**Intro**

The information panels are everywhere. When the technology became cheaper, the paper posters were transformed into luminous signs that show words that appear on one side and come out on the other, like the one on the figure:

When one of these signs starts up, it usually starts empty and the text leaves from the right side to the left, moving until it disappears.

Its functionality is to go on and off the small light bulbs (LEDs) to give the sensation of movement.

If instead of text we only need to show numbers, the poster can be much less sophisticated using the so-called seven-segment markers like the following:

In this case each number is represented by the combination on / off of only 7 light segments that allow to represent all the numbers:

The question we ask ourselves is how many changes of lights (how many on and off) should be made to pass through one of these posters a certain number?

For example, to show the 123 in a 3-digit sign that starts with all the LEDs off we will have:

This makes a total of 42 changes of lights.

---

**Challenge**

Given a non-negative number and a positive sign length calculate the number of lights changes.

**Rules**

* Assume input consist in a non-negative number (N \>= 0) and a positive sign length (M \> 0)
* Assume Sign length \>= Number length (M \>= digits(N))

**Test cases**

```
123, 3        => 42
45, 5         => 60
111, 3        => 12
98765, 10     => 220
0, 3          => 36

```

# Answer
# Python 2, ~~129~~ ~~126~~ ~~119~~ 104 bytes

```
def f(n,k,p=0):z=p<1or n>0;q=-~ord('}/lx2Z^o~z'[n%10])*z;return(z and f(n/10,k,q))+k*bin(p^q).count('1')

```

Try it online!

Thx for a big 15 bytes from ovs.

As specified, takes a non-negative number and a positive sign length, and returns total changes.
> 7 votes

# Answer
# JavaScript (Node.js), ~~104~~ ~~94~~ ~~93~~ 93 bytes

*Saved 1 byte thanks to @Shaggy*

```
B=n=>n&&n%2+B(n>>1)
F=(d,w,q)=>w*B(q^(q=d&&"w`>|i]_p}".charCodeAt(d%10)))+(d&&F(d/10|0,w,q))

```

Try it online!
> 3 votes

# Answer
# Jelly, 23 bytes

```
Dị“¤]þ+>~Œ¶?w‘Ø0j^ƝBFS×

```

A dyadic link accepting the integer to display on the left and the sign length on the right which yields the number of changes (also works if the number of digits in the integer to display is greater than the sign length).

**Try it online!**

### How?

During the entire show each 7-segment display (at some point) transitions from empty to the first digit, then to the second and so on, and finally from the last to empty again. The transitions each cost the bitwise XOR of the on-segments of the from-digit and to-digit (where empty is a "digit" with 0 on-segments). I stole the on-segments as integers from a previous revision of ETHproductions' answer, but any permutation of the 7 segments would do just as well.

```
Dị“¤]þ+>~Œ¶?w‘Ø0j^ƝBFS× - Link: integer to display, V; integer sign length, L  e.g. 123, 3
D                       - cast V to decimal digits                                  [1,2,3]
  “¤]þ+>~Œ¶?w‘          - code-page indices list = [3,93,31,43,62,126,19,127,63,119]
 ị                      - index into (1-based & modular) (vectorises)             [3,93,31]
              Ø0        - literal = [0,0]                                             [0,0]
                j       - join                                                [0,3,93,31,0]
                  Ɲ     - pairwise application of:
                 ^      -   bitwise XOR                                        [3,94,66,31]
                   B    - convert to binary digits (vectorises)               [[1,1],[1,0,1,1,1,1,0],[1,0,0,0,0,1,0],[1,1,1,1,1]]
                    F   - flatten                                             [1,1,1,0,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,1]
                     S  - sum                                                            14
                      × - multiply by L                                                  42

```
> 3 votes

# Answer
# Japt, ~~31~~ 30 bytes

Adapted from Jonathan's Jelly solution. Takes input in reverse order with the number to be displayed as a digit array.

```
*Vm!c"w]+>~?" pT ä^T x_¤¬x

```

Try it
> 2 votes

# Answer
# Clean, 280 bytes

```
import StdEnv,Data.List
~ =toInt
?s=sum[(~s>>p)rem 2\\p<-[0..6]]
$n l#j=repeatn l 0
#n=j++[~c-47\\c<-:toString n]++j
#k=[getItems(map((!!)[0,119,3,62,31,75,93,125,19,127,95])n)[i-l..i-1]\\i<-[0..length n]]
=sum(zipWith@(tl k)k)
@[u][]= ?u
@[u:x][v:y]= ?((bitxor)u v)+ @x y
@[][]=0

```

Try it online!

There has to be a shorter way..
> 2 votes

# Answer
# Charcoal, 40 bytes

```
≔⁺×⁷0⭆Ｓ§⪪”)∧？？%←⁶%*An”⁷ＩιθＩ×ＮΣＥθ¬⁼ι§θ⁺⁷κ

```

Try it online! Link is to verbose version of code. Works by converting the input into the binary segment values, then counting the number of changes between each character. Explanation:

```
      Ｓ                     Convert first input to string
     ⭆                      Map over digits and join
         ”)∧？？%←⁶%*An”      Compressed segment value string
        ⪪             ⁷     Split into groups of seven characters
                        ι   Current digit
                       Ｉ    Convert to integer
       §                    Index into groups
    0                       Literal `0`
  ×⁷                        Repeat seven times
 ⁺                          Concatentate
≔                        θ  Assign to variable `q`

     θ          Variable `q`
    Ｅ           Map over characters
             κ  Current index
           ⁺⁷   Add seven
          θ     Variable `q`
         §      Cyclically index
        ι       Current character
       ⁼        Compare
      ¬         Logical not
   Σ            Sum results
  Ｎ             Second input
 ×              Multiply
Ｉ               Cast to string
                Implicitly print

```
> 1 votes

# Answer
# JavaScript (Node.js), 88 bytes

Takes input as `(integer)(width)`.

```
n=>w=>[...n+'',g=n=>n&&1+g(n&n-1)].map(c=>s+=g(x^(x=Buffer('w$]m.k{%o')[c])),x=s=0)|s*w

```

Try it online!

### How?

Given a list \\$\\{d\_1,d\_2,\dots,d\_n\\}\\$ of \\$n\\$ digits and a display width \\$w\\$, the total number \\$N\\$ of light changes is given by:

$$N=({T'}\_{d\_1}+\sum\_{i=2}^n{T\_{d\_{i-1},d\_i}}+{T'}\_n)\times w$$

Where \\$T\_{x,y}\\$ is the number of light changes for a transition from digit \\$x\\$ to digit \\$y\\$ and \\${T'}\_{x}\\$ is the number of light changes for a transition from the blank digit to digit \\$x\\$ (or the other way around).

### Commented

```
n => w =>                       // n = integer; w = width of display
  [ ...n + '',                  // coerce n to a string and split it
    g = n =>                    // g = helper function counting the number of 1's
      n && 1 + g(n & n - 1)     // by defining it here, we also force an extra iteration
  ]                             // with an undefined digit (interpreted as the blank digit)
  .map(c =>                     // for each entry c in this array:
    s += g(                     //   add to s the result of a call to g():
      x ^ (x =                  //     XOR the previous value of x
        Buffer('w$]m.k{%?o')[c] //     with the new one, picked from a 10-entry lookup
      )                         //     gives undefined (coerced to 0) for the last entry
    ),                          //   end of call to g()
    x = s = 0                   //   start with x = 0 and s = 0
  ) | s * w                     // end of map(); return s * w

```
> 1 votes

---
Tags: code-golf
---


title: Dictionary Code Golf

text:
# Question
Title: Dictionary Code Golf
New to code golf and enjoying it. I have a problem that I cannot figure out and am curious if others can solve it.

Start with two dictionaries, `y` and `z`:

```
y = {'a': 1, 'c': 3, 'e': 5, 'g': 7}
z = {'b': 2, 'd': 4, 'f': 6, 'h': 8}

```

`y` and `z` both map length-1 strings to numbers, where each number is between 1 and 26 (inclusive) and represents an English letter: a = 1, b = 2, c = 3, d = 4 , ... , z = 26.

The goal is as follows:

1. Double each number (i.e. value) in `y`, and replace the key with the letter corresponding to the new number.
2. Do the same for `z`, but triple each number instead.
3. Populate a dictionary `x` with the keys and values from both `y` and `z` in descending numerical order, for instance:

```
x = {'x': 24, 'n':18, 'm': 14, 'l':12, 'j': 10, 'f': 6, 'b':2}

```

Good luck!

Example:

Starting state:

```
y = {'a': 1, 'c': 3, 'e': 5, 'g': 7}
z = {'b': 2, 'd': 4, 'f': 6, 'h': 8}

```

After `y` operations:

```
y = {'b':2, 'f': 6, 'j': 10, 'm': 14}

```

After `z` operations:

```
z = {'f': 6, 'l': 12, 'n': 18, 'x': 24}

```

# Answer
> 10 votes
## Python, 174 155 113 86 70 68 66 bytes

It's actually my first time here and here's my attempt. Let me know if I am doing anything wrong.

```
lambda y,z:{chr(v*(3-v%2)+96):v*(3-v%2)for v in{**y,**z}.values()}

```

**EDIT**: After OP's edit and @Rod 's comment I noticed I have some mistakes. I also took out the sorting attempts because it simply can't work with Python dictionaries.

**EDIT2**: -16bytes thanks to @JonathanAllan

Try it online!

---
Tags: code-golf, python
---


title: Lucas and Fibonacci are in pair

text:
# Question
Title: Lucas and Fibonacci are in pair
Influenced by Non-discriminating Programming, I made up an idea of a similar challenge.

Here, we say a string is a Lucas string if the number of appearances of each character is a Lucas number (2, 1, 3, 4, 7, ...), and a string is a Fibonacci string if the number of appearances of each character is a Fibonacci number (1, 2, 3, 5, 8, ...).

Here are some concrete examples:

```
"Programming Puzzles"
Appearance Count:   P a e g i l m n o r s u z
                  1 2 1 1 2 1 1 2 1 1 2 1 1 2

```

All counts are both Lucas numbers and Fibonacci numbers, so this is both a Lucas string and a Fibonacci String

```
"Sandbox for Proposed Challenges"
Appearance Count:   C P S a b d e f g h l n o p r s x
                  3 1 1 1 2 1 2 3 1 1 1 2 2 4 1 2 2 1

```

All counts are Lucas numbers, so this is a Lucas string. However the count of `o` is not a Fibonacci number, so this is not a Fibonacci string.

```
"Here are some concrete examples: "
Appearance Count:   : H a c e l m n o p r s t x
                  5 1 1 2 2 8 1 2 1 2 1 3 2 1 1

```

All counts are Fibonacci, so this is a Fibonacci string. However the counts of  and `e` are not Lucas numbers, so this is not a Lucas string.

```
"Non-discriminating Programming"
Appearance Count:   - N P a c d g i m n o r s t
                  1 1 1 1 2 1 1 3 5 3 4 2 3 1 1

```

Since count of `i` is not Lucas number, and count of `n` is not Fibonacci number, so this is neither a Lucas string nor a Fibonacci String.

## Challenge

Write 2 programs, one Lucas program and one Fibonacci program, both accepting a string as input, that:

* The Lucas program checks whether the input is Fibonacci; and
* The Fibonacci program checks whether the input is Lucas,

where the definitions of "Lucas" and "Fibonacci" are as above.

## Rules

* Your programs **can choose to receive input either from STDIN or as function/program argument**.
* Your programs **must output or return one of the 2(TWO) distinct values** at your choice, one for the truthy value and one for the falsy value, and the choice **must be consistent across the programs**, i.e. you cannot have one program returning `0/1` while the other one returning `true/false`.
* Your programs **must output or return a truthy value if the source of each other is inputted**, i.e. your Lucas program must return a truthy value if the source of your Fibonacci program is inputted, and vice versa.
* **It is allowed to have program being both Lucas and Fibonacci.**
* Characters not used are apparently not counted, in case you doubt because 0 is not in the Lucas sequence.
* Number of distinct characters in each program are not restricted to either Lucas or Fibonacci numbers.
* Only full programs or functions allowed. Snippets are not accepted.
* Standard loopholes are apparently forbidden.

## Scoring

The score will be calculated as follows:

* For each program, multiply `the number of distinct characters used` by `the maximum number of appearances of the characters in the source`.
* Add the two values calculated in the previous step up. This is your score.

Example:

```
Lucas code :    20 distinct characters, MAX(appearance of each character)=7
Fibonacci code: 30 distinct characters, MAX(appearance of each character)=5
Score: 20*7 + 30*5 = 140 + 150 = 290

```

## Test cases

```
Input                                   | Output of ...
                                        | Lucas Program      | Fibonacci Program
----------------------------------------+---------------------------------------
<Your Lucas program>                    | True if all appe-  | True
(Lucas string by rules)                 | arance counts are  |
                                        | exactly 1, 2 or 3; |
                                        | False otherwise    |
----------------------------------------+--------------------+------------------
<Your Fibonacci program>                | True               | True if all appe-
(Fibonacci string by rules)             |                    | arance counts are
                                        |                    | exactly 1, 2 or 3;
                                        |                    | False otherwise
----------------------------------------+--------------------+------------------
"Programming Puzzles"                   | True               | True
(Both Lucas and Fibonacci)              |                    |
----------------------------------------+--------------------+------------------
"Sandbox for Proposed Challenges"       | False              | True
(Lucas but not Fibonacci)               |                    |
----------------------------------------+--------------------+------------------
"Here are some concrete examples: "     | True               | False
(Fibonacci but not Lucas)               |                    |
----------------------------------------+--------------------+------------------
"Non-discriminating Programming"        | False              | False
(Neither Lucas nor Fibonacci)           |                    |
----------------------------------------+--------------------+------------------
"Hello world!"                          | True               | True
(Both Lucas and Fibonacci)              |                    |
----------------------------------------+--------------------+------------------
"18446744073709551616"                  | False              | True
(Lucas but not Fibonacci)               |                    |
----------------------------------------+--------------------+------------------
"Lucas and Fibonacci are IN pair"       | True               | False
(Fibonacci but not Lucas)               |                    |
----------------------------------------+--------------------+------------------
"Lucas and Fibonacci are in pair"       | False              | False
(Neither Lucas nor Fibonacci)           |                    |

```

## Winning Criteria

The submission with the lowest score in each language wins.

# Answer
# 05AB1E, score: 10 + 8 = 18

This could be a comment on Kevin's post, but I've developed it independently and the technique is slightly different. Therefore I am posting it myself.

### Fibonacci program that checks Lucas (10 bytes)

```
€¢Dā0šÅgÃQ

```

Try it online!

```
€¢Dā0šÅgÃQ -> Full program
€¢         -> Count the occurrences of each character in the string. Call this list C.
  Dā       -> Duplicate and yield the range [1 ... len string].
    0š     -> Prepend 0. [0 ... len string].
      Åg   -> Nth Lucas number (for each).
        Ã  -> Intersection with C.
         Q -> Check equality with C.

```

---

### Lucas program that checks Fibonacci (8 bytes)

```
€¢DāÅfÃQ

```

Try it online!

```
€¢DāÅfÃQ -> Full program
€¢       -> Count the occurrences of each character in the string. Call this list C.
  Dā     -> Duplicate and yield the range [1 ... len string].
    Åf   -> Nth Fibonacci number (for each). We don't need the 0th this time!
      Ã  -> Intersection with C.
       Q -> Check equality with C.

```
> 4 votes

# Answer
# 05AB1E, score: ~~19~~ 17 (9x1 + 8x1)

-2 score thanks to *@Emigna*.

### Lucas (~~10~~ 9 bytes):

```
€¢Z>ÅGKg_

```

Try it online (with the Fibonacci program as input).
Verify all test cases.

### Fibonacci (~~9~~ 8 bytes):

```
€¢ZÅFKg_

```

Try it online (with the Lucas program as input).
Verify all test cases.

Outputs `1` for truthy and `0` for falsey results.

**Explanation:**

```
€¢          # Count each of the characters in the input
            #  i.e. "Programming Puzzles" → [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1]
  Z         # Get the max, without popping the list
            #  i.e. [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1] → 2
   >ÅG      # Calculate the Lucas numbers up to and including this max+1
            # (Note: the +1 is because `1ÅG` returns `[]` instead of `[1]`)
            #  i.e. 2 → [2,1]
   ÅF       # Calculate the Fibonacci numbers up to and including this max
            #  i.e. 2 → [0,1,1,2]
     K      # Remove all these Fibonacci numbers from the count list
            #  i.e. [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1] and [2,1] → []
            #  i.e. [2,2,1,2,2,1,2,2,1,1,2,1,2,1,2,2,1,1,1] and [0,1,1,2] → []
      g_    # Check if the list is not empty
            #  i.e. [] → 0

```
> 3 votes

# Answer
# Perl 6, 32\*2 + 33\*2 = ~~171~~ 130

*-41 points thanks to nwellnhof!*

### Lucas Program:

```
{min([values .ords⊎e]».&{$_∈(1,1,*+*…0)[0…$_]})}

```

### Fibonacci Program:

```
{min([values .ords⊎e]».&{$_∈(2,1,*+*…0)[0…$_]})}

```

Try it online!

Anonymous code blocks that take a string and return a Junction (which can be coerced to truthy/falsey values). Both use the same structure rearranged to get the correct amount of characters.

### Explanation:

```
{min([values .ords⊎e]».&{$_∈(1,1,*+*…0)[0…$_]})}

{  # Anonymous code block
  min(  # Find the minimum of:
      [values .ords⊎e]  # Coerces the string to a list of the number of occurrences
                      ».&{ # Map each value to:
                          $_∈  # Whether the value is an element of:
                             (1,1,*+*…0)   # The sequence
                                        [0…$_]  # Truncated to prevent it evaluating infinitely
                         }
     )
}

```
> 2 votes

# Answer
# Jelly,  ~~19~~  8×1+9×1=17

code-page

Lucas Program:

```
ĠẈfƑJÆḞ$

```

**Try it online!** Or see all-tests.

Fibonacci Program:

```
ĠẈfƑJŻÆĿƊ

```

**Try it online!** Or see all-tests.

### How?

Both work in very similar fashions -- `ÆḞ` gets the nth Fibonacci number while `ÆĿ` gets the nth lucas number. `Ż` adds a zero to the front of the list of n's to use with `ÆĿ` to cater for the fact that the 0th Lucas number is 2, which we need to test for while 0 is the 0th Fibonacci number, which we do not need to test for. `Ɗ` is a quick to chain the last three links together as a monad, while `$` chains the last two links together as a monad...

Lucas Program:

```
ĠẈfƑJÆḞ$ - Link: list of characters, s
Ġ        - group indices by value
 Ẉ       - length of each
       $ - last two links as a monad (f(s))
    J    -   range of length of s
     ÆḞ  -   nth Fibonacci number (vectorises)
   Ƒ     - is left argument is equal to the result of?:
  f      -   filter - remove items from left that are not in right
         -            i.e. groupLengths without those Fibonacci numbers

```

Fibonacci Program:

```
ĠẈfƑJŻÆĿƊ - Link: list of characters, s
Ġ         - group indices by value
 Ẉ        - length of each
        Ɗ - last three links as a monad (f(s))
    J     -   range of length of s
     Ż    -   prepend a zero
      ÆĿ  -   nth Lucas number (vectorises)
   Ƒ      - is left argument is equal to the result of?:
  f       -   filter - remove items from left that are not in right
         -            i.e. groupLengths without those Lucas numbers

```
> 2 votes

# Answer
# Java 8, score ~~1238~~ 1137 (35x18 + 39x13)

### Lucas:

```
c->c.chars().map(a->c.length()-c.replace(""+(char)a,"").length()).allMatch(a->{int n=2,s=1,m=3;for(;a>m;n=s,s=m)m=n+s;return a>0&a<4|a==m;})//",-..mmnrr

```

Try it online.

### Fibonacci:

```
s->s.chars().map(e->s.length()-s.replace(""+(char)e,"").length()).allMatch(a->{int l=(int)Math.sqrt(a=5*a*a+4);return(l*l==a|(l=(int)Math.sqrt(a-=8))*l==a);})//--...===aaanl((((()))))

```

Try it online.

**Explanation (base) Lucas:**

```
s->                     // Method with String parameter and boolean return-type
  s.chars()             //  Loop over the characters as integer-stream
   .map(c->             //  Map each of them to:
     s.length()-s.replace(""+(char)c,"").length())
                        //   The occurrence-count of this character in the input
   .allMatch(n->{       //  Check if all these occurrence-counters are true for:
      int a=2,b=1,c=3;  //    Integer `a`,`b`,`c` starting at 2,1,3 (start of Lucas sequence)
      for(;n>c;         //    Loop as long as the current occurrence-counter is larger than `c`
          ;             //      After every iteration:
           a=b,         //       Replace `a` with `b`
           b=c)         //       Replace `b` with `c`
        c=a+b;          //     Replace `c` with `a` + `b`
      return            //    Return whether the occurrence-counter is one of:
             n>0&n<4    //     1,2,3,
             |n==c;})   //     or `c`

```

**Explanation (base) Fibonacci:**

```
s->                     // Method with String parameter and boolean return-type
  s.chars()             //  Loop over the characters as integer-stream
   .map(c->             //  Map each of them to:
      s.length()-s.replace(""+(char)c,"").length())
                        //   The occurrence-count of this character in the input
   .allMatch(n->{       //  Check if all these occurrence-counters are true for:
      int r=(int)Math.sqrt(n=5*n*n+4);
                        //   Integer `r`, the square of `5*n*n+4` floored
      return r*r==k     //  Return whether `5*n*n+4` is a perfect square,
             |(r=(int)Math.sqrt(n-=8))*r==n;})
                        //  and/or if `5*n*n-4` is a perfect square

```

A number \\$n\\$ is a Fibonacci number, if either or both of \\$5n^2+4\\$ or \\$5n^2-4\\$ is a perfect square (source)

**Explanation modifications:**

After these base programs explained above, I've made the following changes:

* Changed the names of variables to only use letters we've already used to reduce amount of distinct characters; and also so the least amount of characters have to be added at the comment to make the occurrence-counts Lucas/Fibonacci numbers;
* Added parenthesis around the return-statement (to get rid of the space as well);
* Put any remaining character we need to increase for it to become a Lucas/Fibonacci number after the trailing comment `//`.
> 2 votes

# Answer
# Pyt, 11\*1+12\*1=23 bytes

Both return 0 as truthy, 1 as falsy

Fibonacci test:

```
ĐỤ⇹ɔ2ᴇřḞ\Ł±

```

Try it online!

Lucas test:

```
ĐỤ⇹ɔ02ᴇŘĿ\Ł±

```

Try it online!

Explanation:

```
                    Implicit input
Đ                   Duplicate the input
 Ụ                  Get list of unique characters
  ⇹                 Swap the top two elements on the stack
   ɔ                Count the number of occurrences of each character in the input
    2ᴇř             Push [1,...,100] (should be more than enough)
       Ḟ            Get the first 100 Fibonacci numbers
        \           Get all character counts that aren't Fibonacci numbers
         Ł          Get the number of such counts
          ±         Output the sign of the number of such counts
                    Implicit output

```

```
                    Implicit input
ĐỤ⇹ɔ                get count of occurrences of each character
    02ᴇŘ            Push [0,1,...,100] (should be more than enough)
        Ŀ           Get the first 101 Lucas numbers
         \          Get all character counts that aren't Lucas numbers
          Ł         Get the number of such counts
           ±        Output the sign of the number of such counts
                    Implicit output

```
> 0 votes

---
Tags: string, code-challenge, decision-problem, restricted-source, self-validating
---


title: Turn an Array into a Math Problem

text:
# Question
Title: Turn an Array into a Math Problem
Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:

* A plus sign (`+`) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end).
* A minus sign (`-`) is inserted between pairs of numbers that decrease from left to right.
* A multiplication sign (`*`) is inserted between pairs of numbers that are equal.

Said another way: any sublist `a,b` becomes `a+b` if `a<b`, `a-b` if `a>b`, and `a*b` if `a==b`.

For example, the list

```
[12, 0, 7, 7, 29, 10, 2, 2, 1]

```

would become the expression

```
12 - 0 + 7*7 + 29 - 10 - 2*2 - 1

```

which evaluates to `75`.

Write a program or function that takes in such a list and evaluates it, printing or returning the result.

* Order of operations matters. Multiplications should be done before any addition or subtraction.
* If the input list has one number, that should be what it evaluates to. e.g. `[64]` should give `64`.
* Use of `eval` or `exec` or similar constructs is allowed.

Here are some additional examples:

```
[list]
expression
value

[0]
0
0

[1]
1
1

[78557]
78557
78557

[0,0]
0*0
0

[1,1]
1*1
1

[2,2]
2*2
4

[0,1]
0+1
1

[1,0]
1-0
1

[1,2]
1+2
3

[2,1]
2-1
1

[15,4,4]
15-4*4
-1

[9,8,1]
9-8-1
0

[4,2,2,4]
4-2*2+4
4

[10,9,9,12]
10-9*9+12
-59

[1,1,2,2,3,3]
1*1+2*2+3*3
14

[5,5,4,4,3,3]
5*5-4*4-3*3
0

[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29

[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379

```

**The shortest code in bytes wins. Tiebreaker is earlier answer.**

# Answer
## Python 2, 63 bytes

```
p=s='print-'
for x in input():s+='*+-'[cmp(x,p)]+`x`;p=x
exec s

```

Constructs and `eval`s the expression string. The arithmetic symbol is chosen by comparing the previous number `p` to the current one `x`. The symbol is appended followed by the current number.

The first number is handled with a clever trick from Sp3000. The initial value of `p` is set to a string, which is bigger than any number and therefore causes a `-` before the first number. But, `s` is initialized to `print-` at the same time that makes the result start with `print--` (thanks to xsot for saving 2 bytes by initializing with `print`.)
> 15 votes

# Answer
# Pyth, ~~31~~ ~~26~~ ~~19~~ ~~17~~ ~~16~~ 15 bytes

Expressions with `*` won't evaluate online, but they would theoretically work.

2 bytes thanks to Maltysen.

```
vsm+@"*-+"._-~k

```

Test suite (with evaluation).

The other cases (without evaluation).

## History

* 31 bytes: `M+G@"*-+"->GH<GHv+sgMC,JsMQtJ\x60e`
* 26 bytes: `M+G@"*-+"->GH<GHv+sgVQtQ\x60e`
* 19 bytes: `vtssVm@"*-+"->Zd<~Z`
* 17 bytes: `vtssVm@"*-+"._-~Z`
* 16 bytes: `vssVm@"*-+"._-~k`
* 15 bytes: `vsm+@"*-+"._-~k`
> 13 votes

# Answer
# Jelly, ~~18~~ ~~16~~ ~~15~~ 14 bytes

```
I0;ð1g×⁹⁸œṗP€S

```

Uses no built-in eval. Try it online! or verify all test cases.

### How it works

```
I0;ð1g×⁹⁸œṗP€S  Main link. Input: A (list)

I               Increments; compute the deltas of all adjacent items of A.
 0;             Prepend a 0.
   ð            Begin a new, dyadic chain.
                Left argument: D (0 plus deltas). Right argument: A
    1g          Compute the GCD of 1 and each item in D.
                This yields 1 for non-negative items, -1 for negative ones.
      ×⁹        Multiply each 1 or -1 with the corresponding item of A.
                This negates every item in A that follows a - sign.
        ⁸œṗ     Partition the result by D. This splits at occurrences of non-zero
                values of D, grouping items with identical absolute value.
           P€   Take the product of each group.
             S  Sum; add the results.

```
> 12 votes

# Answer
# MATL, 12 bytes

```
Y'^l6MdZSh*s

```

This uses @aditsu's very nice idea of run-length encoding.

**Try it online!**

### Explanation

```
       % Take input vector implicitly
Y'     % RLE. Produces two vectors: values and lengths
^      % Rise each value to the number of consecutive times it appears. This
       % realizes the product of consecutive equal values
l      % Push 1
6M     % Push vector of values again
d      % Consecutive differences
ZS     % Sign function. Gives 1 or -1 (no 0 in this case)
h      % Concatenate horizontally with previous 1
*      % Multiply. This gives plus or minus depending on increasing character
s      % Sum of vector. This realizes the additions or subtractions
       % Display implicitly

```
> 9 votes

# Answer
# CJam, 20

```
q~e`{~_W-g\:W@#*}%:+

```

Try it online

**Explanation:**

```
q~       read and evaluate the input (array of numbers)
e`       RLE encode, obtaining [count number] pairs
{…}%     map each pair
  ~_     dump the count and number on the stack, and duplicate the number
  W-     subtract the previous number (W is initially -1 by default)
  g      get the sign of the result
  \      swap with the other copy of the number
  :W     store it in W (for next iteration)
  @#     bring the count to the top, and raise the number to that power
  *      multiply with the sign
:+       add all the results together

```
> 7 votes

# Answer
# JavaScript (ES6), 54

```
p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

```

`eval` receives a comma separated list of expressions and returns the value of the last one.

**Test**

```
f=p=>eval(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

t=p=>(0+p.map(v=>x+='*-+'[(p>v)+2*(p<v)]+(p=v),x=1))

function Test() {
  var a=I.value.match(/\d+/g).map(x=>+x) // convert input to a numeric array

  var x=f(a),y=t(a)
  O.textContent='Value '+x+'\n(no eval '+y+')'
}

Test()
```

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

```
<input value='12, 0, 7, 7, 29, 10, 2, 2, 1' id=I>
<button onclick='Test()'>Test</button>
<pre id=O></pre>
```
> 7 votes

# Answer
# Julia, ~~76~~ 57 bytes

```
!x=[[" ""-*+"[2+sign(diff(x))]...] x]'|>join|>parse|>eval

```

My first time golfing Julia, so maybe there are obvious improvements. Try it online!

Dennis saved a ton of bytes.
> 5 votes

# Answer
# Pyth - ~~23~~ ~~22~~ 20 bytes

As with Kenny's, multiplication doesn't work online.

```
vs.i+\+@L"*+-"._M-Vt

```

Test Suite without doing eval.
> 4 votes

# Answer
# R, 92 bytes

There's likely still some good golfing that can be done here.

```
eval(parse(t=paste(i<-scan(),c(ifelse(d<-diff(i),ifelse(d>0,"+","-"),"*"),""),collapse="")))

```

Ungolfed:

```
i = scan()                # Read list from stdin
d = diff(i)               # Calculate difference between each element of list
s = ifelse(d,             # If d!=0
             ifelse(d>0,  # And if d>1
                    "+",  # Return plus
                    "-"), # Else return minus
             "*")         # Else (i.e. d==0) return multiply.
s = c(s,"")               # Pad the list s with an empty string, so it's the same
                          # length as i
p = paste(i,s,collapse="")# Paste the elements of i and s into one long string.
eval(parse(t=p))          # Evaluate the string as a language object.

```
> 3 votes

# Answer
# Brachylog, ~~34~~ 32 bytes

```
~b≜ḅ⟨h⟨h≡^⟩l⟩ᵐs₂ᶠ{zh>₁&ttṅ|tt}ᵐ+

```

Try it online!
> 3 votes

# Answer
# TI-BASIC, 146 bytes

I'll format it nicely when not on mobile. Sleep escapes me, so you get this. Enjoy.

```
Prompt L₁
"(→Str1
For(A,1,dim(L₁
{0,1→L₂
{0,L₁(A→L₃
LinReg(ax+b) L₁,L₃,Y₁
Equ►String(Y₁,Str2
sub(Str2,1,-1+inString(Str2,"X→Str2
If A>1
Then
L₁(A-1
2+(Ans>L₁(A))-(Ans<L₁(A
Str1+sub("+*-",Ans,1→Str1
End
Str1+Str2→Str2
End
expr(Str1

```
> 2 votes

# Answer
# Javascript ES6, ~~64~~ 62 chars

```
a=>eval(a.map((x,i)=>x+('*+-'[x<a[++i]|(x>a[i])*2])).join``+1)

```
> 2 votes

# Answer
# Java, 384 bytes

```
int s(int[]l){int n=l[0],m;for(int i=0;i<l.length-1;i++)if(l[i]<l[i+1])if(i<l.length-2&&l[i+1]!=l[i+2])n+=l[i+1];else{m=l[i+1];while(i<l.length-2&&l[i+1]==l[i+2])m*=l[(i++)+1];n+=m;}else if(l[i]>l[i+1])if(i<l.length-2&&l[i+1]!=l[i+2])n-=l[i+1];else{m=l[i+1];while(i<l.length-2&&l[i+1]==l[i+2])m*=l[(i++)+1];n-=m;}else{m=l[i];while(i<l.length-1&&l[i]==l[i+1])m*=l[i++];n+=m;}return n;}

```

**Ungolfed** try online

```
int s(int[] l)
{
    int n=l[0], m;

    for(int i=0; i<l.length-1; i++)
    {
        if(l[i] < l[i+1])
        {
            if (i<l.length-2 && l[i+1]!=l[i+2])
            {
                n += l[i+1];
            }
            else
            {
                m = l[i+1];
                while(i<l.length-2 && l[i+1]==l[i+2]) m *= l[(i++)+1];
                n += m;
            }
        }
        else if(l[i] > l[i+1])
        {
            if (i<l.length-2 && l[i+1]!=l[i+2])
            {
                n -= l[i+1];
            }
            else
            {
                m = l[i+1];
                while(i<l.length-2 && l[i+1]==l[i+2]) m *= l[(i++)+1];
                n -= m;
            }
        }
        else
        {
            m = l[i];
            while(i<l.length-1 && l[i]==l[i+1]) m *= l[i++];
            n += m;
        }
    }

    return n;
}

```
> 1 votes

# Answer
## Perl, 49 bytes

**48 bytes code + 1 for `-p`**

```
s/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval

```

### Usage

```
perl -pe 's/\d+ (?=(\d+))/$&.qw(* - +)[$&<=>$1]/ge;$_=eval' <<< '12 0 7 7 29 10 2 2 1'
75

```

### Notes

I learnt here that you can capture a lookahead in PCRE, although it's a little unintuitive (`(?=(\d+))` instead of `((?=\d+))`). It does make sense after reading though as you would be capturing a zero-length match (the lookahead) with the latter, and instead capture the match with the former).

Thanks to @ninjalj for saving 8 bytes!
> 1 votes

# Answer
# Javascript ES6, 79 chars

```
a=>eval(`${a}`.replace(/(\d+),(?=(\d+))/g,(m,a,b)=>a+('*+-'[+a<+b|(+a>+b)*2])))

```
> 1 votes

# Answer
## Actually, 30 bytes

```
;2@VpXdX`i-su"+*-"E`M' @o♀+εj≡

```

Unfortunately, because the eval () command only evaluates literals on TIO, this program does not work on TIO.

Explanation:

```
;2@VpXdX`i-su"+*-"E`M' @o♀+εj≡
;                               duplicate input
 2@V                            overlapping sublists of length <= 2
    pXdX                        discard first and last element (length-1 sublists)
        `i-su"+*-"E`M           map: for each pair of elements
         i-su                     flatten, subtract, sign, increment (results in a 0 if b < a, 1 if b == a, and 2 if b > a)
             "+*-"E               select the correct operation
                     ' @o       put a space at the beginning of the list to pad it properly
                         ♀+     pairwise addition (since addition is not defined for strings and integers, this just zips the lists and flattens the result into a single flat list)
                           εj   join with empty string
                             ≡  eval

```
> 1 votes

# Answer
# , ~~120~~ 44 bytes

```
r=rle(scan());c(1,sign(diff(r$v)))%*%r$v^r$l

```

Try it online!

The algorithm is similar to this answer's, but I only realized it after coding my answer. Much better than my original answer that was using `eval(parse)`.

Fully leverages R's vectorized operations - does the `*` operation first using `rle(x)$values ^ rle(x)$lenghts` and dot-products this vector with `sign( diff( rle(x)$values ) )` (predended with `1`).
> 1 votes

# Answer
# 05AB1E (legacy), ~~17~~ ~~16~~ 15 bytes

```
ü.S…*-+sè‚ζJJ.E

```

-2 bytes thanks to *@Emigna*.

Try it online or verify all test cases.

**Explanation:**

```
ü                  # Pair-wise loop over the (implicit) input-list
                   #  i.e. [12,0,7,7] → [[12,0],[0,7],[7,7]]
 .S                # Calculate the signum of the pair (-1 for a<b; 0 for a==b; 1 for a>b)
                   #  i.e. [[12,0],[0,7],[7,7]] → [1,-1,0]
   …*-+sè          # Index over "*-+" (with wrap-around)
                   #  i.e. [1,-1,0] → ['-','+','*']
         ‚ζ        # Zip the two lists together (appending the operands to the numbers)
                   #  i.e. [12,0,7,7] and ['-','+','*','+']
                   #   → [[12,'-'],[0,'+'],[7,'*'],[7,' ']]
           JJ      # Join them together
                   #  [[12,'-'],[0,'+'],[7,'*'],[7,' ']] → '12-0+7*7 '
             .E    # Evaluate as Python code
                   #  i.e. '12-0+7*7' → 61

```
> 1 votes

# Answer
# PHP, 103 bytes

Neat challenge. This got longer than expected. I think using `array_map` or similar won't improve the byte count, as anonymous functions are still expensive in PHP.

```
foreach(fgetcsv(STDIN)as$v)(0<=$p?$o.=$p.('*-+'[($p>$v)+2*($p<$v)]):_)&&$p=$v;echo eval("return$o$v;");

```

Runs from command line, will prompt for a comma separated list, like:

```
php array_to_math.php
12, 0, 7, 7, 29, 10, 2, 2, 1

```
> 0 votes

# Answer
## PowerShell v2+, 62 bytes

```
-join($args|%{"$o"+'*+-'[($o-lt$_)+2*($o-gt$_)];$o=$_})+$o|iex

```

Takes input as space-separated command-line arguments, which gets converted into automatic array `$args`. We iterate through each element, using helper variable `$o` each iteration to remember what our previous entry was. We use a indexed-string to pull out the appropriate operator, done by performing math on the implicitly-converted Boolean values (e.g., if the previous entry is smaller, the `[]` evaluates to `1+2*0` so `'*+-'[1]` means the `+` is selected).

The concatenated strings are left on the pipeline. We collect all of those snippets together (e.g., `3-`, `1+`, `4-`, etc.) with a `-join` operation, concatenate on the final number (implicitly converted to string), and pipe it to `iex` (alias for `Invoke-Expression` and similar to `eval`).
> 0 votes

# Answer
# Japt, 25 bytes

Would like to cut it shorter, but I couldn't make an eval-less version work.

```
S+Uä!- ®"*+-"gZÎÃ¬)íU
OxU

```

Try it online!
> 0 votes

# Answer
# Japt `-x`, ~~21~~ 19 bytes

```
änJ f mÎí*Uò¦ ®ÎpZÊ

```

Try it

---

## Explanation

```
                        :Implicit input of array U
  J                     :Prepend -1
än                      :Get deltas
    f                   :Filter (remove 0s)
      m                 :Map
       Î                : Signs
        í               :Interleave
          U             :  Original input
           ò            :  Partition on
            ¦           :   Inequality
              ®         :  Map each sub-array Z
               Î        :    Get first element
                p       :    Raise to the power of
                 ZÊ     :     Length of Z
         *              :Reduce each pair of elements by multiplcation
                        :Implicitly reduce by addition and output

```
> 0 votes

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


title: PNZ (Guess 3 unique digits in order)

text:
# Question
Title: PNZ (Guess 3 unique digits in order)
From a challenge in a programming book long ago, PNZ is a game where the user must guess three unique digits in the correct order.

**Rules**:

1. A random 3 digit number with no repeating digits is generated. (This is what the user is trying to guess)
2. The user inputs a guess of 3 digits, which is to be evaluated by the program.
3. Output a "P" for every correct digit in a correct place.
4. Output a "N" for every correct digit in an incorrect place.
5. Output a "Z" only if no digits are correct.
6. Continue accepting inputs until all digits are correct and in the correct place, then output "PPP" followed by the number of guesses it took on a new line.

**Note**:

* A "Correct digit" means that one of the digits in the guess is also one of the digits in the random 3 digit number.
* A "Correct place" means it is a "Correct digit" AND is in the same place as the 3 digit random number.
* The order of outputting should be all "P"'s first, then "N"'s, or only "Z" if nothing is correct.
* If an input contains repeating digits, "P" takes priority over "N" (Example: `Number: 123` `Input: 111` `Output: P`)
* (OPTIONAL) Inputs that are not exactly 3 digits in length should not be evaluated, nor count towards the running total of guesses

Example if the generated digits were 123

```
> 147
P
> 152
PN
> 126
PP
> 123
PPP
4

```

Example if the generated digits were 047

```
> 123
Z
> 456
N
> 478
NN
> 947
PP
> 047
PPP
5

```

This is CodeGolf, so the shortest program wins!

# Answer
# JavaScript (ES6), ~~195~~ ~~187~~ 184 bytes

**Edit** Saved 8 bytes thx @Neil

**Edit** Saved 3 bytes thx @user81655

(newlines counted as 1 byte)

```
d=[...'0123456789']
x=[10,9,8].map(l=>d.splice(Math.random()*l,1))
for(c=p=a='';!p[2];++c)g=prompt(a),n=p='',x.map((d,i)=>d-g[i]?~g.search(d)?n+='N':0:p+='P'),a=p+n||'Z'
alert(a+' '+c)

```

**Test**

```
d=[...'0123456789']
x=[10,9,8].map(l=>d.splice(Math.random()*l,1))
for(c=p=a='';!p[2];++c)
  g=prompt(a),
  n=p='',
  x.map((d,i)=>
        d-g[i]?~g.search(d)?n+='N':0:p+='P'
       ),
  a=p+n||'Z'
alert(a+' '+c)
```
> 5 votes

# Answer
## PowerShell v2+, ~~177~~ ~~231~~ 168 bytes

```
$g=-join(0..9|Random -c 3);for($c=0;$o-ne"PPP";$c++){$n=$p='';$i=read-host;$o=-join(0..2|%{((("","N")[$i.IndexOf($g[$_])-ge0]),"P")[$g[$_]-eq$i[$_]]}|sort -des);($o,"Z")[!$o]}$c

```

Oddly, I was able to golf the fixed version to be a shorter length than the unfixed version ... o.O

Many thanks to @edc65 for his assistance and inspiration!

### Explanation:

```
$g=-join(0..9|Random -c 3)   # Create an array @(0,1,2,...9) and choose 3 distinct elements
for($c=0;$o-ne"PPP";$c++){   # Loop until output = "PPP", incrementing $count each time
  $i=read-host               # Read input from the user

  $o=-join(0..2|%{((("","N")[$i.IndexOf($g[$_])-ge0]),"P")[$g[$_]-eq$i[$_]]}|sort -des)
       # OK, this is the convoluted part. We're constructing an array of "N", "P", or "",
       # sorting them by descending order (so the P's are first), and then joining them
       # together into a string. The array is constructed by essentially an if/elseif/else
       # statement that is evaluated three times thanks to the 0..2|%{} loop.
       # Starting from the innermost, we choose between "" and "N" based on whether the
       # input number has the current-digit of the secret number somewhere within it. We
       # then choose between that or "P" based on whether it's the _current_ digit of the
       # user input number.

  ($o,"Z")[!$o]
       # Here we output either $o from above or "Z" based on whether $o is empty
}
$c                           # The loop finished (meaning the user guessed), output $count

```

### Example run:

```
PS C:\Tools\Scripts\golfing> .\pnz.ps1
123
N
111
Z
222
P
452
PN
562
NN
275
PN
258
PPP
7

```
> 3 votes

# Answer
# ,~~178~~ 166 bytes

```
y=!(s<-sample(48:57,3))
while(any(y!=s)){F=F+1
y<-utf8ToInt(readline())
cat(rep("P",p<-sum(y==s)),rep("N",n<-sum(y%in%s)-p
),if(!(n+p))"Z","
",if(all(y==s))F,sep="")}

```

Try it online!

TIO link is just for byte count - try this in your R console! (or let me know if there is an alternate option).

See history for less-golfed, more readable version.
> 0 votes

---
Tags: code-golf, interactive
---


title: Risk Battle: Going Down

text:
# Question
Title: Risk Battle: Going Down
Given two lists of dice rolls for a battle in Risk, your program or function must output how many troops each player loses.

## Background

<sup> You do not have to read this, for it is merely background. Skip to "Task" subheading to continue unabated. </sup>

In the game of Risk, one player can attack another player (in fact, this is necessary to win). The outcome of a battle is determined by the roll of dice. Every battle occurs as a succession of sub-battles in which each player can lose up to `2` of their army pieces.

In a sub-battle, the defender and attacker each roll several dice whose number may vary based on circumstances irrelevant to this challenge. The highest-valued die of the attacker is compared to the highest-valued die of the defender. If the attacker's die is higher than the defender's die, the defender loses one piece. Otherwise, the attacker loses one piece.

Then, if both players have at least two dice, the second-highest valued dice of the two players are compared. Again, if the attacker's die is higher than the defender's die, the defender loses one piece. Otherwise, the attacker loses one piece.

(Defender wins ties. If both defender and attacker roll a `4`, then the attacker loses a piece.)

<sub> In this sub-battle from the Wikipedia article, the attacker's dice are red and the defender's dice are white. The highest of the attacker's dice is `4` and the highest of the defender's is `3`. Since the attacker was higher, the defender loses a piece. The second-highest are `3` for the attacker and `2` for the defender. Since the attacker was again higher, the defender loses another piece. Thus in this sub-battle, the attacker loses no pieces and the defender loses `2` pieces.</sub>

Note that the third-highest pieces are not compared. This is because the defender has no more than two dice on a single sub-battle, so there are no third-highest pieces to compare ever.

## Task

Given the unsorted dice rolls (integers in the range 1 to 6 inclusive) of both the attacker and the defender of a sub-battle of Risk in any convenient form, output the number of army pieces each player loses. The output may be in any convenient form, as long as it has different outputs to indicate the five possibilities. You must indicate what those different outputs are in your question.

The output is determined as follows: Start with `def=0` and `atk=0`. If the greatest value of the list of dice rolls of the attacker is greater than the greatest value of the list of dice rolls of the defender, then increment `def`. Otherwise, increment `atk`.

If both lists of dice rolls have length at least `2`, then: if the second-greatest value of the list of dice rolls of the attacker is greater than the second-greatest value of the list, then increment `def` and otherwise increment `atk`.

Finally, the program or function must output a unique identifier for each of the following 5 output possibilities:

```
  ╔═══╦═══╗
  ║atk║def║
  ╠═══╬═══╣
  ║ 1 ║ 0 ║
  ║ 0 ║ 1 ║
  ║ 2 ║ 0 ║
  ║ 1 ║ 1 ║
  ║ 0 ║ 2 ║
  ╚═══╩═══╝

```

## Example

Defender: `[3, 2]` Attacker: `[2, 4, 1]` Max of defender is `3` and max of attacker is `4`. `4>3`, so `def=1` Second of defender is `2` and second of attacker is `2`. `Not(2>2)`, so `atk=1`. The output could then be `[1,1]`.

## Test Cases

```
Defender
Attacker
Output (as [def,atk])
-----
[1]
[1]
[0,1]
-----
[6,6]
[1,1,1]
[0,2]
-----
[1,2]
[5,2,3]
[2,0]
-----
[5]
[3,4]
[0,1]
-----
[4]
[4,5]
[1,0]
-----
[1,3]
[1,2,3]
[1,1]
-----
[4]
[4,5,6]
[1,0]
-----
[4,5]
[6,2]
[1,1]
-----
[5]
[6,1,3]
[1,0]
-----
[5,5]
[4,4,1]
[0,2]
-----
[2,5]
[2,2]
[0,2]
-----
[6,6]
[4,4,3]
[0,2]
-----
[2,1]
[4,3]
[2,0]
-----
[4]
[1,5]
[1,0]
-----
[1]
[5,2]
[1,0]
-----
[6,2]
[4]
[0,1]
-----
[4,2]
[2,5,5]
[2,0]
-----
[2]
[6,6,2]
[1,0]
-----
[6]
[2,6]
[0,1]
-----
[3,1]
[1]
[0,1]
-----
[6,2]
[3,5,2]
[1,1]
-----
[4,2]
[1,1]
[0,2]
-----
[4,3]
[5,4,1]
[2,0]
-----
[5,6]
[1,2]
[0,2]
-----
[3,2]
[4,4]
[2,0]
-----
[2]
[6,3,4]
[1,0]
-----
[1,4]
[6,2,4]
[2,0]
-----
[4,2]
[2,5,4]
[2,0]
-----
[5]
[6,2,1]
[1,0]
-----
[3]
[2,5,4]
[1,0]
-----
[5,4]
[2]
[0,1]
-----
[6,3]
[2,6,5]
[1,1]
-----
[3,1]
[4]
[1,0]
-----
[4]
[6,6,5]
[1,0]
-----
[6,3]
[4,2]
[0,2]
-----
[1,6]
[5,4]
[1,1]
-----
[3,6]
[4,4]
[1,1]
-----
[5,4]
[5,1,1]
[0,2]
-----
[6,3]
[5,4]
[1,1]
-----
[2,6]
[1,2]
[0,2]
-----
[4,2]
[3,5,5]
[2,0]
-----
[1]
[1,2,1]
[1,0]
-----
[4,5]
[1,6]
[1,1]
-----
[1]
[3,5,1]
[1,0]
-----
[6,2]
[6,2]
[0,2]

```

## Sample implementation

Python 2 or 3

```
def risk(atk_rolls,def_rolls):
    # set the rolls in descending order, e.g. [5,3,2]
    atk_rolls = sorted(atk_rolls,reverse = True)
    def_rolls = sorted(def_rolls,reverse = True)
    # minimum length.
    minlen = min(len(atk_rolls),len(def_rolls))
    atk_lost = 0
    def_lost = 0
    # compare the highest-valued rolls
    if atk_rolls[0]>def_rolls[0]:
        def_lost += 1
    else:
        atk_lost += 1
    if minlen == 2:
        # compare the second-highest-valued rolls
        if atk_rolls[1] > def_rolls[1]:
            def_lost += 1
        else:
            atk_lost += 1
    return [def_lost, atk_lost]

```

## Specifications

* The input may be taken as any form that clearly encodes **only** the defender's rolls and the attacker's rolls.
* The output may be in any form that provides a unique output for each of the five possibilities listed above.
* The defender's rolls are a list of `1` or `2` integers in the set `[1,2,3,4,5,6]`. The attacker's rolls are a list of `1` to `3` integers in the set `[1,2,3,4,5,6]`.
* Since this is , shortest code **in each language** wins! Do **not** let answers in golfing languages discourage you from posting answers in other languages.

# Answer
# NAND gates, 237

Created with Logisim

Inputs are 3-bit unsigned binary, entered on the left. Outputs (2 bits) are on the right.

It is too large to fit on the screen and Logisim can't zoom, so the image is black-and-white. Sorry :(

Works for all test cases.

There is likely a better way to do this using some memory circuit, allowing large sections to be reused.
> 8 votes

# Answer
# Jelly,  ~~12~~  11 bytes

```
NṢ€>/Ṡḟ-o-S

```

A monadic link taking a list of `Defender, Attacker` rolls (each as lists), returning an integer between `-2` and `2` inclusive (defender losses - attacker losses):

```
result : [def, atk]
    -2 : [  0,   2]
    -1 : [  0,   1]
     0 : [  1,   1]
     1 : [  1,   0]
     2 : [  2,   0]

```

**Try it online!** or see a test suite (which maps the results to the OP format).

### How?

```
NṢ€>/Ṡḟ-o-S - Link: list [list Def, list Atk]
N           - negate all the rolls
 Ṣ€         - sort €ach of the lists of -1*rolls (max rolls are to the left now)
    /       - reduce by:
   >        -   is greater than?  (when len(Atk) > len(Def) leaves trailing negatives)
     Ṡ      - sign (maps all negatives to -1; zeros and ones of comparison unchanged)
       -    - literal -1
      ḟ     - filter discard (remove the -1s)
         -  - literal -1
        o   - logical or, vectorises (replaces the zeros with minus ones)
          S - sum

```
> 4 votes

# Answer
# Husk, 10 bytes

```
M#eI¬¤z>Ö>

```

Try it online!

Input as two separate lists of rolls, output as in the op.

### Explanation

`¤z>Ö>` sorts each list in descending order and then zips them comparing corresponding elements (and truncating the longer list).

`M#eI¬` creates a 2-element list (`e`) with counts (`#`) of truthy values (through identity `I`) and falsy values (through logical negation `¬`)
> 3 votes

# Answer
# JavaScript (SpiderMonkey), 97 83 78 bytes

```
d=>a=>{for(u=v=0;d.sort()>[]&a.sort()>[];)a.pop()>d.pop()?u++:v++
return[u,v]}

```

Try it online!

-4 bytes and fixed thanks to @ovs and @Craig Ayre
-1 byte thanks to @Shaggy
> 2 votes

# Answer
# Retina, 82 bytes

```
%O^`.
((.)+).*(¶(?<-2>.)+)(?(2)(?!)).*
$1$3
O$`.
$.%`
\d
$*1D
(1+)D1*\1

1+D
A
O`.

```

Try it online! First line of input is attacker's dice, second is defender's dice. Returns (on separate lines) `AA`, `AD`, `DD`, `A` or `D` as appropriate.
> 2 votes

# Answer
# Python 2, ~~83~~ 75 bytes

```
x=0
k=map(sorted,input())
while all(k):x+=cmp(*map(list.pop,k))or 1
print-x

```

Try it online!

Output is defender losses - attacker losses
> 2 votes

# Answer
# MATL, 23 bytes

```
oH2$S1&Y)Y&t1M>t~b,Y&sD

```

Try it online!

Not sure why defenders are allowed more dice than attackers, but maybe I am not that well versed in Risk. The core program is just `>t~,sD`, all the other bytes are there to allow for different input lengths, with a bit of sorting thrown in. Input is attacker followed by defender, output is attacker losses followed by defender losses.

```
o    % Convert input to numeric array, padding with zeroes
H2$S % Sort row-wise (specified to prevent 1v1 sorting)
1&Y) % Split attacker/defender
Y&t  % Logical and to filter out excess dice. Duplicate for 'do twice' later.
1M>  % Get throws again, decide who won
t~   % And the inverse to decide who lost
b,   % Bubble filter to the top. Do twice:
  Y& % Apply filter
  sD % Sum of losses. Display.

```
> 2 votes

# Answer
# Perl 5, 66 + 1 (-a) = 67 bytes

```
@A=sort split/ /,<>;$b+=@A?pop@A>$_?-1:1:0for reverse sort@F;say$b

```

Try it online!

**Input:**

Two lines. First line is defender (player 1), second is attacker (player 2). Individual rolls separated by spaces.

**Output:**

Indicates effective change in defender's strength vs. attacker.

```
Output Attacker Defender
   2      0        2        Defender wins both
   1      0        1        Defender wins the only roll
   0      1        1        Attacker wins first, defender wins second
  -1      1        0        Attacker wins the only roll
  -2      2        0        Attacker wins both rolls

```
> 1 votes

# Answer
# , 46 bytes

```
function(x,y)s(s(y,T)[1:2]>s(x,T)[1:2])
s=sort

```

Try it online!

All this does is three sorts and one comparison... plus extracting the first two elements in the middle.

Input is two vectors of dice rolls.

Output encoded as follows:

```
╔═══╦═══╗
║atk║def║
╠═══╬═══╣
║ 1 ║ 0 ║ TRUE
║ 0 ║ 1 ║ FALSE
║ 2 ║ 0 ║ TRUE  TRUE
║ 1 ║ 1 ║ FALSE TRUE
║ 0 ║ 2 ║ FALSE FALSE
╚═══╩═══╝

```

Works because extraction in R does not recycle its argument, but pads the result with `NA` to get to the requested length.
> 1 votes

# Answer
# Jelly, 30 bytes

```
0,0‘⁸Ṁ€</¤¦‘⁸ḟ"Ṁ€⁺</¤¦⁸L€Ṃ>1¤¡

```

Try it online!

*Veeeeeeeery* ungolfed! \>\_\<

Outputs values exactly as in test cases.
> 0 votes

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