# Question
Title: The Fibonacci Rectangular Prism Sequence
# What is the *Fibonacci Rectangular Prism Sequence*?

The Fibonacci Rectangular Prism Sequence is a sequence derived from the Fibonacci sequence starting with one. The first 3 numbers of the Fibonacci sequence (starting with one) are 1, 1, and 2, so the first number of the Fibonacci Rectangular Prism Sequence is the square of the diagonal length of a rectangular prism (X in this picture) with the dimensions 1x1x2. The next number of the Fibonacci Rectangular Prism Sequence is the square of the diagonal length of a prism with the dimensions 1x2x3, followed by the square of the diagonal of 2x3x5, and so on. The formula for each number in the series would be A127546: $$a(n)={F\_n}^2 + {F\_{n+1}}^2 + {F\_{n+2}}^2$$ where \\$F\_n\\$ is the nth number of the Fibonacci sequence. The convention is that \\$F\_0\\$ is 0, and \\$F\_1\\$ is 1. (See A000045 for more information about the Fibonacci sequence.)

# Your Challenge:

Write code that takes an index \\$n\\$ and outputs the \\$n\\$'th element of the sequence. It’s , so the shortest code wins!

# Test cases:

```
0 ==> 2
1 ==> 6
2 ==> 14
3 ==> 38
4 ==> 98
5 ==> 258
6 ==> 674
7 ==> 1766
8 ==> 4622
9 ==> 12102
10 ==> 31682

```

# Leaderboard:

```
var QUESTION_ID=214423,OVERRIDE_USER=98932,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
# MathGolf, 6 bytes

This is not really interesting (but it is the shortest answer).

```
3r+f²Σ

```

## Explanation

3, range, +, Fibonacci, square, sum.

Try it online!
> 11 votes

# Answer
# Python 2, 33 bytes

```
lambda n:((3-5**.5)/2)**~n//5*4+2

```

Try it online!

**34 bytes**

```
lambda n:(5**.5/2+1.5)**-~n//5*4+2

```

Try it online!

Outputs floats. Based on the closed form by Lynn, simplified to:

$$ f(n) = 4 \left \lfloor{\frac{\phi^{2n+2}}{5}}\right \rfloor + 2.$$

We further convert \\$\phi^{2n+2} = (\phi^2)^{n+1} = (\phi+1)^{n+1}\\$, writing \\$\phi+1\\$ as \\$\frac{\sqrt{5}}{2}+1.5\\$. We could also try writing it out as \\$2.61803398875...\\$ to some precision. The limited precision of floats will cause deviations for large enough outputs for any version of this solution.

**44 bytes**

```
f=lambda n:2*(n<1)or(f(n-1)+f(n-2))*2-f(n-3)

```

Try it online!

An alternative recursive formula that gets rid of the \\$(-1)^n\\$ term by recursing one step further back.

$$ f(n) = 2f(n-1) + 2f(n-2)-f(n-3)$$

where \\$f(n)=2\\$ for \\$n\<1\\$.

**44 bytes**

```
f=lambda n:2*(n<1)or 3*f(n-1)-f(n-2)+n%2*4-2

```

Try it online!

Uses a recursive formula, with base case \\$f(-1)=f(0)=2\\$. Writes `n%2*4-2` for `-2*(-1)**n`.
> 8 votes

# Answer
# JavaScript (ES6), 34 bytes

*Saved 2 bytes thanks to @user and 3 more bytes thanks to @xnor*

The following recursive formula is given for \\$n\>3\\$ on OEIS, but it actually works for \\$n\>1\\$:

$$a(n) = 3a(n-1)-a(n-2)-2(-1)^n$$

As noticed by xnor, we can also make it work for \\$a(1)\\$ by defining \\$a(-1)=a(0)=2\\$.

```
f=n=>n<1?2:3*f(n-1)-f(n-2)+n%2*4-2

```

Try it online!
> 7 votes

# Answer
# 05AB1E, ~~9~~ 7 bytes

```
2Ý+ÅfnO

```

Try it online or verify all test cases.

**Explanation:**

```
2Ý       # Push list [0,1,2]
  +      # Add each to the (implicit) input-integer: [n,n+1,n+2]
   Åf    # Get the Fibonacci numbers at those indices: [F(n),F(n+1),F(n+2)]
     n   # Square each: [F(n)²,F(n+1)²,F(n+2)²]
      O  # Sum them together: F(n)²+F(n+1)²+F(n+2)²
         # (after which the result is output implicitly)

```

---

---

For funsies and since I was curious, here are the ports of the approaches used in *@Razetime*'s Husk and *@Arnauld*'s JavaScript answers:

**10 bytes:**

```
∞<Åfü3nOIè

```

Try it online or verify all test cases.

**11 bytes**

```
₂Sλè3*₂®Nm·Æ

```

Try it online or verify all test cases.

**Explanation:**

```
∞            # Push an infinite positive list: [1,2,3,4,5,...]
 <           # Decrease each by 1 to let it start at 0: [0,1,2,3,4,...]
  Åf         # Get the 0-based Fibonacci number: [0,1,1,2,3,...]
    ü3       # Create overlapping triplets: [[0,1,1],[1,1,2],[1,2,3],[2,3,5],[3,5,8],..]
      n      # Square each inner value: [[0,1,1],[1,1,4],[1,4,9],[4,9,25],[9,25,64],...]
       O     # Sum each: [2,6,14,38,98,...]
        Iè   # Index the input-integer into the list
             # (after which the result is output implicitly)

  λ          # Start a recursive environment
   è         # to output the 0-based (implicit) input'th value implicitly afterwards,
₂S           # starting at a(0)=2,a(1)=6
             # (`₂S`: push builtin 26, convert it to a list of digits)
             # And we calculate every following a(n) as follows:
             #  (implicitly push the value of a(n-1)
    3*       #  Multiply it by 3: 3*a(n-1)
      ₂      #  Push a(n-2)
       ®     #  Push -1
        Nm   #  to the power of the current n: (-1)**n
          ·  #  Double it: 2*(-1)**n
           Æ #  Reduce the three values on the stack by subtracting:
             #   3*a(n-1)-a(n-2)-2*(-1)**n

```
> 5 votes

# Answer
# Husk, 8 bytes

```
ṁ□↑3↓Θİf

```

Try it online!

```
ṁ□↑3↓Θİf
     Θİf    # fibonacci sequence starting with zero
    ↓       # remove first n elements (n = input)
  ↑3        # get first 3 elements of what's left
ṁ□          # square each of them & sum

```
> 5 votes

# Answer
# Haskell, 34 bytes

```
f=2:scanl(+)2f
a n=f!!n^2-2*(-1)^n

```

Try it online!

Uses the \\$a(n)=4F^2\_{n+1}-2(-1)^n\\$ formula.

# Haskell, 34 bytes

```
(0!1!!)
a!b|c<-a+b=a^2+b^2+c^2:b!c

```

Try it online!

Uses the \\$a(n)=F\_n^2+F\_{n+1}^2+F\_{n+2}^2\\$ formula.
> 5 votes

# Answer
# , 20 bytes

*-3 thanks to FrownyFrog*

```
1#.2^~2&(+/@$,$)&1 1

```

Try it online!

* `2& f &1 1` Execute f `n` times with `2` as left argument and `1 1` as right argument.
* `+/@$,$` Sum first `2` elements of the list, and prepend it to itself
* `1#.2^~` Square and sum.
> 5 votes

# Answer
# Husk, 9 bytes

```
!Ẋoṁ□ėΘİf

```

Try it online!

1-indexed.

## Explanation

```
!Ẋoṁ□ėΘİf
       İf infinite fibonacci sequence
      Θ   prepend a 0
 Ẋo       map the following over triplets of values
     ė    make list of 3 elements
   ṁ□     sum their squares
!         index into this list using input

```
> 4 votes

# Answer
# Charcoal, ~~24~~ 23 bytes

```
Ｆ²⊞υ²ＦＮ⊞υ⁻⊗Σ…⮌υ²§υ±³Ｉ⊟υ

```

Try it online! Link is to verbose version of code Uses @xnor's recurrence relation. Explanation:

```
Ｆ²⊞υ²

```

Start with the `-1`th and `0`th terms of the sequence.

```
ＦＮ

```

Generate as many additional terms as required.

```
⊞υ⁻⊗Σ…⮌υ²§υ±³

```

Push twice the sum of the last two terms minus the previous. (On the first loop, there aren't enough terms, but Charcoal indexes cyclically, so it still finds `2` as desired. I could have just started with 3 terms; it makes no difference.)

```
Ｉ⊟υ

```

Output the final term, which is the desired result.

Alternative 23-byte solution generates the Fibonacci series:

```
⊞υ⁰Ｆ⁺²Ｎ⊞υ⊕↨…υι¹ＩΣＸＥ³⊟υ²

```

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

```
⊞υ⁰

```

Start with the first term of the sequence.

```
Ｆ⁺²Ｎ

```

Extend the sequence until we have all the necessary terms.

```
⊞υ⊕↨…υι¹

```

Each term is one more than the sum of all the terms except the previous. I use base conversion from base 1 to avoid the edge case of the empty list.

```
ＩΣＸＥ³⊟υ²

```

Pop the last three terms, square them, and print the sum.
> 4 votes

# Answer
# K (ngn/k), ~~27~~ 25 bytes

```
{+/t*t:x({x,+/x}1_)/|2\6}

```

Try it online!

```
{                       } \ function with parameter x
                     2\6  \ 6 to binary -? 1 1 0
                    |     \ reverse -> 0 1 1
       x(         )/      \ repeat the function in () n times
                1_        \ drop the first number and
         {     }          \ apply this function to the remaining list
            +/x           \ sum
          x,              \ append to the list
     t:                   \ assign to t
   t*                     \ square
 +/                       \ sum

```

I managed to shave off 2 bytes after seeing @xash's J solution \- please upvote their solution!
> 4 votes

# Answer
# , 37 35 31 bytes

Nothing original, given the previous answers:

```
(((3+5^.5)/2)^(scan()+1)/5)%/%1*4+2

```

was 35 bytes, but Guiseppe got rid of four parentheses

```
((3+5^.5)/2)^(scan()+1)%/%5*4+2

```

Try it online!
> 4 votes

# Answer
# Jelly, 8 bytes

```
3Ḷ+µÆḞ²S

```

Try it online!

I feel like it's possible to save a byte here, but I'm not sure how. (EDIT: Apparently the answer was to use 05AB1E; @Kevin Cruijssen's answer, which was written in parallel with this one, uses the same builtins in the same order but 05AB1E happens to parse it the way we'd want.)

You probably shouldn't upvote this answer; it's just a direct translation of the specification and contains no clever golfing tricks. I was just interested in how long it would come out to in Jelly.

## Explanation

```
3Ḷ+µÆḞ²S
3Ḷ         [0,1,2]
  +        add {the input} to {each elemeent}
   µ       (fix for parser ambiguity)
    ÆḞ     take the Fibonacci number whose index is {each element}
      ²    square {each element}
       S   sum the resulting list {and output it}

```
> 3 votes

# Answer
# Python 2, 47 bytes

I tried a few other methods, like the recurrence realtion used by Arnauld and the formaula provided by Emeric Deutsch on the OEIS page, but a literal implemention seems to be the shortest.

```
f=lambda n,a=0,b=1:n+2and(n<2)*b*b+f(n-1,b,a+b)

```

Try it online!
> 3 votes

# Answer
# Scala, 53 bytes

```
def f(n:Int):Int=if(n>0)3*f(n-1)+n%2*4-2-f(n-2)else 2

```

Try it online

This one uses the method used in @Arnauld's answer.

---

# Dotty, 84 bytes

```
n=>{def f:Stream[Int]=0#::1#::f.zip(f.tail).map(_+_);f.slice(n,n+3).map(x=>x*x).sum}

```

Try it online
> 3 votes

# Answer
# C (gcc), ~~42~~ 38 bytes

Saved 4 bytes thanks to xnor!!!

```
f(n){n=n<1?2:3*f(n-1)-f(n-2)+n%2*4-2;}

```

Try it online!

Uses Arnauld's formula from his JavaScript answer.
> 3 votes

# Answer
# Japt `-x`, 9 bytes

```
3ÆMgX+U ²

```

Try it
> 3 votes

# Answer
# Arn, 16 bytes

```
╗¤û°œJ–¬▀ôƒìÚ„")

```

Try it!

# Explained

Unpacked: `2+4*:v(phi^(*2+2)/5`

Uses the same closed-form variant @xnor uses.

```
  2
+  Plus
    4
  *  Times
    :v  Floor of
      (
          phi  The golden ratio
        ^  Exponentiated by
          (
                _  Variable ≡ STDIN; implied
              *
                2
            +
              2
          )
        /  Divided by
          5
      )  Implied

```

Also for fun:

# Arn `-l`, 22 bytes

```
ñf©¶─[•«DWLšií▬Xy®┐Vÿ"

```

Try it!

# Explained

Unpacked: `v:1[2 2{*3- -2*_1^++v}->+2`

Sequence definition, the `-l` flag returns the last entry
> 3 votes

# Answer
# Retina, 39 bytes

```
K`_¶_
"$+"+L$`(_+¶)(_+)
$2$1$&
%`_
$=
_

```

Try it online! No test suite because of the way the program uses history. Explanation:

```
K`_¶_

```

Replace the input with the first terms (in unary) of the Fibonacci sequence.

```
"$+"+`

```

Repeat `n` times...

```
L$`(_+¶)(_+)
$2$1$&

```

... sum the first two terms and drop terms after the third.

```
%`_
$=

```

Square each term separately.

```
_

```

Take the sum and convert to decimal.
> 2 votes

# Answer
# Perl 5, 51 bytes

```
sub a{my$n=pop;(2)[$n]||3*a($n-1)-a($n-2)+$n%2*4-2}

```

Try it online!

Just a translation of Arnaulds Javascript answer.
> 2 votes

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


title: Output visual diagram of picture

text:
# Question
Title: Output visual diagram of picture
Write a program that inputs the dimensions of a painting, the matting width, and the frame width for a framed portrait. The program should output a diagram using the symbol `X` for the painting, `+` for the matting, and `#` for the framing. The symbols must be space-separated. Trailing whitespace is alright, as long as the output visually matches the criteria. The inputs can be `0`.

INPUT: 3 2 1 2 (Width, Height, Matte Width, Frame Width)

OUTPUT:

In text form:

```
# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + X X X + # #
# # + X X X + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

```

The winning code completes the conditions in the least possible bytes.

# Answer
> 6 votes
# Python 2, 98 bytes

```
w,h,a,b=input()
a*='+'
b*='#'
for c in b+a+h*'X'+a+b:print' '.join(min(c,d)for d in b+a+w*'X'+a+b)

```

Try it online!

Prints a space-separated grid, strictly following the spec. I'm amused that `*=` is used to convert `a` and `b` from numbers to strings.

Python 3 can save some bytes by avoiding `' '.join`, maybe more by using f-strings and assignment expressions. Thanks to Jo King for -2 bytes.

**Python 3, 93 bytes**

```
def f(w,h,a,b):a*='+';b*='#';[print(*[min(c,d)for d in b+a+w*'X'+a+b])for c in b+a+h*'X'+a+b]

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6),  ~~118 113~~  107 bytes

```
(w,h,M,F)=>(g=(c,n)=>'01210'.replace(/./g,i=>c(i).repeat([F,M,n][i])))(y=>g(x=>'#+X'[x<y?x:y]+' ',w)+`
`,h)

```

Try it online!

### Commented

```
(w, h, M, F) => (       // given the 4 input variables
  g = (                 // g = helper function taking:
    c,                  //   c = callback function returning a string to repeat
    n                   //   n = number of times the painting part must be repeated
  ) =>                  //
    '01210'             // string describing the picture structure, with:
    .replace(           //   0 = frame, 1 = matte, 2 = painting
      /./g,             // for each character in the above string:
      i =>              //   i = identifier of the current area
        c(i)            //   invoke the callback function
        .repeat         //   and repeat the result ...
        ([F, M, n][i])  //   ... either F, M or n times
    )                   // end of replace()
)(                      // outer call to g:
  y =>                  //   callback function taking y:
    g(                  //     inner call to g:
      x =>              //       callback function taking x:
        '#+X'           //         figure out which character to use
        [x < y ? x : y] //         according to the current position
        + ' ',          //         append a space
      w                 //       repeat the painting part w times
    )                   //     end of inner call
    + '\n',             //     append a line feed
  h                     //   repeat the painting part h times
)                       // end of outer call

```

# Answer
> 3 votes
# MATL, 24 bytes

```
&l,ithYaQ]'#+X'w)TFX*cYv

```

Input is: Height, Width, Matte Width, Frame Width.

Try it online!

### Explanation

```
&l      % Take height and width implicitly. Push matrix of that size with all
        % entries equal to 1
,       % Do twice
  i     %   Take input
  th    %   Duplicate, concatenate: gives a 1×2 vector with the number repeated
  Ya    %   Pad matrix with those many zeros vertically and horizontally
  Q     %   Add 1 to each entry
]       % End
'#+X'   % Push this string
w)      % Index into the string with the padded matrix
TF      % Push row vector [1 0]
X*      % Kronecker product. This inserts columns of zeros
c       % Convert to char again. Char 0 is will be displayed as space
Yv      % Remove trailing spaces in each line. Implicitly display

```

# Answer
> 2 votes
# Charcoal, ~~48~~ ~~47~~ 44 bytes

```
≔×ＮXθ≔×ＮXηＦＥ+#×Ｎι«≔⁺ι⁺θιθ≔⁺ι⁺ηιη»Ｅη⪫⭆θ⌊⟦ιλ⟧

```

Try it online! Link is to verbose version of code. Note: Trailing space. Edit: Now uses @xnor's algorithm. Explanation:

```
≔×ＮXθ≔×ＮXη

```

Input the width and height and convert them into strings of `X`s.

```
ＦＥ+#×Ｎι

```

Loop over the characters `+` and `#`, converting them into strings of length given by the remaining two inputs. Then loop over those two strings.

```
«≔⁺ι⁺θιθ≔⁺ι⁺ηιη»

```

Prefix and suffix the painting with the strings for the matting and framing.

```
Ｅη⪫⭆θ⌊⟦ιλ⟧

```

Loop over the strings, taking the minimum of the horizontal and vertical characters, and then double-spacing the rows, implicitly printing each row on its own line.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 142 bytes

```
(t=(p=Table)["# ",2(c=#4+#3)+#2,2c+#];p[t[[i,j]]="+ ",{j,z=#4+1,c+#3+#},{i,z,c+#3+#2}];p[t[[i,j]]="X ",{j,#3+z,c+#},{i,#3+z,c+#2}];""<>#&/@t)&

```

Try it online!

# Answer
> 2 votes
# 05AB1E (legacy) / 05AB1E `--no-lazy`, ~~32~~ 31 bytes

```
и'X×„+#vyI©×UεX.ø}®FDнgy×.ø]€S»

```

Takes the input in the order `height, width, matte, frame`. If the input order specified in the challenge is strict (still waiting on OP for verification), a leading `s` (swap) can be added for +1 byte.

Required the `--no-lazy` Elixir compiler flag in the new version of 05AB1E, since Elixir has some odd behavior due to lazy evaluation for nested maps/loops (here the result without this flag).

Try it online in the legacy version of 05AB1E.
Try it online in the new version of 05AB1E with added `--no-lazy` flag.

**Explanation:**

```
и              # Repeat the second (implicit) input the first (implicit) input amount of
               # times as list
 'X×          '# Repeat "X" that many times
„+#v           # Loop `y` over the characters ["+","#"]:
    y          #  Push character `y`
     I         #  Push the next input (matte in the first iteration; frame in the second)
      ©        #  And store it in the register (without popping)
       ×       #  Repeat character `y` that input amount of times
        U      #  Pop and store that string in variable `X`
    εX.ø}      #  Surround each string in the list with string `X`
    ®F         #  Inner loop the value from the register amount of times:
      Dнg      #   Get the new width by taking the length of the first string
         y×    #   Repeat character `y` that many times
           .ø  #   And surround the list with this leading and trailing string
   ]           # Close both the inner and outer loops
    €S         # Convert each inner string to a list of characters
      »        # Join every list of characters by spaces, and then every string by newlines
               # (and output the result implicitly)

```

# Answer
> 2 votes
# Jelly, 17 bytes

```
;ŒB“#+X+#”xʋⱮ«Ɱ/G

```

Try it online!

Argument 1: `[Frame width, Matte width]`
Argument 2: `[Width, Height]`

# Answer
> 1 votes
# Python 3.8 (pre-release), ~~116~~ ~~115~~ 113 bytes

```
lambda a,b,c,d:"\n".join((g:=['#'*(a+2*c+2*d)]*d+[(h:='#'*d)+'+'*(a+c*2)+h]*c)+[h+'+'*c+'X'*a+'+'*c+h]*b+g[::-1])

```

Try it online!

First attempt at golfing, will be improved soon. `a` is width, `b` is height, `c` is matte width, and `d` is frame width.

*-1 bytes using the `:=` operator to define `h` as `e * d`*

*-2 bytes thanks to Jo King suggesting me to remove the e and f parameters*

**EXPLANATION:**

```
lambda a,b,c,d:          Define a lambda which takes in arguments a, b, c, and d (The width of the painting, the height of the painting, the padding of the matte, and the padding of the frame width, respectively).
    "\n".join(                       Turn the list into a string, where each element is separated by newlines
        (g:=                         Define g as (while still evaling the lists)...
            ['#'*(a+2*c+2*d)]*d+       Form the top rows (the ones filled with hashtags)
            [(h:='#'*d)+'+'*(a+c*2)+h]*c Form the middle-top rows (uses := to golf this section)
        )+
        [h+'+'*c+'X'*a+'+'*c+h]*b+       Form the middle row
        g[::-1]                      Uses g to golf the code (forms the entire middle-bottom-to-bottom)
    )

```

# Answer
> 1 votes
# Jelly, ~~35~~ ~~31~~ ~~28~~ 24 bytes

```
Dịx@“#+X+#”
⁽-Fç«þ⁽-ȥç$G

```

Try it online!

Takes the input in the order frame, matte, width, height; comma separated. Outputs the ASCII-art picture with frame and matte. If the input order is strict I’d need to add more bytes (as per my original post).

Couple of golfs based on @EriktheOutgolfer’s answer; I’d realised the characters were in ASCII order but hadn’t thought how best to take advantage of that, and had forgotten about `G`. His is still a better answer though!

# Answer
> 1 votes
# Canvas, 24 bytes

```
Ｘ；«［ｌｘ＊ｅ⤢｝
X×＊+⁸#⁸ ＊Ｊ ×Ｏ

```

Try it here!

Should be 5 bytes shorter, but isn't because Canvas is buggy..

# Answer
> 1 votes
# , 119 bytes

```
function(w,h,m,f)write(Reduce(function(x,y)rbind(y,cbind(y,x,y),y),rep(c("+","#"),c(m,f)),matrix("X",w,h)),1,w+2*f+2*m)

```

Try it online!

# Answer
> 1 votes
# Husk, <sup>~~29~~</sup> 25 bytes

```
mm;₁'#⁰₁'+²RR'X
‼‼(m↔Tm+R

```

Try it online!

Ah, this was convoluted.

The input order is `Matte,Frame,Width,Height`.

-4 bytes after simplifying function 2 & 3.

## Explanation

```
Function ₁: framing function
‼‼(m↔Tm+R parameters a(char),n(int),m(matrix)
      m+R add a side
     T    Transpose
   m↔     reverse each row
‼‼(       repeat that 3 more times

Function ₀: main
mm;₁'#⁰₁'+²RR'X
           RR'X make width × height matrix of 'X'es
       ₁'+²     add the matte of '+'es
   ₁'#⁰         add the frame of '#'es
mm;             nest each character(adds spaces)

```

# Answer
> 0 votes
# Javascript, 158 bytes

```
(w,h,m,f)=>(q="repeat",(z=("#"[q](w+2*(m+f)))+`
`)[q](f))+(x=((e="#"[q](f))+(r="+"[q](m))+(t="+"[q](w))+r+e+`
`)[q](m))+(e+r+"X"[q](w)+r+e+`
`)[q](h)+x+z)

```

Can probably be trimmed down a little bit

```
f=

(w,h,m,f)=>(q="repeat",(z=("# "[q](w+2*(m+f))+`
`)[q](f))+(x=((e="# "[q](f))+(r="+ "[q](m))+(t="+ "[q](w))+r+e+`
`)[q](m))+(e+r+"X "[q](w)+r+e+`
`)[q](h)+x+z)

console.log(f(3,2,1,2))
```

# Answer
> 0 votes
# Perl 6, 98 bytes

```
{map(&min,[X] map (($_='#'x$^d~'+'x$^c)~'X'x*~.flip).comb,$^a,$^b).rotor($b+2*($c+$d)).join("\n")}

```

Try it online!

This is a port of xnor's Python answer.

# Perl 6, 115 bytes

```
->\a,\b,\c,\d{$_=['#'xx$!*2+a]xx($!=c+d)*2+b;.[d..^*-d;d..^a+$!+c]='+'xx*;.[$!..^*-$!;$!..^a+$!]='X'xx*;.join("
")}

```

Try it online!

Roughly golfed anonymous codeblock utilising Perl 6's multi-dimensional list assignment. For example, `@a[1;2] = 'X';` will assign `'X'` to the element with index 2 from the list with index 1, and `@a[1,2,3;3,4,5]='X'xx 9;` will replace all the elements with indexes `3,4,5` of the lists with indexes `1,2,3` with `'X'`.

### Explanation:

First, we initialise the list as a `a+2*(c+d)` by `b+2*(c+d)` rectangle of `#`s.

```
$_=['#'xx$!*2+a]xx($!=c+d)*2+a;
State:
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# # # # # # # # #

```

Then we assign the inner rectangle of `+`s

```
.[d..^*-d;d..^a+$!+c]='+'xx*;
State:
# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + + + + + # #
# # + + + + + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

```

Finally, the innermost rectangle of `X`s.

```
.[$!..^*-$!;$!..^a+$!]='X'xx*;
# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + X X X + # #
# # + X X X + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

```

# Answer
> 0 votes
# Perl 5, 115 bytes

```
$_=(X x$F[0].$/)x$F[1];sub F{s,^|\z,/.*/;$_[0]x"@+".$/,ge,s/^|(?=
)/$_[0]/gm while$_[1]--}F('+',$F[2]);F('#',$F[3])

```

TIO

# Answer
> 0 votes
# PowerShell, 132 bytes

```
param($w,$h,$m,$f)filter l{"$(,'#'*$f+,$_[0]*$m+,$_[1]*$w+,$_[0]*$m+,'#'*$f)"}($a=@('##'|l)*$f)
($b=@('++'|l)*$m)
@('+X'|l)*$h
$b
$a

```

Try it online!

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


title: Seidel Triangle

text:
# Question
Title: Seidel Triangle
The Seidel Triangle is a mathematical construction similar to Pascal's Triangle, and is known for it's connection to the Bernoulli numbers.

The first few rows are:

```
      1
      1  1
   2  2  1
   2  4  5  5
16 16 14 10 5
16 32 46 56 61 61

```

Each row is generated as follows:

If the row number is even (1-indexed):

* Bring down the first item of the previous row
* Every next item is the sum of the previous item and the item above it
* Duplicate the last item

If the row number is odd:

* Bring down the last item of the previous row
* Going *backwards*, each item is the sum of the previous item and the item above it
* Duplicate what is now the first item.

Basically, we construct the triangle in a zig-zag pattern:

```
    1
    v
    1 > 1
        v
2 < 2 < 1
v
2 > 4 > 5 > 5

```

For more information, see the Wikipedia page on Bernoulli numbers.

### The Challenge:

Given `n`, either as a function argument or from STDIN, print or return either the `n`th row of the Seidel triangle or the first `n` rows. You may use either 0 or 1 indexing.

You do not need to handle negative or non-integer input (nor 0, if 1-indexed). You do not have to handle outputs larger than `2147483647 = 2^31 - 1`

As this is code-golf, do this in as few bytes as possible.

### Examples:

In these examples the return value is the `n`th row, 0-indexed.

```
Input   ->  Output

0           1
1           1 1
2           2 2 1
6           272 272 256 224 178 122 61
13          22368256 44736512 66750976 88057856 108311296 127181312 144361456 159575936 172585936 183194912 191252686 196658216 199360981 199360981

```

# Answer
# Brain-Flak, 66 bytes

```
<>(())<>{({}[()]<(()[{}]<<>{(({}<>{}))<>}>)>)}{}{{}<>{({}<>)<>}}<>

```

Try it online!

Row is 0-indexed.

```
# Push 1 (the contents of row 0) on other stack; use implicit zero as parity of current row
<>(())<>

# Do a number of times equal to input:
{({}[()]<

  # Subtract the row parity from 1
  (()[{}]<

    # For each entry in old row:
    <>{

      # Add to previous entry in new row and push twice
      (({}<>{}))<>

    }

  >)

>)}{}

# If row parity is odd:
{{}

  # Reverse stack for output
  <>{({}<>)<>}

# Switch stacks for output
}<>

```
> 7 votes

# Answer
# JavaScript (SpiderMonkey), 67 bytes

This code abuses the `sort()` method and doesn't work on all engines.

Rows are 0-indexed.

```
f=(n,a=[1],r)=>n--?f(n,[...a.map(n=>k+=n,k=0),k].sort(_=>n|r),!r):a

```

Try it online!

### How?

We conditionally reverse an array by using the `sort()` method with a callback function that ignores its parameters and returns either **0** or a positive integer. *Don't try this at home!* This only works reliably on SpiderMonkey.

```
let A = [1,2,3,4,5] and B = [1,2,3,4,5,6,7,8,9,10,11]

             | SpiderMonkey (Firefox)  | V8 (Chrome)             | Chakra (Edge)
-------------+-------------------------+-------------------------+------------------------
A.sort(_=>0) | 1,2,3,4,5               | 1,2,3,4,5               | 1,2,3,4,5
A.sort(_=>1) | 5,4,3,2,1               | 5,4,3,2,1               | 1,2,3,4,5
B.sort(_=>0) | 1,2,3,4,5,6,7,8,9,10,11 | 6,1,3,4,5,2,7,8,9,10,11 | 1,2,3,4,5,6,7,8,9,10,11
B.sort(_=>1) | 11,10,9,8,7,6,5,4,3,2,1 | 6,11,1,10,9,8,7,2,5,4,3 | 1,2,3,4,5,6,7,8,9,10,11

```

Note that V8 is probably using different sort algorithms depending on the length of the array (less or more than 10 elements).

### Commented

```
f = (                     // f = recursive function taking:
  n,                      //   n   = row counter
  a = [1],                //   a[] = current row, initialized to [1]
  r                       //   r   = 'reverse' flag, initially undefined
) =>                      //
  n-- ?                   // decrement n; if it was not equal to zero:
    f(                    //   do a recursive call with:
      n,                  //     - the updated value of n
      [ ...a.map(n =>     //     - a new array:
          k += n, k = 0   //       - made of the cumulative sum of a[]
        ), k              //         with the last value appended twice
      ].sort(_ => n | r), //       - reversed if n is not equal to 0 or r is set
      !r                  //     - the updated flag r
    )                     //   end of recursive call
  :                       // else:
    a                     //   stop recursion and return a[]

```
> 5 votes

# Answer
# Perl 6, 52 bytes

```
{(1,{[[\+] |.reverse,0]}...*)[$_].sort((-1)**$_*-*)}

```

Try it online!
> 4 votes

# Answer
# Haskell, ~~89~~ ~~87~~ 82 bytes

```
(cycle[r,id]!!)<*>s
r=reverse
s 0=[1]
s n=let a=zipWith(+)(0:a)$(r.s$n-1)++[0]in a

```

Just `s` prints the lines in the zig-zag order, the anonymous function on the first row reverses half of the rows.

Thanks to @nimi for saving 5 bytes!

Try it online!
> 3 votes

# Answer
# Jelly, 12 bytes

```
1;0SƤUƊ⁸¡U⁸¡

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~98~~ 91 bytes

```
from itertools import*
f=lambda n:n and[*accumulate(f(n-1)[::n&1or-1]+[0])][::n&1or-1]or[1]

```

Try it online!

Switching to 0-based row numbering saved 7 bytes.
> 3 votes

# Answer
# Python 2, ~~103~~ 97 bytes

```
f=lambda n,r=[1],k=2:n and f(n-1,[sum(r[-2::-1][:i],r[-1])for i in range(k)],k+1)or r[::-(-1)**k]

```

Try it online!

Non-recursive version (easier to read):

# Python 2, 106 bytes

```
def f(n,r=[1],j=1):
 while n:
	a=r[-2::-1];r=r[-1:];n-=1;j=-j
	for x in a+[0]:r+=[r[-1]+x]
 return r[::-j]

```

Try it online!

Surely, better is possible!
> 2 votes

# Answer
# Python 3, 91 bytes

```
from numpy import *
s=lambda n:n and cumsum(s(n-1)[::n%2*2-1]+[0]).tolist()[::n%2*2-1]or[1]

```

Try it online!
> 2 votes

# Answer
# Julia 0.6, 85 bytes

```
r(l,n=cumsum(l))=[n...,n[end]]
w=reverse
f(n)=n<2?[1]:n%2<1?r(f(n-1)):w(r(w(f(n-1))))

```

Try it online!

This is a recursive solution in Julia. Note that it has 1-based indexing. Hence the tests.

Ungolfed version, to understand the logic:

```
function new_row(last_row)
    new_row = cumsum(last_row)
    push!(new_row, new_row[end])
    return new_row
end

function triangle(n)
    if n == 1
        return [1]
    elseif mod(n,2) == 0
        return new_row(triangle(n-1))
    else
        return reverse(new_row(reverse(triangle(n-1))))
    end
end

```

Asa bonus, here's a non-recursive version, but this is longer:

```
w=reverse;c=cumsum
r(l,i)=i%2<1?c([l...,0]):w(c(w([0,l...])))
f(n,l=[1])=(for i=2:n l=r(l,i)end;l)

```
> 2 votes

# Answer
# Husk, 16 bytes

```
!z*:1İ_¡ȯ↔S:→∫;1

```

Try it online!

There may be a better way for arriving at the rows in the correct order. To get the correct output, this program reverses every other row.

## Explanation

```
!z*:1İ_¡ȯ↔S:→∫;1
              ;1 array [1]
       ¡ȯ        apply the following functions repeatedly on it, collecting results:
             ∫   cumulative sum
          S:→    repeat the last element
         ↔       reverse it
                 this generates all the required rows
 z*              zip multiply that with:
   :1İ_          [1,-1,1,-1,1,-1,...]
                 which reverses every other row
!                Get row at input index

```

# Husk, 16 bytes

```
?I↔%2¹!¡ȯ↔S:→∫;1

```

Try it online!

Uses a ternary instead.
> 1 votes

# Answer
# APL (Dyalog Unicode), <sup>~~22~~</sup> 18 bytes

```
{⊖⍣⍵{⌽+\⍵,0}⍣⍵,1}

```

Try it online!

Same method as my Husk answer.

-4 bytes from coltim.

## Explanation

```
{⊖⍣⍵{⌽(⊢,⊢/)+\⍵}⍣⍵,1} ⍵ ← input(n)
                  ,1  convert 1 to an array [1]
    {          }⍣⍵    apply the following n times:
            +\⍵       cumulative sum
      (⊢,⊢/)          duplicate the last element
     ⌽                reverse
 ⊖⍣⍵                  then reverse n times

```
> 1 votes

# Answer
# Haskell, 59 bytes

```
(k!!)<*>(iterate(r.scanr1(+).(0:))[1]!!)
r=reverse
k=r:id:k

```

Try it online!
> 1 votes

# Answer
# k4, 17 bytes

```
{x|:/x{|+\x,0}/1}

```

Adapted from @razetime's APL answer.
> 1 votes

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


# Question
Title: Ten-pin bowling score - World Bowling edition
**World Bowling scoring**

Many people have gone to their local bowling center to play a few games of bowling, and many people continue to struggle to calculate their scores. World Bowling has introduced a simplified scoring system in order to attract more people to the sport. This scoring system is utilized in international games.

The scoring system works like this (from Wikipedia):

> The World Bowling scoring system—described as "current frame scoring"\[32\]—awards pins as follows:
>
> * strike: 30 (regardless of ensuing rolls' results)
> * spare: 10 plus pinfall on first roll of the current frame
> * open: total pinfall for current frame

If you're not familiar with ten-pin bowling, here's a recap.

There are 10 pins at the end of a bowling lane where the goal is to knock all of them down with a bowling ball. You get 2 rolls of a ball to attempt to knock them all down, preferably knocking them all down with the first roll (known as a **strike**). If you do get a strike, then that frame is completed and you do not need to roll the ball a second time. A strike is worth 30.

If you don't knock down all ten, you get one more roll. If you knock down all of the remaining pins, that is known as a **spare**. The score is worth 10 pins + the number of pins knocked down on the first roll. For example, if I knocked down 7 pins, then managed to knock down the remaining 3, that would be worth 17.

If after your second roll you fail to knock down all ten, that is known as an **open frame**. The score is worth the total number of pins knocked down for that frame.

There are **10 frames in a game**. If you're familiar with traditional bowling scoring, you don't get an extra roll in the 10th frame with the World Bowling Scoring. In traditional bowling scoring, it takes 12 consecutive strikes to get a perfect score of 300, whereas World Bowling scoring only requires 10 consecutive strikes.

## Challenge

Your challenge is to calculate the score given values from a score sheet.

On a score sheet, a **miss** is indicated by a dash (**-**), a **strike** with an **X**, and a **spare** with a slash (**/**). If these don't apply, then the pinfall count is simply indicated with a number (1-9). Fouls and splits are also recorded onto score sheets but you do not need to worry about these.

## Input

You will be given a string consisting of scores for each frame, and will have a total of ten frames. Each frame will have up to two values, or as little as 1 value if there was a strike. Your input may be string parameter to a function, read from a file, or from STDIN.

For example, if I knocked down 1 pin on my first roll, then knocked down 2, the frame would look like "12". This does not mean 12 (twelve), but means 1 and 2, for a total of 3.

If I missed every pin with both rolls (gutter balls), it would look like this "--" (score of 0).

Each frame will be separated by a space.

## Sample input

```
-- 9- -9 X -/ 8/ 71 15 44 X

```

To break down this example,

* Frame 1 (--) - both rolls missed. scored 0
* Frame 2 (9-) - knocked down 9 on the first roll, missed on the second roll. Score 9
* Frame 3 (-9) - Missed all on the first, got 9 on the second. Score 9
* Frame 4 (X) - Strike, knocked down all ten. Score 30
* Frame 5 (-/) - Spare, missed all on the first, knocked down all with 2nd roll. Score 10 + 0 = 10
* Frame 6 (8/) - Spare, 8 pins on first roll, knocked down the other 2 with 2nd roll. Score 10+8 = 18
* Frame 7 (71) - open frame,7 pins on first roll, 1 pin on second roll. Score 7+1=8
* Frames 8,9,10 follow same examples as above.

## Output

Output will simply be a value that has the sum of the scores from all 10 frames. Using the sample input, the output will be 128. Your output may be a string or a numeric type. It may be a function return value, or written to STDOUT.

## Rules

* Assume that the input will always be valid. For example, an invalid frame would be "/8", "XX", "123", "0", etc.
* You do not need to worry about splits or fouls.
* Your code may be a full program or a function that takes in a string and returns the score.
* Your code must not throw any exceptions.
* This is code golf, the answer with the **fewest number of bytes wins.**
* Languages that use includes or imports must include the import statements as part of their code and count towards the byte count.

## Test Cases

```
"-- 9- -9 X -/ 8/ 71 15 44 X" -> 128
"-- -1 2- 12 22 5- 42 61 8- 72" -> 45
"X X X 1/ 2/ 3/ 4/ 5/ -- 9/" -> 174
"X X X X X X X X X X" -> 300
"-- -- -- -- -- -- -- -- -- --" -> 0

```

# Answer
> 7 votes
# 05AB1E, ~~12~~ 11 bytes

### Code

```
S'/T:'X30:O

```

Try it online!

### Explanation

```
S             # Split the string into a list of characters
 '/T:         # Replace '/' with 10
     'X30:    # Replace 'X' with 30
          O   # Sum up the array (ignoring non-number elements)

```

# Answer
> 7 votes
# JavaScript, 43 bytes

```
f=([c,...s])=>c?({'/':10,X:30}[c]|c)+f(s):0

```

```
f=([c,...s])=>c?({'/':10,X:30}[c]|c)+f(s):0
```

```
Score(<input style="width:200px" oninput="o.value=f(this.value)" />) = <output id=o></output>
```

## How it works

We convert each character to its point:

* 'X' worth 30 point
* '/' worth 10 point
* '1' .. '9' worth 1 .. 9 point
* other characters worth 0 point

Then sum all points.

**Convert**

Bitwise *OR* operator `|` convert its operand to Int32 before operate. When converting to Int32, value first convert to Number (64bit float number) format, then trunk to Int32 (or converted to 0 if invalid).

* `ToInt32({'/':10,X:30}[c])` could be read as:
    + if c == '/': result is 10;
    + if c == 'X': result is 30;
    + otherwise: result is `ToInt32(undefined)` -\> `ToInt32(NaN)` -\> 0;
* `ToInt32(c)` could be:
    + if c == '1' ... '9': result is 1 .. 9;
    + if c == ' ': `Number(c)` is 0, result is 0;
    + otherwise: `Number(c)` is `NaN`, result is 0;
* Bitwise or here is same as "add", since one of its operand will be 0

**Sum**

* `[c,...s] = s` let `c = s[0]`, and `s = s.slice(1)`;
    + if s is empty string, c is *undefined*;
    + otherwise, c is first letter of s
* undefined is falsy, non-empty string (including space) is truthy

# Answer
> 5 votes
# Stax, 13 bytes

```
─*âⁿ┴8òt↨HÉ÷8

```

Run and debug it

Unpacked, ungolfed, and commented it's thus.

```
F               for each character in input, execute...
 9R$'/20*+'X+   build the string "123456789////////////////////X"
 I              get the index of the current character in string
 ^+             increment and add to running total
                (index is -1 when no match; space and dash are 0 score)

```

Run this one

# Answer
> 4 votes
# Python 2, 55 bytes

```
lambda l:sum(map(('123456789/'+'X'*20).rfind,l))+len(l)

```

Try it online!

Based off the string-index approach of many solutions.

# Answer
> 3 votes
# Java 8, ~~64~~ ~~59~~ 46 bytes

```
s->s.map(c->c<46?0:c<48?10:c>87?30:c-48).sum()

```

-5 bytes thanks to *@Neil*.
-13 bytes thanks to *@OlivierGrégoire*.

**Explanation:**

Try it online.

```
s->               // Method with an IntStream parameter and integer return-type
  s.map(c->       //  Loop over the characters
          c<46?   //   If the character is a space or '-':
           0      //    Count it as 0
          :c<48?  //   Else-if it's a '/':
           10     //    Count it as 10
          :c>87?  //   Else-if it's an 'X':
           30     //    Count it as 30
          :       //   Else (it's a digit):
           c-48   //    Count it as the value of the digit
       ).sum()    //   And sum everything

```

# Answer
> 3 votes
# F#, 106 103 bytes

```
let s c=Seq.sumBy(fun x->if x=' '||x='-'then 0 elif x='X'then 30 elif x='/'then 10 else int(string x))c

```

Try it online!

I think that this puzzle (without the golfing) would be a great question for a "Functional programming for beginners" guide. And I should know!

-3 from Kevin Cruijssen, for spotting that the whitespace between ' and "then" can be deleted. Thanks!

recursive's Stax solution of using string indexes is very very good. If you port it to F# you can get it for **77 bytes**:

```
let s c=Seq.sumBy(fun x->"123456789/???????????????????X".IndexOf(char x)+1)c

```

Try this online!

# Answer
> 2 votes
# Jelly, 17 bytes

```
ḟ⁾ -“X0/⁵”yV€o30S

```

A monadic link accepting a list of characters and returning an integer

**Try it online!**

### How?

```
ḟ⁾ -“X0/⁵”yV€o30S - Link: list of characters
 ⁾ -              - literal list of characters [' ','-']
ḟ                 - filter discard
    “X0/⁵”        - literal list of characters ['X','0','/','⁵']
          y       - translate (change 'X's to '0's and '/'s to '⁵'s)
           V€     - evaluate €ach character as Jelly code (the '⁵'s become 10s)
             o30  - logical OR with 30 (change all instances of 0 to 30)
                S - sum

```

---

Also at 17:

```
”/ẋ20ØD;;”XḊiÐ€⁸S

```

Try that

# Answer
> 2 votes
# Perl 5 `-pF`, ~~30~~ 27 bytes

-3 bytes thanks to Xcali

```
#!/usr/bin/perl -pF
$\+=m%/%+3*/X/.0+$_ for@F}{

```

Try it online!

# Answer
> 2 votes
# Perl 6, 30 bytes

```
{TR'-/X '0㉈㉊'.univals.sum}

```

Try it online!

# Answer
> 2 votes
# Retina, 17 bytes

```
X
///
/
55
\d
*
_

```

Try it online!

I'm not quite up to date on the latest Retina changes. I'll be looking more into them when I get a chance and seeing if there's any new tricks for golfing this down. The code turns all strikes in to three spares, all spares into ten points, then all points to the corresponding number of underscores. Then it counts the number of underscores.

# Answer
> 1 votes
# PHP, ~~119~~ 109 bytes

-10 bytes thanks to *@KevinCruijssen*

```
<?foreach(explode(" ",$argv[1])as$f){[$a,$b]=str_split($f);$n+=$f==X?30:(int)$a+($b=='/'?10:(int)$b);}echo$n;

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
þ`I…/aXS¢ƶT*`O

```

Try it online!

**Explanation**

```
þ`              # Push the digits of the input on the stack (removes everyting that isn't a digit)
  I…/aXS        # Push the input and the array "/","a","X" on the stack
        ¢       # Index of each element in the input ...
         ƶT*    # ... multiplied by its index (a could be anything that can't be found in the input), multiplied by 10.
            `O  # Sum the stack, implicit display

```

# Answer
> 1 votes
# Python 2, 67 bytes

-3 bytes thanks to @KevinCruijssen

```
lambda I,p='-123456789/'+20*'X':sum(p.rfind(i)for i in I if i in p)

```

Try it online!

# Answer
> 1 votes
# , 33 bytes

```
1#.31|('-123456789',20 1#'/X')i.]

```

Try it online!

## Explanation:

`]` the input

`('-123456789',20 1#'/X')` appends 20 `/` and one `X` to the string `-123456789`

`i.` finds the indices of the input in the above string

`31|` modulo 31 - to get rid of the spaces - they are not found in the string, so `i.` returns 31 for them

`1#.` finds the sum of the indices

# Answer
> 1 votes
# Jelly, 12 bytes

```
⁾/X,“½œ‘y|0S

```

Try it online!

## How it works

```
⁾/X,“½œ‘y|0S  Main link. Argument: s (string)

⁾/X,“½œ‘      Literal; yield [['/', 'X'], [10, 30]].
        y     Transliterate; replace '/' with 10, 'X' with 30.
         |0   Bitwise OR with 0. Bitwise operators attempt to cast to int, mapping
              '0', ..., '9' to 0, ..., 9. All other characters map to 0.
           S  Take the sum.

```

# Answer
> 1 votes
# Python 3.6, 54 bytes

```
lambda s:sum(map(f'123456789/{6**24}X'.find,s),len(s))

```

Try it online!

# Answer
> 1 votes
# Kotlin, 50 bytes

```
x->x.sumBy{"123456789/_${Math.E}_X".indexOf(it)+1}

```

Try it online!

Hopefully it's not against the rules to answer your own question but I wanted to join in on the fun.

`Math.E` produces the value `2.718281828459045`. I'm using it to create some filler string to push X to position 30.

`indexOf` gets the position (0-based) of the character in the string "12345...". If it isn't found, it returns -1. We add 1 to make these 0, and that also makes the 0-based position the value of the string.

# Answer
> 0 votes
# Charcoal, 23 bytes

```
ＩΣＥχΣＥＳ⎇№-/Xλ×χ⌕-//XλＩλ

```

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

```
  Ｅχ                    Map over 10 frames
      Ｓ                 Input the frame
     Ｅ                  Map over the characters
            λ           Current character
        №-/X            Search the literal string `-/X`
                    λ   Current character
               ⌕-//X    Find position in literal string `-//X`
             ×χ         Multiply by predefined variable 10
                      λ Current character
                     Ｉ  Cast to integer
       ⎇                Ternary
    Σ                   Sum for each frame
 Σ                      Sum over frames
Ｉ                       Cast to string for implicit print

```

# Answer
> 0 votes
# Red, 93 bytes

```
func[b][s: 0
foreach c trim/all b[s: s - 1 + index? find{-123456789/...................X}c]s]

```

Try it online!

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), ~~169~~ ~~151~~ 147 bytes

```
	F =INPUT ' '
R	F '-' =0	:S(R)
T	F 'X' ='_'	:S(T)
S	F LEN(1) . X ARB . Y ' ' REM . F	:F(O)
	X '_' =30
	Y '/' =10
	S =S + X + Y	:(S)
O	OUTPUT =S
END

```

Try it online!

```
	F =INPUT ' '					;* read input and append a space
R	F '-' =0	:S(R)				;* replace - with 0
T	F 'X' ='_'	:S(T)				;* replace X with _
S	F LEN(1) . X ARB . Y ' ' REM . F	:F(O)	;* set first character to x, remainder up to ' ' to y, and remainder to F
	X '_' =20					;* replace _ in x with 20
	Y '/' =10					;* replace / in y with 10
	S =S + X + Y	:(S)				;* else X and Y are their values so we can sum them
O	OUTPUT =S					;* output the sum
END

```

# Answer
> 0 votes
# C# (.NET Core), 40 + 18 = 58 bytes

```
using System.Linq;
s=>s.Sum(c=>c>87?30:c<46?0:c<48?10:c-48)

```

Try it online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 53 bytes

```
Write(ReadLine().Sum(c=>c>87?30:c<46?0:c<48?10:c-48))

```

Try it online!

# Answer
> 0 votes
# Clojure, 70 bytes

```
#(reduce(fn[s i](+ s(case i\- 0\/ 10\X 30\space 0(bigint(str i)))))0%)

```

Try it online!

When `reduce`ing over a String, each char is actually converted into a char - who would have thought. But this meany, I have to write `\space` and that hurts more than one can imagine. Also, when creating an actual number from a char, the combination of `bigint` and `str` seems to be the only usable combination.

Well, aside from all these struggles: Anonymous function that returns the score as a natural.

# Answer
> 0 votes
# Ruby, 38 bytes

```
->s{s.tr("/X -",":N00").sum-s.size*48}

```

Try it online!

# Answer
> 0 votes
# Husk, 17 bytes

```
+ṁi¹*10+#'/¹*3#'X

```

Try it online! This function takes the sum of all digit characters in the string, plus 10 times the number of `/` characters, plus 30 times the number of `X` characters.

---
Tags: code-golf, string, number, arithmetic, parsing
---


# Question
Title: Get delta of days by current hour and added delta of days
**Inputs:**

* `current hour`: from 0 to 23 (inclusive)
* `delta of hours`: `[current hour]` \+ `[delta of hours]` = withing the range of `Integer`

**Output:**

* `delta of days`: the value which shows difference in days between day of `current hour` and day of sum `[current hour]` \+ `[delta of hours]`

**Scoring**

* Answers will be scored in bytes with fewer bytes being better.

**Examples:**

* `[current hour]` = 23; `[delta of hours]` = -23; `delta of days` = 0
* `[current hour]` = 23; `[delta of hours]` = 1; `delta of days` = 1
* `[current hour]` = 23; `[delta of hours]` = 24; `delta of days` = 1
* `[current hour]` = 23; `[delta of hours]` = 25; `delta of days` = 2
* `[current hour]` = 23; `[delta of hours]` = -24; `delta of days` = -1
* `[current hour]` = 23; `[delta of hours]` = -47; `delta of days` = -1

# Answer
> 7 votes
# JavaScript (ES6),  ~~26~~  25 bytes

Takes input as `(current)(delta)`.

```
a=>b=>(a+b-(a<-b)*2)/3>>3

```

Try it online!

### Commented

```
a =>                // a = current hour
b =>                // b = delta of hours
  (                 //
    a + b           // 1) we compute the sum
    - (a < -b) * 2  //    and we subtract 2 if this sum is negative
                    //    examples:
                    //      51 remains 51
                    //      23 remains 23
                    //      -1 is turned into -3
  ) / 3             // 2) float division by 3
                    //    examples:
                    //      51 is turned into 17
                    //      23 is turned into 7.666…
                    //      -3 is turned back into -1
  >> 3              // 3) right arithmetic shift by 3 on the integer part
                    //    examples:
                    //      17 becomes 2
                    //      7.666… becomes 0
                    //      -1 is unchanged

```

---

# JavaScript (ES6), 26 bytes

More straightforward, but less fun and 1 byte longer anyway.

Takes input as `(current)(delta)`.

```
a=>b=>Math.floor((a+b)/24)

```

Try it online!

# Answer
> 6 votes
# Jelly, 4 bytes

```
+:24

```

Try it online!

`+` add the arguments

`:24` integer divide by 24

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

```
+24÷

```

Try it online or verify all test cases.

# 05AB1E, ~~11~~ 5 bytes

```
+24/ï

```

-6 bytes by porting *@Adam*'s approach in his APL answer.

Try it online or verify all test cases.

**Explanation:**

```
+      # Sum the two (implicit) input-integers together
 24÷   # Integer-divide this sum by 24
       # (after which the result is output implicitly)

+      # Sum the two (implicit) input-integers together
 24/   # Divide this sum by 24
    ï  # Floor
       # (after which the result is output implicitly)

```

The legacy version of 05AB1E uses a Python compiler. When integer-dividing, it will always floor the integer, whether the integer it divides is positive or negative.

The new version of 05AB1E uses an Elixir compiler. When integer-dividing in the new version of 05AB1E, it will round towards 0 (so basically truncates the decimal digits after dividing). So this will floor for positive integers, but ceil for negative integers.

# Answer
> 4 votes
# APL (Dyalog Unicode), 6 bytesSBCS

Anonymous tacit infix function, taking current and delta as arguments.

```
⌊24÷⍨+

```

Try it online!

`+` add the arguments

`24÷⍨` divide that by 24

floor

# Answer
> 4 votes
# Python 3, ~~20~~ 19 bytes

*Simple lambda:*

```
lambda*a:sum(a)//24

```

*-1 byte thanx to Jonathan Allan*

Try it online!

*Full program for **38 bytes**:*

```
print((int(input())+int(input()))//24)

```

# Answer
> 3 votes
# Haskell, ~~18~~ 16 bytes

```
((`div`24).).(+)

```

Try it online!

If taking input as a list is allowed, this can be done in **13 bytes** (thanks cole):

```
(`div`24).sum

```

Try it online!

---

I've seen people leave off the function declaration in the byte count for pointfree style, so I'm doing the same here.

**Explanation:**

```
(`div`24)

```

`div` is the shorter integer division operator. Haskell has this nice syntactic sugar where you can curry infixes by putting the argument on its respective side of the infix (thanks mimi), so this is a function that does integer division by 24.

The double composition is a little weird to explain, so I'll follow the template of this great SO answer:

```
f a b = (`div`24) (a + b)       -- what we want
f a b = (`div`24) ((+) a b)     -- un-infixing (+)
f a b = ((`div`24) . ((+) a)) b -- definition of function composition (partially applying (+) onto a)
f a = ((`div`24) . ((+) a)       -- pointfree reduction
f a = ((`div`24) .) ((+) a)     -- associative property
f a = (((`div`24) .) . (+)) a   -- definition of function composition
f = ((`div`24).) . (+)            -- pointfree reduction

```

When this takes a list as input, the sum function only has one argument, so the extra composition isn't needed (since we don't have to do that extra curry).

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

Just a port of most of the other answers...
-12 bytes thanks Giuseppe

```
sum(scan())%/%24

```

Try it online!

# Answer
> 2 votes
# Ohm v2, 4 bytes

```
+24v

```

Try it online!

# Answer
> 1 votes
# Lua, ~~70~~ 50 bytes

```
c,d=io.read():match("(%S+) (%S+)")print((c+d)//24)

```

*-20 bytes thanks to val*

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 26 bytes

```
a=>b=>Math.Floor((a+b)/24)

```

Try it online!

# Answer
> 1 votes
# Lua, ~~32~~ 26 bytes

```
print((arg[1]+arg[2])//24)

```

Try it online!

Rather boring solution. Take input as arguments, print to stdout. Require Lua 5.3 or greater.

# Old solution: Lua, 32 bytes

```
function(a,b)return(a+b)//24 end

```

Try it online!

Same idea, but implemented as function instead of full program.

# Answer
> 1 votes
# Perl 6, 11 bytes

```
(*+*)div 24

```

Try it online!

Anonymous Whatever lambda that takes two arguments and returns the sum of the two integer divided by 24

# Answer
> 1 votes
# Husk, 4 bytes

```
÷24+

```

Try it online! Nothing very original here.

# Answer
> 0 votes
# , 6 bytes

Anonymous tacit infix function, taking current and delta as arguments.

```
+/24.m

```

Try it online!

Beginning with:

`+` the sum of the arguments

`/` divide by:

`24` twentyfour

`.` apply:

`m` floor (**m**inimum)

# Answer
> 0 votes
# Retina 0.8.2, 41 bytes

```
\d+,?
$*
(1+)-\1
-
^((-)1|1{24})*.*
$2$#1

```

Try it online! Link includes test suite. Explanation:

```
\d+,?
$*

```

Convert both inputs to unary and take the sum if the second input is positive.

```
(1+)-\1
-

```

But if the second input is negative then take the difference.

```
^((-)1|1{24})*.*
$2$#1

```

Floor divide the input by 24 and convert to decimal. For positive numbers the first alternation never matches so this just counts the number of whole multiples of 24 in the number. For negative numbers the leading `-1` counts as an extra negative multiple of 24 in addition to any remaining multiples of 24, thus achieving the desired floor division.

# Answer
> 0 votes
# Python 2, 18 bytes

```
lambda*a:sum(a)/24

```

Try it online!

# Answer
> 0 votes
# Perl 5 (`-MPOSIX=floor -MList::Util=sum -alp`), 19 bytes

```
$_=floor+(sum@F)/24

```

TIO

# Answer
> 0 votes
# Whitespace, 49 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][T  S S S _Add][S S S T T   S S S N
_Push_24][T S T S _integer_division][T  N
S T _Print_as_integer]

```

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

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

**Explanation in pseudo-code:**

```
Integer a = STDIN as integer
Integer b = STDIN as integer
a = a + b
a = a integer-divided by 24
Print a as integer to STDOUT

```

# Answer
> 0 votes
# Forth (gforth), 12 bytes

```
: f + 24 / ;

```

Try it online!

### Code Explanation

```
: f           \ start a new word definition
  +           \ add current hour and delta
  24 /        \ (integer) divide result by 24, round towards negative infinity
;             \ end word definition

```

# Answer
> 0 votes
# PHP, 29 bytes

```
<?=floor((date(G)+$argn)/24);

```

Try it online!

Full program, with `current hour` being the current hour on the platform host, and `delta of hours` input via `STDIN`.

**Or**

# PHP, 30 bytes

```
<?=floor(array_sum($argv)/24);

```

Try it online!

Input of `current hour` and `delta of hours` via command line.

---
Tags: code-golf, date
---


title: Permutation Encoding

text:
# Question
Title: Permutation Encoding
Write a program which can encode text to avoid reusing characters, and convert back.

Both normal and encoded forms are restricted to a particular character set: the space character  with code point 32, the tilde character `~` with code point 126, and all characters between. This is 95 total characters. It's a printable subset of ASCII.

The encoded text can be up to 95 characters long. The normal text can be up to 75 characters long, because above 75 it would be impossible to uniquely encode all messages.

## Encoding

There are some requirements for the encoding:

* Uses only characters from the character set described above
* Uses each character at most once
* Uniquely encodes all valid messages

Other than that, you're free to pick any variant.

## Input

Input will consist of 2 items:

* A boolean: false to encode, true to decode
* A string: the message to be encoded/decoded

How you receive the input is up to you.

The boolean can be as a boolean or integer in the range \[-2, 2\] in your language's format. If the esoteric language doesn't have booleans or integers, use the closest analogue. I'm not doing the "or any 2 distinct values" because then you could use an encoding and decoding program as the values and evaluate them.

## Output

Output should consist of only the encoded/decoded string. Leading and trailing newlines are okay.

## Scoring

Your score is the length of your program, shorter is better.

I still encourage you to try harder languages even if they won't win.

## Testing

Testing will generally be done with Try it Online!. For convenience, please provide a link to your program with some test input already filled in.

These are the steps to test a program:

* Pick a valid normal string.
* Encode it using the program.
* Check that the encoded form is valid.
* Decode it using the program.
* Check that the final result matches the original string.

This can be repeated with other test strings for confidence.

If you show a working case and no failing cases have been found, we will assume your program works.

# Reference Implementation

I am providing a reference implementation that shows one possible method, in hopes of making this problem more approachable. I used it to generate the examples. I recommend you try the problem yourself before looking at how I did it, that way you may independently come up with a better mapping.

# Examples

Since you can choose a different encoding, as well as different input/output methods, your program might not match these examples.

## Empty

> Input:
>
> ```
> 0
>
>
> ```
>
> Output:
>
> (none)
>
> Input:
>
> ```
> 1
>
>
> ```
>
> Output:
>
> (none)

## Small

> Input:
>
> ```
> 0
> Hello, world!
>
> ```
>
> Output:
>
> ```
>  #mvcD_YnEeX5?
>
> ```
>
> Input:
>
> ```
> 1
>  #mvcD_YnEeX5?
>
> ```
>
> Output:
>
> ```
> Hello, world!
>
> ```

## Max Size

> Input:
>
> ```
> 0
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> ```
>
> Output:
>
> ```
> C-,y=6Js?3TOISp+975zk}.cwV|{iDjKmd[:/]$Q1~G8vAneoh #&<LYMPNZB_x;2l*r^(4E'tbU@q>a!\WHuRFg0"f%X`)
>
> ```
>
> Input:
>
> ```
> 1
> C-,y=6Js?3TOISp+975zk}.cwV|{iDjKmd[:/]$Q1~G8vAneoh #&<LYMPNZB_x;2l*r^(4E'tbU@q>a!\WHuRFg0"f%X`)
>
> ```
>
> Output:
>
> ```
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> ```

# Extras

How did I get the 75 characters limit? I could have brute force checked it of course, but there's a slightly more mathematical method for counting the number of possible encoded messages for a given character set:

$$ F(n)=\sum\_{k=0}^{n}{\frac{n!}{(n-k)!}}=e\Gamma(n+1,1)\approx en! $$

Here are the relevant bounds. There's plenty more valid encoded messages than normal messages, but still enough normal messages that you'll need a variable length encoding.

$$ F(95)\approx 2.81\times 10^{148} \\ {95}^{75}\approx 2.13\times 10^{148} \\ 95!\approx 1.03\times 10^{148} $$

The problem was inspired by a phenomenon on the Discord chat platform. In Discord, you can "react" to chat messages, which adds a little emoji underneath. You can react many times on a single chat message. Each emoji can only be added once. They remember the order they were added and display oldest to newest, left to right. You can add some non-emojis too. People sometimes write short messages in reactions, and when their message has repeat characters they're forced to get creative, usually they opt for lookalike characters.

# Answer
> 3 votes
# Python 3, ~~339~~ 338 bytes

```
lambda b,s:b and G(f(s))or F(g(s))
a=''.join(chr(32+i)for i in range(95))
f=lambda s:95*f(s[1:])+ord(s[0])-31if s else 0
F=lambda n:chr((n-1)%95+32)+F((n-1)//95)if n else ''
g=lambda s,d=a:1+d.find(s[0])+len(d)*g(s[1:],d.replace(s[0],''))if s else 0
G=lambda n,d=a:d[(n-1)%len(d)]+G((n-1)//len(d),d.replace(d[(n-1)%len(d)],''))if n else''

```

Try it online!

Same length, uses a list instead of a string for the ASCII chars Try it online!.

Overview: WIP

* Because the number of printable ASCII strings with 75 or fewer characters is `21570794844237986466892014672640809417999612393958961235356099871415520891159490775110725336452276983325050565474469409911975201387750975629116626495`, which is less than the number of valid encoded strings (`28079792812953073919740255779032193344167751681188124122118245935431845577725060598682278885127314791932249387894125026034584206856782082066829102875`)

+ All we need to do is theoretically sort the valid encoded strings and the valid non-encoded strings, take the index in the correct list of our given input, then return the string at that index in the *other* list.
* `f`: Converts an input (non-encoded) string to an integer based on its index in the theoretical list of ASCII strings sorted by length and then lexicographically.

+ The empty string is 0
    + Single-char strings are 1 to 95
    + Two-char strings are 96 to 9120, etc.
* `F`: Undoes `f`, converts an integer to a (non-encoded) string.
* `g`: Converts an input (encoded) string to an integer (\<= `28079792812953073919740255779032193344167751681188124122118245935431845577725060598682278885127314791932249387894125026034584206856782082066829102875` for valid inputs) based on its index in the theoretical list of valid encoded strings sorted by length and then lexicographically.

+ The empty string is 0
    + Single-char strings are 1 to 95
    + Two-char strings are 96 to 9025, etc.
* `G`: undoes `g`, converts an integer to an (encoded) string.
* Main function: Unnamed `lambda b,s:b and G(f(s))or F(g(s))`: Uses the boolean `b` to determine whether to encode `G(f(s))` or decode `F(g(s))` the string, and does so.

# Answer
> 2 votes
# Charcoal, 94 bytes

```
≔⁰ζ¿Ｎ«≔γδ≔¹εＦＳ«≧⁺×ε⊕⌕γιζ≧×Ｌγε≔Φγ¬⁼κιγ»Ｗζ«§δ⊖ζ≔÷⊖ζ⁹⁵ζ»»«Ｆ⮌Ｓ≔⁺×⁹⁵ζ⊕⌕γιζＷζ«≦⊖ζ§γζ≔Φγ¬⁼κ§γζγ≧÷⊕Ｌγζ

```

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

```
≔⁰ζ

```

Set `z`, which represents the permutation index, to zero, as both sides of the condition need it.

```
¿Ｎ«

```

If the first input (as a number) is non-zero, then we're doing encoding.

```
≔γδ

```

Save a copy of the predefined ASCII character set `g` in `d`, as we need to change it.

```
≔¹ε

```

Assign `1` to `e`. This represents the place value of each encoded character.

```
ＦＳ«

```

Loop over the encoded characters.

```
≧⁺×ε⊕⌕γιζ

```

Update the permutation index.

```
≧×Ｌγε

```

Update `e` with the place value of the next encoded character.

```
≔Φγ¬⁼κιγ»

```

Remove the character from the encoding set.

```
Ｗζ«

```

Repeat while the permutation number is non-zero.

```
§δ⊖ζ

```

Print the next decoded character.

```
≔÷⊖ζ⁹⁵ζ»»

```

Divide the bijective representation by 95. This completes decoding.

```
«Ｆ⮌Ｓ

```

Loop over the plain text in reverse, to avoid having to calculate the powers of 95.

```
≔⁺×⁹⁵ζ⊕⌕γιζ

```

Convert the plain text as bijective base 95 to the permutation index.

```
Ｗζ«

```

Repeat while the permutation index is non-zero.

```
≦⊖ζ

```

Decrement the permutation index.

```
§γζ

```

Print the next encoded character.

```
≔Φγ¬⁼κ§γζγ

```

Remove that character from the encoding set.

```
≧÷⊕Ｌγζ

```

Divide the permutation index by the previous length of the encoding set.

# Answer
> 1 votes
# Haskell, ~~346~~ 472 bytes

After fixing of the bug noticed by Anders Kaseorg the program unfortunately grew larger.

```
(x:y)?f|f x=(0,x)|0<1=(p+1,q)where(p,q)=y?f
a!n=take n a++drop(n+1)a
x#f=fst$f?(x==)
a x y z=y!!(q z-1)+b z s x
b[]_ _=0
b(x:y)f c=u(x#f)+v f*(b y(c f x)c)
c=const
e=divMod
f n|n<2=1|1<2=n*f(n-1)
g y z x=h(x-r)l s y where(l,r)=z?(x<)
h n l f c|l<1=[]|0<1=f!!w m:h d(l-1)(c f m)c where(d,m)=n`e`v f
i=r(k^)
k=95
o=r(\x->f k`div`f(k-x))
q=length
r f=scanl(+)0$map f[1..k]
s=[' '..'~']
u=toInteger
w=fromInteger
v=u.q
x=g(\a->(\b->a!w b))o.a c i
y=g c i.a(\a->(\b->a!(b#a)))o

```

Try it online!

Use `x "Hello World"` to encode and `y "TR_z"` to decode.

## How?

We can enumerate all possible input sequences and all possible encoded sequences, so the encoding is rather simple:

1) determine the number for the input sequence; 2) construct the output sequence corresponding to that number.

(The decoding is done in the reverse order).

## Explanation

This is an original (pre-golf) version for ease of understanding.

```
-- for ord
import Data.Char

-- all possible characters
s = [' ' .. '~']

-- get the first position in a list where the predicate returns True
(x:y) `firstPosWhere` fn
    | fn x = 0
    | 0<1 = 1 + firstPosWhere y fn

-- the same as above but return both the position and the list element
(x:y) `firstPosAndElemWhere` fn
    | fn x = (0, x)
    | 0 < 1 = (p + 1, q) where (p, q) = firstPosAndElemWhere y fn

-- the sets of numbers corresponding to input strings and to encoded strings are divided into ranges
inputRanges = scanl (+) 0 [95 ^ x | x <- [1..95]]
outputRanges = scanl (+) 0 [fac 95 `div` fac (95 - x)  | x <- [1..95]]

-- convert an input string into a number
toN s = inputRanges !! (length s - 1) + toN' s
toN' [] =0
toN' (x:y) = toInteger (ord x - 32) + 95 * toN' y

-- convert a number into an (unencoded) string
fromN n = fromN' (n - r) l where
    (l, r) = inputRanges `firstPosAndElemWhere` (n <)
    fromN' n l
        | l < 1 = []
        | 0 < 1 = s !! fromInteger m : fromN' d (l - 1) where
            (d, m) = n `divMod` 95

-- factorial
fac n|n<2=1|1<2=n*fac(n-1)

-- remove nth element from a list
a `without` n = take n a ++ drop (n + 1) a

-- construct an encoded string corresponding to a number
encode n = encode' (n - r) l s where
    (l, r) = outputRanges `firstPosAndElemWhere` (n <)
    encode' n l f
        | l < 1 = []
        | otherwise = (f !! m') : encode' d (l - 1) (f `without` m') where
            (d, m) = n `divMod` (toInteger $ length f)
            m' = fromInteger m

-- convert an encoded string back into number
decode z = r + decode' z s  where
    r = outputRanges !! (length z - 1)
    decode' [] _ = 0
    decode' (x:y) f = toInteger p + (toInteger $ length f) * (decode' y (f `without` p)) where
        p = f `firstPosWhere` (x ==)

```

# Answer
> 0 votes
# Clean, 182 bytes

```
import StdEnv,Data.List
$b s=hd[v\\(u,v)<-if(b)id flip zip2(iterate?[])[[]:[p\\i<-inits[' '..'~'],t<-tails i,p<-permutations t|p>[]]]|u==s]
?[h:t]|h<'~'=[inc h:t]=[' ': ?t]
?[]=[' ']

```

Try it online!

Enumerates every valid encoding and every valid message, returning one or the other depending on the order of the arguments `zip2` receives. Explained:

```
$ b s                         // function $ of flag `b` and string `s` is
 = hd [                       // the first element in the list of
  v                           // the value `v`
  \\ (u, v) <-                // for every pair of `u` and `v` from
   if(b)                      // if `b` is true
    id                        // do nothing
    flip                      // otherwise, flip the arguments to
   zip2                       // a function which creates pairs applied to
    (iterate a [])            // repeated application of ? to []
    [[]: [                    // prepend [] to
     p                        // the value `p`
     \\ i <- inits [' '..'~'] // for every prefix `i` in the character set
     , t <- tails i           // for every suffix `t` of `i`
     , p <- permutations t    // for every permutation of the characters in `t`
     | p > []                 // where `p` isn't empty
    ]]
   | u == s                   // where the second element `u` equals `s`
  ]
? [h: t]                      // function ? of a list
 | h < '~'                    // if the first element isn't a tilde
  = [inc h: t]                // increment it and return the list
 = [' ': ? t]                 // otherwise change it to a space
? []                          // function ? when the list is empty
 = [' ']                      // return a singleton list with a space

```

***It's really, really slow!*** Faster (in practice) version below (but with similar time complexity):

```
import StdEnv,Data.List,Data.Func,StdStrictLists,StdOverloadedList

increment :: [Char] -> [Char]
increment []
    = [' ']
increment ['~':t]
    = [' ':increment t]
increment [h:t]
    = [inc h:t]

chars =: hyperstrict [' '..'~']

? :: *Bool [Char] -> [Char]
? b s
    = let
        i :: *[[Char]]
        i = inits (chars)
        t :: *[[Char]]
        t = filter (not o isEmpty) (concatMap tails i)
        p :: *[[Char]]
        p = concatMap permutations t
    in (if(b) encode decode) [] [[]:p]
where
    encode :: [Char] *[[Char]] -> [Char]
    encode d l
        | d == s
            = Hd l
        | otherwise
            = encode (increment d) (Tl l)
    decode :: [Char] *[[Char]] -> [Char]
    decode d l
        | Hd l == s
            = d
        | otherwise
            = decode (increment d) (Tl l)

```

Try it online!

# Answer
> 0 votes
# Jelly, 32 28 27 bytes

```
ØṖµœ!95Ż¤,ṗ75Ż¤$Ẏ€³œ?µḢi⁴ịḢ

```

Try it online!

Since this code generates all the permutations and therefore would take very long to finish, TIO link is to a limited version that supports characters `abcdefg`, message length 4 and encoded length 5. I checked that these numbers follow similar constraints as the actual ones. Only the constants are changed, so the true version should also (theoretically) work.

## Explanation

```
ØṖµœ!95Ż¤,ṗ75Ż¤$Ẏ€³œ?µḢi⁴ịḢ   Dyadic link that accepts the boolean flag and message
ØṖ                            ASCII printable characters
  µ                           Feed into new monadic chain
   œ!                         Permutations of size
     95Ż¤                     0..95
         ,     $              Pair with
          ṗ                   Cartesian power
           75Ż¤               0..75
                Ẏ€            Flatten both lists (non-recursively)
                  ³œ?         Reverse the pair if the boolean flag is set
                     µ        Feed into new monadic chain
                      Ḣ       Pop first item of the pair
                       i⁴     Find index of the message
                         ịḢ   Index into the head of what used to be the pair

```

---
Tags: code-golf, permutations, base-conversion, encoding
---


title: Find a Rocco number

text:
# Question
Title: Find a Rocco number
I was asked this question in an interview but I was unable to figure out any solution. I don't know whether the question was right or not. I tried a lot but couldn't reach any solution. Honestly speaking, nothing came to my mind.

## Rocco numbers

A positive integer \\$n\\$ is a Rocco number if it can be represented either as \\$n=p(p+14)\\$ or \\$n=p(p-14)\\$, where \\$p\\$ is a prime number.

The first 10 Rocco numbers are:

$$32, 51, 95, 147, 207, 275, 351, 435, 527, 627$$

## Task

Your code must accept a positive integer as input and determine if it is a Rocco number or not.

## Brownie points

* Write a function that calculates and prints the count of Rocco numbers less than or equal to 1 million.
* Write a function that calculates and prints the count of Rocco numbers from the bonus question (above one) that are prime.

# Answer
> 11 votes
# 05AB1E, 8 bytes

Returns \\$1\\$ if \\$n\\$ is a Rocco number, or \\$0\\$ otherwise.

```
fDŠ/α14å

```

Try it online!

### How?

Given a positive integer \\$n\\$, we test whether there exists a prime factor \\$p\\$ of \\$n\\$ such that:

$$\left|p-\frac{n}{p}\right|=14$$

### Commented

```
fDŠ/α14å  # expects a positive integer n as input       e.g. 2655
f         # push the list of unique prime factors of n  -->  2655, [ 3, 5, 59 ]
 D        # duplicate it                                -->  2655, [ 3, 5, 59 ], [ 3, 5, 59 ]
  Š       # moves the input n between the two lists     -->  [ 3, 5, 59 ], 2655, [ 3, 5, 59 ]
   /      # divide n by each prime factor               -->  [ 3, 5, 59 ], [ 885, 531, 45 ]
    α     # compute the absolute differences
          # between both remaining lists                -->  [ 882, 526, 14 ]
     14å  # does 14 appear in there?                    -->  1

```

# Answer
> 11 votes
# JavaScript (ES7), 55 bytes

```
n=>(g=k=>k>0&&n%--k?g(k):k==1)(n=(49+n)**.5-7)|g(n+=14)

```

Try it online!

### How?

Given a positive integer \\$n\\$, we're looking for a prime \\$x\\$ such that \\$x(x+14)=n\\$ or \\$x(x-14)=n\\$.

Hence the following quadratic equations:

$$x^2+14x-n=0\tag{1}$$ $$x^2-14x-n=0\tag{2}$$

The positive root of \\$(1)\\$ is:

$$x\_0=\sqrt{49+n}-7$$

and the positive root of \\$(2)\\$ is:

$$x\_1=\sqrt{49+n}+7$$

Therefore, the problem is equivalent to testing whether either \\$x\_0\\$ or \\$x\_1\\$ is prime.

To do that, we use the classic recursive primality test function, with an additional test to make sure that it does not loop forever if it's given an irrational number as input.

```
g = k =>    // k = explicit input; this is the divisor
            // we assume that the implicit input n is equal to k on the initial call
  k > 0 &&  // abort if k is negative, which may happen if n is irrational
  n % --k ? // decrement k; if k is not a divisor of n:
    g(k)    //   do a recursive call
  :         // else:
    k == 1  //   returns true if k is equal to 1 (n is prime)
            //   or false otherwise (n is either irrational or a composite integer)

```

Main wrapper function:

```
n => g(n = (49 + n) ** .5 - 7) | g(n += 14)

```

# Answer
> 6 votes
# Perl 6, ~~45~~ 28 bytes

```
((*+49)**.5+(7|-7)).is-prime

```

Try it online!

Uses Arnauld's construction, that \\$\sqrt{n+49}\pm7\\$ must be prime for \\$n\\$ to be a Rocco number.

### Explanation:

```
 (*+49)**.5                   # Is the sqrt of input+49
           +(7|-7)            # Plus or minus 7
(                 ).is-prime  # Prime?

```

# Answer
> 6 votes
# Regex (ECMAScript), ~~64~~ 62 bytes

```
^(?=(x((x{14})(x+)))(?=(\1*)\4\2*$)(\1*$\5))\6\3?(?!(xx+)\7+$)

```

Try it online!

Takes its input in unary, as a sequence of `x` characters whose length represents the number.

This regex finds two numbers \\$a\\$ and \\$a+14\\$ such that \\$n=a(a+14)\\$. If it finds them, it then asserts that either \\$a\\$ or \\$a+14\\$ is prime.

The multiplication algorithm implemented here searches for two unknown factors which, when multiplied together, equal a known product. The regex for this is also essentially equivalent to that of the shortest form of multiplication for asserting that two known factors multiply to make a known product.

In many of my other posted regex answers, multiplication is implemented as finding the unknown product of two known factors; the shortest form of that is different. Both methods would work in both circumstances, but golf-wise, they're worse at doing each other's job.

Here is an explanation of how this form of multiplication works in general:

We have \\$AB \stackrel{?}{=} C\\$, where \\$A \ge B\\$. The steps to asserting \\$AB=C\\$ are (shown here in an order that's easier to explain conceptually; in the regex they're done in the order that results in the best golf):

* Assert that \\$C-A \equiv 0 \pmod A\\$
    + This is equivalent to \\$C \equiv 0 \pmod A\\$, a direct consequence of \\$C=AB\\$
* Assert that \\$C-A-(B-1) \equiv 0 \pmod {A-1}\\$,
    + This can be shown to result from \\$C=AB\\$:
    \\$\begin{aligned}C-A-(B-1) &= AB-A-(B-1) \\ &= A(B-1)-(B-1) \\ &= (A-1)(B-1)\end{aligned}\\$
* Assert that there is no \\$0\<D\<C\\$ which satisfies both of the above with \\$D\\$ in place of \\$C\\$

This can be expressed as:

* Assert that the only \\$0\<E \le C-A\\$ that satisfies the following moduli is \\$E=C-A\\$:
    + \\$E \equiv 0 \pmod A\\$
    + \\$E \equiv B-1 \pmod {A-1}\\$

We now have two coprime moduli, \\$A\\$ and \\$A-1\\$. By the Chinese remainder theorem, there is one and only one integer \\$E\\$ such that \\$0 \< E \le A(A-1)\\$, or alternatively stated, \\$0 \< E+A \le A^2\\$, and the above moduli are satisfied. And since we know \\$B\le A\\$, it follows that \\$AB\le A^2\\$.

The algebra above shows there is at least one \\$E\\$ satisfying the moduli: \\$E=AB-A\\$. The Chinese remainder theorem shows that there is exactly one \\$E\\$ satisfying the moduli within a certain range. The fact that \\$B\le A\\$ guarantees that \\$AB-A\\$ falls inside that range. We are not guaranteed that \\$C\le A^2\\$, but as long as we search for the *smallest* \\$E\\$ satisfying the moduli, we're guaranteed that \\$E=AB-A\\$, so if \\$E=C-A\\$, then \\$AB=C\\$.

The regex essentially searches for the smallest \\$E\\$ satisfying the moduli, then asserts that \\$E=C-A\\$. The assertion of \\$C \equiv 0 \pmod A\\$ is done afterward, making the regex a bit slower in the name of golf.

Also note that in regex, \\$0 \equiv 0 \pmod 0\\$, so the algorithm works for \\$A=1\\$ without any need for a special case.

In cases where we don't know whether \\$A\ge B\\$, and can't capture them at the source in such a way as to automatically sort them as such, we can simply assert both versions of each:

* \\$C \equiv 0 \pmod A\\$
* \\$C \equiv 0 \pmod B\\$
* \\$C-B \equiv 0 \pmod {A-1}\\$
* \\$C-A \equiv 0 \pmod {B-1}\\$

This makes for shorter golf than actually sorting \\$A\\$ and \\$B\\$ into lesser and greater after they've already been captured. But for this particular problem, only the two assertions need to be used, since by definition \\$A=B+14\\$.

And the regex, pretty-printed and commented:

```
# For the purposes of these comments, the input number = N.
^
# Find two numbers A and A+14 such that A*(A+14)==N.
(?=
    (x((x{14})(x+)))   # \1 = A+14; \2 = \1-1; \3 = 14; \4 = A-1; tail -= \1
    (?=                # Assert that \1 * (\4+1) == N.
        (\1*)\4\2*$    # We are asserting that N is the smallest number satisfying
                       # two moduli, thus proving it is the product of A and A+14
                       # via the Chinese Remainder Theorem. The (\1*) has the effect
                       # of testing every value that satisfies the "≡0 mod \1"
                       # modulus, starting with the smallest (zero), against "\4\2*$",
                       # to see if it also satisfies the "≡\4 mod \2" modulus; if any
                       # smaller number satisfied both moduli, (\1*) would capture a
                       # nonzero value in \5. Note that this actually finds the
                       # product of \4*\1, not (\4+1)*\1 which what we actually want,
                       # but this is fine, because we already subtracted \1 and thus
                       # \4*\1 is the value of tail at the start of this lookahead.
                       # This implementation of multiplication is very efficient
                       # golf-wise, but slow, because if the number being tested is
                       # not even divisible by \1, the entire test done inside this
                       # lookahead is invalid, and the "\1*$" test below will only
                       # fail after this useless test has finished.
    )
    (\1*$\5)           # Assert that the above test proved \1*(\4+1)==N, by
                       # asserting that tail is divisible by \1 and that \5==0;
                       # \6 = tool to make tail = \1
)
# Assert that either A or A+14 is prime.
\6                     # tail = \1 == A+14
\3?                    # optionally make tail = A
(?!(xx+)\7+$)          # Assert tail is prime. We don't need to exclude treating
                       # 1 as prime, because the potential false positive of N==15
                       # is already excluded by requiring \4 >= 1.

```

# Answer
> 3 votes
# Brachylog, ~~13~~ 12 bytes

```
ṗ;14{+|-};?×

```

Enter the candidate number as a command-line argument. Outputs `true` or `false`. Try it online!

### Explanation

The code is a predicate whose input is unconstrained and whose output is the number we're testing.

```
ṗ             Let the input ? be a prime number
 ;14          Pair it with 14, yielding the list [?, 14]
    {+|-}     Either add or subtract, yielding ?+14 or ?-14
         ;?   Pair the result with the input, yielding [?+14, ?] or [?-14, ?]
           ×  Multiply; the result must match the candidate number

```

(Tips are welcome. That `{+|-}` still feels clunky.)

# Answer
> 3 votes
# Brachylog, 9 bytes

Different approach then DLosc's answer

```
Ċ-14&∋ṗ&×

```

Takes N as output, gives \[P, P-14\] or \[P+14,P\] back through input (biggest number first)

## explanation

```
Ċ              # The 'input' is a pair of numbers
 -14           #   where the 2nd is 14 smaller then the first
    &∋ṗ        #   and the pair contains a prime
       &×      #   and the numbers multiplied give the output (N)

```

Try it online!

# Answer
> 2 votes
# Pyth, ~~22~~ 20 bytes

```
}Qsm*Ld+Ld_B14fP_TSh

```

Try it online here.

```
}Qsm*Ld+Ld_B14fP_TShQ   Implicit: Q=eval(input())
                        Trailing Q inferred
                  ShQ   Range [1-(Q+1)]
              fP_T      Filter the above to keep primes
   m                    Map the elements of the above, as d, using:
          _B14            [14, -14]
       +Ld                Add d to each
    *Ld                   Multiply each by d
  s                     Flatten result of map
}Q                      Is Q in the above? Implicit print

```

*Edit: Saved 3 bytes as input will always be positive, so no need to filter out negative values from the list. Also fixed a bug for inputs `1` and `2`, costing 1 byte. Previous version: `}Qsm*Ld>#0+Ld_B14fP_TU`*

# Answer
> 2 votes
# 05AB1E, ~~16~~ ~~15~~ 14 bytes

Saved 1 byte by computing 14 with  instead of `žvÍ` (cant believe I didnt think of this in the first place).

Saved 1 byte thanks to Emigna

```
ÅPε7·D(‚+y*Q}Z

```

Try it online! or Test all inputs

## Explanation

```
                 # Implicit input n
ÅP               # Push a list of primes up to n
  ε         }    # For each prime in the list...
   7·            # Push 14 (by doubling 7)
     D(‚         # Push -14 and pair them together to get [14,-14]
        +        # Add [14,-14] to the prime
         y*      # Multiply the prime to compute p(p-14) and p(p+14)
           Q     # Check if the (implicit) input is equal to each element
             Z   # Take the maximum

```

# Answer
> 2 votes
# , ~~21~~ 15 bytes

Based on Arnauld's solution:

```
14 e.q:|@-(%q:)

```

Try it online!

Previous atempt:

```
e.&,14&(]*+,-~)@p:@i.

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 61 bytes

```
.+
$*
^((1{14})1(1)+)(?<=(?<!^\4+(..+))\2?)(?<-3>\1)+$(?(3)1)

```

Try it online! Explanation:

```
.+
$*

```

Convert to unary.

```
^((1{14})1(1)+)

```

`\1` captures the larger of the two factors. `\2` captures the constant 14, saving a byte. `\3` captures the smaller of the two factors, minus 1. This also ensures that both factors are at least 2.

```
(?<=(?<!^\4+(..+))\2?)

```

Check the two factors to ensure at least one of them is prime. The idea of using `\2?` was shamelessly stolen from @Deadcode's answer.

```
(?<-3>\1)+

```

Repeat the larger of the two factors a number of times equal to one less than the smaller of the two factors. As we've already captured the larger factor once this then ends up capturing the product of the two factors.

```
$(?(3)1)

```

Ensure that the product equals the given number.

A direct translation to Retina 1 by replacing `$*` with `*1` would have the same byte count but a byte could be saved by replacing all the `1`s with `_`s and then the `*1` could be replaced with `*` rather than `*_`. Previous Retina 1 answer for 68 bytes:

```
.+
*
Lw$`^(__+)(?=(\1)+$)
$1 _$#2*
Am` (__+)\1+$
(_+) \1

0m`^_{14}$

```

Try it online! Explanation:

```
.+
*

```

Convert to unary.

```
Lw$`^(__+)(?=(\1)+$)
$1 _$#2*

```

Find all the pairs of factors.

```
Am` (__+)\1+$

```

Ensure one is prime.

```
(_+) \1

```

Take the absolute difference.

```
0m`^_{14}$

```

Check whether any are 14.

# Answer
> 1 votes
# JavaScript (Babel Node), 69 bytes

*Damn, I though I was going to beat Arnaulds' Answer but no..... :c*

```
x=>[...Array(x)].some((a,b)=>x/(a=(p=n=>--b-1?n%b&&p(n):n)(b))-a==14)

```

Try it online!

*I want to get rid of the `x=>[...Array(x)].some(` part using recursion so it might get shorter over time*

**Explanation**

```
x=>[...Array(x)]                                                              Creates a range from 0 to x-1 and map:

                .some((a,b)=>                                                 Returns True if any of the following values is true
                             x/                                              Input number divided by
                                (a=(p=n=>--b-1?n%b&&p(n):n)(b))               recursive helper function. Receives a number (mapped value) as parameters and returns
                                                                              the same number if it is prime, otherwise returns 1. Take this value
                                                                              and assign to variable a
                                                               -a            Subtract a from the result
                                                                     ==14    Compare result equal to 14

```

It uses the formula

$$ n/p-p==14 $$

# Answer
> 1 votes
# APL(NARS) 16 chars, 32 bytes

```
{14=∣r-⍵÷r←↑⌽π⍵}

```

{π⍵} would find the factorization of its argument and we suppose that the last element of its result (the list of divisors of n) is the maximum prime divisor of n; Here we suppose that one equivalent definition of Rocco number is: n is a Rocco number \<=\> max factor prime of n: r is such that it is true 14=∣r-n÷r \[for C pseudocode as 14==abs(r-n/r) this definition of Rocco number seems ok at last in the range 1..1000000\]; the range of ok value would be 1..maxInt; test:

```
 f←{14=∣r-⍵÷r←↑⌽π⍵}
 {⍞←{1=f ⍵:' ',⍵⋄⍬}⍵⋄⍬}¨1..10000
32  51  95  147  207  275  351  435  527  627  851  1107  1247  1395  1551  1887  2067  2255  2451  2655  2867  3551  4047  4307  4575  5135  5427  5727  6035  6351  6675  7347  8051  8787  9167  9951

```

# Answer
> 1 votes
# Japt, 10 bytes

*Same as my Javascript Answer*

```
k d@/X-X¥E

```

Try it online!

# Answer
> 1 votes
# Jelly, 9 bytes

```
:ạ⁹ɗÆf14e

```

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 99 bytes

```
n=>Enumerable.Range(2,n).Any(p=>Enumerable.Range(2,p).All(y=>y>=p|p%y>0)&(n==p*(p+14)|n==p*(p-14)))

```

Try it online!

`Enumerable.Range` strikes again :) Using the crazy compiler flag, you can reduce things quite a bit, although I am kind of a fan of the vanilla solution.

# C# (Visual C# Interactive Compiler) \+ /u:System.Linq.Enumerable, 77 bytes

```
n=>Range(2,n).Any(p=>Range(2,p).All(y=>y>=p|p%y>0)&(n==p*(p+14)|n==p*(p-14)))

```

Try it online!

Below is a port of Arnauld's solution that seemed pretty cool. It is currently the longest, but it can probably be golfed some.

# C# (Visual C# Interactive Compiler), 101 bytes

```
n=>{bool g(int k)=>--k<2?n>1:n%k>0&g(k);var d=Math.Sqrt(n+49)-7;return(n=(int)d)==d&(g(n)|g(n+=14));}

```

Try it online!

# Answer
> 1 votes
# Husk, 10 bytes

```
€14mS≠`/¹p

```

Try it online! Given an integer, the function outputs a truthy or falsy value. A port of Arnauld's answer.

# Answer
> 0 votes
# APL(NARS) 30 chars, 60 bytes

```
{∨/{0=1∣⍵:0π⍵⋄0}¨(7,¯7)+√49+⍵}

```

Here 0π is the function say if one number is a prime, test:

```
 f←{∨/{0=1∣⍵:0π⍵⋄0}¨(7,¯7)+√49+⍵}
 {⍞←{1=f ⍵:' ',⍵⋄⍬}⍵⋄⍬}¨0..700
32  51  95  147  207  275  351  435  527  627

```

# Answer
> 0 votes
# F#, 2 answers (noncompeting)

I really liked @Arnauld 's answers, so I translated them.

**123 bytes**, based on the JavaScript answer

```
fun n->let t=int<|sqrt(float n+49.)in Seq.map(fun n->Seq.filter(fun i->n%i=0)[1..n]|>Seq.length=2)[t-7;t+7]|>Seq.reduce(||)

```

Explanation:

```
fun n->let t=int<|sqrt(float n+49.)in Seq.map(fun n->Seq.filter(fun i->n%i=0)[1..n]|>Seq.length=2)[t-7;t+7]|>Seq.reduce(||) //Lambda which takes an integer, n
       let t=int<|sqrt(float n+49.)                                                                                //let t be n, converted to float, add 49 and get square root, converted back to int (F# type restrictions)
                                   in                                                                                //in the following...
                                                                                [t-7;t+7]                 //Subtract and add 7 to t in a list of 2 results (Lists and Seqs can be interchanged various places)
                                      Seq.map(fun n->Seq.filter(fun i->n%i=0)[1..n]|>Seq.length=2)                          //See if either are prime (here, if either result has 2 and only 2 divisors)
                                                                                |>Seq.reduce(||) //And logically OR the resulting sequence

```

**125 bytes**, based on the 05AB1E answer

```
fun n->let l=Seq.filter(fun i->n%i=0)[2..n-1]in let m=Seq.map(fun i->n/i)l in Seq.map2(fun a b->abs(a-b))l m|>Seq.contains 14

```

Explanation:

```
fun n->let l=Seq.filter(fun i->n%i=0)[2..n-1]in let m=Seq.map(fun i->n/i)l in Seq.map2(fun a b->abs(a-b))l m|>Seq.contains 14  //Lambda which takes an integer, n
       let l=Seq.filter(fun i->n%i=0)[2..n-1]                                                                                //let l be the list of n's primes
                                             in                                                                                //in...
                                                let m=Seq.map(fun i->n/i)l                                                     //m, which is n divided by each of l's contents
                                                                           in                                                  //and then...
                                                                              Seq.map2(fun a b->abs(a-b))l m                   //take the absolute difference between each pair of items in the two sequences to make a new sequence
                                                                                |>Seq.contains 14  //and does the resulting sequence contain the number 14?

```

# Answer
> 0 votes
# Python 2, 58 bytes

Outputs by exit code, fails (`1`) for Rocco numbers.

```
P=k=1.
n=input()
exec"P*=k*k;k+=1;P%k*abs(n/k-k)==14>y;"*n

```

Try it online!

---
Tags: code-golf, decision-problem, number-theory
---