title: Split, flip and recombine integers

text:
# Question
Title: Split, flip and recombine integers
## Background

It's well known in mathematics that integers can be put into a one-to-one correspondence with pairs of integers. There are many possible ways of doing this, and in this challenge, you'll implement one of them *and* its inverse operation.

## The task

Your input is a positive integer `n > 0`. It is known that there exist unique non-negative integers `a, b ≥ 0` such that `n == 2<sup>a</sup> * (2*b + 1)`. Your output is the "flipped version" of `n`, the positive integer `2<sup>b</sup> * (2*a + 1)`.

You can assume that the input and output fit into the standard unsigned integer datatype of your language.

## Rules and scoring

You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

These are given in the format `in <-> out`, since the function to be implemented is its own inverse: if you feed the output back to it, you should get the original input.

```
1 <-> 1
2 <-> 3
4 <-> 5
6 <-> 6
7 <-> 8
9 <-> 16
10 <-> 12
11 <-> 32
13 <-> 64
14 <-> 24
15 <-> 128
17 <-> 256
18 <-> 48
19 <-> 512
20 <-> 20
28 <-> 40
30 <-> 384
56 <-> 56
88 <-> 224
89 <-> 17592186044416

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=70299,OVERRIDE_USER=32014;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 11 votes
# Jelly, ~~17~~ ~~16~~ 15 bytes

```
BUi1µ2*³:2*×Ḥ’$

```

Try it online!

### How it works

```
BUi1µ2*³:2*×Ḥ’$    Main link. Input: n

B                  Convert n to base 2.
 U                 Reverse the array of binary digits.
  i1               Get the first index (1-based) of 1.
                   This yields a + 1.
    µ              Begin a new, monadic chain. Argument: a + 1
     2*            Compute 2 ** (a+1).
       ³:          Divide n (input) by 2 ** (a+1).
                   : performs integer division, so this yields b.
         2*        Compute 2 ** b.
              $    Combine the two preceding atoms.
            Ḥ      Double; yield 2a + 2.
             ’     Decrement to yield 2a + 1.
           ×       Fork; multiply the results to the left and to the right.

```

# Answer
> 10 votes
# Pyth, ~~16~~ 15 bytes

```
*hyJ/PQ2^2.>QhJ

```

*1 byte thanks to Dennis*

Test suite

**Explanation:**

```
*hyJ/PQ2^2.>QhJ
                    Implicit: Q = eval(input())
     PQ             Take the prime factorization of Q.
    /  2            Count how many 2s appear. This is a.
   J                Save it to J.
  y                 Double.
 h                  +1.
          .>QhJ     Shift Q right by J + 1, giving b.
        ^2          Compute 2 ** b.
*                   Multiply the above together, and print implicitly.

```

# Answer
> 7 votes
# Python 2, 39 bytes

```
lambda n:2*len(bin(n&-n))-5<<n/2/(n&-n)

```

`n & -n` gives the largest power of 2 that divides `n`. It works because in two's-complement arithmetic, `-n == ~n + 1`. If `n` has *k* trailing zeros, taking its complement will cause it to have *k* trailing ones. Then adding 1 will change all the trailing ones to zeroes, and change the *2^k* bit from 0 to 1. So `-n` ends with a 1 followed by *k* 0's (just like `n`), while having the opposite bit from `n` in all higher places.

# Answer
> 7 votes
# MATL, 22 bytes

```
Yft2=XK~)pq2/2w^Ks2*Q*

```

**Try it online!**

### Explanation

```
Yf      % factor
t       % duplicate
2=      % compare to 2 (yields a logical array)
XK      % save a copy of that to variable K
~)      % keep only values != 2 in the factors array
p       % multiply that factors
q2/     % product - 1 / 2
2w^     % 2^x

K       % load variable K (the logical array)
s       % sum (yields the number of 2s)
2*Q     % count * 2 + 1

*       % multiply both values

```

# Answer
> 6 votes
# MATL, 25 ~~26~~ bytes

```
:qt2w^w!2*Q*G=2#f2*q2bq^*

```

This uses current release (10.2.1) of the language/compiler.

**Try it online!**

### Explanation

Pretty straightforward, based on brute force. Tries all combinations of *a* and *b*, selects the appropriate one and does the required computation.

```
:q          % implicit input "n". Generate row vector [0,1,...,n-1], say "x"
t2w^        % duplicate and compute 2^x element-wise
w!2*Q       % swap, transpose to column vector, compute 2*x+1
*           % compute all combinations of products. Gives 2D array
G=2#f       % find indices where that array equals n
2*q2bq^*    % apply operation to flipped values

```

# Answer
> 5 votes
# Julia, 41 bytes

```
n->2^(n>>(a=get(factor(n),2,0)+1))*(2a-1)

```

This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable.

We define `a` as 1 + the exponent of 2 in the prime factorization of `n`. Since `factor` returns a `Dict`, we can use `get` with a default value of 0 in case the prime factorization doesn't contain 2. We right bit shift `n` by `a`, and take 2 to this power. We multiply that by `2a-1` to get the result.

# Answer
> 4 votes
# Perl 5, 40 bytes

38 bytes plus 2 for `-p`

```
$i++,$_/=2until$_%2;$_=2*$i+1<<$_/2-.5

```

`-p` reads the STDIN into the variable `$_`.

`$i++,$_/=2until$_%2` increments `$i` (which starts at 0) and halves `$_` until `$_` is nonzero mod 2. After that, `$_` is the odd factor of the original number, and `$i` is the exponent of 2.

`$_=2*$i+1<<$_/2-.5` — The right-hand side of the `=` is just the formula for the number sought: {1 more than twice the exponent of 2} times {2 to the power of {half the odd factor minus a half}}. But "times {2 to the power of…}" is golfed as "bit-shifted leftward by…". And that right-hand side is assigned to `$_`.

And `-p` prints `$_`.

# Answer
> 2 votes
## JavaScript ES6, ~~36~~ 33 bytes

```
n=>63-2*Math.clz32(b=n&-n)<<n/b/2

```

My understanding is that `Math.clz32` is going to be shorter than fiddling around with `toString(2).length`.

Edit: Saved 3 bytes thanks to @user81655.

# Answer
> 2 votes
# C, 49 bytes

```
a;f(n){for(a=0;n%2-1;a++)n/=2;return 2*a+1<<n/2;}

```

# Answer
> 2 votes
# Vyxal, 13 bytes

```
2Ǒ:£E/‹½E¥d›*

```

Try it Online!

```
2Ǒ            # Multiplicity by 2 = a
  :£          # Store a copy to the register
     /        # Divide the input by...
    E         # 2 ** A
      ‹½      # Decrement and halve = b
        E     # 2 ** b
            * # Multiplied by
         ¥    # a (register)
          d›  # Doubled and incremented

```

# Answer
> 1 votes
# PARI/GP, 38 bytes

```
f(n)=k=valuation(n,2);(2*k+1)<<(n>>k\2)

```

Note that `>>` and `\` have the same precedence and are computed left-to-right, so the last part can be `n>>k\2` rather than `(n>>k)\2`. The ungolfed version would make `k` lexical with `my`:

```
f(n)=
{
  my(k=valuation(n,2));
  (2*k+1) << ((n>>k)\2);
}

```

# Answer
> 1 votes
# Pip, ~~24~~ ~~23~~ 18 bytes

```
Wa/2=HV:ai+:2Ui*Ea

```

Try It Online!

Loops, halving `a` and incrementing `i` by 2, until `a` halved (int division) is different from `a/2` (float division), thus indicating `a` had become odd. The way the loop is set up, `a` is now half of that odd number, rounded down: i.e., if the odd factor of the original input is \\$2k+1\\$, `a` is now \\$k\\$. Meanwhile, if the largest power-of-two factor of the original input is \\$2^n\\$, then `i` is now \\$2n\\$. It remains only to increment `i` to \\$2n+1\\$ and multiply that by \\$2^k\\$.

---

The new `U`, `E`, and `HV` operators make a big difference for this one. Here's the original 23-byte version in Pip Classic:

```
Wa/2=Ya//:2i+:2++i*2**a

```

Try it online!

# Answer
> 1 votes
# HBL, 22 bytes

```
1(1.)(1.).
?(%.)(1(12(/.2))?)(()(?(/.2
+(().

```

Try it here!

### Ungolfed/explanation

Here's the same thing in HBL's companion language Thimble:

```
'(cons (head arg1) (head arg1) arg1)

'(cond (odd? arg1)
   (cons
     (pow 2 (div arg1 2))
     nil)
   (prev
     (recur (div arg1 2))))

'(sum (prev arg1))

```

The first line is a helper function that takes a list and prepends two copies of its first element to it.

The second function does most of the work. If the argument is odd (base case):

* Int-divide it by 2
* Raise 2 to that power
* Return that value wrapped in a singleton list

If the argument is even (recursive case):

* Int-divide it by 2
* Recurse
* Apply the helper function to the resulting list

Thus, given \\$n = 2^p \cdot (2k + 1)\\$, this function returns a list containing \\$2p + 1\\$ copies of \\$2^k\\$.

The third function passes its argument to the second function and then simply sums the result.

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
Ò2¢©o/<;§o®·>*

```

Port of *@emanresuA*'s Vyxal answer.

Should have been 13 bytes, but there is a bug in 05AB1E's `o` with certain decimal values.

Try it online or verify all test cases.

**Explanation:**

```
Ò            # Get all prime factors of the (implicit) input
 2¢          # Count how many 2s are in this list
   ©         # Store it in variable `®` (without popping)
    o        # Pop it, and push 2 to the power this value
     /       # Divide the (implicit) input by this value
      <      # Decrease it by 1
       ;     # Halve it
        §    # (Cast it to a string - bugfix)
         o   # Pop it, and push 2 to the power this (strinified) decimal
      ®      # Push variable `®`
       ·     # Double it
        >    # Increase it by 1
          *  # Multiply the two together
             # (which is output implicitly as result)

```

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


title: IMO Question Six with a difference

text:
# Question
Title: IMO Question Six with a difference
In 1988, the International Mathematical Olympiad (IMO) featured this as its final question, Question Six:

> Let \\$a\\$ and \\$b\\$ be positive integers such that \\$ab + 1\\$ divides \\$a^2 + b^2\\$. Show that \\$\frac{a^2 + b^2}{ab + 1}\\$ is the square of an integer.

(IMO problems)

This can be proven using a technique called Vieta jumping. The proof is by contradiction - if a pair did exist with an integer, non-square \\$N=\frac{a^2 + b^2}{ab + 1}\\$ then there would always be a pair with a smaller \\$a+b\\$ with both \\$a\\$ and \\$b\\$ positive integers, but such an infinite descent is not possible using only positive integers.

The "jumping" in this proof is between the two branches of the hyperbola \\$x^2+y^2-Sxy-S=0\\$ defined by \\$S\\$ (our square). These are symmetrical around \\$x=y\\$ and the implication is that if \\$(A,B)\\$ is a solution where \\$A\ge B\\$ then \\$(B,SB-A)\\$ is either \\$(\sqrt S,0)\\$ or it is another solution (with a smaller \\$A+B\\$). Similarly if \\$B\ge A\\$ then the jump is "down" to \\$(SA-B,A)\\$.

### Challenge

Given a non-negative integer, \\$n\\$, determine whether a pair of positive integers \\$(a,b)\\$ with \\$n=|a-b|\\$ exists such that \\$ab+1\\$ divides \\$a^2+b^2\\$.

This is , so try to write the shortest code in bytes that your chosen language allows.

Your output just needs to differentiate between "valid" \\$n\\$ and "invalid" \\$n\\$, some possible ways include the below, feel free to ask if unsure:

* Two distinct, consistent values
* Truthy vs Falsey using your language's definition (either way around)
* A solution if valid vs something consistent and distinguishable if not
* Return code (if using this be sure that errors are not due to resource limits being hit - your program would still need to produce the expected error given infinite time/memory/precision/etc)

### Valid inputs

Here are the \\$n\lt 10000\\$ which should be identified as being possible differences \\$|a-b|\\$:

```
0 6 22 24 60 82 120 210 213 306 336 504 720 956 990 1142 1320 1716 1893 2184 2730 2995 3360 4080 4262 4896 5814 6840 7554 7980 9240

```

For example \\$22\\$ is valid because \\$30\times 8+1\\$ divides \\$30^2+8^2\\$ and \\$|30-8| = 22\\$
...that is \\$(30, 8)\\$ and \\$(8, 30)\\$ are solutions to Question Six. The first jumps "down" to \\$(8, 2)\\$ then \\$(2, 0)\\$ while the second jumps "down" to \\$(2, 8)\\$ then \\$(0, 2)\\$.

---

Note: One implementation approach would be to ascend (jump the other way) from each of \\$(x, 0) | x \exists \[1,n\]\\$ until the difference is greater than \\$n\\$ (move to next \\$x\\$) or equal (found that \\$n\\$ is valid). Maybe there are other, superior methods though?

# Answer
# Python, 49 bytes

```
f=lambda n,a=1:a>n+1or(n*n-2)%~(a*(a+n))*f(n,a+1)

```

Try it online!

Outputs Truthy/Falsey reversed.

Checks whether $$\frac{n^2-2}{a(a+n)+1}$$ is ever an integer for any \\$a\\$ with \\$1 \leq a \leq n+1\\$. This upper bound suffices because for \\$ a \geq n \> 1 \\$, the denominator is larger than the numerator, and for \\$n=0\\$ we just need to get a positive on \\$a=1\\$.
> 7 votes

# Answer
# JavaScript (ES6), 43 bytes

*-4 bytes with the formula used in @xnor's answer*

Returns either 0 (falsy) or a positive integer (truthy).

```
f=(n,a=n)=>(n*n-2)%~(a*(a+n))?f(n,a-1):a|!n

```

Try it online!
> 2 votes

# Answer
# C (gcc), 50 bytes

```
a;f(n){for(a=0;a++<=n&&(n*n-2)%~(a*(a+n)););a-=n;}

```

Try it online!

*Port of xnor's Python answer.*

Returns \\$2\\$ for invalid and an integer less than \\$2\\$ for valid.
> 2 votes

# Answer
## Pyth, 18 bytes

```
lfsIc-*QQ2h*T+QTSh

```

Test suite

A naïve implementation of the algorithm layed out in @xnor's answer. I'll see if I can get a better score later.
> 2 votes

# Answer
# PARI/GP, 33 bytes

```
n->n*prod(a=1,n,n^2%(1+a*a+=n)-2)

```

Attempt This Online!

A port of @pajonk's R port of @xnor's Python answer. Returns falsy when there is a solution.

---

# PARI/GP, 40 bytes

```
n->sumdiv(n^2-2,d,d--*issquare(n^2+4*d))

```

Attempt This Online!

Longer but faster. Checks if there is a divisor \\$d\>1\\$ of \\$n^2-2\\$ such that \\$n^2+4d-4\\$ is a square.

Returns truthy when there is a solution.
> 2 votes

# Answer
# 05AB1E, ~~13~~ 11 bytes

```
nÍILDI+*>Öà

```

-2 bytes porting *@xnor*'s formula as well

Outputs `1`/`0` as truthy/falsey respectively.

Try it online or verify the range \[0,100\].

**Original 13 bytes approach:**

```
L©+®ø.ΔnOyP>Ö

```

Outputs a valid pair as truthy or `-1` as falsey.

If looping indefinitely would have been a valid falsey result, `L©+®` could have been `∞+∞` instead for -1 byte.

Try it online or verify the range \[0,100\].

**Explanation:**

Uses formula \\$n^2-2 = 0 \mod a(a+n)+1\\$ on the range \\$\[1,n\]\\$.

```
n           # Square the (implicit) input-integer n
 Í          # Decrease it by 2
  IL        # Push a list in the range [1, input n]
            # (note: n=0 will become list [1,0])
    D       # Duplicate it
     I+     # Add input `n` to each value in the copy
       *    # Multiply the values at the same positions in the lists together
        >   # Increase each by 1
         Ö  # Check for each value in the list if it evenly divides the n²-2
          à # Check if any is truthy
            # (which is output implicitly as result)

```

Creates a list of pairs \\$\[a,b\]\\$ where \\$a\\$ is in the range \\$\[n+1,2n\]\\$ and \\$b\\$ in the range \\$\[1,n\]\\$, and does the check defined in the challenge description on each pair: \\$(a^2+b^2) = 0 \mod (ab+1)\\$.

```
L           # Push a list in the range [1, (implicit) input-integer n]
            # (note: n=0 will become list [1,0])
 ©          # Store this list in variable `®` (without popping)
  +         # Add the (implicit) input to each value in the list
   ®ø       #  Pair it with list [1,n] of variable `®`
            # (we now have a list of pairs [a,b], where `a` is in the range [n+1,2n] and
            # `b` in the range [1,n] and |a-b|==n)
.Δ          # Pop and find the first pair of this list which is truthy for,
            # resulting in -1 if none are truthy:
  n         #  Square the values in the pair
   O        #   Sum them together
    y       #   Push the pair again
     P      #  Take the product
      >     #  Increase it by 1
       Ö    #  Check if (a²+b²) is divisible by (a*b+1)
            # (after which the result is output implicitly)

```
> 2 votes

# Answer
# , 35 bytes

```
\(n,a=1:n)all(n^2%%(a*(a+n)+1)-2)&n

```

Attempt This Online!

Outputs reversed `TRUE`/`FALSE`.

Slight modification of @xnor's algorithm: checks whether $$ n^2 = 2 \mod a(a+n)+1.$$ This needs handling \\$0\\$ as a special case (`&n`), so we may check \\$a\\$ only up to \\$n\\$.

---

Actually a direct port works for the same byte-count:

### , 35 bytes

```
\(n,a=1:n)all((n^2-2)%%(a*(a+n)+1))

```

Attempt This Online!

It's because for \\$n=0\\$ `a=1:n` becomes `[1 0]`, so we actually check \\$a\\$ up to \\$n+1\\$ for \\$n=0\\$, and up to \\$n\\$ for \\$n\>0\\$, which is sufficient.
> 2 votes

# Answer
# Ruby, 43 bytes

```
->n{(0..n).any?{|a|(n*n-2)%~(~a*~a+=n)==0}}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 21 bytes

```
Ｎθ⊙…·¹⊕θ¬﹪⁻×θθ²⊕×ι⁺ιθ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for valid, nothing if invalid. Explanation: Uses @xnor's algorithm. I tried writing it using vectorisation but that weighed in at 27 bytes:

```
Ｎθ¬Π﹪⁻×θθ²⊕÷⁻Ｘ⁺θ⊗⊕…⁰⊕θ²×θθ⁴

```

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

```
Ｎθ                          Input `n` as a number
       θ                    Input `n`
      ×                     Multiplied by
        θ                   Input `n`
     ⁻                      Minus
         ²                  Literal integer `2`
    ﹪                       Vectorised modulo by
               θ            Input `n`
              ⁺             Vectorised plus
                  …         Range from
                   ⁰        Literal integer `0` to
                     θ      Input `n`
                    ⊕       Incremented
                 ⊕          Vectorised incremented
                ⊗           Vectorised doubled
             Ｘ              Vectorised raise to power
                      ²     Literal integer `2`
            ⁻               Vectorised subtract
                        θ   Input `n`
                       ×    Multiplied by
                         θ  Input `n`
           ÷                Vectorised divided by
                          ⁴ Literal integer `4`
          ⊕                 Incremented
   Π                        Take the product
  ¬                         Is zero (i.e. was any remainder zero)

```
> 1 votes

# Answer
# J, 38 bytes

```
3 :'*/0<1|(_2+*:y)%1+(a+y)*a=.1+i.1+y'

```

Uses @xnor's formula, but implements it directly on an array containing a from 1 to n+1.

Try it here
> 1 votes

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


title: Sudoku Solver Diagonal Constraint

text:
# Question
Title: Sudoku Solver Diagonal Constraint
This is the follow up question to standard Sudoku solver.

You are given a Sudoku grid where `.` represents an empty cell and the other cells are filled with numbers `0-8` (inclusive).

Rules:

* All the numbers in Sudoku must appear exactly once in all left-top to right-bottom diagonals.
* All the numbers in Sudoku must appear exactly once in all right-top to left-bottom diagonals.
* All the numbers in Sudoku must appear exactly once in all squares (3\*3).

However numbers can repeat in rows or columns.

This is . Please post your shortest code in any language that solves this problem. Winner will be the shortest solution by byte count.

Input:

```
. 3 7 . 4 2 . 2 .
5 . 6 1 . . . . 7
. . 2 . . . 5 0 .
2 8 3 . . . . . .
. 5 . . 7 1 2 . 7
. . . 3 . . . . 3
7 . . . . 6 . 5 0
. 2 3 . 3 . 7 4 2
0 5 . . 8 . . . .

```

Output:

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

```

# Answer
# Prolog (SWI) \+ clpfd, 231 bytes

```
\R:-append(R,V),V ins 0..8,-R,R-Q,maplist(reverse,R,W),W-Y,+Y,+Q,maplist(label,R).
-[[A,B,C|D],[E,F,G|H],[I,J,K|L]|Q]:- +[A,B,C,E,F,G,I,J,K],-[D,H,L],-Q.
-_.
[]-[].
[[E|_]|S]-[E|D]:-maplist(*,S,Q),Q-D.
[_|Q]*Q.
+Q:-all_distinct(Q).

```

Try it online!

This will produce as many choicepoints as solutions there are - Try it online! As you can see, there are plenty :P
> 2 votes

# Answer
# 05AB1E, 50 bytes

```
8ÝI'.¢ãε'.s.;¶¡€#©3δô3ô€ø€€˜€`®Å\ª®Å/ªε{ā<Q}Pi®»,q

```

Try it online.

Brute-force, so very slow. The more dots the input contains, the slower it becomes. It therefore won't be able to complete the example test case of the challenge description, but it can with just a few dots.

**Explanation:**

```
8Ý            # Push a list in the range [0,8]
  I           # Push the input-string
   '.¢       '# Pop and count the amount of "."
      ã       # Cartesian product this count with the [0,1,2,3,4,5,6,7,8] list
ε             # Map over each list:
    .;        #  Replace every first
 '.          '#  character "."
              #  in the (implicit) input-string, one by one with
   s          #  the digits of the current list
 ¶¡           #  Split the string on newlines
   €#         #  Then split each inner string on spaces
     ©        #  Store this matrix in variable `®` (without popping)
  δ           #  Map over each row:
 3 ô          #   Split it into three triplets
    3ô        #  Then split the rows into three inner lists as well
      €       #  Map over each list of three rows:
       ø      #   Zip/transpose; swapping rows/columns, to group blocks together
        €€˜   #  Flatten each inner block
           €` #  Flatten one level to a list of lists
 ®            #  Push matrix `®` again
  Å\          #  Pop and push its main diagonal
    ª         #  Append it to the list
 ®Å/ª         #  Do the same for the main anti-diagonal
 ε            #  Map over each inner list:
  {           #   Sort it
   ā          #   Push a list in the range [1,length] (without popping)
    <         #   Decrease it to range [0,length], which will be [0,8] basically
     Q        #   Check if the two lists are equal
 }Pi          #  After the map: if all are truthy:
    ®         #   Push matrix `®` yet again
     »        #   Join each inner row by spaces, and then string by newlines
      ,       #   Pop and print it
       q      #   And then exit the program

```
> 0 votes

# Answer
# JavaScript (ES6), 149 bytes

Expects a matrix of integers with \\$0\\$'s for empty cells and \\$1\\$ to \\$9\\$ for filled cells. Returns another matrix in the same format.

This is a brute-force approach which aborts as soon as the grid is inconsistent, making it reasonably fast -- at least for the unique test case (solved in ~6 seconds on TIO).

```
f=(m,X,R)=>m.every(q=(r,y)=>r.every((v,x)=>v?(g=k=>q[k]^(q[k]|=1<<v))(x-y)*g(x+y+9)*g(x/3|y/3+8<<2):(X=x,R=r)))?R?m.some(_=>f(m,R[X]++))?m:R[X]=0:m:0

```

Try it online!

### Commented

```
// m[] = input matrix
// (X, R) = local variables to store the position of an empty cell
//          (more specifically: the last empty cell of the grid)
f = (m, X, R) =>
  // for each row r[] at position y in m[]
  // using q as an object for bit-mask storage
  m.every(q = (r, y) =>
    // for each value v at position x in r[]
    r.every((v, x) =>
      // is this cell empty?
      v ?
        // it's not: make sure its value is valid
        // g is a helper function testing whether q[k] is modified
        // when its v-th bit it set; if not, it means that we have
        // twice the same digit on a diagonal or a square
        (
          g = k => q[k] ^ (q[k] |= 1 << v)
        )(
          // invoke g for the current anti-diagonal,
          // with k in [-8..8]
          x - y
        ) *
        g(
          // invoke g for the current diagonal,
          // with k in [9..25]
          x + y + 9
        ) *
        g(
          // invoke g for the current square,
          // with k in [32..42]
          x / 3 | y / 3 + 8 << 2
        )
      :
        // this cell is empty: save its position in (X, R)
        // NB: this is guaranteed to be truthy (having empty
        // cells does not invalidate the grid)
        (X = x, R = r)
    )
  ) ?
    // the grid is valid so far
    R ?
      // there's an empty cell: attempt to set it to 1 .. 9 and
      // do recursive calls to see if it leads to a solution
      m.some(_ => f(m, R[X]++)) ?
        // if successful, return m[]
        m
      :
        // otherwise, reset the cell to 0 afterwards and abort
        R[X] = 0
    :
      // the grid is valid and there's no empty cell: return m[]
      m
  :
    // the grid is invalid: abort right away
    0

```
> 0 votes

---
Tags: code-golf, sudoku
---


title: Compute GPA for a set of grades

text:
# Question
Title: Compute GPA for a set of grades
Given a set of letter grades, output the GPA (grade point average) of those grades, rounded to one decimal place.

Valid grades and their corresponding value are the following:

```
A = 4 grade points
A- = 3.7 grade points
B+ = 3.3 grade points
B = 3 grade points
B- = 2.7 grade points
C+ = 2.3 grade points
C = 2 grade points
C- = 1.7 grade points
D+ = 1.3 grade points
D = 1 grade point
D- = 0.7 grade points
F = 0 grade points

```

The formula for GPA is simply the average of the points values of the grades. The rounding scheme used should be round half up (i.e. less than 0.05 gets rounded down to 0 and greater than or equal to 0.05 gets rounded up to 0.1). The average should be unweighted (all inputs are treated equally). Note that the same grade can show up multiple times in the input, in which case each instance of that grade should be a separate element in the average.

So for example, if the input was \[A, B+, A, C-\], the GPA is (4 + 3.3 + 4 + 1.7)/4 = 3.25, which rounds to 3.3.

The program should take as input the grades to be averaged using whatever format is convenient, such as a list, or a string with a delimiter of your choice. Each input grade should be a single string (i.e. the letter components and +/- shouldn't be separate inputs). You can assume the input will always contain at least one grade. Note that grades may be repeated in the input.

Output can optionally include the ".0" suffix in the event of an integer result but this is not required.

This is code golf, so shortest solution in bytes wins.

Test cases:

```
[A] => 4
[F, F, F] => 0
[D+, D-] => 1
[A, B, C, D] => 2.5
[A-, B-, C-, D-] => 2.2
[A, A-, B+, B, B-] => 3.3
[A, B+, A, C-] => 3.3
[C+, C+, A, C+] => 2.7
[A, B, F, F] => 1.8

```

# Answer
# Jelly, 24 bytes

```
ON%7’»0_2¦€4ḋ10,3Æm+.Ḟ÷⁵

```

A monadic Link that accepts a list of lists of characters and yields a number.

**Try it online!**

### How?

```
ON%7’»0_2¦€4ḋ10,3Æm+.Ḟ÷⁵ - Link: list of grades  e.g. ['A-', 'B+', 'F', 'F']
O                        - ordinals (vectorises)      [[65, 45], [66, 43], [70], [70]]
 N                       - negate                     [[-65, -45], [-66, -43], [-70], [-70]]
  %7                     - mod seven                  [[5, 4], [4, 6], [0], [0]]
    ’                    - decrement                  [[4, 3], [3, 5], [-1], [-1]]
     »0                  - max with zero              [[4, 3], [3, 5], [0], [0]]
        2¦€              - from 2nd of each:
       _   4             -   subtract four            [[4, -1], [3, 1], [0], [0]]
            ḋ10,3        - dot product with [10,3]    [37, 33, 0, 0]
                 Æm      - mean                       17.5
                   +.    - add a half                 18.0
                     Ḟ   - floor                      18
                      ÷⁵ - divide by ten              1.8

```

---

If banker's rounding was used \\$21\\$ bytes is possible with `ON%7’»0_2¦€4Uḅ.3Æmær1` (`U` reverses each, `ḅ.3` converts from base \\$0.3\\$, and `ær1` uses Python's `round` to round to 1 decimal place).
> 3 votes

# Answer
# JavaScript (ES6), 67 bytes

Returns a number.

```
a=>(a.map(([x,y])=>t+=940.5%(n++,'0x5'+x)%85+~~(y+3),n=t=0)|t/n)/10

```

Try it online!

### How?

The purpose of the black-magic formula `940.5 % ('0x5' + x) % 85` is to turn a grade into its base value pre-multiplied by \\$10\\$ and with an offset of \\$1/2\\$ for the final rounding.

| x | N = '0x5' + x | As decimal | 940.5 mod N | mod 85 |
| --- | --- | --- | --- | --- |
| A | 0x5A | 90 | 40.5 | 40.5 |
| B | 0x5B | 91 | 30.5 | 30.5 |
| C | 0x5C | 92 | 20.5 | 20.5 |
| D | 0x5D | 93 | 10.5 | 10.5 |
| F | 0x5F | 95 | 85.5 | 0.5 |

We use the expression `~~(y + 3)` to add an additional offset of \\$\pm 3\\$ if the grade is followed by `+` or `-`. This evaluates to `~~NaN` (which is \\$0\\$) if there's no modifier.

Given the sum \\$t\\$ of all these values, the GPA is given by \\$\lfloor t/n\rfloor/10\\$, where \\$n\\$ is the number of grades.

---

# JavaScript (ES6), 76 bytes

Original answer, returning a string.

```
a=>(eval(a.map(s=>s<'F'&&'14-0x'+s+[s[1]&&.3]).join`+`)/a.length).toFixed(1)

```

Try it online!

### How?

If the grade is `"F"`, we turn it into `"false"`.

Otherwise:

* we add the prefix `"14-0x"`
* if this is a two-character grade, we add the suffix `"0.3"`

Examples:

* `"A"` is turned into `"14-0xA"` (\\$14-10=4\\$)
* `"B+"` is turned into `"14-0xB+0.3"` (\\$14-11+0.3=3.3\\$)
* `"C-"` is turned into `"14-0xC-0.3"` (\\$14-12-0.3=1.7\\$)
> 22 votes

# Answer
# Excel, ~~89~~ 84 bytes

Saved 5 bytes thanks to JvdV

```
=ROUND(AVERAGE(IF(A:A=0,"",FIND(LEFT(A:A),"FDCBA")-1+IFERROR(--RIGHT(A:A)&.3,0))),1)

```

Input is in the first column. One grade per row. When you paste the formula, Excel will automatically add a leading zero so `.3` becomes `0.3`.

* `ROUND(~,1)` will round the final result to one decimal place.
* `AVERAGE(~)` will average the array we're about to calculate.
* `IF(A:A=0,"",~)` will ignore all the blank cells below the input. Without this, the above solution produces around 1 million zeroes so that throws off the average a bit.
* BASE VALUE: `FIND(LEFT(A:A),"FDCBA")-1` get the base GPA value of each letter from 0 - 4.
* ADJUSTMENT VALUE: `IFERROR(--RIGHT(A:A)&.3,0)`
    + `RIGHT(A:A)&.3` combines the right-most character (which may be a letter) with `.3`.
    + `--~` tries to coerce that value into a number which throws an error if the right-most character was a letter since something like `--A.3` is not a number.
    + `IFERROR(~,0)` corrects all those errors to `0` instead.
* When you add the base value and adjustment value (which may be negative), you get the GPA value for that letter grade.
* All those grades are calculated individually and then averaged and rounded to one decimal place.
> 8 votes

# Answer
# APL(Dyalog Unicode), 38 bytes SBCS

Anonymous prefix lambda taking a string argument of whatever format is convenient.

```
{1⍕(+/l,.3×-⌿'+-'∘.=⍵)÷≢l←0⌈5-⎕A⍳⍵∩⎕A}

```

Try it on APLgolf!

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

`⍵∩⎕A` intersection of argument and uppercase **A**lphabet

`⎕A⍳` indices of those letters in the uppercase Alphabet (A=1)

`5-` subtract those indices from 5

`0⌈` maximum of 0 and those numbers

`l←` assign to `l`

count those

`(` divide the following by that:

`'+-'∘.=⍵` comparison table of signs vs the argument characters

`-⌿` subtract the bottom row from the top row

`.3×` multiply those differences by 0.3

`l,` prepend `l`

`+/` sum

`1⍕` format as string with 1 decimal
> 5 votes

# Answer
# sed `-E`, ~~302~~ 299 bytes

```
:a
s/ //
s/[A-D]/&aaaaaaaaaa/g
y/ABCD/BCDF/
s/\+/aaa/
/-/{s/-//;s/a//;s/a//;s/a//}
s/Fa/aF/
ta
s/F/!F/
:b
s/F/a/
s/(a+)(a*!)\1$/X\2\1/
tb
s/!.*/\U&/
s/AA?/a/g
/(a+)!\1$/s/a/X/
s/[a!]//g
s/X{10}/Y/g
s/$/I.0/
:c
/X/y/012345678/123456789/
/Y/y/IJKLMNOPQ/JKLMNOPQ9/
s/X//
s/Y//
tc
y/IJKLMNOPQ/012345678/

```

Attempt This Online!

**Explanation:**

```
                  # store dividend as unary "a" and divisor as unary "F"
:a
s/ //                 # removes all spaces
s/[A-D]/&aaaaaaaaaa/g # for each of letters ABCD ten "a" are added
y/ABCD/BCDF/          # each of letters ABCD are substracted to BCDE
s/\+/aaa/             # for every + three "a" are added
/-/{s/-//;s/a//;s/a//;s/a//} # for every - three "a" are removed
s/Fa/aF/              # sort the string into format "aaaaaFFFFF"
ta
                  # now perform the division
s/F/!F/               # transforms string to format "aaaaa!FFFFF"
:b
s/F/a/                # transforms string to format "aaaaa!aaaaa"
s/(a+)(a*!)\1$/X\2\1/ # if there are more or equal "a" on left side than on the right append "X" to beggining
tb
                  # now do the rounding
s/!.*/\U&/            # transorm "a" after "!" to "A"
s/AA?/a/g             # now the amount of "A" is divided by 2
/(a+)!\1$/s/a/X/      # check if the reminder is more or equal to half of divisor and if so, then add one more "X"
s/[a!]//g             # remove leftover characters
                  # now the result is stored as unary "X"
                  # conversion from unary to decimal
s/X{10}/Y/g           # convert every ten "X" to "Y"
s/$/I.0/              # adds string for output "I.0"
:c
/X/y/012345678/123456789/ # for every "X" the "0" is increased
/Y/y/IJKLMNOPQ/JKLMNOPQ9/ # for every "Y" the "I" is increased
s/X//
s/Y//
tc
y/IJKLMNOPQ/012345678/ # now the "I" is transformed to digit

```
> 5 votes

# Answer
# Python, 98 bytes

```
lambda i:round(sum(x*i.count(y)for y,x in zip("FDCBA-+",[*range(5),-.3,.3]))/len(i.split())+.01,1)

```

Attempt This Online!
> 5 votes

# Answer
# Python 3.8, ~~95~~ ~~93~~ 92 bytes

```
s=.01;i=0
for g,a,*_ in open(0):i+=1;s+='FDCBA'.find(g);exec(f's=s{a}.3')
exit(f'{s/i:.1f}')

```

Input (stdin)

```
A
B+
C
D

```

Very straightforward. Open `stdin` with `open(0)`, then read each line with `for g`. Python has an annoying property where it leaves a trailing `\r` after each line, which we exploit in an f-string passed to `exec`. In case there's no appendix after grade, f-string becomes `s=s\r.3`, which is essentially a no-op. Very unsafe ;)
> 5 votes

# Answer
# Pyth, ~~24~~ 29 bytes

```
.OmeS,0v++"14-0x"d?tld".3";.z

```

Try it online!
> 4 votes

# Answer
# Python 3, 93 bytes

```
lambda l:int(0.5+sum(3*(c=='+')-3*(c=='-')or'FDCBA'.index(c)*10for c in''.join(l))/len(l))/10

```

Takes input as a list of strings (`['A', 'B+']`).
> 4 votes

# Answer
# C (clang), ~~113~~ 96 bytes

-17 bytes thanks to celingcat and jdt

```
k;i;main(j){for(;gets(&j);k++)i+=j%8<5?50-j%8*10:0,i+=(j>>=8)?132-j*3:0;printf("%.1f",i/10./k);}

```

Try it online!

Attempt This Online!

Takes input as one grade per line.

## Explanation

```
gets(&j)

```

Read the string into a integer field `j`. This is perfectly valid in C, and is a compact way to read strings of upto 3 bytes long.

```
j%8<5

```

Check for F

```
50-j%8*10

```

Extract the last byte from the string, this will be the letter (since little endian). 178-10\*char will be the letter grade, 40, 30, 20, 10 etc.

```
0,

```

I think this just changed the operator precidence? Not sure.

```
i+=(j>>=8)?132-j*3:0

```

Add or subtract 3 depending on the sign, since `+` is 43 and `-` is `45`

```
printf("%.1f",i/10./k)

```

Round and print the final number as a float.
> 3 votes

# Answer
# 05AB1E, ~~30~~ 26 bytes

```
ε14sáC-.3y¦'\ìθ.VDd*}ÅA1.ò

```

-4 bytes by semi-porting *@Arnauld*'s JavaScript answer

Try it online or verify all test cases.

**Original 30 bytes answer:**

```
•H₁yΔи•.¥RA4£…+ -â¦ðмuIkèÅAòT/

```

Try it online or verify all test cases.

**Explanation:**

```
ε            # Map over the (implicit) input-list:
 14          #  Push 14
   s         #  Swap so the current grade-string is at the top
    á        #  Only keep its letters (removing a potential "+"/"-")
     C       #  Convert it to 'binary': "A"=10, "B"=11, "C"=12, "D"=13, "F"=15
      -      #  Subtract it from the 14
 .3          #  Push 0.3
   y         #  Push the current grade-string again
    ¦        #  Remove its first character (the letter)
     '\ì    '#  Prepend a leading "\"
        θ    #  Pop and only keep its last character
         .V  #  Execute it as 05AB1E code
             #  ("+"/"-" does what you'd expect; "\" discards the 0.3 from the stack)
 D           #  Duplicate the decimal
  d          #  Check if it's non-negative (1 if >=0; 0 if <0)
   *         #  Multiply that to the decimal to change the "F"=1 to 0
}            # Close the map
 ÅA          # Get the average of this list
   1.ò       # Round it to 1 decimal point
             # (after which the result is output implicitly)

```

```
•H₁yΔи•      # Push compressed integer 73343343343
       .¥    # Undelta its digits with leading 0: [0,7,10,13,17,20,23,27,30,33,37,40]
         R   # Reverse it: [40,37,33,30,27,23,20,17,13,10,7,0]
A            # Push the lowercase alphabet
 4£          # Only keep its first four characters: "abcd"
   …+ -      # Push string "+ -"
       â     # Get the cartesian product of the two: ["a+","a ","a-",...,"d+","d ","d-"]
        ¦    # Remove the leading "a+"
         ðм  # Remove all spaces from each string
Il           # Push the input-list, and convert each grade-string to lowercase
  k          # Get the indices of each lowercase grade-string in the string-list we've created)
             # (-1 for "f", since it's not in the list)
  è          # Use that to index into the earlier list of integers
             # (-1 wraps around to the last item, which is the 0)
   ÅA        # Get the average of this list
     ò       # Round it to an integer
      T/     # Divide it by 10
             # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•H₁yΔи•` is `73343343343`.
> 3 votes

# Answer
# Red, 124 bytes

```
func[a][forall a[parse a/1[change p: skip(rejoin[max 69 - p/1 0" "])opt[skip insert" .3"]]a/1: do a/1]round/to average a .1]

```

Try it online!

More readable:

```
f: func [a][
    forall a [
        parse a/1 [
            change set g skip (rejoin [max 69 - g 0 space])
            opt [skip insert " 0.3"]
        ]
        a/1: do a/1
    ]
    round/to average a 0.1
]

```

The input is a block (list) of strings. I modify each string in place by changing the letter with the corresponding grade value and optionally appending "0.3" after `+` or `-`. Then the string is replaced by its evaluated value. Finally I find and round the average of the block.
> 2 votes

# Answer
# Retina 0.8.2, 90 bytes

```
T`L`4-0
\d
0$&$*
1
20$*
\+
6$*
1{6}-

O`.
0+
$.&$*1$.&$*1,$.&$*
\D*(1+),(\1)*1*
$#2
.$
.$&

```

Try it online! Link includes test cases. Output always includes the decimal but omits the leading `0` on scores of less than `1`. Explanation:

```
T`L`4-0

```

Translate uppercase letters to digits `A=4, B=4, C=2, D=1`, otherwise `0`.

```
\d
0$&$*

```

Convert to unary and prefix a marker `0` to keep count of the number of grades.

```
1
20$*

```

Multiply by `20`.

```
\+
6$*

```

Add 6 for a `+`.

```
1{6}-

```

Subtract 6 for a `-`.

```
O`.

```

Collect the markers and scores together.

```
0+
$.&$*1$.&$*1,$.&$*

```

Add the count to the sum (so that the division will round) and double the count.

```
\D*(1+),(\1)*1*
$#2

```

Divide the sum by the doubled count.

```
.$
.$&

```

Divide by `10`.
> 2 votes

# Answer
# PHP, ~~165~~ 100 bytes

Thanks to @Steffan for the whopping 39% size reduction.

```
function($a){foreach($a as$v)$r+=strpos("FDCBA",$v[$l++*0])+($v[1]?$v[1]..3:0);echo round($r/$l,1);}

```

Try it online!

### Original Solution

```
function($a){$i='array_search';$g=str_split("FDCBA");$r=0;foreach($a AS$v){@$r+=eval("return {$i($v[0], $g)}".($v[1]?$v[1].".3;":";"));}die(round($r/count($a),1));};

```

Try it online!

This is my first time golfing in PHP, so I probably missed a few places where I could have been more efficient.

### Original Explanation

PHP is completely and utterly broken, which is why golfing in it is so fun. We approach this problem by using a string and splitting it, using the index as GPA value. The `array_search` function grabs the proper GPA value for us. We then use the `+` or `-` in the input to add or subtract `0.3` to the GPA value and use a standard algorithm to find the average value.
> 2 votes

# Answer
# Knight (v2.0-alpha), 81 bytes

```
O+++=s=n"";W=gP;=n+1n=s++*100&!?70=cA[g-69c*30&]g-44A]g s/=q/+/s n 5=t 10t'.'%q t

```

Try it online!

The basic algorithm is as follows, with a few golfing optimizations added:

# Set `s` and `n` to the empty string. This could be any zero value,3
# but an empty string helps with `OUTPUT`
; + = s = n ""

# Each grade is on a separate line
; WHILE = grade PROMPT
    ; = n + 1 n # increment the amount of grades

    # The grade part is `100 * (c == 'F' ? 0 : 69 - c)`,
    # ie the grade offset for normal grades, or `0` for `F`.
    ; = grade_part * 100 &(!? 70 = c ASCII [grade) (- 69 c) #nice

    # The modifier is `grade.len == 1 ? 0 : 30 * (44 - grade[1].ascii)`
    ; = modifier_part * 30 (& ]grade (- 44 ASCII ]grade))

    # `s` will be coerced to an int the first tiem around.
    : = sum ++ grade_part modifier_part s

# Calculate the average * 10. To accommodate the rounding rule,
# we add five, then divide (`sum`, which is 100x a GPA) by ten.
; = avg / (+ /sum n 5) 10

# Now, simply output the number in the float format
: OUTPUT ++(+ "" /avg 10) '.' (% avg 10)

```
</code></pre>
> 2 votes

# Answer
# Python 3, ~~168 150~~ 144 bytes

```
lambda n:int(sum([{'A':4,'A-':3.7,'B+':3.3,'B':3,'B-':2.7,'C+':2.3,'C':2,'C-':1.7,'D+':1.3,'D':1,'D-':0.7,'F':0}[i]for i in n])/len(n)*10+.5)/10

```

Could save some bytes on the dictionary creation.

Returns a float.
> 1 votes

# Answer
# Charcoal, 34 bytes

```
ＷＳ⊞υ⁺⌕FDCBA§ι⁰×·³⁻№ι+№ι-﹪%.1f∕ΣυＬυ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated grade strings. Explanation:

```
ＷＳ

```

Repeat for each input grade...

```
⊞υ⁺⌕FDCBA§ι⁰×·³⁻№ι+№ι-

```

... calculate its value by looking up the letter in the string `FDCBA` and adjusting by `0.3` depending on the number of `+`s or `-`s.

```
﹪%.1f∕ΣυＬυ

```

Take the average and format it to one decimal place.
> 1 votes

---
Tags: code-golf
---


title: Code Golf: Number of paths!

text:
# Question
Title: Code Golf: Number of paths!
## Challenge

> Consider a square matrix of order N(N rows and N columns). At each step you can move one step to the right or one step to the top. How many possibilities are to reach (N,N) from (0,0)?

## Constraints

* Assume input will be a positive integer N satisfying 1 \<= N \<= 125
* No special characters, only 0-9
* Output should be in a separate line for ever test-case.

**Sample test Cases:**

**Input:**

```
32
99
111
98
101
69
23
56
125
115

```

**Output:**

```
1832624140942590534
22750883079422934966181954039568885395604168260154104734000
360523470416823805932455583900004318515997845619425384417969851840
5716592448890534420436582360196242777068052430850904489000
360401018730232861668242368169788454233176683658575855546640
23623985175715118288974865541854103729000
8233430727600
390590044887157789360330532465784
91208366928185711600087718663295946582847985411225264672245111235434562752
90678241309059123546891915017615620549691253503446529088945065877600

```

## Good luck!

The `shorter` an answer is, the better!

# Answer
## J, 8

```
(!+:)~x:

```
* `x:` forces arbitrary precision
* `+:` doubles its argument
* `!` is the binomial
* `a !+: b` is the binomial of a out of 2\*b
* `(!+:)~ b` is the binomial of b out of 2\*b
> 4 votes

# Answer
**PARI GP**

```
n->binomial(2*n,n)

```

**Mathematica**

```
Binomial[2#,#]&

```
> 6 votes

# Answer
## C# (203 chars)

```
using System;using i=System.Numerics.BigInteger;class X{static void Main(){Func<i,i>f=null;f=n=>n<2?1:n*f(n-1);try{i p=i.Parse(Console.In.ReadLine());Console.WriteLine(f(2*p)/f(p)/f(p));Main();}catch{}}}

```

Readable:

```
using System;
using i = System.Numerics.BigInteger;
class X
{
    static void Main()
    {
        Func<i, i> f = null;
        f = n => n < 2 ? 1 : n * f(n - 1);
        try
        {
            i p = i.Parse(Console.In.ReadLine());
            Console.WriteLine(f(2 * p) / f(p) / f(p));
            Main();
        }
        catch { }
    }
}

```

Tricks I used:

* Using try/catch instead of an explicit end condition for the main loop
* Calling `Main()` recursively is slightly shorter than `for(;;){`...`}` or `x:`...`goto x;`
> 4 votes

# Answer
## Ruby, 48 characters

```
#!ruby -n
s=1;1.upto(l=$_.to_i){|a|s+=s*l/a};p s

```
> 4 votes

# Answer
**Python ~~67~~ 57 Characters**

```
while 1:s=i=1;n=input();exec"s=s*(n+i)/i;i+=1;"*n;print s

```
> 4 votes

# Answer
## DC -- 27 character

```
 ?d2*[d1-d1<F*]dsFxrlFxd*/pq

```

Invoke it like

```
echo 125 | dc -e '?d2*[d1-d1<F*]dsFxrlFxd*/pq'

```

or

```
echo 23 | dc -f

```

The bit in the brackets is a recursive factorial, `?` reads the standard input, and the rest is stack management and operations.
> 2 votes

# Answer
## PARI/GP -- 14 bytes

```
n->(2*n)!/n!^2

```

Shorter than the built-in

```
n->binomial(2*n,n)

```
> 2 votes

# Answer
# Vyxal, 3 bytes

```
d$ƈ

```

Try it Online!

Port of all the other answers

```
  ƈ # Binomial coefficient of...
d   # Double input
 $  # Input

```
> 1 votes

# Answer
## Golf-Basic 84, 37 characters

```
l`A:1_S:1_Ii`N:(S*(N+I)/I:I++I)N_Sd`S

```

I can't test this right now, but I think that the the `:` and/or the multiplying of the result of `I++I` and an integer result from `S*(N+I)/I` will cause it to return `ERR:UNDEFINED`
> 0 votes

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


title: Help me carry my shopping bags

text:
# Question
Title: Help me carry my shopping bags
# It was a warm summer evening...

when my stupid car decided to break down in the middle of the road on my way back from the supermarket. I pushed it to the sideline and decided to walk home. I opened the trunk to take out the grocery and remaining stuff. It was then that I noticed the items were not evenly bagged. Some bags had more heavy items while others had few lighter stuff - some even had a mix of such items. To make it easy for me to carry, I decided to group everything in to two bags and make their weights as close to each other as possible.

# Your goal

is to help me rearrange the items in to two shopping bags in such a way that the difference between both bags is close to zero as possible.
**Mathematically:**

> **WEIGHT LEFT HAND — WEIGHT RIGHT HAND ≈ 0**

# Example

If I had only 2 items, Bread and Peanut butter, and the weight of bread is 250 grams and peanut butter is 150 grams, the best way is to carry them separately in two hands.

> **WLH \- WRH = W(BREAD) \- W(P.BUTTER)
250 - 150 = 100**

The other possibility is :

> **W(BREAD, P.BUTTER) \- W(empty hand) = (250 + 150) - 0 = 400**

This is not better than our first case, so you should go with the first one.

# Your code should

1. take inputs of numbers indicating weights of items in the shopping bag. Units are not important, but they should be the same (ideally kilograms or grams). Input can be done one by one or all at once. You may restrict the total count to 20 items max, if you want.
2. The input format/type is up to you to choose, but nothing else should be present other than the weights.
3. Any language is allowed, but stick to standard libraries.
4. Display output. Again, you're free to choose the format, but explain the format in your post. ie, how can we tell which ones are left hand items and which ones are right hand items.

# Points

1. Shortest code wins.

# Hint

> The two possible algorithms that I could think of are differentiation (faster) and permutations/combinations (slower). You may use these or any other algorithm that does the job.

# Answer
# Pyth, 9 bytes

```
ehc2osNyQ

```

Input, output formats:

```
Input:
[1, 2, 3, 4, 5]
Output:
[1, 2, 4]

```

Demonstration.

```
ehc2osNyQ
             Q = eval(input())
       yQ    Take all subsets of Q.
    osN      Order those element lists by their sums.
  c2         Cut the list in half.
eh           Take the last element of the first half.

```

This works because `y` returns the subsets in such an order that each subset and its complement are equidistant fom the center. Since the sum of a subset and the sum of its complement will always be equidistant from the center, the list after `osNyQ` will also have this property. Thus, the center two elements of `osNyQ` are complements, and must have an optimal split. We extract the first of those two elements and print it.
> 15 votes

# Answer
# Pyth, 16

```
ho.a-FsMNs./M.pQ

```

This takes the inputs as a pythonic list on STDIN. The output is a list of 2 lists with the first list being the items in one bag, and the second list representing the items in the second bag. This brute forces all combinations, so it will run very slowly (or run out of memory) for large inputs.

Try it online here

To support the handling of just one input, this goes up to 17:

```
hho.a-FsMNs./M.pQ

```

This will print the values that go in one hand.
> 6 votes

# Answer
# CJam, ~~19~~ 18 bytes

```
{S+m!{S/1fb:*}$W=}

```

This is an anonymous function that pops an array of integers from the stack and returns an array of integers separated by a space.

*Thanks to @jimmy23013 for his ingenious `:*` trick, which saved 1 byte.*

Try it online in the CJam interpreter.

### How it works

```
S+    e# Append a space to the array of integers.
m!    e# Push the array of all possible permutations.
{     e# Sort the array by the following:
  S/  e#   Split the array at the space.
  1fb e#   Add the integers in each chunk (using base 1 conversion).
  :*  e#   Push the product of both sums.
}$    e# Permutations with a higher product will come last.
W=    e# Select the last permutation.

```

Denote the total weight of the shopping bags with **W**. Then, if the bags in one of the hands weigh **W/2 - D/2**, those in the other hand must weigh and **W - (W/2 - D/2) = W/2 + D/2**.

We are trying to minimize the difference **D**. But **(W/2 - D/2)(W/2 + D/2) = W^2/4 - D^2/4**, which becomes larger as **D** becomes smaller.

Thus, the maximal product corresponds to the minimal difference.
> 6 votes

# Answer
# Python 2.7, 161, 160

## code

```
from itertools import*
m=input();h=sum(m)/2.;d=h
for r in(c for o in range(len(m)+1) for c in combinations(m,o)):
 t=abs(h-sum(r))
 if t<=d:d=t;a=r
print a

```

# Algorithm

> **2 x Wone hand = Total weight
Wone hand ~ Total weight / 2**

Check if each combination is getting closer to half of total weight. Iterate and find the best one.

## input

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

```

## output

```
(2, 3)

```

The displayed tuple goes in one hand, the ones that are not displayed goes in the other (it is not against the rules).
> 5 votes

# Answer
# JavaScript (*ES6*) 117

Using a bit mask to try every possible split, so it is limited to 31 items (ok with the rules). Like the ref answer it outputs just one hand. Note: i look for the minimum difference \>=0 to avoid Math.abs, as for each min \< 0 there is another \> 0, just swapping hands.

To test: run the snippet in Firefox, input a list of numbers comma or space separated.

```
f=(l,n)=>{ // the unused parameter n is inited to 'undefined'
  for(i=0;++i<1<<l.length;t<0|t>=n||(r=a,n=t))
    l.map(v=>(t+=i&m?(a.push(v),v):-v,m+=m),m=1,t=0,a=[]);
  alert(r)
}

// Test

// Redefine alert to avoid that annoying popup when testing
alert=x=>O.innerHTML+=x+'\n';

go=_=>{
  var list=I.value.match(/\d+/g).map(x=>+x); // get input and convert to numbers
  O.innerHTML += list+' -> ';
  f(list);
}
```

```
#I { width: 300px }
```

```
<input id=I value='7 7 7 10 11'><button onclick='go()'>-></button>

<pre id=O></pre>
```
> 4 votes

# Answer
# Haskell, 73 bytes

```
import Data.List
f l=snd$minimum[(abs$sum l-2*sum s,s)|s<-subsequences l]

```

Outputs a list of items in one hand. The missing elements go to the other hand.

Usage: `f [7,7,7,10,11]` -\> `[7,7,7]`

For all subsequences `s` of the input list `l` calculate the absolute value of the weight difference between `s` and the missing elements of `l`. Find the minimum.
> 2 votes

# Answer
## Haskell, 51 bytes

```
f l=snd$minimum$((,)=<<abs.sum)<$>mapM(\x->[x,-x])l

```

Output format is that left-hand weights are positive and right-hand weights are negative.

```
>> f [2,1,5,4,7]
[-2,-1,5,4,-7]

```

To generate every possible split, we use `mapM(\x->[x,-x])l` to negate every possible subset of elements. Then, `((,)=<<abs.sum)` labels each one with its absolute sum and `snd$minimum$((,)=<<abs.sum)` take the smallest-labeled element.

I couldn't get it point-free because of type-checking issues.
> 1 votes

# Answer
# Axiom, 292 bytes

```
R==>reduce;F(b,c)==>for i in 1..#b repeat c;p(a)==(#a=0=>[a];w:=a.1;s:=p delete(a,1);v:=copy s;F(s,s.i:=concat([w],s.i));concat(v,s));m(a)==(#a=0=>[[0],a];#a=1=>[a,a];b:=p(a);r:=[a.1];v:=R(+,a)quo 2;m:=abs(v-a.1);F(b,(b.i=[]=>1;d:=abs(v-R(+,b.i));d<m=>(m:=d;r:=copy b.i);m=0=>break));[[m],r])

```

A brute force application. This would minimize the set

```
A={abs(reduce(+,a)quo 2-reduce(+,x))|x in powerSet(a)}

```

because if is minimum

```
y=min(A)=abs(reduce(+,a)quo 2-reduce(+,r))

```

it would be minimum too

```
2*y=abs(reduce(+,a)-2*reduce(+,r))=abs((reduce(+,a)-reduce(+,r))-reduce(+,r))

```

where (reduce(+,a)-reduce(+,r)) and reduce(+,r) are the 2 weight of two bags.( But that last formula not find to me the minimum, in the application). Ungolf and results

```
-- Return the PowerSet or the Powerlist of a
powerSet(a)==
    #a=0=>[a]
    p:=a.1;s:=powerSet delete(a,1);v:=copy s
    for i in 1..#s repeat s.i:=concat([p],s.i)
    concat(v,s)

-- Return one [[m], r] where
-- r is one set or list with reduce(+,r)=min{abs(reduce(+,a)quo 2-reudece(+,x))|x in powerSet(a)}
-- and m=abs(reduce(+,a) quo 2-reduce(+,r))
-- because each of two part, has to have the same weight
MinDiff(a)==
    #a=0=>[[0],a]
    #a=1=>[ a ,a]
    b:=powerSet(a)
    r:=[a.1];v:=reduce(+,a) quo 2;m:=abs(v-a.1)
    for i in 1..#b repeat
        b.i=[]=>1
        k:=reduce(+,b.i)
        d:=abs(v-k)
        d<m=>(m:=d;r:=copy b.i)
        m=0=>break
    [[m],r]

--Lista random di n elmenti, casuali compresi tra "a" e "b"
randList(n:PI,a:INT,b:INT):List INT==
    r:List INT:=[]
    a>b =>r
    d:=1+b-a
    for i in 1..n repeat
          r:=concat(r,a+random(d)$INT)
    r

(5) -> a:=randList(12,1,10000)
   (5)  [8723,1014,2085,5498,2855,1121,9834,326,7416,6025,4852,7905]
                                                       Type: List Integer
(6) -> m(a)
   (6)  [[1],[1014,2085,5498,1121,326,6025,4852,7905]]
                                                  Type: List List Integer
(7) -> x:=reduce(+,m(a).2);[x,reduce(+,a)-x]
   (7)  [28826,28828]
                                               Type: List PositiveInteger
(8) -> m([1,2,3,4])
   (8)  [[0],[2,3]]
                                                  Type: List List Integer
(9) -> m([10,1,2,3,4])
   (9)  [[0],[10]]
                                                  Type: List List Integer
(10) -> m([40,20,80,50,100,33,2])
   (10)  [[0],[40,20,100,2]]
                                                  Type: List List Integer
(11) -> m([7,7,7,10,11])
   (11)  [[0],[10,11]]
                                                  Type: List List Integer

```
> 1 votes

# Answer
# Vyxal, 7 bytes

```
ṗµ∑;Iht

```

Try it Online!

Port of isaacg's Pyth answer, go upvote that

```
ṗ       # Subsets
 µ∑;    # Sorted by sum
    I   # Cut in half
     ht # Get the second element of the first half

```
> 1 votes

# Answer
# R (234)

a longer and slower solution with R.

Function:

```
function(p){m=sum(p)/2;n=100;L=length(p);a=matrix(0,n,L+2);for(i in 1:n){idx=sample(1:L,L);a[i,1:L]=idx;j=1;while(sum(p[idx[1:j]])<=m){a[i,L+1]=abs(sum(p[idx[1:j]])-m);a[i,L+2]=j;j=j+1}};b=which.min(a[,L+1]);print(p[a[b,1:a[b,L+2]]])}

```

Expected input - vector with the weights.
Expected output - vector with the weights for one hand.

Example

```
> Weight(c(1,2,3,4))
[1] 3 2
> Weight(c(10,1,2,3,4))
[1] 10
> Weight(c(40,20,80,50,100,33,2))
[1] 100  40  20  2
> Weight(c(7,7,7,10,11))
[1] 7 7 7

```

Human readable code version:

```
weight <- function(input) {
  mid <- sum(input)/2
  n <- 100
  input_Length <- length(input)
  answers <- matrix(0, n, input_Length+2)
  for(i in 1:n){
    idx <- sample(1:input_Length, input_Length)
    answers[i, 1:input_Length ] <- idx
    j <- 1
    while(sum(input[idx[1:j]]) <= mid){
        answers[i, input_Length+1] <- abs(sum(input[idx[1:j]]) - mid)
        answers[i, input_Length+2] <- j
        j <- j + 1
    }
  }
  best_line <- which.min(answers[, input_Length+1])
  print(paste("weight diference: ", answers[best_line, input_Length+1]))
  print(input[answers[best_line, 1:answers[best_line, input_Length+2]]])
}

```
> 0 votes

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


title: The Letter E with E

text:
# Question
Title: The Letter E with E
Your task is to display the below letter "E" shaped ASCII art, given five inputs.

Examples:

Input: `7,2,+,|,-` (Note: You don't have to follow this exact input format, and if you don't use it, then you must explain how your own input format works)

Explanation:

* `7` *total width, including the left and right edge characters.*
* `2` *Number of vertical characters.*
* `+` *The character that should display at the edges.*
* `|` *The character that should display vertically between the edges.*
* `-` *The character that should display horizontally.*

Output of the above example:

```
+-----+
|
|
+-----+
|
|
+-----+

```

---

---

Other examples:

Input: `7,2,@,|,-`

Output:

```
@-----@
|
|
@-----@
|
|
@-----@

```

---

---

Input: `7,2,+,|,#`

Output:

```
+#####+
|
|
+#####+
|
|
+#####+

```

---

---

Input: `8,3,+,|,#`

Output:

```
+######+
|
|
|
+######+
|
|
|
+######+

```

---

---

Input: `8,3,+,@,#`

Output:

```
+######+
@
@
@
+######+
@
@
@
+######+

```

---

---

Input: `9,4,^,$,!`

Output:

```
^!!!!!!!^
$
$
$
$
^!!!!!!!^
$
$
$
$
^!!!!!!!^

```

---

---

Cheating and standard loopholes are not allowed.

Your code must not print anything to STDERR.

Your code may accept any character encoding you choose as the input, but any character encoding you choose must, as a minimum, support all the 95 printable ASCII characters.

The shortest code, in bytes, that completes this challenge successfully, is the winning code.

### Leaderboard

```
var QUESTION_ID=92138,OVERRIDE_USER=58717;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&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(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.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(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# 05AB1E, ~~16~~ 14 bytes

```
Í×s.ø©|`×`»D®»

```

**Explanation**

```
Í×                  # create a string of the correct nr of horizontal chars
  s.ø               # add the corner char on both sides
     ©              # save in register while keeping it on the stack
      |`            # push the remaining inputs to the top of the stack
        ×`          # push the correct nr of vertical chars on the stack
          »         # join on newline (joining the top vertical and horizontal sections)
           D        # duplicate this
            ®       # push the horizontal part again
             »      # join everything on newline

```

Try it online!

Saved 4 bytes thanks to Adnan.
> 6 votes

# Answer
# Python, ~~53~~ ~~51~~ 55 Bytes

```
lambda a,b,c,d,e:d.join("\n"*-~b).join([c+e*(a-2)+c]*3)

```

*+4 Bytes thanks to @nimi*

anonymous lambda function, to call it, write `f=` before it. Example:

```
>>> print f(4,1,"€","|","-")
€--€
|
€--€
|
€--€

```

## alternative, 53 Bytes

```
lambda a,b,c,d,e:((c+e*a+c+"\n"+(d+"\n")*b)*3)[:-b*2]

```

## old version with the special case of no input, ~~69~~ ~~65~~ 63 Bytes

yay to changing the requirements mid-challenge...

```
lambda a=1,b=1,(c,d,e)="+|-":d.join("\n"*-~b).join([c+e*a+c]*3)

```
> 6 votes

# Answer
# C, ~~167~~ ~~161~~ 159 bytes

Yeah.

```
#define p putchar
i,j;g(a,c,e){p(c);for(i=2;i++<a;)p(e);p(c);p(10);}h(b,d){for(i=0;i++<b;){p(d);p(10);}}f(a,b,c,d,e){g(a,c,e);h(b,d);g(a,c,e);h(b,d);g(a,c,e);}

```

Try it on Ideone, with some test cases
> 4 votes

# Answer
## Javascript (ES6), 64 bytes

```
(h,v,e,V,H)=>(v=(h=e+H.repeat(h-2)+e)+`
${V}`.repeat(v)+`
`)+v+h

```

### Example

```
let f =
(h,v,e,V,H)=>(v=(h=e+H.repeat(h-2)+e)+`
${V}`.repeat(v)+`
`)+v+h

console.log(f(8,3,'+','@','#'))
```
> 3 votes

# Answer
# Ruby, ~~54~~ ~~45~~ 42 bytes

```
->x,y,c,v,h{[c+h*~-~-x+c+$/]*3*((v+$/)*y)}

```

It's an anonymous function that takes the different part of the input as separate parameters and returns the result as a complete string.

For example,

```
f=->x,y,c,v,h{[c+h*~-~-x+c+$/]*3*((v+$/)*y)}
puts f[6, 2, 'Ø', 'V', '>']

```

prints

```
Ø>>>>Ø
V
V
Ø>>>>Ø
V
V
Ø>>>>Ø

```
> 3 votes

# Answer
## Pyke, ~~16~~ 15 bytes

```
*2mtz:zn+Q*' +D

```

Try it here!
> 3 votes

# Answer
# , 18 bytes

```
älJxxÀPjddÀpkäGYGp

```

Try it online!
> 3 votes

# Answer
# R, 80 bytes

Pretty repetitive :

```
function(h,v,a,b,c)cat(t<-c(a,rep(c,h),a,"\n"),d<-rep(c(b,"\n"),v),t,d,t,sep="")

```

**Ungolfed :**

```
function(h,v,a,b,c)

cat(t<-c(a,rep(c,h),a,"\n"),
    d<-rep(c(b,"\n"),v),
    t,d,t,
    sep="")

```
> 3 votes

# Answer
## Perl, 40 + 1 (`-n`) = 41 bytes

*Thanks to @Ton Hospel for saving 14 bytes and allowing the program to work with entry greater than 10.*

```
/.$/;$,=$/.<>x<>;say+($`.$&x(<>-2).$`)x3

```

Need `-n` as well as `-E` (or `-M5.010`) to run. For instance :

```
perl -nE '/.$/;$,=$/.<>x<>;say+($`.$&x(<>-2).$`)x3' <<< '^$
!
4
9'

```
> 2 votes

# Answer
# MATL, 15 bytes

*Thanks to @muddyfish for a correction*

```
2-Y"yv!iiY"!yyy

```

Try it online!

### Explanation

The stack contents after each step are indicated for clarity, using the first example in the challenge.

```
2-    % Implicitly input number of repetitions of the char of the horizontal line.
      % Subtract 2
      %   STACK: 5
Y"    % Implicitly input char of the horizontal line. Apply run-length decoding
      %   STACK: '-----' (string)
y     % Implicitly input (from below) the char of the corners. Duplicate onto the top
      %   STACK: '+', '-----', '+'
v!    % Concatenate all the stack horizontally. We now have the horizontal line
      % including the corners
      %   STACK: '+-----+'
iiY"  % Take two inputs: char of the vertical line and number of repetitions
      %   STACK: '+-----+', '||'
!     % Transpose. This tranforms the string into a vertical char array, which
      % gives the vertical line
      %   STACK: '+-----+', ['|';'|'] (vertical char array)
y     % Duplicate from below: this pushes a new copy of the horizontal line
      % onto the top of the stack
      %   STACK: '+-----+', ['|';'|'], '+-----+'
y     % Duplicate from below: this pushes a new copy of the vertical line
      % onto the top of the stack
      %   STACK: '+-----+', ['|';'|'], '+-----+', ['|';'|'],
y     % Duplicate from below: this pushes a new copy of the horizontal line
      % onto the top of the stack
      %   STACK: '+-----+', ['|';'|'], '+-----+', ['|';'|'], '+-----+'
      % Implicitly display

```
> 2 votes

# Answer
# Pyth, 19 bytes

```
jP*3,++Jw*-E2wJj*Ew

```

A program that takes newline-separated input on STDIN of the corner character, number of horizontal characters, horizontal character, number of vertical characters and the vertical character, and prints the result.

Try it online

**How it works**

```
jP*3,++Jw*-E2wJj*Ew  Program.
       Jw            Get the corner character. Store in J
           E         Get the number of horizontal characters
          - 2        -2
         *   w       Get the horizontal character and repeat it that many times
      +              Add J at the beginning of that
     +         J     and at the end
                 E   Get the number of vertical characters
                * w  Get the vertical character and repeat it that many times
               j     Join the above on newlines
    ,                Construct a 2-element list from the horizontal and vertical strings
  *3                 Repeat it 3 times
 P                   Everything except the last element
j                    Join the above on newlines
                     Implicitly print

```
> 2 votes

# Answer
# MATLAB, ~~95 92 91 85~~ 81 bytes

MATLAB 'E' function. (edit: doesn't work on Octave)

```
function a=e(n,m,c,h,v);a(1:n)=h;a=[c a c];a(2:m+1,1)=v;a=[a;a;a];a=a(1:3+2*m,:);

```

And ungolfed:

```
function a=e(n,m,c,h,v); %Declare the function
a(1:n)=h;                %Initialise return with top line excluding the corners
a=[c a c];               %Then add corner pieces
a(2:m+1,1)=v;            %Next add the first vertical part
a=[a;a;a];               %Repeat three times vertically to get an E with a tail
a=a(1:3+2*m,:);          %And then lop off the tail

```

The function should be called like:

```
e(5,2,'*','-','|')

```

Which will return:

```
+-----+
|
|
+-----+
|
|
+-----+

```

This can probably be simplified a bit, I'll keep working on it. I don't like having the entire function declaration to get the input, so will see if I can improve that.

---

* Saved 3 bytes by simplifying generation of first line to first make the line without corners and then add the corners as this reduces the number of times indexing is required.
* Another byte saved by starting with the first corner.
* 6 more bytes by replacing `repmat(a,3,1)` call with `[a;a;a]`.
* Saved 4 bytes by using `a` without specific initialisation (it's already declared in the function declaration) - thanks @LuisMendo
> 2 votes

# Answer
# Dyalog APL, ~~31~~ 29 bytes

Prompts for horizontal-character, width, junction-character, height, vertical-character – in that order.

```
h↓⊃⍪/3/⊂↑(⍞⍴⍨h←⎕),⊂⍞{∊⍺⍵⍺}⎕⍴⍞

```

`⎕⍴⍞` input-horizontal-character and repeat input-width times ( below)

`⍞{`...`}` input-junction-character which will be  in the function...

`∊⍺⍵⍺` flatten \[\[junction\],\[horizontals\],\[junction\]\]

encapsulate so it can be part of a list

`(`...`),` prepend...

`h←⎕` input-height

`⍞⍴⍨` input-vertical-character and repeat it that many times

make the list of strings into a character table

encapsulate (so it can be repeated as a whole)

`3/` repeat it three times

```
╻  ╻  ╻
┗━ ┗━ ┗━

```

`⍪/` concatenate the three pieces vertically

```
╻
┣━
┣━
┗━

```

(this encapsulates them too, so we need to...)

remove the encapsulation

`h↓` drop the first **h** (rows)

```
┏━
┣━
┗━

```

TryAPL online!
> 2 votes

# Answer
# Java 7, ~~205~~ 129 bytes

```
String c(int w,int h,String a,char b,char c){String r=a,n="\n",l="";for(;w-->2;r+=c);r+=a+n;for(;h-->0;l+=b+n);return r+l+r+l+r;}

```

*-76 bytes thanks to an anonymous stranger.<br>PS: Don't go edit other people's posts next time. If you have something to golf please leave it as a comment, or if it's using a completely different approach you could make your own answer. Still thanks for golfing away all these bytes, though - whoever you are..*

**Ungolfed & test cases:**

Try it here.

```
class M {
    static String c(int w, int h, String a, char b, char c){
        String r = a,
               n = "\n",
               l = "";
        for(; w-- > 2; r += c);
        r += a+n;
        for( ;h-- > 0; l += b+n);
        return r+l+r+l+r;
    }

    public static void main(String[] a) {
        System.out.print(c(7, 2, "+", '|', '-'));
        System.out.print(c(9, 4, "?", '¡', '¿'));
    }
}

```

**Output:**

```
+-----+
|
|
+-----+
|
|
+-----+

?¿¿¿¿¿¿¿?
¡
¡
¡
¡
?¿¿¿¿¿¿¿?
¡
¡
¡
¡
?¿¿¿¿¿¿¿?

```
> 2 votes

# Answer
## C, 130 bytes

```
#define p putchar
#define E for(o=0;o++<O;p(10))p(S);
#define W for(p(P),D=0;D++<C-2;)p(_);p(P);p(10);
f(C,O,P,S,_,D,o){W E W E W}

```

### Usage:

```
main(){f(7,2,'+','|','-');}

```

**Output**

```
+-----+
|
|
+-----+
|
|
+-----+

```
> 2 votes

# Answer
# C#, 108 bytes

```
(m,n,e,v,h)=>{string x=e+new string(h,m-2)+e+"\n",y=new string(v,n).Replace(v+"",v+"\n");return x+y+x+y+x;};

```

Anonymous function which generates each horizontal and vertical line and builds the final output.

Ungolfed function:

```
(m,n,e,v,h)=>
{
    string x = e + new string(h, m - 2) + e + "\n",
        y = new string(v, n).Replace(v + "", v + "\n");
    return x + y + x + y + x;
};

```

Full program with test cases:

```
using System;

namespace LetterEWithoutE
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,int,char,char,char,string>f= (m,n,e,v,h)=>{string x=e+new string(h,m-2)+e+"\n",y=new string(v,n).Replace(v+"",v+"\n");return x+y+x+y+x;};

            Console.WriteLine(f(7,2,'+','|','-'));
            Console.WriteLine(f(7,2,'@','|','-'));
            Console.WriteLine(f(7,2,'@','|','#'));
            Console.WriteLine(f(8,3,'+','|','#'));
            Console.WriteLine(f(8,3,'+','@','#'));
            Console.WriteLine(f(9,4,'^','$','!'));
        }
    }
}

```
> 2 votes

# Answer
# Python 3, 60 bytes

**A Function**

```
def p(a,b,c,d,e):q=c+e*(a-2)+c;return(q+'\n'+(d+'\n')*b)*2+q

```

**Test Case**

```
>>> print(p(8,2,'+','|','#'))
+######+
|
|
+######+
|
|
+######+

```
> 1 votes

# Answer
# Bash + coreutils, 105 bytes

```
printf -- "$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)`%.0s\n" {1..3}|sed -n 1,$(($2*2+3))p

```

Assuming the file within which this is stored is named `A.sh`, the usage would be:

```
bash A.sh <Horizontal Segment Length w/out Edge Chars> <Vertical Segment Length> '<Left/Right Edge Char>' '<Char Between Edges>' '<Vertical Char>'

```

The `--` are needed, just in case one of the character inputs happens to be a `-`, and `printf` apparently doesn't handle dashes in the beginning of a string very nice without the double-dashes.

## Explanation

Assuming that the input is `5 2 + * |`...

1. `$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)``

Create the first horizontal segment and vertical segment all together. This would result in:

```
+*****+
|
|

```
2. `printf -- "$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)`%.0s\n" {1..3}`

Repeat the previously created part `3` times over. This now results in:

```
+*****+
|
|
+*****+
|
|
+*****+
|
|

```
3. `printf -- "$3`printf -- "$4%.0s" $(seq $1)`$3`printf "\n$5%.0s" $(seq $2)`%.0s\n" {1..3}|sed -n 1,$(($2*2+3))p`

Finally pipe the previous output to `sed` to get rid of the last 2 line segments by only outputting the first `<Vertical Segment Length>*2+3` lines of the `E`. We finally get the `E` we want:

```
+*****+
|
|
+*****+
|
|
+*****+

```
> 1 votes

# Answer
## PowerShell v2+, ~~60~~ 59 bytes

```
param($a,$b,$c,$d,$e)(,($x="$c$($e*($a-2))$c")+,$d*$b)*2;$x

```

Takes input as individual command-line arguments. Constructs the horizontal string, stores that into `$x` for use later, then forms that into an array with the comma-operator `,`. Performs array concatenation (i.e., adding elements to the end) of `$d` formulated into an array of `$b` elements. That, in turn, is formulated into an array of two elements with another comma operator, and is left on the pipeline. Then, the horizontal `$x` is left on the pipeline. Abuses the default formatting of `Write-Output` to put a newline between elements.

### Example

```
PS C:\Tools\Scripts\golfing> .\the-letter-e-without-e.ps1 5 3 "z" "v" "d"
zdddz
v
v
v
zdddz
v
v
v
zdddz

```
> 1 votes

# Answer
# Brainf\*ck, 147 bytes

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

```

Takes input from stdin as first 5 characters entered. The first two are have 48 subtracted from their ASCII code so 0-9 behave as expected. For numbers \> 9, add 48 to the number and use the corresponding character. The other three characters are as specified in the challenge.

I'm sure it's not the optimal solution but life is too short to golf brainf\*ck.

With comments:

```
[
    Input: number number corner vertical horizontal
    Numbers are single digits; add 48 and use the ASCII character corresponding
    to the number you want for numbers > 9.
    First number is the number of characters across. Second is the number down.

    Layout: {first number-2} {second number} {temp} {a} {b} {c}
]

,>,>++++++++[<------<------>>-]<<-->>>,>,>,
now we should have the first five cells with the specified layout
the 6th will hold 3 as a counter and the 7th 2 and the 8th 10 '\n'

>+++>++>++++++++++<<
[  while the 6th cell is not 0
    -
    <<<.    print corner
    <<<[->>+>>>.<<<<<]  print horizontal characters
    >>[-<<+>>]         copy temp back to 1st cell
    >.>>>>>.           print corner and newline
    <
    [ If the second counter is not zero
        -
        <<<<<<[->+>>.>>>>.<<<<<<<]  print vertical and newline n times
        >[<+>-]           copy temp back to 2nd cell
    ]
    >>>>
]

```

Example run:

```
sean@SEANSBOX:~/Dropbox/Code/BF$ ./bf E.b
94^$!
^!!!!!!!^
$
$
$
$
^!!!!!!!^
$
$
$
$
^!!!!!!!^

```
> 1 votes

# Answer
## Lua(5.2), 144 bytes

```
k,a,p,q=loadstring,arg,io.write,print l,d=k"for i=3,a[1]do p(a[5])end",k"for i=1,a[2]do q(a[4])end"b=a[3]p(b)l()q(b)d()p(b)l()q(b)d()p(b)l()p(b)

```

Try it online! (Coding Ground)

It should output something like that right now:

```
+@@@@@+
l
l
+@@@@@+
l
l
+@@@@@+

```

Own input: `7 2 + l @`

You can change the input in project-\>compile options and there change the values, each value as in the example but not separated by commas but by spaces.
> 1 votes

# Answer
# PHP, 97 bytes

```
list(,$w,$h,$c,$v,$r)=$argv;echo$b=str_pad($a=str_pad($c,++$w,$r)."$c\n",--$h*2+$w,"$v\n"),$b,$a;

```

no loop, only builtins.

Run with `php -r '<code>' <parameters>`.
> 1 votes

# Answer
# Vyxal, 10 bytes

```
⇩*+Ǐ∇εJǏ∞⁋

```

Try it Online!

```
 *         # Repeat the horizontal character...
⇩          # Horizontal distance - 2 times
  +Ǐ       # Prepend and append the corner character
    ∇ε     # Push the vertical character repeated by the amount
      J    # Append that to the line
       Ǐ   # Append the first line
        ∞  # Mirror
         ⁋ # Join by newlines

```
> 1 votes

# Answer
**Racket 124 bytes**

```
(λ(w h a b c)(for((i 3))(display a)(for((i w))(display c))(display a)(when(< i 2)(displayln "")(for((j h))(displayln b)))))

```

More readable form:

```
(define(f w h a b c)
  (for((i 3))
    (display a)
    (for((i w))
      (display c))
    (display a)
    (when(< i 2)
      (displayln "")
      (for((j h))
        (displayln b)))))

```

Testing:

```
(f 7 2 "+" "|" "-" )

+-------+
|
|
+-------+
|
|
+-------+

```
> 0 votes

# Answer
# PHP, 94 Bytes

```
<?list($v,$h,$p,$d,$r)=$_GET[a];for($h++;$i<=2*$h;)echo$i++%$h?$d:str_pad($p,$v-1,$r).$p,"\n";

```

Input format an array in the same order as the suggested string
> 0 votes

# Answer
# C++, 121 Bytes

```
#import<string>
#import<iostream>
#define f(w,h,C,W,H){std::string s(w,W),t;s=C+s+C+"\n";for(int i=h;i--;)t=t+H+"\n";std::cout<<s+t+s+t+s;}

```

Ungolfed:

```
#import<string>
#import<iostream>
#define f(w,h,C,W,H){
    std::string s(w,W),t;  //define two strings, one empty, one with horizontal characters
    s = C+s+C+"\n";        //assemble a horizontal bar
    for(int i=h;i--;)
        t=t+H+"\n";        //assemble a vertical bar
    std::cout<<s+t+s+t+s;  //print
}

```

In C++ its not allowed to declare functions without type as in C. But macros that behave just like a function are totally possible. Note also that the ungolfed version will not compile until you add a "\\" to each but the last line of the macro. You might save two additional bytes by removing the {}, but then you can't use the macro twice in a row.

Usage:

```
int main() {
    f(4,2,'+','-','|')
    f(2,1,'@','#','i')
    return 0;
}

```

Output:

```
+----+
|
|
+----+
|
|
+----+
@##@
i
@##@
i
@##@

```

Try it online
> 0 votes

# Answer
# CJam, 23 bytes

```
riri)N*r2*\r*\@r**a3*\*

```

Try it online!

The input is is in the given order, but should be space separated instead of using a comma. Some of the difficulty is getting the input the right order for CJam's join operation `*`; for comparison rearranging the input in could save 4 bytes.

If the inputs are dubbed `A B C D E` then the program works something like this:

```
ri     e# get A as integer
ri)N*  e# create B+1 newlines
r2*    e# create 2 Cs
\r*    e# join newlines with D (hereafter ND)
\@     e# bring A & Cs to the front
r*     e# create A Es
*      e# join, puts Es between Cs (hereafter CEC)
a3*    e# makes 3 copies of CEC strings
\*     e# join, puts NDs between CECs

```
> 0 votes

# Answer
## QBIC, 44 bytes

```
::;;;X=A[q,a-2|X=X+C]X=X+A ?X[1,2|[1,b|?B]?X

```

Explanation

```
::;;;                 Get the input parameters, 2 numbers and 3 strings
X=A[q,a-2|X=X+C]X=X+A Build the horizontal string: The corner string, x-2 times the filler string and another corner
?X                    Print the horizontal string
[1,2|                 Do the next thing twice
[1,b|?B]?X            Print the right number of vertical strings, then the horizontal string.

```
> 0 votes

# Answer
# Japt `-R`, 18 bytes

Can't seem to do better than 18 :\

```
5õ_gVÇXÃ·¸pW²ùUY é

```

Try it

```
[W²ùUY é XpV y]ê ê

```

Try it
> 0 votes

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


# Question
Title: What is the average of n, the closest prime to n, the square of n and the closest Fibonacci number to n?
This is a math problem which takes quite many things into question, making it rather challenging, and as you might have guessed, it's a code golf, so it should be as short as possible as well.

The **input**, \\$n\\$, is any *integer* number (should at least support integers, but needn't be limited to). The **output** is the *average* of:

* \\$n\\$
* The square of \\$n\\$, \\$n^2\\$
* The closest prime number to \\$n\\$, \\$p\\$
* The closest number to \\$n\\$ in the Fibonacci sequence, \\$f\\$

Shortly, the program should **print to the standard output channel** the *result* of $$\frac {n + n^2 + p + f} 4$$.

You *don't* have to care about possible overflows etc. Normal floating point precision is also ok.

The way the input is given is completely up to you. Shortest program (in characters) wins, as always with code golfs.

In the case a tie occurs when you are looking for the closest, choose one of the following:

1. Go up
2. Go down
3. Choose one randomly

# Answer
**Python 160 Chars**

```
p=lambda n:any(n%x<1for x in range(2,n))
N=input()
a=0;b=1
while b<N:a,b=b,a+b
c=d=N
while p(c)and p(d):c-=1;d+=1
print (N+N*N+[b,a][2*N-a-b<0]+[c,d][p(c)])/4.0

```

A little explanation about the closestFib part:

> When the while loop ends a is smaller than N and b is either equal to or greater than N. Now the `[b,a][2*N-a-b<0]` part. Look at it as \[b,a\]\[(N-a)-(b-N)\]. (N-a) is the difference between N and a and similarly (b-N) the difference between b and N. If the difference between these two is less than 0 it means a is closer to N and vice-versa.
> 9 votes

# Answer
## GolfScript, 59 characters

```
~:N..*.,2>{:P{(.P\%}do(!},{{N-.*}$0=}:C~[1.{.@+.N<}do]C+++4/

```

This script does not fulfill some of the requirements:

* It only works correctly for inputs `n >= 2`, otherwise it crashes.
* The output is truncated to an integer.
* Terrible performance for any moderately large `n`

A brief walkthrough of the code:

1. `~:N..*` The input is stored in N, and we push both `n` and the square `n*n` right away.
2. `.,2>` We will generate a list of primes by filtering the array `[2..n*n]`. We use our previous calculation of `n*n` as a (very bad!) upper bound for finding a prime that is larger than n.
3. `{:P{(.P\%}do(!},` Our previous array is filtered by trial division. Each integer P is tested against every integer \[P-1..1\].
4. `{{N-.*}$0=}:C~` Sorts the previous array based on the distance to `n`, and grabs the first element. Now we have the closest prime.
5. `[1.{.@+.N<}do]C` We generate Fibonnacis until we get one greater than `n`. Fortunately, this algorithm naturally keeps track of the previous Fibonnaci, so we throw them both in an array and use our earlier distance sort. Now we have the closest Fibonnaci.
6. `+++4/` Average. Note that GolfScript doesn't have support for floats, so the result is truncated.

## GolfScript, 81 characters

Here is a variant that fulfills all of the requirements.

```
~:N..*2N*,3,|2,^{:P{(.P\%}do(!},{{N-.*}$0=}:C~[0.1{.@+.N<}do]C+++100:E*4/.E/'.'@E%

```

To ensure proper behavior for `n<2`, I avoid `2<` (crashes when the array is small), and instead use `3,|2,^`. This makes sure the prime candidate array is just `[2]` when `n < 2`. I changed the upper bound for the next prime from `n*n` to `2*n` (Bertrand's postulate). Also, 0 is considered a Fibonnaci number. The result is calculated in fixed point math at the end. Interestingly, it seems like the result is always in fourths (0, .25, .5, .75), so I hope 2 decimal places of precision is sufficient.

My first crack at using GolfScript, I'm sure there is room for improvement!
> 7 votes

# Answer
# JavaScript, 190

```
function n(n)
{z=i(n)?n:0
for(x=y=n;!z;x--,y++)z=i(x)?x:i(y)?y:0
for(a=b=1;b<n;c=a+b,a=b,b=c);
return(n+n*n+(2*n-a-b<0?a:b)+z)/4}
function i(n)
{for(j=2;j<n;j++)
if(!(n%j))return 0
return 1}

```

\[257\]

```
function n(n)
{return(n+n*n+p(n)+f(n))/4}
function p(n)
{if(i(n))return n
for(a=b=n;;a--,b++){if(i(a))return a
if(i(b))return b}}
function i(n)
{for(j=2;j<n;j++)
if(!(n%j))return 0
return 1}
function f(n)
{for(a=b=1;b<n;c=a+b,a=b,b=c);
return 2*n-a-b<0?a:b}

```

Uncompressed:

```
function closest( a, b, c )
{
  return 2*a-b-c < 0 ? b : c;
}

function closestPrime( n )
{
  a=b=n;
  if (isPrime( n ) ) return n;
  while ( true )
  {
    a-=1;
    b+=1;
    if (isPrime(a))return a;
    if (isPrime(b))return b;
  }
}

function isPrime( n )
{
  for (i=2;i<n;i++)
  {
    if ( !( n % i ) ) return false;
  }
  return true;
}

function closestFib( n )
{
  for(fib1=0,fib2=1;fib2<n;fib3=fib1+fib2,fib1=fib2,fib2=fib3);
  return closest( n, fib1, fib2 );
}

function navg(n)
{
  n2 = n*n;
  np = closestPrime( n );
  nf = closestFib( n );
  return ( n + n2 + np + nf ) / 4;
}

```
> 3 votes

# Answer
# Mathematica, ~~70~~ 69 bytes

One byte saved thanks to Sp3000 (sometimes built-ins aren't the best way to go).

```
((n=#)+#^2+(f=#&@@#@Range@Max[1,2n]~Nearest~n&)@Prime+f@Fibonacci)/4&

```

This defines an unnamed function taking an integer and producing the exact mean as a rational number. In the case of ties, the smaller prime/Fibonacci number is chosen.

This is very inefficient for large inputs, because it actually generates the first `2n` primes and Fibonacci numbers before picking the closest.
> 1 votes

# Answer
# Vyxal, ~~18~~ 15 bytes

```
₌∆p²?:ɾ∆f‡?ε∵Wṁ

```

*-3 bytes thanks to emanresu A*

Try it online!

Explanation:

```
₌                # Parallel apply:
 ∆p              #   Nearest prime
   ²             #   Square
    ?            # Push the input
     :           # Duplicate
      ɾ          # Range from 0 to n
       ∆f        # Nth fibonacci number
            ∵    # Minimum by:
         ‡       # A two element lambda that gets
           ε     #   The absolute difference of it's input
          ?      #   And the program's input
              ṁ  # Mean of
             W   # The stack

```
> 1 votes

# Answer
# Q, 119

Not the most efficient.

```
{%[;4]x+(x*x)+((*:)a(&)b=min b:abs x-a:{x,sum -2#x}/[x-2;1 1])+(*:)d(&)e=min e:x-d:(&)1={(min x mod 2_(!)x)}each(!)x+2}

```
> 0 votes

# Answer
# MATLAB 88 Chars

```
C=@(F)(F(abs(F-n)==min(abs(F-n))));(n+n^2+C(primes(n*2))+C(round(1.618.^(1:n)/2.236)))/4

```

n is your integer

Works with non integers, as far as I've tested it works with very large numbers as well, runs pretty damn quickly too.
> 0 votes

# Answer
### Scala 299

```
object F extends App{type I=Int
def f(n:I,b:I=1,a:I=1):I=if(a>=n)if(a-n>n-b)b else a else f(n,a,b+a)
def p(n:I)=(2 to n-1).exists(n%_==0)
def i(n:I,v:I):Int=if(!p(n+v))n+v else i(n+v,v)
val a=readInt
println(({val p=Seq(-1,1).map(i(math.max(a,3),_))
if(a-p(0)>p(1)-a)p(1)else p(0)}+f(a)+a+a*a)/4.0)}

```

Test and invocation:

```
a  a² nP(a) nF  ∑   /4.0
------------------------
-2  4   2   1   5   1.25
-1  1   2   1   3   0.75
0   0   2   1   3   0.75
1   1   2   1   5   1.25
2   4   2   2   10  2.5
3   9   2   3   17  4.25
4   16  3   5   28  7.0
5   25  3   5   38  9.5

```

The question talks about `any Integer` but the problem isn't that interesting for values below 0. However - how do we start? At 0? At 1? And what is the next prime for 11? 11 itself?

The idea to allow the next bigger or lower in case of a tie is bad, because it makes comparing needless difficult. If your results differ, they can have chosen the other fib, the other prime, the other fib and the other prime, or yours are wrong, or the result of the other person is wrong, or it is a combination: different choice, but wrong although, maybe both wrong.
> 0 votes

# Answer
# Jelly, 19 bytes

```
ÆnÆRạÞ+ÆḞ€ạÞ$Ḣ++²÷4

```

Try it online!

## How it works

```
ÆnÆRạÞ+ÆḞ€ạÞ$Ḣ++²÷4 - Main link. Takes N on the left
Æn                  - Get the next prime after N
  ÆR                - Primes up to this
     Þ              - Sort by:
    ạ               -   Absolute difference with N
                      This moves the smallest, closest prime to N to the front, p

            $       - Last 2 links as a monad f(N):
         €          -   For each 1 ≤ i ≤ N:
       ÆḞ           -     Get the ith Fibonacci number
          ạÞ        -   Sort by abs diff with N
                      This moves the smallest, closest Fib to N to the front, f

      +             - Add element-wise. The first element will be p+f
             Ḣ      - Extract p+f
              +     - Add N
                ²   - N²
               +    - Add N². We now have N+N²+p+f
                 ÷4 - Divide by 4

```
> 0 votes

# Answer
# Haskell, 150 bytes

```
import Data.List
f n=print$let q=head.sortOn(abs.(n-)).take(1+n^2);z=1:zipWith(+)z(1:z)in(read$show$q[p|p<-[2..],all((>0).mod p)[2..p-1]]+q z+n+n^2)/4

```

Try it online!
> 0 votes

# Answer
# Japt, 24 bytes

```
+²+UÆMgXÃñaU Î+_j}c+U)*¼

```

Try it
> 0 votes

---
Tags: code-golf, math, primes, fibonacci
---