title: Naismith's rule

text:
# Question
Title: Naismith's rule
Naismith's rule helps to work out the length of time needed for a walk or hike, given the distance and ascent.

Given a non-empty list of the altitude at points evenly spaced along a path and the total distance of that path in metres, you should calculate the time needed according to Naismith's rule.

Naismith's rule is that you should allow one hour for every five kilometres, plus an additional hour for every 600 metres of ascent.

Input must be taken in metres, which is guaranteed to consist of non-negative integers, and output should consistently be either hours or minutes (but not both), and must be able to give decimal numbers where applicable (floating point inaccuracies are OK).

For example, given:

```
[100, 200, 400, 200, 700, 400], 5000

```

For the first two elements `[100, 200]` you have 100 metres of ascent which is 10 minutes. With `[200, 400]` you have 200 metres of ascent which is 20 minutes, `[400, 200]` is not ascending so no time is added for that. `[200, 700]` is 500 metres of ascent which is 50 minutes, and finally `[700, 400]` is not ascending. One extra hour is added for the distance of five kilometres. This totals to **140** minutes or **2.333...** hours.

## Test Cases

```
[0, 600] 2500 -> 1.5 OR 90
[100, 200, 300, 0, 100, 200, 300] 10000 -> 2.8333... OR 170
[40, 5, 35] 1000 -> 0.25 OR 15
[604] 5000 -> 1 OR 60
[10, 10, 10] 2000 -> 0.4 OR 24
[10, 25, 55] 1000 -> 0.275 OR 16.5

```

# Answer
> 6 votes
# ,  ~~44~~  ~~43~~ 42 bytes

```
function(A,D)sum(pmax(0,diff(A)),D*.12)/10

```

Try it online!

*-1 byte by using `pmax` as multiple other answers do*

Takes inputs as `A`scent and `D`istance, and returns the time in minutes.

```
function(A,D)                                 # take Ascent and Distance
                        diff(A)               # take successive differences of ascents
                 pmax(0,       )              # get the positive elements of those
                                 D*.12        # multiply distance by 0.12
             sum(               ,     )       # take the sum of all elements
                                       /10    # and divide by 10, returning the result

```

# Answer
> 3 votes
# JavaScript (ES6), 50 bytes

*Saved 1 byte thanks to Giuseppe's answer (dividing by 10 at the end of the process)*

Takes input as `([altitudes])(distance)`. Returns the time in minutes.

```
a=>d=>a.map(p=n=>d-=(x=p-(p=n))<0&&x,d*=.12)&&d/10

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 15 bytes

```
¥ʒ0›}OT÷s₄;6//+

```

Try it online!

Returns time in minutes.

**Explanation**

```
              + # sum of ...
¥ʒ0›}OT÷        # the sum of positive deltas of the altitude divided by 10
        s₄;6//  # the distance divided by 83.33333333 (500/6, or the amount of meters per minute)

```

# Answer
> 2 votes
## Haskell, ~~47~~ 46 bytes

```
d#l@(_:t)=d/5e3+sum(max 0<$>zipWith(-)t l)/600

```

Returns the time in hours.

Try it online!

# Answer
> 2 votes
# Python 2, ~~62~~ 60 bytes

Saved 2 bytes thanks to ovs.

```
lambda e,d:sum((a-b)*(a>b)for a,b in zip(e[1:],e))*.1+d*.012

```

Try it online!

Returns time in minutes.

```
# add all increasing slope differences together
sum(
    # multiply the difference by 0 if a<b, else by 1
    (a-b)*(a>b)
                # create a list of pairs by index, like [(1,0), (2,1) ...(n, n-1)]
                # then interate thru the pairs where a is the higher indexed item and b is the lower indexed item
                for a,b in zip(e[1:],e)
    )
    # * 60 minutes / 600 meters == .1 min/m
    *.1
    # 60 minutes / 5000 meters = .012 min/m
    +d*.012

```

# Answer
> 2 votes
# Perl 6, ~~45~~ ~~39~~ 37 bytes

*6 bytes saved thanks to Jo King.*

*2 bytes saved thanks to nwellnhof.*

(Thanks to both of them, this no longer looks anything like my original submission :—).)

```
*.&{sum (.skip Z-$_)Xmax 0}/600+*/5e3

```

Try it online!

The first argument is the list with elevations, the second argument is the length of the trek.

The whole thing is a WhateverCode. If an expression is recognized as such, then each `*` is one argument.

So, in `*.&{sum (.skip Z-$_)Xmax 0}/600`, we take the first argument (the first occurence of `*`), and use a block on it with a method-like construct `.&{}`. The block takes one argument (the list), which goes into `$_`, so `.skip` is that list without the first element. We subtract the original array, element by element, from that, using `Z-`. Zipping stops as soon as the shorter list is depleted, which is OK.

We then use the cross product operator `X`. `list X(op) list` creates all possible pairs where the first element is from the left list and the second from the right, and uses the operator `(op)` on them. The result is returned as a Seq (a one-shot list). However, the right list has only one element, 0, so it just does `* max 0`, element by element. That makes sure that we count only ascending parts of the trek. Then we add it up and divide by 600.

Then we add `*/5e3`, where the `*` occurs for the second time, and so it's the second argument, and divide it by 5000. The sum is then the time in hours. (This is more efficient than the time in minutes since we'd need to multiply, and the `*` would need to be separated by a space from the WhateverStar `*`.)

# Answer
> 2 votes
# oK, 21 bytes

```
{y+/0|1_-':x}..1.012*

```

Try it online! Abusing a parsing bug where `.1.012` is the same as `.1 .012`.

```
              .1.012* /a = [0.1 * input[0], 0.012 * input[1]]
{           }.        /function(x=a[0], y=a[1])
      1_-':x          /  a = subtract pairs of elements from x
    0|                /  a = max(a, 0) w/ implicit map
 y+/                  /  y + sum(a)

```

-1 thanks to streester.

# , 23 bytes

```
{.1*(.12*y)++/0|1_-':x}

```

Try it online!

# Answer
> 1 votes
# Jelly, 12 bytes

```
×.12;I}»0÷⁵S

```

Try it online!

-1 thanks to Mr. Xcoder.

# Answer
> 1 votes
# Python 2, 59 bytes

```
lambda a,d:d/5e3+sum(max(0,y-x)/6e2for x,y in zip(a,a[1:]))

```

Try it online!

returns hours as a decimal.

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~21 20~~ 18 bytes

```
.1×.12⊥⎕,-+/0⌊2-/⎕

```

Try it online!

Traditional function taking input (from right to left) as `1st ⎕`=Heights/Depths, `2nd ⎕`=Distance.

Thanks to @ngn for ~~being a wizard one~~ three bytes.

### How it works:

```
.1×.12⊥⎕,-+/0⌊2-/⎕ ⍝ Function;
                 ⎕ ⍝ Append 0 to the heights vector;
              2-/  ⍝ Pairwise (2) differences (-/);
            0⌊     ⍝ Minimum between 0 and the vector's elements;
          +/       ⍝ Sum (yields the negated total height);
         -         ⍝ Subtract from;
   .12⊥⎕,          ⍝ Distance × 0.12;
.1×                ⍝ And divide by 10;

```

# Answer
> 1 votes
# Pyth, 15 bytes

```
c+*E.12s>#0.+QT

```

Full program, expects the set of heights as the first argument, distance as the second. Returns the time in minutes.

Try it online here, or verify all test cases at once here.

```
c+*E.12s>#0.+QT   Implicit: Q=input 1, E=input 2
           .+Q    Take the differences between each height point
        >#0       Filter to remove negative values
       s          Take the sum
  *E.12           Multiply the distance by 0.12
 +                Add the two previous results
c             T   Divide the above by 10, implicit print

```

# Answer
> 0 votes
# Java 8, 89 bytes

```
a->n->{int s=0,p=0,i=a.length;for(;i-->0;p=a[i])s+=(p=p-a[i])>0?p:0;return s/10+n/500*6;}

```

Try it online.

**Explanation:**

```
a->n->{                   // Method with integer-array and integer parameter and integer return-type
  int s=0,                //  Sum-integers, starting at 0
      p=0,                //  Previous integer, starting at 0
  i=a.length;for(;i-->0;  //  Loop `i` backwards over the array
                 ;        //    After every iteration:
                  p=a[i]) //     Set `p` to the current value for the next iteration
    s+=(p=p-a[i])>0?      //   If the previous minus current item is larger than 0:
         p                //    Add that difference to the sum `s`
        :                 //   Else:
         0;               //    Leave the sum the same
   return s/10            //  Return the sum integer-divided by 10
          +n/500*6;}      //  Plus the second input divided by 500 and then multiplied by 6

```

# Answer
> 0 votes
# Japt, 39 bytes

```
0oUl)x@W=UgXÄ -UgX)g ¥É?0:W/#ɘ} +V/(#Ǵ0

```

Try it online!

Likely can be golfed quite a bit more.

# Answer
> 0 votes
# Stax, 17 bytes

```
ü;█y☼òΓ▀ßîP<<╪⌠öß

```

Run and debug it at staxlang.xyz!

Takes all inputs as floats, though this saves a byte only in the unpacked version. Likely improvable; just now returning to code golf, I'm somewhat rusty.

### Unpacked (20 bytes) and explanation:

```
0!012*s:-{0>f{A/m|++
0!012*                  Float literal and multiplication for distance
      s                 Swap top two stack values (altitudes to the top)
       :-               List of deltas
         {0>f           Filter: keep only positive changes
             {A_m       Map: divide all ascents by 10
                 |++    Add these times to that for horizontal travel
                        Implicit print

```

`0!012*s:-{0>f{A_:m|++` works for integral inputs for 21 bytes unpacked and still 17 packed.

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


title: Palindrome polyglot

text:
# Question
Title: Palindrome polyglot
Your task is to write a program that runs in two different languages, and does the following:

* In one language, it palindromizes a given string.
    + Take the string. `abcde`
    + Reverse the string. `edcba`
    + Remove the first character. `dcba`
    + Glue it onto the original string. `abcdedcba`
* In another language, it depalindromizes a given string.
    + Take a string palidromized by the above method. `abcdedcba`
    + Get the characters from the start to the middle. `abcde`

Remember, this is , so the code with the fewest **characters** (not bytes) wins.

## Leaderboards

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 1/Language 2, 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/Python, <s>104</s> <s>101</s> 96 bytes

```

If there 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/C, 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)/Python, 121 bytes

```

```
var QUESTION_ID=98776,OVERRIDE_USER=12537;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 / MATL, ~~10~~ 9 characters

```
9LQ2/)%¹û

```

In 05AB1E this palindromizes. In MATL it depalindromizes.

### Explanation in 05AB1E

This part of the code does nothing (globally):

```
9L    Pushes array [1, 2, ... 9]
Q     Consumes the array, takes the input implicitly, and produces no output
2/    With no further input to take implicitly, this gives no output
)     Wrap stack into an array: gives an empty array
%     Consumes that array and, with no further input to take implicitly, gives no ouput

```

This is the part that does the work:

```
¹     Push input again
û     Palindromize. Implicitly display

```

### Explanation in MATL

This is the part that does the work:

```
9L    Push array [0, 1j]
Q2/   Add 1, divide by two: transforms into [1/2, (1+1j)/2]
)     Use as index into implicit input. [1/2, (1+1j)/2] is interpreted as
      1/2:(end+1)/2, which is rounded to 1:(end+1)/2. So this takes elements
      from first to half, including both. Implicitly display

```

This is ignored:

```
%¹û   Everything after '%' is a comment

```
> 14 votes

# Answer
# 05AB1E / Jelly, 6 characters

Palindromizes in 05AB1E.
Depalindromizes in Jelly.

```
œs2Ḣ¹û

```

Try it in 05AB1E

**05AB1E Explanation**

```
œ       # compute powerset of input
 s      # swap (does nothing)
  2     # push 2
   Ḣ    # does nothing
    ¹û  # palindromize input

```

Try it in Jelly

**Jelly Explanation**

```
œs2     # split input in 2 chunks (first chunk is larger for odd length strings)
   Ḣ    # head, take first
    ¹û  # does nothing

```
> 12 votes

# Answer
# Scala / Javascript, 106 bytes

```
/*\u002A/print(args(0)+args(0).reverse.tail)//*/
/*/**/
alert((s=prompt()).slice(0,-s.length/2))//\u000A*/

```

Palindromizes in scala and depalindromizes in javascript.

Try it on ideone (scala) - Warning: wrong syntax highlighting

Try it on jsfiddle (javascript).

### Explanation:

Scala, like java, processes unicode escapes before everything else, so scalac sees the code like this:

```
/**/                                //\u002A is as asterisk, results in an empty block comment
print(args(0)+args(0).reverse.tail) //scala code
//*/                                //a line comment
/*                                  //scala supports nested block comments, so this comment...
  /*
  */
  alert((s=prompt()).slice(0,-s.length/2))
  //                                  //\u000A (newline) inserted here
*/                                  //...ends here

```

The javascript gets parsed like this:

```
/*\u002A/print(args(0)+args(0).reverse.tail)//*/ //block comment
/*                                               //a block comment...
  /*
*/                                               //...ending here, no nesting
alert((s=prompt()).slice(0,-s.length/2))         //code
//\u000A*/                                       //line comment

```
> 6 votes

# Answer
# Python 3 / JavaScript, 83 chars

*Saved 2 bytes thanks to @LevitatingLion*

```
1//2;x=input();print(x+x[-2::-1]);"""
x=prompt();alert(x.slice(0,-x.length/2))//"""

```

Python palindromizes, JavaScript depalindromizes.

I tried keeping more code constant between the two, but I couldn't figure out a good way to sneak `.slice` into Python. Here's an alternate method:

```
1//2;prompt=input,alert=print
x=prompt();1//2;x+=x[-2::-1]);"""
x=x.slice(0,-x.length/2))//"""
alert(x)

```
> 6 votes

# Answer
# CJam / MATL, 18 characters

```
r_W%(;
"j9LQ2/)%";

```

In CJam this palindromizes. In MATL it depalindromizes.

### Explanation in CJam

Working part:

```
r           Read string
_           Duplicate
W%          Reverse
(;          Remove first element

```

Dummy part:

```
"j9LQ2/)%"  Push this string
;           Remove it from the stack
            Implicitly display both strings obtained previously

```

### Explanation in MATL

Dummy part:

```
r           Push random number between 0 and 1
_           Negate
W           2 raised to that
%(;  Comment (ignored)

```

Working part:

```
"           For each element in the array at the top of the stack. Since it is a number,
            which is the same as a length-1 array, the following is executed once
  j         Input string
  9L        Push array [0, 1j]
  Q2/       Add 1, divide by 2: transforms into [1/2, (1+1j)/2]
  )         Use as index. [1/2, (1+1j)/2] is interpreted as 1/2:(end+1)/2, which is
            rounded to 1:(1+end)/2. So this takes elements from first to half,
            including both

```

Another dummy part:

```
   %";      Comment (ignored)
            Implicitly display the previously obtained string

```
> 4 votes

# Answer
# Jelly / CJam, ~~15~~ 14 chars

```
q_,2./m]<e#¶ŒB

```

-1 char thanks to 42545 (ETHproductions)

Try it online! (Jelly) (Palindromization)

CJam interpreter (Depalindromization)

Jelly explanation:

In Jelly,  is the same as `\n`, so this is what Jelly sees:

```
q_,2./m]<e#
ṖṚṭ

ṖṚṭ         Main link. Arguments: z
Ṗ           Pop
 Ṛ          Reverse
  ṭ         Append
   ⁸        (implicit) z

```

CJam explanation:

In CJam, everything after `e#` on a line is a comment. So, this is what CJam sees:

```
q_,2./m]< Code
q         All input
 _        Duplicate
  ,       Length
   2.     2.0
     /    Float division
      m]  Ceil
        < Take

```
> 4 votes

# Answer
# / Javascript ES6, 55 chars

```
this._?Σ(`ï+ï.Ħ⬮.Đ1`):(x=prompt()).slice(0,-x.length/2)

```

`Try it here (ES6 browsers only).`

Palindromizes in , depalindromizes in Javascript ES6.

I though this was going to be easy, since compiles to ES6 and most of ES6 can be run in . Apparently, I'm completely wrong.

# Explanation

`this._` checks to see if variable `_` exists in the global scope; uses Lodash and therefore has `_` stored, but pure ES6 doesn't.

The segment - `Σ(`ï+ï.Ħ⬮.Đ1`)` \- evaluates from string the code that palindromizes input. Normally, the code would be `ï+ïĦ⬮Đ1`, but I put the dots in to *make the compiler happy*.

The Javascript segment - `(x=prompt()).slice(0,-x.length/2)` \- depalindromizes a string from a prompt.

---

I was going to use a function (so I didn't have to deal with `prompt`), but 's evaluation function didn't like that, so I used `prompt` and no function to *make the compiler happy*.
> 4 votes

# Answer
# JavaScript ES6 / JavaScript ES3, 143 bytes

```
function(x){'use strict';function a(){return x+x.split('').reverse().slice(1).join('')}{function a(){return x.slice(0,-x.length/2)}}return a()}

```

Palindromizes in JavaScript ES6, depalindromizes in JavaScript ES3. *Non competing*, it's just a try to make a polyglot for two versions of the same language.

In ES3 functions are allowed in blocks, but as blocks don't define scopes the new function just replaces the first function. In ES5 strict mode it fails because it don't allow functions to be defined in blocks. In ES6 it's allowed and, because blocks now define scopes, the first function isn't replaced.

Tested in Internet Explorer 5 (emulated) for ES3 and Node.JS and Firefox for ES6.
> 4 votes

# Answer
## Perl / JavaScript, 73 bytes

Perl returns a palindrome and JavaScript 'de-palindromizes' the input string.

```
s=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg

```

### JavaScript

Assumes the string is a valid palindrome already.

All the work happens in the first section:

```
s=prompt();console.log(s.slice(0,-s.length/2));

```

Stores input in `s`, then returns the first half (rounded-up) of the string. The rest of the script is pointless variable assignments:

```
eg=1;t=eg;s=$=reverse$_=eg

```

Try it here:

```
s=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg
```

### Perl

Must be run with `-pl`, eg:

```
perl -ple 's=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg' <<< 'test'
# returns testtset

```

The code is basically two substitutions (`s///`), but using `=` as the delimiter instead of `/`:

```
s/prompt();console.log(s.slice(0,-s.length\/2));eg/1;t/eg;s/$/reverse$_/eg

```

The first, replacing `prompt();console.log(s.slice(0,-s.length\/2));eg` (which, admittedly will mess up your string if it contains something like `"prompt;console.logs.slice0,-s.length/2;eg"`...) with `1;t` which is `eval`ed, returning `t`, the second replaces the end of the string (`$`) with `reverse$_` which is then also `eval`ed and appends the original source string reversed.

Try it online!
> 4 votes

# Answer
# Python 2 / Nim, ~~76~~ 74 bytes

```
#[
s=input();print s+s[-2::-1]#let s=stdin.readLine;echo s[0..s.len div 2]

```

Palindromizes in Python, depalindromizes in Nim. Abuses comment syntax.

Python and Nim both use `#` for comments. Python doesn't support block comments at all (except for multiline strings with `"""`), but Nim does with `#[ comment ]#`.

We abuse this to comment out the Python (at the beginning) for Nim, then use the trailing `]` in the Python to start the Nim code, looking like a comment for Python.

The Python code requires its input surrounded with quotes. The Nim code doesn't have this restriction.

Tested on Python 2.7.8 and Nim 0.14.2.

Ideone it! -- Python 2, palindromizing

~~Ideone it! -- Nim, depalindromizing~~ Apparently the version of Nim Ideone uses (0.11.2) doesn't support multiline comments. Works on Nim 0.14.2.
> 3 votes

# Answer
# 05AB1E/, 14 bytes

```
û,ò"Bx$xh|ò"bP

```

Try it online!

Palindromizes in 05AB1E

Try it online!

Depalindromizes in V, using this answer from DrMcMoylex.
> 3 votes

# Answer
# Jelly / Pyth, ~~15~~ 14 chars

```
<Q.EclQ2*0"¶ŒB

```

Credit where credit is due.

Try it online! (Jelly) (Palindromizes)

pyth.herokuapp.com (Pyth) (Depalindromizes) (trailing newline)
> 2 votes

# Answer
# Japt / JavaScript, 63 chars

Lesson of the day: Japt/JavaScript polyglots are always a bad idea...

```
$Oq=1;$Oq &&0
alert(($U=prompt()).slice(0*$U,-$U.length/2));$Uê

```

## JavaScript

The first line sets the variable `$Oq` to 1, then performs a no-op with `$Oq &&0`.

The second line prompts the user for an input string, assigning it to the variable `$U`, then slices it from index `0*$U` (always 0) to index `-$U.length/2`. This performs the necessary depalindromization; the result is then `alert`ed. The program ends on a ReferenceError because variable `$Uê` is not defined.

## Japt

In Japt, anything between dollar signs is inserted directly into the transpiled source code. Other than that, each lowercase letter transpiles to e.g. `.q(`, unless the previous char was another lowercase letter, in which case it becomes `"q"`. A space is transpiled to `)`, and all missing parens are automatically added. The above program transpiles roughly to:

```
Oq=1;O.q()&&0
.a("l".e("r".t((U=prompt()).slice(0*U,-U.length/2))));U.ê()

```

This is then executed as JavaScript. `Oq=1;` sets the variable `Oq` to 1. This is never used again, so it's a no-op. `O.q()` is a function that clears STDOUT and returns `undefined`; this is falsy, so the entire `&&0 .a("l".e(...` part is not executed.

The only part that really matters is `U.ê()`. Implicit input puts the input string in `U`, `.ê()` turns it into a palindrome, and implicit output sends the result to STDOUT.

---

If function entries are allowed, the following will work for 34 chars:

```
X=>($X=X).slice(0,-X.length/2);$Uê

```

The first part defines an ES6 function, but it's still a full program in Japt. Test it online!
> 2 votes

# Answer
# Java / Brainfuck, 71 bytes

```
/*+[,>]<[<]>[.>]<<[.<][*/a->a.substring(0,Math.ceil(a.length()/2d));//]

```

Palindromizes in BF, depalindromizes in Java.

For the sake of clarity, this is what matters to the BF interpreter:

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

```

where the last loop containing characters from the Java lambda is skipped because the pointer points to a null character at that point.
> 2 votes

# Answer
# 05AB1E / Java 8, 102 chars

```
//¹ûq
interface M{static void main(String[]a){System.out.print(a[0].substring(0,a[0].length()/2+1));}}

```

Palindromize in 05AB1E.
Depalindromize in Java 8.

**Explanation 05AB1E:**

```
//     # No-ops
¹      # First input
 û     # Palindromize it
  q    # Terminate the program
interface M{static void main(String[]a){System.out.print(a[0].substring(0,a[0].length()/2+1));}}
       # No-ops

```

**Explanation Java 8:**

```
//¹ûq                           // No-ops
interface M{                    // Class
  static void main(String[]a){  //  Mandatory main-method
    System.out.print(           //   Print to STDOUT:
      a[0].substring(0,         //    The substring of the input-argument from index 0 to
        a[0].length()/2+1));}}  //    the length of the input integer-divided by 2 plus 1

```
> 0 votes

---
Tags: code-golf, palindrome, polyglot
---


title: Is there a bump?

text:
# Question
Title: Is there a bump?
Given a list of positive integers determine if there is an element that is either greater than its two neighbors or less than its two neighbors (a "bump"). To be clear a bump can never be the first or last item of the list because they only have one neighbor.

Your program should output one of two consistent values each corresponding to either a list with no bumps or a list with bumps. What the values are is unimportant you may choose them yourself.

This is so answers will be scored in bytes with fewer bytes being better.

## Test cases

```
[] -> False
[1] -> False
[1,2] -> False
[1,2,1] -> True
[1,2,2] -> False
[1,2,3] -> False
[1,2,2,1] -> False
[1,2,2,3] -> False
[1,2,1,2] -> True
[1,3,2] -> True
[3,1,2] -> True
[2,2,2] -> False

```

# Answer
# Jelly, 5 bytes

```
IṠIỊẠ

```

Returns **0** if there's a bump, **1** if not.

Try it online!

### How it works

```
IṠIỊẠ  Main link. Argument: A (integer array)

I      Increments; take all forward differences of A.
 Ṡ     Take the signs.
       The signs indicate whether the array is increasing (1), decreasing (-1), or
       constant at the corresponding point. A 1 followed by a -1 indicates a local
       maximum, a -1 followed by a 1 a local minimum.
  I    Increments; take the forward differences again.
       Note that 1 - (-1) = 2 and (-1) - 1 = -2. All other seven combinations of
       signs map to -1, 0, or 1.
   Ị   Insignificant; map each difference d to (-1 ≤ d ≤ 1).
    Ạ  All; return 1 if all differences are insignificant, 0 if not.

```
> 15 votes

# Answer
# JavaScript (ES6), 38 bytes

Returns a boolean.

```
a=>a.some(x=n=>x*(x=a<n|-(a>(a=n)))<0)

```

### Test cases

```
let f =

a=>a.some(x=n=>x*(x=a<n|-(a>(a=n)))<0)

console.log(f([]))              // False
console.log(f([1]))             // False
console.log(f([1,2]))           // False
console.log(f([1,2,1]))         // True
console.log(f([1,2,2]))         // False
console.log(f([1,2,3]))         // False
console.log(f([1,2,2,1]))       // False
console.log(f([1,2,2,3]))       // False
console.log(f([1,2,1,2]))       // True
console.log(f([1,3,2]))         // True
console.log(f([2,0,1]))         // True
console.log(f([2,2,2]))         // False
console.log(f([-4,100000,89]))  // True
```

### How?

We use **a** to store the previous value of **n**. We set **x** to **1** if **a \< n**, **-1** if **a \> n** or **0** if **a = n**. And we test whether **old\_x * x \< 0**, which is only possible if (**old\_x = 1** and **x = -1**) or (**old\_x = -1** and **x = 1**).

Because **x** is initialized to the anonymous callback function of **some()**, it is coerced to **NaN** during the first iteration, which makes the test falsy.
> 10 votes

# Answer
# Haskell, 42 bytes

```
any(<0).f(*).f(-)
f a b=zipWith a b$tail b

```

Try it online!

## Explanation

First we have the function `f` that takes a binary function and a list and applies the binary function to every adjacent pair in the list.

Then our main function applies `f(-)` to the input list. This calculates the difference list. We then apply `f(*)` to the list to multiply every adjacent pair. Lastly we ask if any pair is less than zero.

A number in the end list can only be negative if it is the product of a negative and positive number from the difference list. Thus in order to produce a negative entry (and then return true) the original list must switch from increasing to decreasing or vice versa, that is it must have a bump.
> 8 votes

# Answer
# Python 2, 43 bytes

```
f=lambda x,y,z,*t:0>(y-x)*(z-y)or f(y,z,*t)

```

Returns *True* if there's a bump, errors if there isn't. (allowed by default)

Try it online!
> 6 votes

# Answer
# Octave with Image Package, ~~34~~ 32 bytes

*2 bytes saved thanks to @StewieGriffin!*

```
@(x)0||prod(im2col(diff(x),2))<0

```

**Try it online!**

### Explanation

Computes consecutive differences, arranges them in sliding blocks of length 2, obtains the product of each block, and tests if any such product is negative.
> 5 votes

# Answer
# Haskell, 33 bytes

```
f(p:r@(c:n:_))=(c-p)*(c-n)>0||f r

```

Try it online!

`True` if there's a bump, errors if there's not.
> 4 votes

# Answer
# Perl 6, 39 bytes

```
{so~(.[1..*]Zcmp$_)~~/'re L'|'s M'/}

```

Try it online!

`$_` is the list argument to this anonymous function. `.[1..*]` is the same list, but with the first element dropped. `Zcmp` zips the two lists together with the `cmp` operator, resulting in a list of `Order` values. For example, for an input list `1, 2, 2, 2, 1` this would result in the list `More, Same, Same, Less`.

Now we just need to know whether that list contains two adjacent elements `More, Less` or `Less, More`. The trick I used is to convert the list to a space-delimited string with `~`, then test whether it contains either substring `re L` or `s M`. (The first one can't be just `e L` because `Same` also ends with an "e".)

The smart match operator returns either a `Match` object (if the match succeeded) or `Nil` (if it didn't), so `so` converts whatever it is into a boolean value.
> 4 votes

# Answer
# R, 48 bytes

```
function(x)any(apply(embed(diff(x),2),1,prod)<0)

```

Try it online!

How it works step-by-step using c(1,4,1,4) as example:

```
> x=c(1,4,1,4)
> diff(x)
[1]  3 -3  3
> embed(diff(x),2)
     [,1] [,2]
[1,]   -3    3
[2,]    3   -3
> apply(embed(diff(x),2),1,prod)
[1] -9 -9
> any(apply(embed(diff(x),2),1,prod)<0)
[1] TRUE

```

As a bonus, here is a solution of similar length and concept using package `zoo`:

```
function(x)any(zoo::rollapply(diff(x),2,prod)<0)

```
> 4 votes

# Answer
# Ruby, ~~55~~ 46 bytes

```
->a{a.each_cons(3).any?{|x,y,z|(y-x)*(y-z)>0}}

```

Try it online!

A lambda accepting an array and returning boolean.

-9 bytes: Replace `(x<y&&y>z)||(x>y&&y<z)` with `(y-x)*(y-z)>0` (thanks to GolfWolf)

```
->a{
  a.each_cons(3)              # Take each consecutive triplet
    .any?{ |x,y,z|            # Destructure to x, y, z
      (y-x)*(y-z) > 0         # Check if y is a bump
    }
}

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 40 bytes

```
MatchQ[{___,x_,y_,z_,___}/;x<y>z||x>y<z]

```

Try it online!
> 3 votes

# Answer
# , ~~58~~ 56 bytes

```
function(x)any(abs(diff(sign(diff(c(NA,x)))))>1,na.rm=T)

```

Try it online!

Saved 2 bytes thanks to Giuseppe
> 3 votes

# Answer
# Husk, 8 bytes

```
±V<0Ẋ*Ẋ-

```

Try it online!

## Explanation

```
±V<0Ẋ*Ẋ-  Implicit input, say [2,5,5,1,4,5,3]
      Ẋ-  Consecutive differences: [3,0,-4,3,1,-2]
    Ẋ*    Consecutive products: [0,0,-12,3,-2]
 V<0      Is any of them negative? Return 1-based index: 3
±         Sign (to make output consistent): 1

```
> 3 votes

# Answer
# , 16 15 bytes

-1 byte thanks to FrownyFrog

```
1 e.0>2*/\2-/\]

```

Try it online!

## Original: 16 bytes

```
0>[:<./2*/\2-/\]

```

`2-/\]` \- differences of each adjacent items

`2*/\` \- products of each adjacent items

`[:<./` \- the minimum

`0>` \- is negative?

Try it online!
> 3 votes

# Answer
# Java 8, ~~108~~ ~~104~~ ~~101~~ ~~86~~ ~~84~~ ~~79~~ 72 bytes

```
a->{int i=a.length,p=0;for(;i-->1;)i|=p*(p=a[i]-a[i-1])>>-1;return-i>1;}

```

-2 bytes thanks to *@OlivierGrégoire*.
-13 bytes thanks to *@Nevay*.

Try it online.
> 3 votes

# Answer
# PostgreSQL 173 bytes

```
SELECT DISTINCT ON(a)a,x>j and x>k OR x<least(j,k)FROM(SELECT a,x,lag(x,1,x)OVER(w)j,lead(x,1,x)OVER(w)k FROM d WINDOW w AS(PARTITION BY rn ORDER BY xn))d ORDER BY 1,2 DESC;
     a     | c
-----------+---
 {1}       | f
 {1,2}     | f
 {1,2,1}   | t
 {1,2,1,2} | t
 {1,2,2}   | f
 {1,2,2,1} | f
 {1,2,2,3} | f
 {1,2,3}   | f
 {1,3,2}   | t
 {2,2,2}   | f
 {3,1,2}   | t
(11 rows)

```
> 3 votes

# Answer
# Japt, 11 bytes

*-5 bytes thanks to @ETHproductions*

```
ä- mÌäa d>1

```

Try it online! | Test cases

This uses Dennis's algorithm
> 2 votes

# Answer
# Japt, 9 bytes

```
ä- ä* d<0

```

Try it online!

A mashup of Oliver's answer with the approach used by several other answers.
> 2 votes

# Answer
# Attache, 39 bytes

```
Any&:&{_*~?Sum[__]}@Slices&2@Sign@Delta

```

Try it online!

Pretty happy with how this turned out.

## Explanation

This is a composition of four functions:

```
Delta
Sign
Slices&2
Any&:&{_*~?Sum[__]}

```

`Delta` gets the differences between elements. =

Then, `Sign` is applied to each difference, giving us an array of `1`s, `0`s, and `-1`s. =

Then, `Slices&2` gives all slices of length two from the array, giving all pairs of differences.

Finally, `Any&:&{_*~?Sum[__]}` is equivalent to, for input `x`:

```
Any[&{_*~?Sum[__]}, x]
Any[[el] -> { el[0] and not (el[0] + el[1] = 0) }, x]

```

This searches for elements which sum to zero but are not zero. If any such pair of elements exist, then there is a bump.
> 2 votes

# Answer
# Octave, 33 bytes

```
@(x)0||abs(diff(sign(diff(x))))>1

```

Try it online!

### Explanation:

```
@(x)                           % Anonymous function taking x as input
                  diff(x)       % Takes the difference between consecutive elements
             sign(diff(x))      % The sign of the differences
        diff(sign(diff(x)))     % The difference between the signs
    abs(diff(sign(diff(x)))>1   % Check if the absolute value is 2
@(x)abs(diff(sign(diff(x)))>1   % Output as matrices that are treated truthy or falsy

```
> 2 votes

# Answer
# MATL, 8 bytes

```
dZSd|1>a

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
¥ü‚P0‹Z

```

Try it online!

**Explanation**

```
¥         # calculate delta's
 ü‚       # pair each element with the next element
   P      # product of each pair
    0‹    # check each if less than 0
      Z   # max

```
> 2 votes

# Answer
# Brachylog, 10 bytes

```
s₃.¬≤₁∧¬≥₁

```

Try it online!

Succeeds (`true.`) if there is a bump, and fails (`false.`) if there is no bump.

### Explanation

This is fairly readable already:

```
s₃.           There is a substring of the input…
  .¬≤₁        …which is not non-decreasing…
      ∧       …and…
       ¬≥₁    …which is not non-increasing

```
> 2 votes

# Answer
# Brachylog, 10 bytes

```
s₃s₂ᶠ-ᵐ×<0

```

Try it online!

Not nearly as neat and elegant as @Fatalize's existing 10 byte answer, but it works!

```
s₃   % There exists a substring of three elements [I,J,K] in the array such that

s₂ᶠ  % When it's split into pairs [[I,J],[J,K]]

-ᵐ   % And each difference is taken [I-J, J-K]

×    % And those differences are multiplied (I-J)*(J-K)
     % (At a bump, one of those will be negative and the other positive.
     % At other places, both differences will be positive, or both negative,
     %  or one of them 0 - ultimately resulting in a non-negative product.)

<0   % The product is negative

```
> 2 votes

# Answer
# APL (Dyalog), ~~15~~ ~~19~~ 20 bytes

*2 bytes saved thanks to @EriktheOutgolfer*

```
{2>≢⍵:0⋄2∊|2-/×2-/⍵}

```

Try it online!

**1** for bump, **0** for no bump.
> 1 votes

# Answer
# Python 2, 60 bytes

```
lambda l:any(p>c<n or p<c>n for p,c,n in zip(l,l[1:],l[2:]))

```

Try it online!

Pretty much the same thing, thought it would be shorter though...

# Python 2, 63 bytes

```
f=lambda l:l[3:]and(l[0]>l[1]<l[2]or l[0]<l[1]>l[2]or f(l[1:]))

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 57 56 bytes

```
l->any(p>c<n||p<c>n for(p,c,n)=zip(l,l[2:end],l[3:end]))

```

Basically just totallyhuman's python answer. -1 byte from user71546

Try it online!

# Julia 0.6, 39 bytes

```
f(x,y,z,a...)=x>y<z||x<y>z||f(y,z,a...)

```

Lispy recursion style, aka Dennis's python answer. Returns `true` when a bump exists, otherwise throws an error. This should maybe be 42 bytes since you have to splat it when calling. Eg for `a=[1,2,1]` you call as `f(a...)`. `f(a)=f(a...)` would remove that need, but is longer. I need to get better a recursion, and I don't really like writing code that throws an error.

Try it online!
> 1 votes

# Answer
# Husk, 9 bytes

```
▼mεẊ-Ẋo±-

```

Try it online!

Uses Dennis's algorithm.
> 1 votes

# Answer
# Perl 5, 54 + 2 (`-pa`) = 56 bytes

```
map$\|=$F[$_-1]!=(sort{$a-$b}@F[$_-2..$_])[1],2..$#F}{

```

Try it online!
> 1 votes

# Answer
# Pyt, ~~11~~ 7 bytes

```
₋ʁ*0<Ʃ±

```

Outputs 1 if there is a bump, 0 otherwise

Try it online!

Port of Wheat Wizard's Haskell answer

---

# Old way (11 bytes):

```
₋±₋Å1≤ĐŁ↔Ʃ=

```

Try it online!

Returns False if there is a bump, True otherwise

Port of Dennis' Jelly answer
> 1 votes

# Answer
# Windows Batch, ~~126~~ ~~120~~ 114 bytes

I was pretty excited about my first use of the `shift` command.

This script generally works for numbers within 9 digits(no matter positive or negative.)

```
:L
@if %3.==. exit/b
@if %2 gtr %1 if %3 lss %2 goto:e
@if %2 lss %1 if %3 gtr %2 goto:e
@shift
@goto:L
:e
@echo T

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~37~~ 36 bytes

```
FreeQ[(d=Differences)@Sign@d@#,-2|2]&

```

Gives the opposite of the test case answers (False and True reversed). Prepend a `!` to switch to the normal form.

OR

```
Abs@(d=Differences)@Sign@d@#~FreeQ~2&

```

Also reversed output, so replace `FreeQ` with `MatchQ` for normal form.

Explanation: Take the sign of the differences of the sequence. Iff the resulting sequence includes {1,-1} or {-1,1} there is a bump. The absolute value the differences of {1,-1} or {-1,1} is 2 in either case.

Shave off another byte by squaring the final list instead of taking the absolute value:

```
FreeQ[(d=Differences)@Sign@d@#^2,4]&

```

Try it online!
> 1 votes

# Answer
# Perl, 35 bytes

Includes `+3` for `-p`

`bump.pl`:

```
#!/usr/bin/perl -p
s%\S+ %$a*1*($a=$&-$')%eg;$_=/-/

```

Run as:

```
bump.pl <<< "3 1 2"

```
> 1 votes

# Answer
# C (gcc), 101 97 bytes

```
r,i;f(a,n)int*a;{for(i=n|1;--i;a[i]-=a[i-1]);for(r=0;--n>0;r=a[n]<0&a[n-1]>0|a[n]>0&a[n-1]<0|r);}

```

Try it online!

Differences the list, then looks for two neighboring differences that are not zero and have opposite sign.
> 1 votes

# Answer
# C (gcc), 78 bytes

*Variant: loop*

```
r,i;f(a,n)int*a;{for(r=n>2,i=0;i<n-2;)r=(a[i++]-a[i])*(a[i]-a[i+1])<0&&r;i=r;}

```

Try it online!

*Variant: recursive*

```
f(a,n)int*a;{n=(n<3)?0:((a[--n]-a[--n])*(a[n]-a[n-1])<0&&((n<2)?1:f(a,n+1)));}

```

Try it online!

The criteria is that `a[i]-a[i+1] and a[i+1]-a[i+2]` are non-zero and have opposite sign. `i=r` is just a way to return the value (described here).

P. S. Additional two test cases may reveal bugs: `{ 1, 2, 1, 2, 2 }` and `{ 2, 2, 1, 2, 1 }`
> 1 votes

# Answer
# APL (Dyalog Classic), 15 bytes

```
0∨.>2×/2-/⊃,⊃,⊢

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 43 bytes

```
.+
$*
1`(1+)1¶\1¶1\1|¶(1+)(?<!\2¶\2)¶(?!\2)

```

Try it online! Takes input on separate lines and outputs 0 or 1. Explanation:

```
.+
$*

```

Convert to unary.

```
1`            |

```

Count at most one matching regex.

```
  (1+)1¶\1¶1\1

```

Match a number that is surrounded by greater numbers on both sides.

```
               ¶(1+)(?<!\2¶\2)¶(?!\2)

```

Match a number that is not surrounded by greater or equal numbers on either side, i.e. both are less.
> 0 votes

# Answer
# Python, 91 bytes

```
def f(a):return[i for i,j in enumerate(a[1:-1])if(j>max(a[i+2],a[i])or j<min(a[i+2],a[i]))]

```

An empty array is a falsey value, while a populated array is truthy
> 0 votes

# Answer
# Perl 6, ~~50~~ 47 bytes

```
{?grep {0>(.[1]-.[2])*[-] .[^2]},.rotor(3=>-2)}

```

Try it online!
> 0 votes

# Answer
# **GFORTH 71 Bytes**

```
: B ROT 2DUP = -1 = IF DROP ROT = -1 = IF  ELSE ." TRUE " THEN THEN ;

```

Output:

```
1 2 1 B TRUE  ok
19 4 19 B TRUE  ok
5 4 6 B  ok

```
> 0 votes

# Answer
# Elm, 102 bytes

```
f a b=case b of
 c::d::e->a c d::f a(d::e)
 _->[]
a g=case g of
 []->1<0
 i::k->i<0||a k
a<<f(*)<<f(-)

```

## Explanation

This works very similar to my Haskell answer. Except Elm is missing all of the functions that do stuff so I had to make every thing from the ground up. You can test it by running the following here

```
import Html exposing (text)
f a b=case b of
 c::d::e->a c d::f a(d::e)
 _->[]
a g=case g of
 []->1<0
 i::k->i<0||a k
g=a<<f(*)<<f(-)
s x=case x of
 True->"True"
 False->"False"
main=g[1,1,1,1,1,0,1]|>s|>text

```
> 0 votes

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


title: 8 8's make 1000

text:
# Question
Title: 8 8's make 1000
Print the following output of a happy coincidence addition pattern:

```
   8
   8
   8
  88
+888
----
1000

```

Rules:

* No leading spaces except the ones already present
* There can be a trailing newline
* `+` sign needs to be displayed
* Order of parcels needs to be the same

No winner. It is per language.

# Answer
# PowerShell, ~~34~~ ~~33~~ 31 bytes

```
,'   8'*3+"  88
+888"+'-'*4+1e3

```

Try it online!

Five bytes shorter than printing the string as-is, ~~but still not very golfy.~~ now getting to be golfy.

Constructs an array of 3x `' 8'` (saving a byte), then array-concatenates the remaining items, with `'-'*4` saving a byte. The other byte savings comes from using `1e3` in place of `1000`.
> 5 votes

# Answer
# Charcoal, ~~15~~ 14 bytes

```
Ｇ↑↑↓↙³8←→⟦+⁴Ｉφ

```

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

```
Ｇ↑↑↓↙³          Draw a polygon implicitly closing the path
      8         Filled with the string 8
       ←        Move left one character
          +     Literal string +
           ⁴    Integer 4 (prints as ----)
             φ  Predefined variable 1000
            Ｉ   Cast to string
         ⟦      Wrap in array (implicit ⟧)
        →       Override ← print direction
                Implicitly print one per line

```
> 5 votes

# Answer
# Bash, 35 bytes

```
printf %4s\\n {,,,8,+88}8 ---- 1000

```

Try It Online
> 4 votes

# Answer
# Python 2, 40 bytes

```
print"   8\n"*3+"  88\n+888\n----\n1000"

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~57~~ ~~52~~ ~~51~~ 50 bytes

-5 bytes thanks to Mr. Xcoder.

-1 byte thanks to Dennis.

-1 byte again, thanks to Mr. Xcoder.

```
for i in 8,8,8,88,'+888','-'*4,1000:print('%4s'%i)

```

Try it online!
> 2 votes

# Answer
# SOGL V0.12, 15 bytes

```
≥č*xi«∙tν↔β⁸‘4n

```

Try it Here! \- simply  `8 8 8 88+888----1000` compressed, then split to line lengths of 4

~~20~~ 19 byte non-compression based method:

```
8³'E■888+⁰§o┌4*LM*⁰

```

Try it Here!

```
8                    push 8
 ³                   triplicate the 8
  'E                 push 88
    ■888+            push "888+"
         ⁰           wrap those in an array
          §          reverse horizontally, padding with spaces
           o         output that
            ┌4*      push "-"*4
               LM*   push 100*10
                  ⁰  wrap those two in an array, outputting both

```
> 2 votes

# Answer
# 05AB1E, 20 bytes

-1 byte thanks to Riley

```
8ÐÐ«D„8+«'-4×₄R).Bí»

```

Try it online!
> 2 votes

# Answer
# brainfuck, 107 bytes

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

```

Try it online!

## Explanation

```
++++++++[>+++++>+>+++++++>++++<<<<-]>+++++>++<<+++
TAPE:
>V_LOOP< C_DASH C_NL C_EIGHT C_SPACE
003      045    010  056     032

~~~OUTPUT SECTION~~~
V_LOOP TIMES DO                     [-
    PRINT C_SPACE x 3                 >>>> ...
    PRINT C_EIGHT                     <.
    PRINT C_NL                        <.
                                    <<]
PRINT C_SPACE x 2                   >>>>..
PRINT C_EIGHT x 2                   <..
PRINT C_NL                          <.
C_DASH = C_DASH MINUS 2 (PLUS SIGN) <--
PRINT PLUS SIGN                     .
PRINT C_EIGHT x 3                   >>...
PRINT C_NL                          <.
PRINT C_DASH x 4                    <++....
PRINT C_EIGHT                       >.
C_DASH = C_DASH PLUS 2 ('1')        <++++
PRINT '1'                           .
C_DASH = C_DASH MINUS 1 ('0')       -
PRINT '0' x 3                       ...

```
> 2 votes

# Answer
# Bubblegum, 23 bytes

```
00000000: 5350 50b0 e042 262c 2cb8 b42d 8084 2e10  SPP..B&,,..-....
00000010: 7019 1a18 1800 00                        p......

```

Try it online!
> 2 votes

# Answer
# , 23 bytes

```
3o³ 8òÙhr8òR1³0-Ò-kr+

```

Try it online!
> 1 votes

# Answer
# J, 37 bytes

```
  7 4 $'   8   8   8  88+888----1000'

```
> 1 votes

# Answer
# Javascript 44 bytes

```
a=x=>`   8
`.repeat(3)+`  88
+888
----
1000`

console.log(a())
```
> 1 votes

# Answer
## GNU sed, 37 bytes

```
s:$:   8:p;p
a\  88
a+888
a----
a1000

```

Try it online!

I use the `a` command to append text lines to output. For comparison, the trivial solution is to print the hardcoded text like below, 42 bytes. Reduction is 11.9 %.

```
c\   8\n   8\n   8\n  88\n+888\n----\n1000

```
> 1 votes

# Answer
# ///, 31 bytes

```
/!/   8
/!!!  88
+888
----
1000

```

Try it online!

A measly 3 bytes savings.
> 1 votes

# Answer
# QBIC, 36 bytes

```
?@   8`?A?A?@  88`?@+888`?@----`?z^3

```
> 1 votes

# Answer
# Java 8, 45 bytes

```
v->"   8\n   8\n   8\n  88\n+888\n----\n1000"

```

Boring hard-coded output, but this can't be done any shorter in Java. Just utilizing the repeated part `" 8\n"` is already 52 bytes..
`v->"aaa 88\n+888\n----\n1000".replace("a"," 8\n")`

Try it here.
> 1 votes

# Answer
# , ~~28~~ 27 bytes

```
|.|:'1-+','0-88888'$~3,4,:7

```

Try it online!

```
                                             0-8
          '0-88888'$~3,4,:7      Three rows: 0-88
                                             0-88888
    '1-+',                       "1-+" on top
|.|:                             Rotate counter-clockwise

```
> 1 votes

# Answer
# LOLCODE, 66 bytes

```
HAI 1.3
VISIBLE "   8:)   8:)   8:)  88:)+888:)----:)1000"
KTHXBYE

```

Try it online!
> 1 votes

# Answer
# , ~~46 bytes~~41 bytes

```
cat('   8
   8
   8
  88
+888
----
1000')

```

Try it online!

Thanks to Dennis for golfing off 5 bytes.
> 1 votes

# Answer
# Brainfuck, 104 bytes

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

```

Uses the same technique as this genius answer.
> 0 votes

# Answer
# Tcl, 42 bytes

```
puts "   8
   8
   8
  88
+888
----
1000"

```

Try it online!
> 0 votes

# Answer
# Stax, 19 bytes

```
∩π╚nY╤¼æ♂ç♦d└tä♂&lò

```

Run and debug it

ASCII equivalent:

```
.-+]125E{'8*eN$m+MrVk+m

```

Build the `8`s together with the line below by transposing the string representation of the array `[-8,-88,-88888]`.
> 0 votes

# Answer
# Befunge-93, 66 bytes

```
"0001"25*"-":::25*"888+"25*"88  "25*"8 "::25*"8 "::25*"8 "::>:#,_@

```

Try it online!
> 0 votes

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


title: Random dice tipping

text:
# Question
Title: Random dice tipping
In a standard dice (die) the numbers are arranged so that opposite faces add to seven. Write the shortest possible program in your preferred language which outputs a random throw followed by 9 random tippings. A tipping is a quarter turn of the dice, e.g. if the dice is facing 5, all possible tippings are 1,3,4 and 6.

Example of desired output:

> 1532131356

# Answer
### GolfScript, 26 chars

```
0{(.6,5@--\-.,rand=).}10*;

```

A slight more compressed version of Joey's, basically working around the issue with zero-indexing.
> 5 votes

# Answer
## Ruby, 44

```
c=0;10.times{$><<c=([*1..6]-[c,7-c]).sample}

```

I found the \[\*1..6\] trick by lucky experimenting.
> 9 votes

# Answer
## JavaScript (71 characters)

You may need to replace `print` with `alert` or something else, depending on your JavaScript environment.

```
for(C=L=T=0;C++<10;print(L=T))while(!(T-L&&T+L-7))T=Math.random()*6+1|0

```
> 4 votes

# Answer
## GolfScript, 28

```
0:|;{7,[0|7|-]-.,rand=:|}10*

```
> 4 votes

# Answer
**Bash**

```
#/!bin/bash
f=`expr $RANDOM % 6`
f=`expr $f + 1`
printf "$f"
for ((i=0; i<9; i++))
do
   ((bad=7-$f))
   next=`expr $RANDOM % 6`
   next=`expr $next + 1`
   while [ $next -eq $bad ] || [ $next -eq $f ]
   do
      next=`expr $RANDOM % 6`
      next=`expr $next + 1`
   done
printf "$next"
f=$next
done

```

sample code: http://ideone.com/CCfro
> 3 votes

# Answer
### Bash: 97 94 92 90 89 87

Heavily golfed from Aman ZeeK Verma's answer:

```
for((i=10,f=0;i--;))do
for((n=f;n==f||n+f==7;f=RANDOM%6+1))do :
done
printf $f
done
```

http://ideone.com/QiuTx

NB arguably it can be shrunk by 5 chars by changing the first line to `for((;i++<10;))` but that makes assumptions which aren't always valid. It would work ok in ideone but someone running it from a shell could have `i` or `f` exported to something non-zero.
> 3 votes

# Answer
## R, 56 52

```
for(i in 0:9)cat(F<-sample(setdiff(1:6,c(F,7-F)),1))

```
> 3 votes

# Answer
## J, 30 characters

```
>:(?@4:{(i.6)-.],5&-)^:(<10)?6

```

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

Explanations (read from right to left):

* `?6` returns a random number between 0 and 5
* `^:(<10)` applies a function 9 times, accumulating the results along the way. The function is:
* `?@4:{(i.6)-.],5&-`
    + `] , 5&-` returns an array of the input number and its complement to 5 (we're handling 0-based numbers currently, so the sum of opposite faces is 5)
    + `(i. 6) -.` removes them from the full set of integers 0 to 5. We're left with all valid positions after a single tipping operation from the input position.
    + `?@4: {` picks one of those at random.
* `>:` increments the whole sequence to bring the figures back to the 1 to 6 interval.
> 2 votes

# Answer
## J

This should work but unfortunately J's random generator gets stuck after the 3rd iteration:

```
a=:>:i.6
f=:a#~1-(+&(a=])7&-)
((,(?4)&{@f@(_1&{))^:9)>:?6

```

`6 4 5 4 5 4 5 4 5 4`
> 2 votes

# Answer
### Bash with only one loop: 100 99 98 96

```
for((i=10,f=RANDOM%6+1;i--;))do
printf $f
((n=RANDOM%4+1,m=f<4?f:7-f,f=n<m||++n<7-m?n:n+1))
done
```

http://ideone.com/XrZO7

The key idea is that to pick a random number in \[1,x\] which isn't equal to y you can pick a random number in \[1,x-1\] and then increment if it's \>= y. For this problem we want a random number in \[1,6\] which isn't equal to f or 7-f. We have to do the two tests in order min(f,7-f), max(f,7-f).

Assuming an initially empty environment could save 2 chars by not initialising i and changing the loop condition to `i++<10`
> 2 votes

# Answer
## Windows PowerShell, 45

```
-join(0..9|%{($d=1..6-ne(7-$d)-ne$d|random)})

```

Pretty trivial, actually. I generate a list of possible dice rolls `1..6` and then select only those not equal to seven minus the last roll and then only those not equal to the last roll. From the remaining list I then select a random item and assign it to `$d`. Since `$d` is initially treated as `0` it rolls a normal die the first time.

Test script:

```
for($i=0;$i-lt20;$i++){
    $o=@(./tipping.ps1)
    if ($i-gt0-and$o-eq$o2) { throw "Must have random output" }
    if ($o.count-ne1) { throw "Must only have one line of output" }
    if ($o[0]-match'[^1-6]'){ throw "Invalid characters" }
    if($o[0].length-ne10){ throw "Wrong length: $($o[0].length)" }
    $r=[char[]]($o[0])|%{$_-48}
    for ($x=1;$x-lt$r.count;$x++){
        if ($r[$x-1]+$r[$x]-eq7) { throw "Not a tipping: $($r[$x-1]) and $($r[$x])" }
    }
    $o2=$o
}

```

History:

* 2011-02-18 11:57 (61) First attempt.
* 2011-02-18 11:58 (45) I don't need to generate the first number separately.
> 2 votes

# Answer
## Ruby

### 66 characters

```
(0..9).reduce([]){|m|m<<((1..6).to_a-[d=m[-1]||0,7-d]).shuffle[0]}

```
> 2 votes

# Answer
# TI-BASIC, ~~38~~ 34

```
For(I,1,9
Ans→X
Repeat Ans≠X and Ans≠7-X
randInt(1,6
End
Disp Ans
End

```

Boring solution, but it's shorter than the previous revision. I take advantage of the fact that on a fresh calculator, `Ans` is initialized to zero.
> 2 votes

# Answer
## GS2, 16 bytes

```
16 2f 25 08 41 20 17 30 16 2f 31 31 25 09 19 32

```

Here's how it works

```
16 2f 25     # make range from 1 to 6 and push random element
08           # start block
    41       # duplicate top of stack twice
    20 17 30 # negate top of stack and add 7
    16 2f    # push range from 1 to 6
    31 31    # do set-wise difference with each of the two previous numbers
    25       # push a random element from the list
09           # end block
19 32        # repeat block 9 times

```
> 2 votes

# Answer
## QBasic (71 characters)

The two newlines are necessary and included in the character count as one character each.

```
RANDOMIZE:FOR I=0TO 9
1N=INT(RND*6)+1:IF L=N OR L+N=7THEN 1
?N:L=N:NEXT

```
> 1 votes

# Answer
# Java 8, 130 bytes

```
v->{int d=(int)(Math.random()*6+1),i=10,p;String r=""+d;for(;i-->0;r+=d)for(p=d;p==d|p+d==7;d=(int)(Math.random()*6+1));return r;}

```

Try it here.

As full program with verbose main-method this would be **178 bytes** instead:

```
interface M{static void main(String[]a){int d=(int)(Math.random()*6+1),i=10,p;String r=""+d;for(;i-->0;r+=d)for(p=d;p==d|p+d==7;d=(int)(Math.random()*6+1));System.out.print(r);}}

```

Try it here.

Semi-port of *@AmanZeeKVerma*'s Bash answer.

**Explanation:**

```
 v->{              // Method with empty unused parameter and String return-type
   int d=(int)(Math.random()*6+1),
                   //  Random dice-roll 1-6
       i=10,       //  Counter-integer, starting at 10
       p;          //  Temp integer to store new side
   String r=""+d;  //  Result-String, starting at the first dice-roll
   for(;i-->0;     //  Loop (1) 10 times:
       r+=d)       //    After every iteration, append the result with a random side
     for(p=d;      //   Set the new side to the current side
         p==d      //   Loop (2) as long as the new side and current side are the same
         |p+d==7;  //   or as long as both combined are exactly 7:
       d=(int)(Math.random()*6+1)
                   //    Set the new side to a random side 1-6
     );            //   End of loop (2)
                   //  End of loop (1) (implicit / single-line body)
  return r;        //  Return the result-String
}                  // End of method

```
> 1 votes

# Answer
## MATLAB 58 bytes

```
a=randi(6)
for i=1:9;b=1:6;b([a,7-a])=[];a=b(randi(4))
end

```
> 1 votes

# Answer
# \>\<\>, 71 bytes

I'm glad I could showcase \>\<\>'s `x` code-pointer randomization as I don't recall seeing it here.

```
a&0 v
 /2v
1x3v
>x< <<
6x4v
 \5v ~
:{:/ ^?=}
:{:/ ^?=7+}
:~$<^&;!?:-1&n

```

You can try it on this online interpreter (paste code, submit, start).
> 0 votes

# Answer
# , 67 bytes

```
c(3,5,1,4,2,6)[(sample(1:6,1)+cumsum(sample((-2:2)[-3],9,T)))%%6+1]

```

Try it online!

There is a golfier R answer but this I think is a different approach from the answers submitted so far.

```
c(3,5,1,4,2,6)                                                     #A dice and its facets
               (sample(1:6,1)                                      #Initial dice roll
                             +cumsum(sample((-2:2)[-3],9,T)))      #9 tippings in c(-2,-1,1,2)
                                                             %%6+1 #converts to values in [0,6]
              [                                                   ]#

```
> 0 votes

# Answer
# 05AB1E, 23 bytes

```
6LΩUTFX?6LʒDXÊsX+7Ê*}ΩU

```

Can definitely be golfed, but I'm currently not seeing it..

Try it online.

**Explanation:**

```
6LΩ              # Pick a random value from the range [1,6]
                 #  i.e. [1,2,3,4,5,6] → 3
   U             # Save this random value in variable `X`
TF               # Loop 10 times:
  X?             #  Print `X` without newline to STDOUT
  6Lʒ     }      #  Create a range [1,6] again, and filter it by:
     DXÊ         #   Check if the current value is not equal to `X`
                 #    i.e. 1 and 3 → 1 (truthy)
                 #    i.e. 3 and 3 → 0 (falsey)
     sX+         #   Sum the current value with `X`
                 #    i.e. 1 and 3 → 4
                 #    i.e. 3 and 3 → 6
        7Ê       #   And check if it's not equal to 7
                 #    i.e. 4 and 7 → 1 (truthy)
                 #    i.e. 6 and 7 → 1 (truthy)
     *           #   If both checks are truthy, keep it in the filtered list
                 #    i.e. 1 and 1 → 1 (truthy)
                 #    i.e. 0 and 1 → 0 (falsey)
           Ω     #  Pick a random value from the filtered list
                 #   i.e. [1,2,5,6] → 1
            U    #  And save it in variable `X` for the next iteration of the loop

```
> 0 votes

---
Tags: code-golf, random, repeated-transformation
---


title: Help me play the Trumpet

text:
# Question
Title: Help me play the Trumpet
The trumpet is a valved aerophone instrument, usually pitched in `B♭`. The sound is made when the player vibrates their lips to displace air inside the instrument. That vibration is acquired by setting one's mouth in a specific way, called the embouchure. Different embouchures, with tighter or looser lips, produce different pitches.

Furthermore, each valve in the trumpet also changes the pitch of the instrument. When depressed, a valve closes a path inside the tubing of the instrument, making the air flow through a longer path, thus lowering the pitch of the original sound. For the purposes of this challenge, we'll consider the standard, `B♭` trumpet, in which the first valve lowers the pitch by a full step, the second lowers the pitch by a half-step, and the third lowers the pitch by one and a half step.

### The Challenge

Your challenge is to create a program or function that, given two inputs `embouchure` and `valves`, determines the pitch of the note being played.

For the purposes of this challenge, the notes will follow the sequence:

```
B♭, B, C, C♯, D, E♭, E, F, F♯, G, G♯, A.

```

### Rules

* I/O can be taken/given in any reasonable method.
* Standard loopholes apply.
* You're allowed to use `b` and `#` instead of  and  if you wish to.
* Input for `valves` can be taken as a list of depressed valves (`1, 3`) or a boolean list (`1, 0, 1`).
* This is , so shortest code in each language wins.

### Test Cases:

`Valves` in these test cases is given as a boolean list, where 0 means depressed and 1 means pressed.

```
Embouchure:    Valves:   Output:
B♭             0 0 0     B♭
B♭             0 1 0     A
B♭             1 0 1     F
C♯             0 0 1     B♭
C♯             1 1 1     G
E♭             1 0 0     C♯
G              0 1 1     E♭
G♯             1 0 0     F♯
G♯             0 0 1     F
G              1 0 0     F
F♯             1 0 0     E
D              1 0 1     A
A              1 1 1     E♭
E              1 1 0     C♯
E              0 0 1     C♯

```

**Disclaimer:** I'm not much of a musician yet, so I do apologize for any butchering I might've made on the test cases. Corrections are appreciated.

# Answer
> 4 votes
# Python ~~3~~ 2, ~~125~~ ~~119~~ 81 bytes

```
lambda e,f,s,t,n=2*'A G# G F# F E Eb D C# C B Bb'.split():n[n.index(e)+2*f+s+3*t]

```

Try it online!

Saved a lot of bytes thanks to Jonathan Allan.

---

My original solution (in **Python 3**):

```
n=2*'Bb B C C# D Eb E F F# G G# A'.split()
e,f,s,t=str(input()).split()
print(n[n.index(e,9)-2*int(f)-int(s)-3*int(t)])

```

Try it online!

Saved 6 bytes thanks to @HyperNeutrino.

---

### Explanation

First, I make an array of notes, but doubled in length so I don't have to worry about looping around from `Bb` to `A`.

Then, I take input in the following format (for example):

```
Bb 1 0 1

```

I then find the index of the starting note using `n.index(e,9)` (the `9` is there to make sure that I start well in the middle of the (doubled) list. I calculate the desired offset with the expression:

```
2*int(f) - int(s) - 3*int(t)

```

Where `f` is the first valve, `s` is the second valve, and `t` is the third.

Finally, it simply prints the note found in the list by subtracting the offset from the starting index.

# Answer
> 3 votes
# Wolfram Language (Mathematica), 100 bytes (and 134 for a working trumpet)

```
l="Bb,B,C,C#,D,Eb,E,F,F#,G,G#,A"~StringSplit~",";f=l[[Mod[#&@@#&@@l~Position~#-2#2-#3-3#4-1,12]+1]]&

```

Try it online!

Quite straightforward.

```
l="Bb,B,C,C#,D,Eb,E,F,F#,G,G#,A"~StringSplit~",";f=EmitSound@SoundNote[l[[Mod[#&@@#&@@l~Position~#-2#2-#3-3#4-1,12]+1]],1,"Trumpet"]&

```

A better output for the cost of 34 bytes.

# Answer
> 2 votes
# Jelly,  ~~37~~  36 bytes

```
ØAḣ7;⁾#b“®JXrẊỤȥ’ṃnŒl$œṗ$Ḋ©i_⁸æ.J¤ị®

```

A dyadic link accepting the valves as a list of `1`s or `0`s as a list representing `[second, first, third]` on the left and the embouchure as a list of characters on the right which returns a list of characters.

**Try it online!**

### How?

```
ØAḣ7;⁾#b“®JXrẊỤȥ’ṃnŒl$œṗ$Ḋ©i_⁸æ.J¤ị® - Link: list of integers, V; list of characters, E
ØA                                   - yield uppercase alphabet
  ḣ7                                 - head to index 7 = "ABCDEFG"
     ⁾#b                             - literal list of characters = "#b"
    ;                                - concatenate = "ABCDEFG#b"
        “®JXrẊỤȥ’                    - literal integer = 2270857278734171
                 ṃ                   - base decompress (i.e. convert to base 9 using the 'digits' "bABCDEFG#")
                                     -                 = "ABbBCC#DEbEFF#GG#"
                        $            - last two links as a monad:
                     $               -   last two links as a monad:
                   Œl                -     to lower case = "abbbcc#debeff#gg#"
                  n                  -     not equal? (vectorises) = [1,1,0,1,1,1,0,1,1,0,1,1,1,0,1,1,0]
                      œṗ             -   partition at truthy indices = [[],"A","Bb","B","C","C#","D","Eb","E","F","F#","G","G#"]
                         Ḋ           - dequeue = ["A","Bb","B","C","C#","D","Eb","E","F","F#","G","G#"]
                          ©          - copy to register and yield
                           i         - first index of E in there
                                 ¤   - nilad followed by links as a nilad:
                             ⁸       -   chain's left argument, V
                                J    -   range of length [1,2,3]
                              æ.     -   dot product (i.e. 1*second + 2*first + 3*third)
                            _        - subtract
                                   ® - recall from register
                                  ị  - index into (1-based and modular)

```

# Answer
> 2 votes
# Ruby, 71 bytes

```
->e,(b,c,d){a=%w{Bb B C C# D Eb E F F# G G# A};a[a.index(e)-b*2-c-d*3]}

```

Try it online!

### 70 chars but 80 bytes

```
->e,(b,c,d){a="B♭BCC♯DE♭EFF♯GG♯A".scan /.\W?/;a[a.index(e)-b*2-c-d*3]}

```

Try it online!

# Answer
> 1 votes
## Javascript 96 bytes

Following @vasilescur idea, this is the implementation in js

```
(a,b,c,d,_="B♭,B,C,C♯,D,E♭,E,F,F♯,G,G♯,A".split`,`)=>(l=_.concat(_))[l.indexOf(a,9)-(2*b+c+3*d)]

```

```
a=(a,b,c,d,_="B♭,B,C,C♯,D,E♭,E,F,F♯,G,G♯,A".split`,`)=>(l=_.concat(_))[l.indexOf(a,9)-(2*b+c+3*d)]
console.log(a('B♭',0,0,0))
console.log(a('B♭',0,1,0))
console.log(a('B♭',1,0,1))
console.log(a('C♯',0,0,1))
console.log(a('C♯',1,1,1))
console.log(a('E♭',1,0,0))
console.log(a('G',0,1,1))
console.log(a('G♯',1,0,0))
console.log(a('G♯',0,0,1))
console.log(a('G',1,0,0))
console.log(a('F♯',1,0,0))
console.log(a('D',1,0,1))
console.log(a('A',1,1,1))
console.log(a('E',1,1,0))
console.log(a('E',0,0,1))
```

# Answer
> 1 votes
## Batch, 188 bytes

```
@set n=%1
@set/aC=0,D=2,Eb=3,E=4,F=5,G=7,A=9,Bb=10,B=11,n=(%n:#=+1%+12-%2*2-%3-%4*3)%%12
@for %%n in (C.0 C#.1 D.2 Eb.3 E.4 F.5 F#.6 G.7 G#.8 A.9 Bb.10 B.11)do @if %%~xn==.%n% echo %%~nn

```

Uses `#` and `b`: this means that `Eb` and `Bb` are legal variable names; `#` is handled by doing a string replacement to `+1`. The result of the string replacement is then automatically evaluated and the valves are then taken into account before the result is looked up in a list.

# Answer
> 1 votes
# Stax, 32 bytes

```
τ┤=Yº○!AÄΔâß₧←╥╟ö'ÄD├æñßf╧å▬tó÷╖

```

Run and debug it online

It takes a note name and a list of depressed valves. It builds an array of note names, then calculates the total valve interval, and gets the note at that offset in the array.

```
"AbABbBCC#DEbEFF#G" just a literal
{VA#}(Y             partition at capital letters and store in y
,]I                 get the index of the input note
,2R:t               swap 1s and 2s in valve list
{-F                 subtract valve list from note index
y@                  look up result from note array

```

Run this one

# Answer
> 1 votes
# Python 2, ~~84~~ 79 bytes

```
lambda e,a,b,c,s='Bb B C C# D Eb E F F# G G# A'.split():s[s.index(e)-2*a-b-3*c]

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~92 86~~ 82 bytes

```
*r=L"扢bc⍣d扥ef⍦g⍧a",*u;v(z,y,x,w)short*z;{u=wcschr(r,*z);u-=2*y+x+3*w;u+=(u<r)*12;}

```

Try it online!

Adapted from @Vazt's implementation.

# Answer
> 0 votes
# Perl6/Rakudo 73 chars

Technically this is 83 bytes because I put the Unicode characters in, but swapping them for the ASCII equivalents would give 73 bytes.

As a `{code block}` with parameters like `$^a` this is a lambda, with a signature `($a, $b, $c, $d)`.

```
{$_=2*$^b+$^c+3*$^d;'AG♯GF♯FEE♭DC♯CBB♭'x 2~~/$^a(\w\W?)**{$_}/~~/\w\W?$/}

```

Call it:

```
say { ... }("D", 1, 0, 1)
>> A

```

Less-golfed:

```
sub f($a, $b, $c, $d) {
   my $totalShift = 2*$b + $c + 3*$d;
   my $doubledScale = 'AG♯GF♯FEE♭DC♯CBB♭' x 2;
   my $matchEmbOnward = $doubledScale ~~ / $^a (\w\W?)**{$totalShift} /;
   my $matchFinalNote = $marchEmbOnward ~~ / \w \W? $ /;
   return $matchFinalNote;
}

```

Here we double a string `'...' x 2` using the `x` infix operator, then searching for the embouchure followed by n notes using the smartmatch operator `'...' ~~ /.../` \- the regex hinges on `\w\W?` which is a word char then maybe a non-word char.

We look for n instances of that via `(\w\W?)**{$_}`, where we've already calculated n=`$_` from params `$b` to `$d`. This yields a match from the embouchure note to the resulting note, of which we just want the last so we match that with another `~~ /\w\W?$/`.

The calculation of `$_` first is necessary to permit `$^b` implicit param creation on the block.

## 76 chars

An alternative using an array rather than string matches is 3 more chars:

```
{$_=<B♭ B C C♯ D E♭ E F F♯ G G♯ A>;.[((.first: $^a,:k)-2*$^b-$^c-3*$^d)%12]}

```

Finding the embouchure in the list is achieved with `@arr.first: $^a, :k`, which returns the index (key) of the found element with `:k`.

Setting the array to `$_` (as an object) lets us use `.first` and `.[ ]` on it without spending too many characters.

# Answer
> 0 votes
# C (gcc), 155 bytes

```
char r[][12]={"bb","b","c","c#","d","eb","e","f","f#","g","g#","a"};u;v(z,y,x,w)char*z;{for(;u<12;u++)if(!strcmp(z,r[u]))break;u=u-2*y-x-3*w;u=u<0?12+u:u;}

```

Try it online!

Simple approach.

Valve input is 0,1.

Embouchure input must be lowercase. Interestingly, TiO is not finding `strcmpi()` without including `string.h`, whereas mingw-gcc allows it with the standard `-Wimplicit-function-declaration` warning.

---
Tags: code-golf, music
---


title: Which dominoes are missing?

text:
# Question
Title: Which dominoes are missing?
A standard domino set has 28 unique pieces:

Given a list of 28 or fewer unique dominoes, output the list required to make a complete set.

Input and output dominoes are specified by two digits - the number of pips on each side of the domino, e.g. `00`, `34`, `40`, `66`.

The digits may be given in any order, so `34` is the same domino as `43`

### Example Inputs

```
00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 33 34 35 36 44 45 46 55 56 66
00 10 11 20 21 22 30 31 32 33 40 41 42 43 44 50 51 52 53 54 55 60 61 62 63 64 65 66
00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 34 35 36 44 45 46 55 56 66
00 02 03 04 05 06 11 13 14 15 16 22 24 25 26 33 35 36 44 46 55 66
<empty list>

```

### Corresponding Example Outputs

```
<empty list>
<empty list>
33
01 12 23 34 45 56
00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 33 34 35 36 44 45 46 55 56 66

```

# Answer
> 10 votes
## CJam, 11 bytes

```
{:$7Ym*:$^}

```

An unnamed block (function) with I/O as a list of pairs of integers.

Test it here.

### Explanation

```
:$   e# Sort each pair in the input.
7Ym* e# Get all pairs with elements in range [0 .. 6] using a Cartesian product.
:$   e# Sort each pair.
^    e# Symmetric set-difference. This will remove all pairs that are in the input
     e# and also remove duplicates, because it's a set operation.

```

# Answer
> 6 votes
## Pyth, ~~12~~ 10 bytes

```
-.CU7 2SMQ

```

Input and output in format `[[0, 0], [0, 1], ...]`.

```
   U7       generate range [0, 1, ..., 6]
 .C   2     all combinations-with-replacement of 2, generates [[0,0],[0,1],...]
         Q  get the input
       SM   sort each domino (turns ex. [1,0] into [0,1])
-           remove the map-sort'd input from the full array

```

Try it here.

Thanks to @MartinBüttner for saving 2 bytes with a different input/output format!

# Answer
> 5 votes
## JavaScript (ES7 proposed), ~~80~~ 76 bytes

```
s=>[for(n of d="0123456")for(o of d.slice(n))if(s.search(n+o+'|'+o+n)<0)n+o]

```

Takes input as a space-separated string and returns an array of strings. Array comprehensions really pull their weight for this one.

# Answer
> 3 votes
# Ruby 74 bytes

```
->b{a=(0..27).map{|i|"%d%d"%[i%7,(i+i/7)%7]}
b.map{|e|a-=[e,e.reverse]}
a}

```

Takes an array of strings, returns an array of strings.

**Commented in test program**

```
f=->b{a=(0..27).map{|i|"%d%d"%[i%7,(i+i/7)%7]} #generate complete set of dominos (each domino once) and store in a
b.map{|e|a-=[e,e.reverse]}                     #remove provided dominos (check both forward and reverse representations)
a}                                             #return a

p f[%w{00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 33 34 35 36 44 45 46 55 56 66}]
p f[%w{00 10 11 20 21 22 30 31 32 33 40 41 42 43 44 50 51 52 53 54 55 60 61 62 63 64 65 66}]
p f[%w{00 01 02 03 04 05 06 11 12 13 14 15 16 22 23 24 25 26 34 35 36 44 45 46 55 56 66}]
p f[%w{00 02 03 04 05 06 11 13 14 15 16 22 24 25 26 33 35 36 44 46 55 66}]
p f[[]]

```

**Output**

```
[]
[]
["33"]
["01", "12", "23", "34", "45", "56"]
["00", "11", "22", "33", "44", "55", "66", "01", "12", "23", "34", "45", "56", "60", "02", "13", "24", "35", "46", "50", "61", "03", "14", "25","36", "40", "51", "62"]

```

In the last example (input empty list) note the order of generation of the complete list of dominoes using modular arithmetic. 7 Doubles are generated first, then 7 dominoes with a difference of 1 (or 6) pips between each side, then 7 dominoes with a difference of 2 (or 5) pips, and finally 7 dominoes with a difference of 3 (or 4) pips.

# Answer
> 3 votes
# Julia 0.6, 47 bytes

```
A->setdiff([[i,j]for i=0:6 for j=i:6],sort.(A))

```

Try it online!

*(Corrected range start thanks to JayCe.)*

---

## 48 bytes

```
A->[(i,j)for i=0:6 for j=i:6 if[i,j]∉sort.(A)]

```

Try it online!

# Answer
> 2 votes
# Perl, 48 + 1 = 49 bytes

```
for$=(0..6){for$.($=..6){/$=$.|$.$=/||say$=.$.}}

```

Requires the `-n` flag, and the free `-M5.010`|`-E`:

```
$ perl -nE'for$=(0..6){for$.($=..6){/$=$.|$.$=/||say$=.$.}}' <<< '00 02 03 04 05 06 11 13 14 15 16 22 24 25 26 33 35 36 44 46 55 66'
01
12
23
34
45
56

```

Pretty boring answer overall, but here goes with an ungolfed version:

```
# '-n' auto reads first line into `$_`:
# $_ = <>;
foreach $a (0..6) {
  foreach $b ($a..6) {
    say $a . $b unless $_ =~ /$a$b|$b$a/;
  }
}

```

# Answer
> 2 votes
# Python 2, 91 bytes

```
lambda A,S="0123456":sum([[i+j for j in S[int(i):]if(i+j in A)+(j+i in A)<1]for i in S],[])

```

**Try it online!**

# Answer
> 2 votes
# JavaScript (SpiderMonkey), 69 bytes

```
s=>[for(n of d="0123456")for(o of d)if(n<o<!s.match(n+o+'|'+o+n))n+o]

```

Try it online!

optimized from Neil's

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

```
6Ýã€{JI€{KÙ

```

-1 byte thanks to *@Emigna*.

Try it online.

**Explanation:**

```
6Ý         # [0,1,2,3,4,5,6]
  ã        # Duplicate and take the cartesian product (pair up each)
   €{      # Sort each pair
     J     # Join them together to strings
I€{        # Sort each pair-string of the input
K          # Remove all pairs from the input from the cartesian list
Ù          # Only leave unique values

```

# Answer
> 2 votes
# , 111 bytes

```
function(s,p=paste0,L=lapply)setdiff(p(sequence(1:7)-1,rep(0:6,t=1:7)),L(L(strsplit(s,''),sort),p,collapse=''))

```

Try it online!

Not really proud of this, but R is not very "golfy" in splitting/concatenating strings...

# Answer
> 1 votes
# Mathematica, 49 bytes

```
Complement[Join@@Table[{x,y},{x,0,6},{y,0,6}],#]&

```

Input is list of list of integers.

# Answer
> 1 votes
# Java 8, 105 bytes

A void lambda accepting a mutable `java.util.Set<String>`.

```
s->{for(int i=0,a,b;i<49;)if(s.add(""+(a=i/7)+(b=i++%7))&(s.add(""+b+a)|a==b))System.out.print(" "+a+b);}

```

Try It Online

## Ungolfed

```
s -> {
    for (int i = 0, a, b; i < 49;)
        if (
            s.add("" + (a = i / 7) + (b = i++ % 7))
            & (
                s.add("" + b + a)
                | a == b
            )
        )
            System.out.print(" " + a + b);
}

```

## Acknowledgments

* -1 byte thanks to Jonathan Frech

# Answer
> 1 votes
# J, 26, 24 bytes

*-2 bytes thanks to FrownyFrog*

```
(;(,.i.,])&.>i.7)-.\:~"1

```
* `(;(,.i.,])&.>i.7)` calculates the full set (this part could be golfed further, I believe. And please do if you see how...)
* `-.` is "set minus"
* `/:~"1` orders each of the inputs

Try it online!

## Original

Try it online!

```
((#~<:/"1)>,{;~i.7)-./:~"1

```

# Answer
> 1 votes
# Jelly, 8 bytes

```
Ṣ€7ḶŒċ¤ḟ

```

Try it online!

Argument is a list of length-2 lists of integers. The footer transforms the input from the format in the test cases to the format this solution accepts.

# Answer
> 1 votes
# Python 2, ~~89~~ 86 bytes

Saved a few bytes by simplifying domino set generation.

```
lambda z,s="0123456":{x+y for x in s for y in s[int(x):]}-{(a+b,b+a)[a>b]for a,b in z}

```

Try it online!

Takes a list of strings like \["00", "10", "02\] as an argument for the dominoes. Returns python set objects, which are unordered distinct lists.

**Explanation**

```
# anonymous function, s should always have its default value
lambda z,s="0123456":
                     # contents are a set
                     {                                  }
                          # iterate over characters in string
                          for x in s
                                     # for each x, iterate over x from index of current item forward
                                     for y in s[int(x):]
                     # add characters together for domino string
                     x+y
                                                         # contents are a set, return the difference between these two sets
                                                         -{                          }
                                                             # iterate over items in input list, split strings into two characters
                                                                         for a,b in z
                                                             # sort strings in input list (so that i.e. "10" => "01")
                                                             # essentially, "ab" if a<b, otherwise "ba"
                                                             (a+b,b+a)[a>b]

```

# Answer
> 0 votes
## Haskell, 65 bytes

```
f x=[[a,b]|a<-"0123456",b<-[a..'6'],notElem[a,b]x&&notElem[b,a]x]

```

Usage example:

```
*Main> f ["00","02","03","04","05","06","11","13","14","15","16","22","24","25","26","33","35","36","44","46","55","66"]
["01","12","23","34","45","56"]

```

Iterate `a` in an outer loop over all digits from `0` to `6` and `b` in an inner loop over all digits from `a` to `6` and keep those `ab` where neither `ab` nor `ba` are found in the input string.

# Answer
> 0 votes
## Seriously, 16 bytes

```
,`S`M7r;∙`εjS`M-

```

Takes input as a list of strings, outputs a list of strings

Try it online!

Explanation:

```
,`S`M7r;∙`εjS`M-
,`S`M             map: sort each input string
     7r;∙         cartesian product of range(0,7) ([0,1,2,3,4,5,6]) with itself
         `εjS`M   map: join on empty string, sort (results in all valid dominoes with some duplicates)
               -  set difference (all values present in valid dominoes set not present in input, with duplicates removed)

```

---

## Actually, 13 bytes (non-competing)

```
♂S7r;∙`εjS`M-

```

This is identical to the Seriously answer (with the exception of implicit input and `♂S` being a shorter way to short each input string).

Try it online!

# Answer
> 0 votes
# racket

```
(define (missing-dominoes input)
  (filter
   (lambda (n)
     (not (member n (map
                     (lambda (n)
                       (let ((x (quotient n 10)) (y (remainder n 10)))
                         (if (<= x y) n (+ (* y 10) x))))
                     input))))
   (for*/list ([i (in-range 7)] [j (in-range i 7)])
     (+ (* 10 i) j))))

```

---
Tags: code-golf, dominoes
---


title: White Elephant Exchange

text:
# Question
Title: White Elephant Exchange
It's Christmas in July, so what better way to celebrate than a virtual white elephant gift exchange!

For this King of the Hill challenge, you must create a bot that plays in a White Elephant exchange simulation, trying to get the highest-valued present it can.

# Game Rules

* The game will be played over many rounds, each made up of a variable number of turns.
* **Round Setup**: There will be as many presents as there are players in the game, each valued randomly uniformly in the range \[0...1), with this value being unknown until the present is "opened". Players will be put in a random order in a queue. The first player will be popped from the front of the queue.
* When it is a player's turn, they may either open a present or steal another player's present, passing turn to the player whose present was stolen.
    + Each present may be stolen up to 3 times.
    + You cannot steal from the player that just stole from you.
    + Each player can only have one present at a time.
* After a present is opened, play advances to the next player popped from the front of the queue. This will be the next player in turn order who has not yet had a turn.
* **Round End**: When all presents have been opened, the round ends, and the value of the present held by each player is added to that player's score. A new round begins, with each player now holding no present and the player order shuffled.
* **Game End**: The game will end when at least one player has at scored 100 500 points, with victory being awarded to the player with the highest total value of presents.

# Coding

All submissions should be compatible with Python 3.7. You must write a class that directly inherits from `WhiteElephantBot`. For instance:

```
class FooBot(WhiteElephantBot):
    # Your implementation here

```

You may provide an `__init__` method (which takes one argument, `name`) in your bot class, which must call `super().__init__(name)`. Your class must have a `take_turn` method expecting the following arguments in this order:

* `players`: The list of player names, in turn order, of all players that do not yet have presents.
* `presents`: A dictionary that maps player names to 2-tuples containing the present value held by that player and the number of times that present has been stolen. This will only include other players who are currently holding presents.
* `just_stole`: If the last action taken was a steal, this will be the name of the player who just stole. If not, it will be `None`.

Each argument will be immutable or a new object so that mutating any of them will not have an effect on the game. You may keep a copy of any of the arguments if you so desire.

An example value for `presents`:

```
{
    'Alice':   (0.35, 0),
    'Bob':     (0.81, 2),
    'Charlie': (0.57, 1)
}

```

Your `take_turn` method should return the name of the player you wish to steal from or `None` to open a present. If it raises an exception, returns something other than a `str` or `None`, or the name of a player you cannot steal from, you will open a present by default.

Your constructor will be called at the beginning of each round, so you do not get to remember state from round to round.

By inheriting from `WhiteElephantBot`, you will have access to a `steal_targets` method that will take the presents dict and `just_stole` and return a list of names of players you can steal from.

Any modules your script needs must be imported at the top of your entry.

# Test Driver

The test driver can be found here. You do not need to include `from white_elephant import WhiteElephantBot` in your posted answer, however a local module will need to do that.

# Baseline Competitors

* **Random**: Chooses randomly whether to open a new present or to steal, with the steal target chosen uniformly randomly.
* **Greedy**: steal the most valuable present that can be stolen. If no presents can be stolen, open a present.
* **Nice**: Always opens a new present. Never steals.

# Additional Rules

* It is your responsibility to catch all exceptions. If your class fails to catch an exception, it will be disqualified. In addition, please do not catch KeyboardInterrupts.
* Do not use files or other methods to bypass the inability to save state between games. You may not, for instance, save a neural network state to a file mid-run.
* Your bot must be self-contained within class code and related constants.
* You may only use standard library imports.
* There is no strict performance requirement. Be reasonable and prudent. If performance becomes an issue, I reserve the right to add time limits.
* One entry per person. If you submit more than one entry, your bots may not work together. I'm going to allow multiple entries per person for now, though I may reban it later if it becomes a problem.
* This is an open competition with no distinct end date. It will be rerun any time I am able when there have been significant changes.

EDIT1: Changed winning score from 100 to 500 so that rankings are more consistent. The test driver has a new bugfix and also reflects the win score changes.

EDIT2: Clarifying note on required imports.

---

# Leaderboard (as of Aug 8, 2018)

1. SampleBot (500.093)
2. LastMinuteBot (486.163)
3. RobinHood (463.160)
4. OddTodd (448.825)
5. GreedyBot (438.520)
6. SecondPlaceBot (430.598)
7. ThresholdBot (390.480)
8. Gambler (313.362)
9. NiceBot (275.536)
10. RandomBot (256.172)
11. GoodSamaritan (136.298)

# Answer
# LastMinuteBot

(With big thanks to @Mnemonic for the skeleton of the code, since I barely know Python.)

```
class LastMinuteBot(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        targets = self.steal_targets(presents, just_stole)
        if len(targets) <= 1:
            return None

        target = None

        # If most of the presents are already distributed, try to steal an
        #  un-restealable gift of high value
        if len(presents) > (len(players) + len(presents)) * 0.75:
            at_threshold = [t for t in targets if presents[t][1]==2 and presents[t][0]>=0.8]
            if at_threshold:
                target = max(at_threshold, key=lambda x: presents[x][0])

        # Otherwise, take the best available
        if not target:
            target = max(targets, key=lambda x: presents[x][0])

        return target if presents[target][0] > 0.5 else None

```

Take advantage of the fact that gifts can't be stolen more than thrice, do the third stealing yourself if you find a high value gift and most presents have been opened.
> 3 votes

# Answer
# Odd Todd

```
class OddTodd(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):

        targets = self.steal_targets(presents, just_stole)

        # if none to steal, pick present
        if len(targets) <= 1:
            return None

        # steals the best gift that he can, as long as he's the 1st/3rd steal
        targets = [t for t in targets if presents[t][1] % 2 == 0]
        if targets:
            return max(targets, key=lambda x:presents[x][0])

        else:
            return None

```

Steals the best gift that he can, but doesn't want to be the second person to steal a gift, because if it gets stolen from him he can't get it back.
> 3 votes

# Answer
# SecondPlaceBot

```
class SecondPlaceBot(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        targets = self.steal_targets(presents, just_stole)
        if len(targets) <= 1:
            return None

        # If most of the presents are already distributed, take the second best.
        if len(presents) > (len(players) + len(presents)) * 0.8:
            target = sorted(targets, key=lambda x: presents[x][0])[-2]
        # Otherwise, take the best and hope someone steals it later.
        else:
            target = max(targets, key=lambda x: presents[x][0])

        return target if presents[target][0] > 0.5 else None

```

Everyone's going to be fighting for the most valuable gift. The next best gift is almost as good, but much less likely to be stolen.
> 1 votes

# Answer
# ThresholdBot

```
import random

class ThresholdBot(WhiteElephantBot):
    def __init__(self, name):
        self.name = name
        # Choose a minimum value to be happy.
        self.goal = 1 - random.random() ** 2

    def take_turn(self, players, presents, just_stole):
        # Find who has a gift that's sufficiently valuable.
        targets = self.steal_targets(presents, just_stole)
        targets = [x for x in targets if presents[x][0] >= self.goal]
        targets = sorted(targets, key=lambda x: presents[x][0])

        if not targets:
            return None

        # Choose a target (biased toward the best gifts).
        weighted = []
        for i, target in enumerate(targets, 1):
            weighted += [target] * i ** 2
        return random.choice(weighted)

```

We don't really care about getting the *best* gift, just something *good enough*. So long as there's something worth stealing, we'll do it.
> 1 votes

# Answer
# SampleBot

```
import random

class SampleBot(WhiteElephantBot):
    def rollout(self, values, counts, just_stole, next_move):
        targets = set()
        move_chosen = False
        for i, (v, n) in enumerate(zip(values, counts)):
            if v and n < 3 and i != just_stole and i != 0:
                targets.add(i)
        for i in range(len(values)):
            if values[i]:
                break
            while True:
                if not targets:
                    break
                if move_chosen:
                    j = max(targets, key=lambda i: values[i])
                    if values[j] < 0.5:
                        break
                else:
                    move_chosen = True
                    if next_move is None:
                        break
                    j = next_move
                values[i] = values[j]
                counts[i] = counts[j] + 1
                values[j] = 0
                counts[j] = 0
                if just_stole is not None and counts[just_stole] < 3:
                    targets.add(just_stole)
                if j in targets:
                    targets.remove(j)
                just_stole = i
                i = j
            values[i] = random.random()
            for player in (just_stole, i):
                if player is not None and values[player] and counts[player] < 3:
                    targets.add(player)
        return values[0]
    def take_turn(self, players, presents, just_stole, n_rollouts=2000):
        names = [self.name] + players + list(presents.keys())
        values = [presents[name][0] if name in presents else None for name in names]
        counts = [presents[name][1] if name in presents else 0 for name in names]
        if just_stole is not None:
            just_stole = names.index(just_stole)
        targets = [None]
        for i, (v, n) in enumerate(zip(values, counts)):
            if v and n < 3 and i != just_stole and i != 0:
                targets.append(i)
        if len(targets) == 1:
            return targets[0]
        scores = [0. for _ in targets]
        n = n_rollouts // len(targets)
        for i, target in enumerate(targets):
            for _ in range(n):
                scores[i] += self.rollout(list(values), list(counts), just_stole, target) / float(n)
        target_index = targets[scores.index(max(scores))]
        if target_index is None:
            return None
        return names[target_index]

```

Runs 2000 simulations with each player acting greedily and chooses the best action.
> 1 votes

# Answer
# GoodSamaritan

```
class GoodSamaritan(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        targets = self.steal_targets(presents, just_stole)

         #if only one player has a gift, don't steal it!
        if len(presents)<=1 or len(targets)==0:
             return None
        else:
             #Steal the worst present
             return min(targets, key=lambda x: presents[x][0])

```

Give unlucky people another chance at good fortune
> 1 votes

# Answer
# RobinHood

```
class RobinHood(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        #get the possible steal targets
        targets = self.steal_targets(presents, just_stole)
        #who stole his gift?
        targets = [x for x in targets if presents[x][1] > 0]
        #sort by value
        targets = sorted(targets, key=lambda x: presents[x][0])
        #only steal back if it's worth it
        targets = [x for x in targets if presents[x][0] > 0.5]

        if len(targets)>0:
           return targets.pop()

```

Steal from the rich who didn't earn their present
> 1 votes

# Answer
# Gambler

```
class Gambler(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        #get the possible steal targets
        targets = self.steal_targets(presents, just_stole)

        #last player
        if len(players)==0:
            #lets gamble! Try and get the highest score
            return None

        #If you are not last, steal the best gift that can be restolen so maybe you can become the last player
        targets = [t for t in targets if presents[t][1]<2 ]
        if targets:
            return max(targets, key=lambda x: presents[x][0])

```

The Gambler is addicted, he tries to be the last player, then he gambles on a new present to beat all the other players.
> 0 votes

# Answer
# Top3Bot

```
class Top3Bot(WhiteElephantBot):
    def __init__(self, name):
        super().__init__(name)
        self.firstturn = True

    def take_turn(self, players, presents, just_stole):
        if self.firstturn:
            num_presents = len(players) + len(presents) + 1
            self.value_limit = (num_presents - 3) / num_presents
            self.firstturn = False

        targets = self.steal_targets(presents, just_stole)

        if players:
            targets += None

        return max(
            targets,
            key=lambda name: self.steal_ranking(name, presents, len(players))
        )

    def steal_ranking(self, name, presents, presents_remaining):
        if name is None:
            return (0, 0)

        present_value = presents[name][0]
        num_steals = presents[name][1]
        if present_value >= self.value_limit:
            if num_steals == 2:
                return (5, present_value)
            elif  num_steals == 0:
                return (4, -presemt_value)
            elif num_steals == 1 and presents_remaining == 0:
                return (3, -present_value)
            else:
                return (-1, present_value)
        else:
            if num_steals < 2:
                return (2, present_value)
            else:
                return (-2, present_value)

```

This bot does not try to get the best present possible, but tries to get a present that is valued \>= (n-3)/n, where n is the number of presents. In most of the cases, there will be presents valued that much, and Top3Bot will try to get its hands on one of these, but he doesn't really care which of those he gets.
> 0 votes

---
Tags: king-of-the-hill, python
---