# Question
Title: Erverse Hte Ifrst Wto Eltters fo Aech Owrd
> *Inspired by this accidental misspelling*

If you could read the title, then you already know what the challenge is about. If not, then I'll tell you. Easy: simply take each word (single space delimited), and swap the positions of the first two letters. You may assume that the input will contain only lowercase ASCII letters and spaces and that there will be no one-letter words. You many optionally take a list of words instead of a sentence.

## Testcases

```
hello world -> ehllo owrld
this is an easy challenge -> htis si na aesy hcallenge
reverse the first two letters of each word -> erverse hte ifrst wto eltters fo aech owrd
pptx is one of ooxml format -> pptx si noe fo ooxml ofrmat
(empty) -> (empty)

```

## Leaderboard

```
/* Configuration */

var QUESTION_ID = 249523; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 107299; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{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
> 17 votes
# x86-64 machine code, 12 bytes

```
B0 20 66 C1 07 08 AE 72 FD 74 F7 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of the input, as a null-terminated byte string, in RDI, and modifies the string in place.

In assembly:

```
f:
    mov al, ' '     # Set AL to the ASCII code of the space.
nextword:
    rol WORD PTR [rdi], 8   # Rotate 2 bytes at the address RDI left by 8 bits.
                            # This swaps the current and next characters.
nextletter:
    scasb           # Compare AL with the current character, advancing the pointer.
    jb nextletter   # Jump back if AL is less than the character read.
    je nextword     # Jump back further if AL is equal to the character read.
    ret             # Return (if AL is greater than the character read).

```

# Answer
> 10 votes
# 05AB1E, ~~7~~ ~~6~~ ~~5~~ 4 bytes

```
εΣN≠

```

-1 byte thanks to *@CommandMaster*

Try it online.

**Explanation:**

```
ε     # Map over each word of the (implicit) input-list:
 Σ    #  (Stable) sort its characters by:
  N   #   Where the 0-based index
   ≠  #   Is not 1
      # (after which the list of modified words is output implicitly)

```

The `N≠` will make the 0-based indices of the characters in each word `[1,0,1,1,1,...]`, basically putting the second character at the front.

# Answer
> 9 votes
# V (vim), 4 bytes

```
òxpW

```

Try it online!

Explanation:

```
ò       # Recursively...
 x      #   Delete one letter
  p     #   Paste the last deleted letter
   W    #   Move forward one word

```

# Answer
> 8 votes
# Brainfuck, 30 bytes

*Thanks to tsh for -4 bytes.*

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

```

Explanation:

```
,[                loop every word
  >,.             print second character of word
  <[              loop through next letters of word including first one
    .             print next letter
    [-<++++++++>] multiply the letter by 8 (8*32=256; 256%256=0)
    <[            check if the result is zero
      ,>          if not then load next letter
    ]<
  ]
,]

```

Characters `@` and ``` can also be used as word separators as `8*64=512; 512%256=0` and `8*96=768; 768%256=0`.

Attempt This Online!

# Answer
> 7 votes
# Jelly, 4 bytes

```
żḢF)

```

A monadic Link that takes, as allowed in the comments, a list of words and yields a list of words.

**Try it online!**

### How?

```
żḢF) - Link: list of lists of characters, words  e.g. [..., "upend", ...]
   ) - for each word:
 Ḣ   -   head (word) -> remove and get the first character  "u"
ż    -   (beheaded word) zip with (head character)          ["pu","e","n","d"]
  F  -   flatten that back into to a list of characters     "puend"

```

Also requires no empty words, also allowed in the comments (as  would yield a zero).

Note: I would say that the `F` is necessary since without this flatten a callable link would return each new word as a list of lists of characters while as a full program it would smash the characters together when it prints.

# Answer
> 6 votes
# Vyxal, 9 8 5 4 bytes

\- x bytes thanks to @Steffan

```
ƛḣ$Y

```

Try it Online! | `S` Flag to join by spaces

## Explanation

```
ƛḣ$Y
ƛ     Map through each word
 ḣ    Push all but the first letter and the first letter
  $   Swap the first two elements
   Y  Interleave

```

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

```
s=>s.replace(/\b(\S)(.)/g,'$2$1')

```

Try it online!

# Answer
> 6 votes
# Brachylog, ~~9~~ 8 bytes

```
{pᶠkt↔}ᵐ

```

Try it online!

An extremely stupid solution but shorter than my initial, more straightforward idea.

*-1 byte thanks to @UnrelatedString with an event stupider idea*

### Explanation

```
{     }ᵐ    Map for each word:
 pᶠ           Find all permutations of the word
   kt         Get the penultimate one
     ↔        Reverse it

```

This works because `p` will always try permutations in the same order, and it happens that the penultimate one is the input in reverse order, with the last two characters swapped. It also works for 2 letter words because the penultimate permutation here will be the first one, i.e. the identity, and reversing it is the same as swapping the two characters.

# Answer
> 6 votes
# Python 3, 35 bytes

*Thanks to steffan for -34 bytes.*

```
lambda a:[x[1::-1]+x[2:]for x in a]

```

Try it out

p.s. This is my first serious attempt at Code Golf all feedback is appreciated!

# Answer
> 6 votes
# Piet \+ ascii-piet, ~~28~~ 25 bytes (13×2=26 codels)

```
tU?QjCuJsNrMbQvQsQjIJjMmm

```

Try Piet online!

−3 by switching to a vertical layout, allowing two white codels to be removed and one black codel to be implicit.

The program starts with *in(char), in(char), out(char), out(char)*, taking the first two letters from the input and outputting them in reversed order.

After that, it enters a loop:

* *in(char), duplicate, out(char)*: Read the next character from the input, and output it while leaving a copy on the stack.
* *push\[3\], duplicate, multiply, duplicate, multiply, push\[1\], add*: Create the value 82 on the stack.
* *divide*: Divide the character code by 82. This produces 1 for lowercase letters (97–122) and 0 for a space (32).
* *pointer*: Rotate the Direction Pointer clockwise by the value on the stack.
    + For lowercase letters, this sends execution rightwards and executes *subtract, out(char)*, which does nothing with the stack empty, before repeating the loop.
    + For spaces, execution continues upwards into the white area and returns to the start of the program to process the next word.
    + When the end of the input is reached, *in(char), duplicate, out(char)* does nothing and leaves the stack empty. The calculation of 82 still works, but then the *divide* does nothing because there is only one value on the stack, and the *pointer* rotates the Direction Pointer by 82, which is congruent to 2 modulo 4, sending it downwards. None of the reversed instructions are *push*es, so they all do nothing (because the stack is empty), and execution reaches the halting structure at the bottom.

# Answer
> 5 votes
# Zsh `--extendedglob`, 29 bytes

```
<<<${@/(#m)??/`rev<<<$MATCH`}
```

Attempt This Online!

Zsh's pattern matching is pretty limited.

-1 byte thanks to @GammaFunction.

# Answer
> 5 votes
# , 28 bytes

```
\(x)sub("(.)(.)","\\2\\1",x)
```

Attempt This Online!

Simple regex-breast, errr..., I mean... regex-based solution.

Takes input as a vector of words - this works nicely as `sub` is vectorised over the 3rd argument.

# Answer
> 5 votes
# Ruby, 28 bytes

```
->s{s.map{|w|(w.slice!1)+w}}

```

Try it online!

# Answer
> 4 votes
# QuadR, ~~18~~ ~~14~~ 9 bytes

```
\b\w.
⌽⍵M

```

Try it online!

PCRE **R**eplace:

`\b` a word boundary

`\w` any word character, and then

`.` any character

with:

`⌽⍵M` the reversed Match

# Answer
> 4 votes
# APL (dzaima/APL), 6 bytes

OP seems to have allowed input as a list, so here goes…

```
⌽@1 2¨

```

Try it online!

reverse

`@` at indices

`1 2` one and two

`¨` for each word

# Answer
> 4 votes
# BQN, ~~10~~ 8 bytes

*Edit: -2 bytes thanks to DLosc*

```
⌽⌾(2⊸↑)¨

```

Try it at BQN REPL

```
         ¨   # for each element of input
⌽            # reverse
 ⌾           # under
  (2⊸↑)      # take first 2 elements

```

The BQN 'under' modifier applies a function (here, take first 2 elements) and then applies another function on the result (here, reverse), and finally undoes the first function (so, it 'undoes' taking elements 1&2, thereby putting the result back into these positions).
Think 'operating under anaesthetic', where the anaesthetic is done before the operation and undone afterwards.

# Answer
> 4 votes
# Perl 5 \+ `-p040`, 13 bytes

Uses `-040` to work on each space separated section so that the replacement can be one off avoiding the need for `/g`, which makes it possible to use the implicit `;` from `-p` as the terminating separator.

```
s;(.)(.);$2$1

```

Try it online!

# Answer
> 4 votes
# sed `-r`, 17 bytes

```
s/\<(.)(.)/\2\1/g

```

Try it online!

Uses the rare 'start of word' marker `\<`.

# Answer
> 4 votes
# Haskell, 34 bytes

```
unwords.map(\(a:b:c)->b:a:c).words

```

Try it online!

# Answer
> 3 votes
# Jelly, <sup>~~10~~ ~~7~~</sup> 6 bytes

```
U2œ?U)
```

Attempt This Online!

-3 bytes by doing I/O as a list rather than a space-separated string, now that the OP has allowed that.

-1 thanks to @Unrelated String

Explanation:

Given a word \\$ a\_n \cdots a\_3 a\_2 a\_1 \\$, the permutation \\$ a\_n \cdots a\_3 a\_1 a\_2 \\$ is at index 2 in the list of permutations of that word.

```
     )       map over each word:
U            reverse
 2œ?         index 2 into all permutations of the reversed input
    U        (un-)reverse

```

# Answer
> 3 votes
# Python, 48 bytes

*Thanks to user `Kalobi` for -3 bytes and `pxeger` for another -3 bytes.*

```
print(*(i[1::-1]+i[2:]for i in input().split()))

```

Attempt This Online!

# Answer
> 3 votes
# Retina, 7 bytes

```
V`\b\w.

```

Try it online! Link includes test cases. Explanation: A simple use of Retina's reVerse command on the first two letters of each word.

# Answer
> 3 votes
# Java (OpenJDK 8), ~~38~~ 37 bytes

```
s->s.replaceAll("\\b(\\S)(.)","$2$1")

```

Try it online!

-1 thanks to @KevinCruijssen

Couldn't come up with a less boring version. The shortest other idea I had was just swapping `i+1` and `i+2` in an array where index `i` is a space, but just `toCharArray()` is 13 chars :(

# Answer
> 3 votes
# Nibbles, 5 bytes (10 nibbles)

```
:\<2@>2@

```

```
           # implicit map over input:
:          # append
 \         # the reverse of
  <2@      # take first 2 characters of each arg
           # onto
     >2@   # drop first 2 characters from each arg

```

# Answer
> 3 votes
# Java (JDK), 36 bytes

```
l->l.peek(s->s[0]^=s[1]^(s[1]=s[0]))

```

Try it online!

* Takes input as `Stream<char[]>`, and returns another `Stream<char[]>`, with each `char[]` being a word.

# Answer
> 3 votes
# K (ngn/k), 11 bytes

```
{x@>1=!#x}'

```

Try it online!

# Answer
> 3 votes
# Knight, 78 bytes

```
;=s+" "P;=i~1;=r"";W<=i+1iLs=r+r+=gGs i 1I?g" ";=i+2i+Gs i 1Gs-i 1 1""O Gr 1Lr

```

Try it online!

Expanded code:

```
;= s (+" " PROMPT)
;= i ~1
;= r ""
;WHILE <(= i + 1 i) (LENGTH s)
  =r + r
     + (=g (GET s i 1))
     IF (?g " ")
       ;=i (+ 2 i)
       + ((GET s i 1)
          (GET s (- i 1) 1))
       ""
OUTPUT (GET r 1 (LENGTH r))

```

# Answer
> 2 votes
# Jelly, 8 bytes

```
Ḳµḣ2Uo)K

```

Try it online!

## How it works

```
Ḳµḣ2Uo)K - Main link. Takes a string
Ḳ        - Split by spaces
 µ    )  - Over each word:
  ḣ2     -   Take the first two characters
    U    -   Reverse them
     o   -   Logical Or, overwriting the first two characters of the word
       K - Join with spaces

```

# Answer
> 2 votes
# Python 3, 51 bytes

```
lambda s:' '.join(w[1::-1]+w[2:]for w in s.split())

```

Try it online!

# Answer
> 2 votes
# Python 3, 73 bytes

```
f=lambda s:' '.join([''.join(list(i[:2])[::-1])+i[2:]for i in s.split()])

```

Try it online!

# Answer
> 2 votes
# APL+WIN, 26 bytes

Prompts for sentence

```
(⌽¨2↑¨s),¨2↓¨s←(s≠' ')⊂s←⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# C (gcc), 55 bytes

```
f(char*s){for(;s-1;s=index(s,32)+1)*s^=s[1]^(s[1]=*s);}

```

Try it online!

Inputs a pointer to a string.
Performs the reversing in place.

# Answer
> 2 votes
# Prolog (SWI), 34 bytes

```
[[X,Y|R]|A]^[[Y,X|R]|O]:-A^O.
A^A.

```

Try it online!

-6 bytes thanks to Jo King

I/O as list of list of codepoints.

# Answer
> 2 votes
# Desmos, 90 bytes

```
k=l.length
i=\{k=0:[],[1...k]\}
L=join(32,l)
f(l)=\{L[i-1]=32:L[i],L[i]=32:L[i+2],L[i+1]\}

```

Takes in space separated words as a list of codepoints, and returns another list of codepoints.

Probably a terrible way of doing this but whatever.

Here's a Python program that takes in a string as input and outputs a list of codepoints that Desmos can read. (e.g.: `hello world` -\> `o\to f\left(\left[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100\right]\right)`)

Here's a Python program that takes in the outputted list of codepoints from Desmos and converts it into a string. (e.g.: `\left[104,116,105,115,32,115,105,32,110,97,32,97,101,115,121,32,104,99,97,108,108,101,110,103,101\right]` -\> `htis si na aesy hcallenge`)

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# Chocolate \\$\ge\\$ commit 8b0b99b, 5 bytes

```
γỴD_Ḣ

```

Try it online!

Previously:

## Chocolate, 8 bytes

```
γC⅃:2_DD

```

Try it online!

# Answer
> 2 votes
# GolfScript, 17 bytes

```
' '/{2/(-1%\' '}/

```

Try it online!

# Answer
> 2 votes
# Python 3, 44 bytes

```
lambda s:[x[1]+x[0]+x[2:]for x in s.split()]

```

Try it online!

Outputs as a list of words.

# Answer
> 2 votes
# Japt, 5 bytes

I/O as an array of words.

```
ËÅíDÎ

```

Try it

```
ËÅíDÎ     :Implicit input of array
Ë         :Map each D
 Å        :  Slice off the first character
  í       :  Interleave with
   DÎ     :    First character of D

```

## 6 bytes

```
Ëò vÔ¬

```

Try it

```
Ëò vÔ¬     :Implicit input of array
Ë          :Map
 ò         :  Partitions of length 2
   v       :  Modify first element
    Ô      :    Reverse
     ¬     :  Join

```

# Answer
> 2 votes
# CJam, 16 bytes

```
{1Se[2/(W%\+}%S*

```

Try it online!

A function which takes an array of strings as input. Link includes test cases.

# Explanation

```
{1Se[2/(W%\+}%S* # whole function which takes an array of inputs
{           }%   # for each value in the input
   e[            # pad to length
 1               # `1` using
  S              # `S`paces
     2/          # split into chunks of length `2`
       (         # get the first split chunk
        W%       # map by `W` (shorthand for -1), reversing
          \+     # swap to the beginning of the stack and add to the rest of the array
              S* # join this array by `S`paces

```

# Answer
> 1 votes
# Lexurgy, 23 bytes

```
a:
[]$1 []$2=>$2 $1/$ _

```

Performs metathesis on the first 2 characters of each whitespace-delimited series of characters.

# Answer
> 1 votes
# sed, 23 bytes

```
s/(^| +)(.)(.)/\1\3\2/g
```

Can be shortened if one assumes that there are no consecutive spaces, or that the input starts with a space.

Attempt This Online!

# Answer
> 1 votes
# Ly, ~~18~~ 19 bytes

```
irf[' =fo[pfoo0]p]

```

Try it online!

This relies on the fact that each word will have at least two characters, which is noted in the description. It also assumes the input will not start or end with a space, and that there won't be multiple spaces in a row. That assumption is currently an open question. If that doesn't turn out to be OK, this approach won't work.

```
ir                 - read input as codepoints, reverse stack
  f                - reverse first two chars
   [             ] - for each char/codepoint on the stack...
    ' =            - is the current char a space?
       fo          - pull char forward and print
         [p   0]p  - if/then
           foo     - flip the top two chars and print them

```

# Answer
> 1 votes
# Rust, 164 bytes

```
|t:String|t.split(" ").filter(|i|i.len()>0).map(|i|{let k=i.chars().collect::<Vec<_>>();[&k[1..2],&k[0..1],&k[2..],&[' ']].concat()}).flatten().collect::<String>();
```

Strings will have a extra space at the end.

Attempt This Online!

# Answer
> 1 votes
# Factor, ~~51~~ 29 bytes

```
[ [ 0 1 pick exchange ] map ]

```

Try it online!

-22 bytes from OP allowing lists after I answered.

# Answer
> 1 votes
# Java, 148 bytes

```
class H {public static void main(String[]a){String l="";for(String s:a[0].split(" ")){l+=s.charAt(1);l+=s.charAt(0);l+=s.substring(2)+" ";}a[0]=l;}}

```

# Answer
> 1 votes
# Charcoal, 17 bytes

```
⪫Ｅ⪪Ｓ ⭆ι⎇‹μ²§ι¬μλ

```

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

```
   Ｓ                Input string
  ⪪                 Split on spaces
 Ｅ                  Map over words
      ι             Current word
     ⭆              Map over letters and join
         μ          Current index
        ‹           Is less than
          ²         Literal integer `2`
       ⎇            If true then
            ι       Current word
           §        Indexed by
              μ     Current index
             ¬      Logical Not (i.e 1 - index)
               λ    Else current letter
⪫                   Join with spaces
                    Implicitly print

```

Note: A trailing newline is needed in the input field otherwise Charcoal thinks you're supplying multiple inputs.

# Answer
> 1 votes
# Burlesque, 15 bytes

```
{2coq<-0ap++}ww

```

Try it online!

Unfortunately

```
 q<-"\b.."~a

```

Doesn't work as expected

```
{
 2co # Chunks of 2
 q<- # Quoted reverse
 0ap # Apply to first block
 ++  # Concat
}ww  # Apply to each word

```

# Answer
> 1 votes
# Pyth, 6 bytes

```
+L.(d1

```

Try it online!

Accepts a list of lists of characters ("words"), and returns a list of lists of characters.

```
+L.(d1
 L      Left map over the input:
  .(d1  Pop and return the second letter of each word
+       Append the popped letter to the remaining letters

```

---

If a list of strings is required as input/output:

### Pyth, 7 bytes

```
m.itdhd

```

Try it online!

# Answer
> 1 votes
# SM83, 19 bytes

Input pointer in `hl`, output pointer in `de`.

```
46 23 2A 12 13 78 12 13
2A 12 13 B7 C8 FE 20 20
F7 18 ED

```

```
f:
    ld b,[hl]       // 46       // y = *in
    inc hl          // 23       // in++
    ld a,[hl+]      // 2A       // x = *(in++)
    ld [de],a       // 12       // *out = x
    inc de          // 13       // out++
    ld a,b          // 78       // x = y
    ld [de],a       // 12       // *out = x
    inc de          // 13       // out++
l:
    ld a,[hl+]      // 2A       // x = *(in++)
    ld [de],a       // 12       // *out = x
    inc de          // 13       // out++
    or a            // B7       // is x NUL?
    ret z           // C8       // Y: return
    cp ' '          // FE 20    // is x SPACE?
    jr nz,l         // 28 F7    // N: continue copying
    jr f            // 18 ED    // Y: start all over

```

# Answer
> 1 votes
# Stacked, 14 bytes

```
[[0 1 exch]"!]

```

Try it online!

Alternatively, `0 1`  can be `0:#+`, but it's the same byte count.

## Explanation

Uses the classic golf `map``"!` (each execute).

```
[[0 1 exch]"!]
[            ]    anonymous lambda
 [        ]"!     execute this code on each cell
  0 1 exch        exchange indices 0 and 1

```

# Answer
> 1 votes
# Lua, 39 bytes

```
return(...):gsub("%f[%w](.)(.)","%2%1")

```

Try it online!

# Answer
> 1 votes
# Pip `-p`, 10 bytes

```
gR`^..`RV_

```

Inputs an array as multiple command-line arguments; outputs an array in Pip array syntax. Try It Online!

### Explanation

```
gR`^..`RV_
g           In array of command-line args,
 R          replace
  `   `     all matches of this regex:
   ^         Beginning of string
    ..       followed by two characters
       RV_  with the reverse of the match

```

---

An interesting alternate 10-byter can be achieved by porting math junkie's Pyth answer:

```
{aPK1}._Mg
        Mg  To each command-line arg, map this function:
{aPK1}       Pick the character at index 1 out of the string
      ._     and concatenate it to the rest of the string

```

Try It Online!

# Answer
> 1 votes
# GolfScript, 23 bytes

```
' '/{(\(@[\\]\+}[/]' '*

```

Try it online!

# Answer
> 1 votes
# str, 16 bytes

```
gg~:o;d' =?ogg~:

```

Try it online!

# Answer
> 1 votes
# \>\<\>, 10 bytes

```
r$:o84*)0.

```

Try it online!

**Explanation**

```
r           # reverse stack to get input in correct order
 $          # swap the top 2 letters of the stack
  :o        # print a copy of the letter
    84*)0.  # jump to coordinates x=previousLetterCharCode>32, y=0

```

# Answer
> 1 votes
# Arturo, 34 bytes

```
$[a][map a'w[t:w\0w\0:w\1w\1:t w]]

```

Try it

# Answer
> 1 votes
# Uiua <sup>SBCS</sup>, ~~8~~ 7 bytes

```
⍚⍜(↙2)⇌

```

Try it!

```
⍚⍜(↙2)⇌
⍚        # apply function to each item in list, unboxing and re-boxing
 ⍜       # apply one function 'under' another
  (↙2)   # take first two
      ⇌  # reverse

```

# Answer
> 1 votes
# morsecco:  ~~110~~  100 bytes

```
.    . - ..- - -- - . - .-. - - .-.. --.. --. - .- .   -. - .  -.-.  - . -.-. . -.-. .. --. - .- ---

```

Saved some bytes by combining three `-.-.` operations. Explanation:

* `. . - ..- -` to `E`nter an empty cell and `U`se stdin for `T`oken reading
* `-- - . - .-.` to `M`ark the beginning of the loop and `R`ead next word
* `- - .-.. --.. --.` to test the `L`ength of the token to `Z`eroskip the loop
* `- .- - .- . -. - .`  drops the length and prepares the `C` sequence: `C`ut the first two letters, than `C`ut the first and `C`oncatenate both in reverse order
* `-.-. - . -.-. .` execute that sequence, and `C`oncatenate the swapped word parts
* `-.-. .. --.` `C`oncatenates to the previous word and `G`oes to the mark
* `- .- ---` after jumping out of the loop, `O`utput the line

# Answer
> 1 votes
# TypeScript’s type system, 90 bytes

```
type X<L>=L extends[`${infer A}${infer B}${infer C}`,...infer R]?`${B}${A}${C} ${X<R>}`:""

```

Try it at the TS playground

# Answer
> 1 votes
# Gema, 11 characters

```
\X<L1>?=?$1

```

Sample run:

```
bash-5.2$ gema '\X<L1>?=?$1' <<< 'reverse the first two letters of each word'
erverse hte ifrst wto eltters fo aech owrd

```

Try it online! / Try all test cases online!

# Answer
> 0 votes
# Thunno 2, 5 bytes

```
ıÞṅ1Q

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
ıÞṅ1Q  # Implicit input
ı      # Map over each word:
 Þ     #  Sort the characters by:
  ṅ    #   Get the 0-based iteration index
   1Q  #   And check if it's not equal to 1
       # Implicit output

```

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


title: Count occurrences in Pascal's Triangle

text:
# Question
Title: Count occurrences in Pascal's Triangle
Pascal's triangle is a triangular diagram where the values of two numbers added together produce the one below them.

This is the start of it:

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

```

You can see that the outside is all 1s, and each number is the sum of the two above it. This continues forever.

Your challenge is to count the number of times a value \\$\> 1\\$ appears in Pascal's triangle.

For example, with the value 6:

```
       1
      1 1
     1 2 1
   1  3 3  1
  1 4  **6**  4 1
 1 5 10  10 5 1
1 **6** 15 20 15 **6** 1

```

It occurs three times. It will never occur more because after this, all numbers other than 1s will be greater than it.

As pointed out by tsh, this is A003016.

# Scoring

This is , shortest wins!

# Testcases

```
2 => 1
4 => 2
6 => 3
10 => 4
28 => 4
20 => 3
120 => 6

```

# Answer
# Gaia, 4 bytes

Full program. Doesn't work as a function because of the way it reuses the input.

```
K‡_C

```

Try it online!

`K‡` Table of binomial coefficients,  casts integer arguments to the range `[1 .. x]`.
`_` Flatten the table.
`C` count the number of occurences of the input in this list. `C` doesn't care about the order of arguments as long as one is a list and the other is not.
> 6 votes

# Answer
# Jelly, 5 bytes

```
c€ŻFċ

```

Try it online!

## How it works

```
c€ŻFċ - Main link. Takes n on the left
  Ż   - Range from zero; [0, 1, ..., n]
 €    - Over each integer 1 ≤ i ≤ n:
c     -   Calculate iCr for each r in [0, 1, ..., n]
   F  - Flatten
    ċ - Count occurrences of n

```
> 5 votes

# Answer
# , ~~41~~ 40 bytes

Or **\>=4.1, 33 bytes** by replacing the word `function` with `\`.

*Edit: -1 byte thanks to @Giuseppe.*

```
function(n)sum(outer(0:n,0:n,choose)==n)

```

Try it online!
> 5 votes

# Answer
# Ruby, ~~54~~ 53 bytes

```
->n,*a{(0..n).sum{y=0;a.map!{|x|y+y=x}<<1;a.count n}}

```

Try it online!

Thanks Dingus for -1 byte
> 5 votes

# Answer
# Vyxal, 7 bytes

```
ƛɾƈ;f?O

```

Try it Online!

Basically, just generate Pascal's triangle (sans the first row of just `1`) and get the count. Flagless just for Redwolf.

## Explained

```
ƛɾƈ;f?O
ƛ  ;     # for each n in the range [1, input]:
 ɾƈ      #   n c x for x in range [1, n] - ʀƈ also works if you want the full row for some reason.
    f    # flatten that
     ?O  # and get the count of the input in that

```
> 4 votes

# Answer
# Husk, 12 bytes

```
ṁ#¹↑¡Sż+Θ;1→

```

Try it online!

The last part of this answer (`Sż+Θ;1`) was copied verbatim from DLosc's clever answer to Generate Pascal's triangle. Go upvote that!

```
ṁ#¹↑¡Sż+Θ;1→
    ¡Sż+Θ;1  Generate Pascal's triangle (an infinite list)
         ;1  Start with the list [1]
    ¡        Repeatedly
        Θ    prepend 0 to the list,
      ż+     then add that to the original list,
      ż      keeping the last element of the new, longer list
   ↑         Take the first
           → n + 1 rows
ṁ            For each,
 #           find how many occurrences of
  ¹          the input they contain,
ṁ            then sum those counts

```
> 4 votes

# Answer
# JavaScript (ES6), 61 bytes

```
n=>eval("for(i=t=0;i++<=n;)for(q=j=1;q*=i-j,q/=j++;)t+=q==n")

```

Try it online!

Or **65 bytes** for a BigInt version:

```
n=>eval("for(i=t=0n;i++<=n;)for(q=j=1n;q*=i-j,q/=j++;)q-n?t:++t")

```

Try it online!
> 4 votes

# Answer
# Python 3, 67 bytes

```
f=lambda n,*r:r.count(n)+(r<(n,)and f(n,*map(sum,zip(r,(1,*r))),1))

```

Try it online!
> 4 votes

# Answer
# Excel (Insider Beta), ~~59~~ 55 bytes

*-4 using COMBIN(x+y,y) instead of COMBIN(x,y) eliminates need for IF*

```
=SUM(MAKEARRAY(A1,A1,LAMBDA(x,y,(COMBIN(x+y,y)=A1)*1)))

```

`LAMBDA` and `MAKEARRAY` are not in the current release of Excel Office 365.

## Excel Office 365, ~~67~~ 63 bytes

```
=LET(x,SEQUENCE(A1),y,TRANSPOSE(x),SUM((COMBIN(x+y,y)=A1)*1)))

```

Link to Spreadsheet
> 4 votes

# Answer
# Dyalog APL, ~~11~~ 10 bytes

*Thanks to ovs for -1 byte*

```
≢∘⍸⊢=⍳∘.!⍳

```

Try it online!

How it works:

```
         ⍳      Range [1, n]
      ∘.!      Outer product binomial with
     ⍳          Range [1, n]
    =          Equals
   ⊢            Right argument
 ⍸            Generate list of indices from truthy values
≢            Tally, get length

```
> 4 votes

# Answer
# K (ngn/k), 19 bytes

```
{+/,/x=x(+':|0,)\1}

```

Try it online!

* `x(+':|0,)\1` generate the first x+1 rows of Pascal's Triangle
    + `x(...)\1` run the code in `(...)` `x` times, seeded with `1`, returning a list containing the original input and the results from each iteration
    + `(+':|0,)` prepend a 0, then reverse the sequence. add each value to its predecessor
* `x=` check where the original input appears in these rows
* `+/,/` flatten the rows into a single list, then take the sum
> 4 votes

# Answer
# K (ngn/k), 15 bytes

```
{+//x=x+\\1+!x}

```

Try it online!

Different approach from @coltim, uses Pascal matrix.

Explanation:

```
{+//x=x+\\1+!x}
                / construct the pascal matrix:
      x  \      /  do x times saving intermediate results
       +\       /  cumulative sum
          1+!x  /  starting at the range [1,x]
    x=          / equals x?
 +//            / sum all elements in the binary matrix, giving the count

```
> 4 votes

# Answer
# MATL, 6 bytes (using Pascal matrix)

```
t2YL=z

```

Try it online! Or verify all test cases.

How it works, using input `6` as an example:

```
t    % Implicit input. Duplicate
     % STACK: 6, 6
2YL  % Pascal matrix of that size
     % STACK: 6, [1   1   1   1   1   1
                  1   2   3   4   5   6
                  1   3   6  10  15  21
                  1   4  10  20  35  56
                  1   5  15  35  70 126
                  1   6  21  56 126 252]
=    % Test for equality, element-wise
     % STACK: [0 0 0 0 0 0
               0 0 0 0 0 1
               0 0 1 0 0 0
               0 0 0 0 0 0
               0 0 0 0 0 0
               0 1 0 0 0 0]
z    % Number of nonzeros. Implicit display
     % STACK: 3

```

# MATL, 8 bytes (using binomial coefficients)

```
t:t!Xn=z

```

Try it online! Or verify all test cases.

How it works, using input `6` as an example:

```
t    % Implicit input. Duplicate
     % STACK: 6, 6
:    % Range. Gives a row vector
     % STACK: 6, [1 2 3 4 5 6]
t!   % Duplicate, transpose. Gives a column vector
     % STACK: 6, [1 2 3 4 5 6], [1
                                 2
                                 3
                                 4
                                 5
                                 6]
Xn   % Binomial coefficient, element-wise with broadcast. Gives a matrix
     % 6, [1  2  3  4  5  6
           0  1  3  6 10 15
           0  0  1  4 10 20
           0  0  0  1  5 15
           0  0  0  0  1  6
           0  0  0  0  0  1]
=    % Test for equality, element-wise
     % STACK: [0 0 0 0 0 1
               0 0 0 1 0 0
               0 0 0 0 0 0
               0 0 0 0 0 0
               0 0 0 0 0 1
               0 0 0 0 0 0]
z    % Number of nonzeros. Implicit display
     % STACK: 3

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 32 bytes

```
Count[Binomial~Array~{#,#},#,2]&

```

Try it online!
> 3 votes

# Answer
# Jelly, 7 bytes

```
ŻcŻ$€Fċ

```

Try it online!

A port of my Vyxal answer, and contains part of my Jelly answer to the "vanilla" pascal triangle generation.

(yes, this is the exact same as caird's answer but with an extra atom and quick because fgitw reasons)

## Explained

```
ŻcŻ$€Fċ # A monadic chain with argument n. Let the current value be λ
Ż       # λ = [0, n]
    €   # over each item in λ:
 cŻ$    #   yield item choose [0, item] (vectorising)
     F  # flatten that
      ċ # and get the count of n

```
> 2 votes

# Answer
# Ruby, 67 bytes

```
->n{a=[1]
n.times{|x|a=[1]+(1..x).map{|y|a[y]+a[y-1]}+a}
a.count n}

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 38 bytes

```
n->sum(i=0,n,#[1|j<-binomial(i),j==n])

```

Try it online!

When `binomial` takes only one argument, it returns the `n`'th row of the Pascal's triangle.
> 2 votes

# Answer
# Python 3.8 (pre-release), 80 bytes

```
lambda n:sum(math.comb(x,z)==n for x in range(n+1)for z in range(x))
import math

```

Try it online!
> 2 votes

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

```
δc˜I¢

```

Try it online or verify all test cases.

**Explanation:**

```
δc   # Create a binomial coefficients table:
δ    #  Apply double-vectorized:
     #  (which implicitly converts the implicit input-integer to the range
     #  [1,input] first, used twice)
 c   #   Binomial coefficient
˜I¢  # Count the amount of times the input occurs in this matrix:
˜    #  Flatten the matrix to a single list
 I¢  #  Count how many times the input is in this list
     # (after which the result is output implicitly)

```
> 2 votes

# Answer
# Perl 5, 91 bytes

```
sub{($i,$c)=@_;for$r(1..$i+1){$n=1;map$c+=$i-~~($n*=$r/$_-1)?0:$_>$r/2-1?1:2,1..$r/2-.5}$c}

```

Try it online!
> 2 votes

# Answer
# TI-Basic, 27 bytes

```
Input N
For(I,2,N
Ans+sum(N=I nCr seq(J,J,0,I
End

```

Output is stored in `Ans`.
> 2 votes

# Answer
# C (gcc), ~~96~~ \\$\cdots\\$ ~~81~~ 77 bytes

```
c;i;f(n){for(int p[n],r=c=0;p[i=r++]=r<=n;)for(;i;)c+=(p[i--]+=p[i])==n;i=c;}

```

Try it online!

Inputs integer \\$n \> 1\\$ and returns the number of times \\$n\\$ appears in Pascal's triangle.

*Saved a byte thanks to ceilingcat!!!*

#### Commented code

```
c;i;                           // declare counter (c) and
                               //   index (i).
f(n){                          // declare function f taking an
                               //   int parm (n).
     for(                      // outer loop over rows of Pascal's
                               //  triangle.
         int p[n],             // declare int array (p) that will
                               //  store successive rows of
                               //  Pascal's triangle.
         r=c=0;                // declare int row (r) and
                               //   init r and c to 0.
         p[                    // set the rth element in p to 1:
                               //   the first time through this
                               //   sets p[0] = 1, and every
                               //   time after that sets
                               //   p[current last position] = 1.
           i=r++               // init i to r and post bump r.
                ]=r<=n;)       // loop until r is greater than n.
      for(;i;)                 // inner loop over current row's
                               //    elements backwards but
                               //    stops before touching p[0].
              c+=(             // bump c...
                  p[i--]       // update current ith element by
                   +=p[i]      //   adding previous values:
                               //   p[i] = p[i] + p[i-1].
                         )==n; // ...if this new value of
                               //    Pascal's triangle is
                               //    equal to n.
     i=c;                      // return counter c.
}

```

Aside: This method golfed the best but also calculating rows of Pascal's triangle through repeated summation works well with \\$32\\$-bit integers, calculating \\$\binom{n}{m}\\$ as \\$\frac{(n-m)!}{m!}\\$ quickly overflows, even for \\$64\\$-bit integers. This method might also be faster, especially for \\$n\<=16\\$ where rows of Pascal's triangle will fit on a single cache line.
> 1 votes

# Answer
# Charcoal, 32 bytes

```
Ｎθ⊞υ¹≔⁰ηＦθ«⊞υ⁰ＵＭυ⁺κ§υ⊖λ≧⁺№υθη»Ｉη

```

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

```
Ｎθ

```

Input the target `n`.

```
⊞υ¹

```

Start with the `0`th row of Pascal's triangle.

```
≔⁰η

```

Start with `0` occurrences of `n`.

```
Ｆθ«

```

Loop `n` times.

```
⊞υ⁰

```

Append a `0` to the row.

```
ＵＭυ⁺κ§υ⊖λ

```

For each element, add the original previous element to it. (Due to cyclic indexing, the `0` at the end gets added to the first element.)

```
≧⁺№υθη

```

Keep a running total of the number of occurrences of `n`.

```
»Ｉη

```

Output the final total.
> 1 votes

# Answer
# Python 3, 117 109 94 bytes

*-23 bytes thanks to Jo King*

```
f=lambda n,k=0:(k:=k or n)-1and[math.comb(k,i)for i in range(k)].count(n)+f(n,k-1)
import math

```

Try it online!

Generates each line of Pascal's triangle recursively and counts times `n` appeared.

Sorry for causing so much trouble with this solution. Much thanks to Jo King and Bubbler for helping me out.
> 1 votes

# Answer
## Clojure, 94 bytes

```
#((frequencies(apply concat(take(inc %)(iterate(fn[i](concat[1](map +'(rest i)i)[1]))[1]))))%)

```

Actually `frequencies` calculates the frequencies of all numbers, and it is used in a function context of that S-expression, thus returning the frequency of the queried number. One must use `+'` for summation to handle integer overflows properly. A `loop` implementation should be shorter than this `iterate` \- `take` \- `frequencies` combination. TIO.
> 1 votes

# Answer
# Swift, 129 bytes

Short version:

```
func c(_ n:Int)->Int{var l=[0,1,0];var c=0;while l[2]<=n{for i in 0..<l.count-1{l[i]+=l[i+1];c+=l[i]==n ?1:0};l=[0]+l};return c}

```

Verbose version:

```
func c2(number: Int) -> Int {
    var line: [Int] = [0, 1, 0]
    var count = 0
    while line[2] <= number {
        for i in line {
            if i == number {
                count += 1
            }
        }
        for i in 0 ..< line.count - 1 {
           line[i] += line[i + 1]
        }
        line.insert(0, at: 0)
    }
    return count
}

```
> 1 votes

# Answer
# Perl 5 `-ap`, 59 bytes

```
$i=0,$\+=grep"@F"==$_,@a=(1,map$_+$a[++$i],@a)while@a<=$_}{

```

Try it online!
> 0 votes

# Answer
# APL(NARS), 43 chars

```
r←P w;a
a←⍬⋄r←0
r+←+/w=a←2+/1,a,1⋄→2×⍳w≥↑a

```

7+7+26+3=43. Use & test

```
  P¨2 4 6 10 28 20 120
1 2 3 4 4 3 6
  P 1002
2

```
> 0 votes

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


# Question
Title: Find the sum of the numbers on the circle
Consider an \\$n \times n\\$ grid and a circle of radius \\$r \leq \sqrt{2} n\\$ with its center in the top left. In each square there is an integer from the range -3 to 3, inclusive. For a given radius, there is a set of squares in the grid which are not at least half covered by a circle of radius \\$r\\$ but are at least half covered by a circle of larger radius. Your task to output the sum of the integers in those squares.

Takes this example:

The smaller circle has radius \\$3.5 \cdot \sqrt{2}\\$ and the larger circle has radius \\$4.5 \cdot \sqrt{2}\\$. The numbers for squares that are at least half covered by the larger circle but not the smaller one are \\$1, -1, 3, 3, 2, -1, -1, 1, -3, -1, 1\\$. These sum to \\$4\\$.

You might be wondering why the \\$-1\\$ number in square (4,4) is not included. If we zoom in we can see why. The blue dots are the center of the squares.

If we had chosen the smaller radius to be \\$2.5 \cdot \sqrt{2}\\$ and the larger circle has radius \\$3.5 \cdot \sqrt{2}\\$ then we get the sum of the values we need is \\$-1\\$.

Here is the matrix from the examples given:

```
  [[ 3,  0,  1,  3, -1,  1,  1,  3, -2, -1],
   [ 3, -1, -1,  1,  0, -1,  2,  1, -2,  0],
   [ 2,  2, -2,  0,  1, -3,  0, -2,  2,  1],
   [ 0, -3, -3, -1, -1,  3, -2,  0,  0,  3],
   [ 2,  2,  3,  2, -1,  0,  3,  0, -3, -1],
   [ 1, -1,  3,  1, -3,  3, -2,  0, -3,  0],
   [ 2, -2, -2, -3, -2,  1, -2,  0,  0,  3],
   [ 0,  3,  0,  1,  3, -1,  2, -3,  0, -2],
   [ 0, -2,  2,  2,  2, -2,  0,  2,  1,  3],
   [-2, -2,  0, -2, -2,  2,  0,  2,  3,  3]]

```

# Input

A 10 by 10 matrix of integers in the range -3 to 3, inclusive and a radius \\$r=\sqrt{2} (a+1/2)\\$ where \\$a\\$ is a non negative integer. The radius input will be the integer \\$a\\$.

# Output

The sum of the numbers in the squares in the matrix which are not at least half covered by a circle of radius \\$r\\$ but are at least half covered by a circle of radius \\$r + \sqrt{2}\\$.

These are the outputs for some different values of \\$a\\$ using the example matrix.

```
a = 0 gives output 6  ( 0 + 3 + 3)
a = 1 gives output 3  (1 + -1 + -1 + 2 + 2)
a = 2 gives output -1 (3 + -1 + 1 + 0 + -2 + -3 + -3 + +0 + 2 + 2)
a = 3 gives output 4  (1 + -1 + -3 + 1 + -1 + -1 + 2 + 3 + 3 + -1 + 1)

```

# Accuracy

Your answer should be exactly correct. The question of which squares to include can be resolved exactly mathematically.

# Answer
> 4 votes
# Jelly, 22 bytes

```
ŒJ_.²§<Ɱ+.+Ø.²ḤƲ}^/ḋF{

```

Try it online!

A dyadic link taking a 10x10 integer matrix as its first argument and an integer as its second argument and returning an integer. Doesn’t use any fractions other than halves and quarters so should not lose anything to floating point accuracy.

Uses the same methodology as @Ajax1234’s Python answer so be sure to upvote that one too!

## Explanation

```
ŒJ_.²§<Ɱ+.+Ø.²ḤƲ}^/ḋF{
ŒJ                      # Indices along matrix
  _.                    # Subtract 0.5
    ²                   # Square
     §                  # Sum inner lists
      <Ɱ       Ʋ}       # Less than each of the following applied to the right argument as a monad:
        +.              # Add 0.5
          +Ø.           # Add zero and one
             ²          # Square
              Ḥ         # Double
                 ^/     # Reduce using xor
                   ḋF{  # Dot product with the flattened matrix

```

Created with the help of Luminespire.

## Alternative approach Jelly, ~~47~~ 45 bytes

```
+1.,.²Ḥµæ._²}½÷@ÆṬ,×ʋʋ¥Ɱ⁵ŻHI+.ḞḞRŒṪfU$)ḟ/œị⁹S

```

Try it online!

This is a dyadic link that takes the integer a as its first argument and the 10x10 matrix as its second and returns an integer. This uses the integral of the circle equation to calculate the area in each column. This is useful on the left hand part of the quarter circle but not on the right when it’s harder to calculate which squares are partially filled. My code therefore uses symmetry to control for this. There could be floating point error, but it’s not apparent in the example used here.

The formula used for the integral of \\$\sqrt{r^2 - x^2}\\$ is:

\\$\frac{1}{2} (x \sqrt{r^2 - x^2} + r^2 \arctan{\frac{x}{\sqrt{r^2 - x^2}}})\\$

This was generated using Wolfram Alpha.

## Explanation

```
+1.,.²Ḥµæ._²}½÷@ÆṬ,×ʋʋ¥Ɱ⁵ŻHI+.ḞḞRŒṪfU$)ḟ/œị⁹S
+1.,.                                          # Add [1.5, 0.5]
     ²                                         # Squared
      Ḥ                                        # Doubled
       µ                              )        # For each of these squared radii:
                      ¥Ɱ⁵                      # - Following as a dyad using the squared radius as the left argument and each integer from 1 to 10 inclusive as the right (referred to as x below)
        æ.           ʋ                         #   - Dot product of [the squared radius, 1] with the result of the following:
          _²}                                  #     - Subtract x squared from the squared radius
             ½                                 #     - Square root
                    ʋ                          #     - Following as a dyad using the above as the left argument (called z below) and x as the right argument
              ÷@                               #       - Divide x by z
                ÆṬ                             #       - Arctan
                  ,×                           #       - Paired with z multiplied by x
                         Ż                     # - Prepend zero
                          H                    # - Half
                           I                   # - Increments
                            +.                 # - Add 0.5
                              Ḟ                # - Real part of complex values; floor real values
                               Ḟ               # - Floor the real values generated from the complex values above
                                R              # - Range from 1 to each of these
                                 ŒṪ            # - Two-dimensional indices of truthy values
                                   fU$         # - Keep only those which also exist in their reversed form
                                       ḟ/      # Remove the squares captured by the smaller circle from those captured by the larger one
                                         œị⁹   # Multidimensional index into the matrix
                                            S  # Sum

```

Created with the help of Luminespire.

# Answer
> 4 votes
# Python3, 105 bytes:

```
E=enumerate
f=lambda m,d:sum(v for x,r in E(m)for y,v in E(r)if(U:=x*x+x+y*y+y+1)>d*d*2 and U<(d+1)**2*2)

```

Try it online!

# Answer
> 3 votes
# Google Sheets, 104 bytes

```
=sum(makearray(10,10,lambda(x,y,isbetween(((x-0.5)^2+(y-0.5)^2)^0.5,K4,K4+2^0.5,1,)*index(A1:J10,x,y))))

```

Put the matrix in cells `A1:J10`, the integer \\$a\\$ in cell `K4`, the formula for \\$r\\$ `=2 ^ 0.5 * (K2 + 0.5)` in cell `K4` and the formula in cell `K7`.

The input is the matrix `A1:J10` and the value \\$r\\$ in `K4`. Uses the same approximation as the Python and Jelly answers.

---
Tags: code-golf
---


# Question
Title: The Math is Right, But the Answer is Wrong - Robbers
## Challenge

The cops created code challenges which result in certain wildly incorrect answers despite correct math. Choose an uncracked, not safe formula from the cop thread.

Your task is to find an incorrect answer and describe its underlying cause. The challenge author has the responsibility to confirm whether the explanation is valid, but the incorrect answer does not have to be the same one the challenge creator had in mind.

## Scoring, Rules, and Notes

* Score 1 point for each successfully cracked answer.
* If the error is caused by a particular usage of an external library (or specific version of it), it is sufficient to simply state that there is a known bug with a particular usage of the library used by the cop challenge. Link to a relevant bug report or article.
    + This is to avoid having to pour through potentially millions of lines of source code in libraries (which may be closed source anyway) to find the exact cause of the error.

## Example

### Cop Challenge

* Formula: The Pythagorean Theorem, \\$ a^2 + b^2 = c^2 \\$
* Inputs: 2 nonnegative real numbers
* Off by more than either input number
* Affects most inputs
* WSL (Ubuntu 18.04) on Windows 10, Python 3.6.9

```
def badpythag(a, b):
    a2 = (a / 1e200) ** 2
    b2 = (b / 1e200) ** 2
    return math.sqrt(a2 + b2) * 1e200

```

### Cracked Answer

This will fail on many inputs (e.g. 3, 4 =\> 0, but should be 5) due to floating point underflow and return 0. The answer is correct with very large inputs e.g. 3e150 and 4e150, however.

# Answer
# Python 3 \+ Sympy, Sisyphus' Answer

```
from sympy.ntheory.primetest import mr
from sympy.ntheory.generate import primerange

def is_prime(n: int) -> bool:
	if n < 2: return False
	return mr(n, primerange(2, 800))

def is_prime_2(n: int) -> bool:
	if n < 2: return False
	return mr(n, [1009])

n = 2809386136371438866496346539320857607283794588353401165473007394921174159995576890097633348301878401799853448496604965862616291048652062065394646956750323263193037964463262192320342740843556773326129475220032687577421757298519461662249735906372935033549531355723541168448473213797808686850657266188854910604399375221284468243956369013816289853351613404802033369894673267294395882499368769744558478456847832293372532910707925159549055961870528474205973317584333504757691137280936247019772992086410290579840045352494329434008415453636962234340836064927449224611783307531275541463776950841504387756099277118377038405235871794332425052938384904092351280663156507379159650872073401637805282499411435158581593146712826943388219341340599170371727498381901415081480224172469034841153893464174362543356514320522139692755430021327765409775374978255770027259819794532960997484676733140078317807018465818200888425898964847614568913543667470861729894161917981606153150551439410460813448153180857197888310572079656577579695814664713878369660173739371415918888444922272634772987239224582905405240454751027613993535619787590841842251056960329294514093407010964283471430374834873427180817297408975879673867

print(is_prime(n))    # Prints True
print(is_prime_2(n))  # Prints False

```

Try it online!

`n` is strongly pseudoprime for all prime bases below 1,000, which means the Miller-Rabin test will give a false positive for any bases in the `(2, 800)` range. As soon as you use a prime base above 1,000, the Miller-Rabin test correctly identifies it as composite.

I did not calculate this number myself. I took it from this answer from Joe53 on Mathematics Stack Exchange, which in turn was calculated using the technique in this paper.
> 8 votes

# Answer
# JavaScript (Node.js), tsh's answer

```
function max(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw TypeError("This function only accept numbers");
  }
  if (a === b) {
    return a;
  } else if (a > b) {
    return a;
  } else if (a < b) {
    return b;
  } else {
    return Math.max(a, b);
  }
}

function max_ref(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw TypeError("This function only accept numbers");
  }
  return Math.max(a, b);
}

console.log(max(-0, 0));
console.log(max_ref(-0, 0));

```

Try it online!

```
-0
0

```

According to `===`, signed `0` is equal to unsigned `0`, but as shown in this SO post, `Math.max` has a special case for signed `0`.

The first argument is returned when the `===` is true, so all we have to do is call it with `-0, 0` for it to return the wrong answer.
> 2 votes

# Answer
# Lua (LuaJIT), cracks @LuaNoob's answer

```
function Fails(i)
    local max = i * 80
    local a = 0

    while true do
        if a < max then
            a = a + 0.2
        else
            break
        end
    end

    print("Input", i)
    print("Max", max)
    print("Expected Value", string.format("%.64f", max))
    print("Value", string.format("%.64f", a))
    print("Value-0.2", string.format("%.64f", a-0.2))
    print("Equal?", a == max)
    print()
end

Fails(0.46) -- fails
Fails(0.47) -- works

```

Try it online!

Works with `0.47` (found by trial and error). No doubt many other values also produce the 'expected' answer.

With the slightly modified code above we see that the failure for some inputs is due to floating point errors. Specifically, repeated addition (`a + 0.2`) is not the same as multiplication (`i * 80`) in floating point arithmetic. Compensated summation algorithms, such as Kahan summation, are designed to reduce precision loss due to repeated addition.
> 2 votes

# Answer
# Python 3.9+, The Empty String Photographer

```
## 'Solution'
import math
def fails(x: float, y: float) -> int:
    return math.lcm(x.as_integer_ratio()[1], y.as_integer_ratio()[1])

## Crack
assert fails(2/3, 2/3) > 1000000 # Expected 3
# Instead is equal to 2**57 due to floating point using bas

```

Valid crack according to poster's comment even though technically `2/3` is equal to `6004799503160661/9007199254740992` before the function is even called, making the function 'correct' by returning `2**57`=`9007199254740992`
> 0 votes

---
Tags: cops-and-robbers
---


title: Clone GNU cat 8.32

text:
# Question
Title: Clone GNU cat 8.32
Write a program that precisely clones GNU `cat` version 8.32, which is installed on my computer.

In any case, if called with the same arguments, same stdin, and same files, your program's output to both stdout and stderr must by byte-for-byte identical to that of GNU `cat`, and the exit code must be the same. This applies to both valid and invalid commands. It must be impossible to distinguish between GNU `cat` and your program without inspecting the file content or analyzing performance.

As usual, arguments starting with hyphens are considered options, except that `--` indicates that arguments after that point are not options. `cat -- --help` reads a file literally called `--help` from the current directory. Options and non-options may be freely mixed, except no options are allowed after `--`.

`cat` has no options that take arguments. Options may be long or short. Long options begin with two hyphens, and must be given separately. Short options begin with one hyphen and can be combined; `cat -v -E -T` can be combined into `cat -vET` with precisely the same effect.

The options are documented in the output of `cat --help`:

```
Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s) to standard output.

With no FILE, or when FILE is -, read standard input.

  -A, --show-all           equivalent to -vET
  -b, --number-nonblank    number nonempty output lines, overrides -n
  -e                       equivalent to -vE
  -E, --show-ends          display $ at end of each line
  -n, --number             number all output lines
  -s, --squeeze-blank      suppress repeated empty output lines
  -t                       equivalent to -vT
  -T, --show-tabs          display TAB characters as ^I
  -u                       (ignored)
  -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB
      --help     display this help and exit
      --version  output version information and exit

Examples:
  cat f - g  Output f's contents, then standard input, then g's contents.
  cat        Copy standard input to standard output.

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation <https://www.gnu.org/software/coreutils/cat>
or available locally via: info '(coreutils) cat invocation'

```

There are some exceptions to the requirement for a perfect clone. Your program does not have to properly handle file read errors except "file not found" and "permission denied," and it does not need to be internationalized.

Calling GNU `cat` is cheating.

Because `cat` 8.32 is not available on all systems, a Python reference implementation is provided. I believe it meets the challenge requirements, although it is entirely ungolfed. Any variation between GNU cat and this program, except as allowed in this challenge, is a bug in this program. You are welcome to use it as the basis of an answer if you would like.

```
#!/usr/bin/env python3
import sys
import getopt

try:
    full_opts, file_names = getopt.gnu_getopt(
        sys.argv[1:],
        "AbeEnstTuv",
        longopts=[
            "show-all",
            "number-nonblank",
            "show-ends",
            "number",
            "squeeze-blank",
            "show-tabs",
            "show-nonprinting",
            "help",
            "version",
        ],
    )
except getopt.GetoptError as e:
    invalid_option = str(e)[7:-15]
    if invalid_option.startswith("--"):
        print(f"cat: unrecognized option '{invalid_option}'", file=sys.stderr)
    else:
        letter = invalid_option[1]
        print(f"cat: invalid option -- '{letter}'", file=sys.stderr)
    print("Try 'cat --help' for more information.", file=sys.stderr)

    sys.exit(1)

raw_opts = [opt[0] for opt in full_opts]

opts = []

for raw_opt in raw_opts:
    if raw_opt in ["-A", "--show-all"]:
        opts.append("--show-nonprinting")
        opts.append("--show-ends")
        opts.append("--show-tabs")
    elif raw_opt == "-e":
        opts.append("--show-nonprinting")
        opts.append("--show-ends")
    elif raw_opt == "-t":
        opts.append("--show-nonprinting")
        opts.append("--show-tabs")
    elif raw_opt == "-u":
        pass
    elif raw_opt.startswith("--"):
        opts.append(raw_opt)
    else:
        opts.append(
            {
                "-b": "--number-nonblank",
                "-E": "--show-ends",
                "-n": "--number",
                "-s": "--squeeze-blank",
                "-T": "--show-tabs",
                "-v": "--show-nonprinting",
            }[raw_opt]
        )

help_text = """Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s) to standard output.

With no FILE, or when FILE is -, read standard input.

  -A, --show-all           equivalent to -vET
  -b, --number-nonblank    number nonempty output lines, overrides -n
  -e                       equivalent to -vE
  -E, --show-ends          display $ at end of each line
  -n, --number             number all output lines
  -s, --squeeze-blank      suppress repeated empty output lines
  -t                       equivalent to -vT
  -T, --show-tabs          display TAB characters as ^I
  -u                       (ignored)
  -v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB
      --help     display this help and exit
      --version  output version information and exit

Examples:
  cat f - g  Output f's contents, then standard input, then g's contents.
  cat        Copy standard input to standard output.

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation <https://www.gnu.org/software/coreutils/cat>
or available locally via: info '(coreutils) cat invocation'"""

version_text = """cat (GNU coreutils) 8.32
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Torbjorn Granlund and Richard M. Stallman."""

nonprinting = {
    b"\x00": b"^@",
    b"\x01": b"^A",
    b"\x02": b"^B",
    b"\x03": b"^C",
    b"\x04": b"^D",
    b"\x05": b"^E",
    b"\x06": b"^F",
    b"\x07": b"^G",
    b"\x08": b"^H",
    b"\x0b": b"^K",
    b"\x0c": b"^L",
    b"\r": b"^M",
    b"\x0e": b"^N",
    b"\x0f": b"^O",
    b"\x10": b"^P",
    b"\x11": b"^Q",
    b"\x12": b"^R",
    b"\x13": b"^S",
    b"\x14": b"^T",
    b"\x15": b"^U",
    b"\x16": b"^V",
    b"\x17": b"^W",
    b"\x18": b"^X",
    b"\x19": b"^Y",
    b"\x1a": b"^Z",
    b"\x1b": b"^[",
    b"\x1c": b"^\\",
    b"\x1d": b"^]",
    b"\x1e": b"^^",
    b"\x1f": b"^_",
    b"\x7f": b"^?",
    b"\x80": b"M-^@",
    b"\x81": b"M-^A",
    b"\x82": b"M-^B",
    b"\x83": b"M-^C",
    b"\x84": b"M-^D",
    b"\x85": b"M-^E",
    b"\x86": b"M-^F",
    b"\x87": b"M-^G",
    b"\x88": b"M-^H",
    b"\x89": b"M-^I",
    b"\x8a": b"M-^J",
    b"\x8b": b"M-^K",
    b"\x8c": b"M-^L",
    b"\x8d": b"M-^M",
    b"\x8e": b"M-^N",
    b"\x8f": b"M-^O",
    b"\x90": b"M-^P",
    b"\x91": b"M-^Q",
    b"\x92": b"M-^R",
    b"\x93": b"M-^S",
    b"\x94": b"M-^T",
    b"\x95": b"M-^U",
    b"\x96": b"M-^V",
    b"\x97": b"M-^W",
    b"\x98": b"M-^X",
    b"\x99": b"M-^Y",
    b"\x9a": b"M-^Z",
    b"\x9b": b"M-^[",
    b"\x9c": b"M-^\\",
    b"\x9d": b"M-^]",
    b"\x9e": b"M-^^",
    b"\x9f": b"M-^_",
    b"\xa0": b"M- ",
    b"\xa1": b"M-!",
    b"\xa2": b'M-"',
    b"\xa3": b"M-#",
    b"\xa4": b"M-$",
    b"\xa5": b"M-%",
    b"\xa6": b"M-&",
    b"\xa7": b"M-'",
    b"\xa8": b"M-(",
    b"\xa9": b"M-)",
    b"\xaa": b"M-*",
    b"\xab": b"M-+",
    b"\xac": b"M-,",
    b"\xad": b"M--",
    b"\xae": b"M-.",
    b"\xaf": b"M-/",
    b"\xb0": b"M-0",
    b"\xb1": b"M-1",
    b"\xb2": b"M-2",
    b"\xb3": b"M-3",
    b"\xb4": b"M-4",
    b"\xb5": b"M-5",
    b"\xb6": b"M-6",
    b"\xb7": b"M-7",
    b"\xb8": b"M-8",
    b"\xb9": b"M-9",
    b"\xba": b"M-:",
    b"\xbb": b"M-;",
    b"\xbc": b"M-<",
    b"\xbd": b"M-=",
    b"\xbe": b"M->",
    b"\xbf": b"M-?",
    b"\xc0": b"M-@",
    b"\xc1": b"M-A",
    b"\xc2": b"M-B",
    b"\xc3": b"M-C",
    b"\xc4": b"M-D",
    b"\xc5": b"M-E",
    b"\xc6": b"M-F",
    b"\xc7": b"M-G",
    b"\xc8": b"M-H",
    b"\xc9": b"M-I",
    b"\xca": b"M-J",
    b"\xcb": b"M-K",
    b"\xcc": b"M-L",
    b"\xcd": b"M-M",
    b"\xce": b"M-N",
    b"\xcf": b"M-O",
    b"\xd0": b"M-P",
    b"\xd1": b"M-Q",
    b"\xd2": b"M-R",
    b"\xd3": b"M-S",
    b"\xd4": b"M-T",
    b"\xd5": b"M-U",
    b"\xd6": b"M-V",
    b"\xd7": b"M-W",
    b"\xd8": b"M-X",
    b"\xd9": b"M-Y",
    b"\xda": b"M-Z",
    b"\xdb": b"M-[",
    b"\xdc": b"M-\\",
    b"\xdd": b"M-]",
    b"\xde": b"M-^",
    b"\xdf": b"M-_",
    b"\xe0": b"M-`",
    b"\xe1": b"M-a",
    b"\xe2": b"M-b",
    b"\xe3": b"M-c",
    b"\xe4": b"M-d",
    b"\xe5": b"M-e",
    b"\xe6": b"M-f",
    b"\xe7": b"M-g",
    b"\xe8": b"M-h",
    b"\xe9": b"M-i",
    b"\xea": b"M-j",
    b"\xeb": b"M-k",
    b"\xec": b"M-l",
    b"\xed": b"M-m",
    b"\xee": b"M-n",
    b"\xef": b"M-o",
    b"\xf0": b"M-p",
    b"\xf1": b"M-q",
    b"\xf2": b"M-r",
    b"\xf3": b"M-s",
    b"\xf4": b"M-t",
    b"\xf5": b"M-u",
    b"\xf6": b"M-v",
    b"\xf7": b"M-w",
    b"\xf8": b"M-x",
    b"\xf9": b"M-y",
    b"\xfa": b"M-z",
    b"\xfb": b"M-{",
    b"\xfc": b"M-|",
    b"\xfd": b"M-}",
    b"\xfe": b"M-~",
    b"\xff": b"M-^?",
}

if "--help" in opts or "--version" in opts:
    for opt in opts:
        if opt == "--help":
            print(help_text)
            sys.exit(0)
        if opt == "--version":
            print(version_text)
            sys.exit(0)

if not file_names:
    file_names = ["-"]

index = 1

exit_code = 0

for file_name in file_names:
    if file_name == "-":
        is_file = False
        f = sys.stdin.buffer
    else:
        is_file = True
        try:
            f = open(file_name, "rb")
        except FileNotFoundError:
            print(
                f"cat: {file_name}: No such file or directory", file=sys.stderr
            )
            exit_code = 1
            continue
        except PermissionError:
            print(f"cat: {file_name}: Permission denied", file=sys.stderr)
            exit_code = 1
            continue

    last_blank = False

    while True:
        line = f.readline()

        if line:
            blank = line == b"\n"
            if blank and last_blank and "--squeeze-blank" in opts:
                continue
            last_blank = blank

            number = ("--number-nonblank" in opts and not blank) or (
                "--number" in opts and not "--number-nonblank" in opts
            )
            prefix = f"{index:>6}\t".encode("utf-8") if number else b""

            if "--show-ends" in opts:
                line = line.replace(b"\n", b"$\n")

            if "--show-tabs" in opts:
                line = line.replace(b"\t", b"^I")

            if "--show-nonprinting" in opts:
                for key, value in nonprinting.items():
                    line = line.replace(key, value)

            sys.stdout.buffer.write(prefix + line)
            sys.stdout.buffer.flush()

            if number:
                index += 1
        else:
            break

    if is_file:
        f.close()

sys.exit(exit_code)

```

# Answer
> 1 votes
# Python, 5179 bytes

```
a=b'\n'
Z=False
N='number'
v='version'
Y='--'+v
X='--help'
W='--squeeze-blank'
V='--'+N
O=f'--{N}-nonblank'
S='--show-'
I=S+'tabs'
H=S+'ends'
F=S+'nonprinting'
G=S+'all'
C="coreutils"
D="GNU "+C
s=" "
t="standard"
T=" output"
o=t+T
i=t+" input"
E=" and exit\n"
c="'s contents"
q="equivalent to -v"
f=f"Usage: cat [OPTION]... [FILE]...\nConcatenate FILE(s) to {o}.\n\nWith no FILE, or when FILE is -, read {i}.\n\n  -A, {G}{s*11}{q}ET\n  -b, {O}    {N} nonempty{T} lines, overrides -n\n  -e{s*23}{q}E\n  -E, {H}{s*10}display $ at end of each line\n  -n, {V}{s*13}{N} all{T} lines\n  -s, {W}{s*6}suppress repeated empty{T} lines\n  -t{s*23}{q}T\n  -T, {I}{s*10}display TAB characters as ^I\n  -u{s*23}(ignored)\n  -v, {F}   use ^ and M- notation, except for LFD and TAB\n{s*6}{X}     display this help{E}{s*6}{Y} {T} {v} information{E}\nExamples:\n  cat f - g  Output f{c}, then {i}, then g{c}.\n  cat{s*8}Copy {i} to {o}.\n\n{D} online help: <https://www.gnu.org/software/{C}/>\nFull documentation <https://www.gnu.org/software/{C}/cat>\nor available locally via: info '({C}) cat invocation'"
g=f'cat ({D}) 8.32\nCopyright (C) 2020 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL {v} 3 or later <https://gnu.org/licenses/gpl.html>.\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n\nWritten by Torbjorn Granlund and Richard M. Stallman.'
E=print
from sys import*
from getopt import*
try:b,J=gnu_getopt(argv[1:],'AbeEnstTuv',[G[2:],O[2:],H[2:],N,W[2:],'show-tabs',F[2:],'help',v])
except GetoptError as c:
 K=str(c)[7:-15]
 if K[:2]=='--':E(f"cat: unrecognized option '{K}'",file=stderr)
 else:d=K[1];E(f"cat: invalid option -- '{d}'",file=stderr)
 E("Try 'cat --help' for more information.",file=stderr);exit(1)
e=[A[0]for A in b]
A=[]
a=A.append
for D in e:
 if D in['-A',G]:a(F);a(H);a(I)
 elif D=='-e':a(F);a(H)
 elif D=='-t':a(F);a(I)
 elif D=='-u':0
 elif D[:2]=='--':a(D)
 else:a({'-b':O,'-E':H,'-n':V,'-s':W,'-T':I,'-v':F}[D])
h={b'\x00':b'^@',b'\x01':b'^A',b'\x02':b'^B',b'\x03':b'^C',b'\x04':b'^D',b'\x05':b'^E',b'\x06':b'^F',b'\x07':b'^G',b'\x08':b'^H',b'\x0b':b'^K',b'\x0c':b'^L',b'\r':b'^M',b'\x0e':b'^N',b'\x0f':b'^O',b'\x10':b'^P',b'\x11':b'^Q',b'\x12':b'^R',b'\x13':b'^S',b'\x14':b'^T',b'\x15':b'^U',b'\x16':b'^V',b'\x17':b'^W',b'\x18':b'^X',b'\x19':b'^Y',b'\x1a':b'^Z',b'\x1b':b'^[',b'\x1c':b'^\\',b'\x1d':b'^]',b'\x1e':b'^^',b'\x1f':b'^_',b'\x7f':b'^?',b'\x80':b'M-^@',b'\x81':b'M-^A',b'\x82':b'M-^B',b'\x83':b'M-^C',b'\x84':b'M-^D',b'\x85':b'M-^E',b'\x86':b'M-^F',b'\x87':b'M-^G',b'\x88':b'M-^H',b'\x89':b'M-^I',b'\x8a':b'M-^J',b'\x8b':b'M-^K',b'\x8c':b'M-^L',b'\x8d':b'M-^M',b'\x8e':b'M-^N',b'\x8f':b'M-^O',b'\x90':b'M-^P',b'\x91':b'M-^Q',b'\x92':b'M-^R',b'\x93':b'M-^S',b'\x94':b'M-^T',b'\x95':b'M-^U',b'\x96':b'M-^V',b'\x97':b'M-^W',b'\x98':b'M-^X',b'\x99':b'M-^Y',b'\x9a':b'M-^Z',b'\x9b':b'M-^[',b'\x9c':b'M-^\\',b'\x9d':b'M-^]',b'\x9e':b'M-^^',b'\x9f':b'M-^_',b'\xa0':b'M- ',b'\xa1':b'M-!',b'\xa2':b'M-"',b'\xa3':b'M-#',b'\xa4':b'M-$',b'\xa5':b'M-%',b'\xa6':b'M-&',b'\xa7':b"M-'",b'\xa8':b'M-(',b'\xa9':b'M-)',b'\xaa':b'M-*',b'\xab':b'M-+',b'\xac':b'M-,',b'\xad':b'M--',b'\xae':b'M-.',b'\xaf':b'M-/',b'\xb0':b'M-0',b'\xb1':b'M-1',b'\xb2':b'M-2',b'\xb3':b'M-3',b'\xb4':b'M-4',b'\xb5':b'M-5',b'\xb6':b'M-6',b'\xb7':b'M-7',b'\xb8':b'M-8',b'\xb9':b'M-9',b'\xba':b'M-:',b'\xbb':b'M-;',b'\xbc':b'M-<',b'\xbd':b'M-=',b'\xbe':b'M->',b'\xbf':b'M-?',b'\xc0':b'M-@',b'\xc1':b'M-A',b'\xc2':b'M-B',b'\xc3':b'M-C',b'\xc4':b'M-D',b'\xc5':b'M-E',b'\xc6':b'M-F',b'\xc7':b'M-G',b'\xc8':b'M-H',b'\xc9':b'M-I',b'\xca':b'M-J',b'\xcb':b'M-K',b'\xcc':b'M-L',b'\xcd':b'M-M',b'\xce':b'M-N',b'\xcf':b'M-O',b'\xd0':b'M-P',b'\xd1':b'M-Q',b'\xd2':b'M-R',b'\xd3':b'M-S',b'\xd4':b'M-T',b'\xd5':b'M-U',b'\xd6':b'M-V',b'\xd7':b'M-W',b'\xd8':b'M-X',b'\xd9':b'M-Y',b'\xda':b'M-Z',b'\xdb':b'M-[',b'\xdc':b'M-\\',b'\xdd':b'M-]',b'\xde':b'M-^',b'\xdf':b'M-_',b'\xe0':b'M-`',b'\xe1':b'M-a',b'\xe2':b'M-b',b'\xe3':b'M-c',b'\xe4':b'M-d',b'\xe5':b'M-e',b'\xe6':b'M-f',b'\xe7':b'M-g',b'\xe8':b'M-h',b'\xe9':b'M-i',b'\xea':b'M-j',b'\xeb':b'M-k',b'\xec':b'M-l',b'\xed':b'M-m',b'\xee':b'M-n',b'\xef':b'M-o',b'\xf0':b'M-p',b'\xf1':b'M-q',b'\xf2':b'M-r',b'\xf3':b'M-s',b'\xf4':b'M-t',b'\xf5':b'M-u',b'\xf6':b'M-v',b'\xf7':b'M-w',b'\xf8':b'M-x',b'\xf9':b'M-y',b'\xfa':b'M-z',b'\xfb':b'M-{',b'\xfc':b'M-|',b'\xfd':b'M-}',b'\xfe':b'M-~',b'\xff':b'M-^?'}
if X in A or Y in A:
 for Q in A:
  if Q==X:E(f);exit(0)
  if Q==Y:E(g);exit(0)
if not J:J=['-']
R=1
L=0
for G in J:
 if G=='-':S=Z;M=stdin.buffer
 else:
  S=True
  try:M=open(G,'rb')
  except FileNotFoundError:E(f"cat: {G}: No such file or directory",file=stderr);L=1;continue
  except PermissionError:E(f"cat: {G}: Permission denied",file=stderr);L=1;continue
 T=Z
 while True:
  C=M.readline()
  if C:
   N=C==a
   if N and T and W in A:continue
   T=N;U=O in A and not N or V in A and not O in A;i=f"{R:>6}\t".encode('utf-8')if U else b''
   if H in A:C=C.replace(a,b'$\n')
   if I in A:C=C.replace(b'\t',b'^I')
   if F in A:
    for(j,k)in h.items():C=C.replace(j,k)
   stdout.buffer.write(i+C);stdout.buffer.flush()
   if U:R+=1
  else:break
 if S:M.close()
exit(L)

```

A golfed version of the example I wrote for the question.

---
Tags: code-golf
---


# Question
Title: Finding the optimal straight line boundary
Consider an \\$n \times n\\$ grid of integers. The task is to draw a straight line across the grid so that the part that includes the top left corner sums to the largest number possible. Here is a picture of an optimal solution with score 45:

We include a square in the part that is to be summed if its middle is above or on the line. Above means in the part including the top left corner of the grid. (To make this definition clear, no line can start exactly in the top left corner of the grid.)

The task is to choose the line that maximizes the sum of the part that includes the top left square. The line must go straight from one side to another. The line can start or end anywhere on a side and not just at integer points.

The winning criterion is worst case time complexity as a function of \\$n\\$. That is using big Oh notation, e.g. \\$O(n^4)\\$.

# Test cases

I will add more test cases here as I can.

The easiest test cases are when the input matrix is made of positive (or negative) integers only. In that case a line that makes the part to sum the whole matrix (or the empty matrix if all the integers are negative) wins.

Only slightly less simple is if there is a line that clearly separates the negative integers from the non negative integers in the matrix.

Here is a slightly more difficult example with an optimal line shown. The optimal value is 14.

The grid in machine readable form is:

```
[[ 3 -1 -2 -1]
 [ 0  1 -1  1]
 [ 1  1  3  0]
 [ 3  3 -1 -1]]

```

Here is an example with optimal value 0.

```
[[-3 -3  2 -3]
 [ 0 -2 -1  0]
 [ 1  0  2  0]
 [-1 -2  1 -1]]

```

Posted a question to cstheory about lower bounds for this problem.

# Answer
# Python3, O(n^4):

I'm not 100% sure this is correct, but I think at least the approach is solid and it seems to work OK.

```

import numpy as np
import fractions

def best_line(grid):
    n, m = grid.shape
    D = [(di, dj) for di in range(-(n - 1), n) for dj in range(-(n - 1), n)]
    def slope(d):
        di, dj = d
        if dj == 0:
            return float('inf') if di <= 0 else float('-inf'), -di
        else:
            return fractions.Fraction(di, dj), fractions.Fraction(-1, dj)
    D.sort(key=slope)
    D = np.array(D, dtype=np.int64)
    s_max = grid.sum()
    for grid in (grid, grid.T):
        left_sum = 0
        for j in range(grid.shape[1]):
            left_sum += grid[:,j].sum()
            for i in range(grid.shape[0]):
                p = np.array([i, j], dtype=np.int64)
                Q = p + D
                Q = Q[np.all((0 <= Q) & (Q < np.array(grid.shape)), axis=1)]
                s = left_sum
                for q in Q:
                    if not np.any(q):
                        break
                    if q[1] <= j:
                        s -= grid[q[0],q[1]]
                    else:
                        s += grid[q[0],q[1]]
                    s_max = max(s_max, s)
    return s_max

```
> 4 votes

---
Tags: integer, matrix, optimization, fastest-algorithm
---


# Question
Title: Output: Calendar Month (without native calendar generating functions)
Upon receiving month and year in YYYYMM format, generate output of the corresponding **calendar month** for that year.

For example the input `201312` should generate the following output:

```
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

```

Only trick is, NO native calendar generating functions... so Linux clones, no "cal" function... Muahahahahah!

PS: The calendar must start out with Monday as the left-most day, this is to ensure that the output is like the "cal" function, but does not output like "cal", which has Sunday as its left-most day...

Smallest code size wins.

# Answer
> 6 votes
## Python 2.7 - 152

Unfortunately it fails for September 1752. Granted, it imports all of the calender functions, but only *uses* 1, and that just returns the start day of the week and the number of days.

```
from calendar import*
w,l=monthrange(*divmod(input(),100))
print" Mo Tu We Th Fr Sa Su\n"+"   "*w+''.join(["%3d"%s+"\n"*((s+w)%7<1)for s in range(1,l+1)])

```

Relatively standard code, but this is my favourite bit:

```
"\n"*((s+w)%7<1)

```

It prints the new line using string multiplication, if the number of the current day and start day of the week is Sunday (e.g. 7) as the boolean is cast to an integer.

This saves a character on the more intuitive `x%7==0` by using `x%7<1` instead.

Test output:

```
> 198210
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

```

# Answer
> 9 votes
# Ruby, ~~170~~ 168 characters

```
g=gets.to_i
require'date'
d=Date.new g/100,g%100
puts'Mo Tu We Th Fr Sa Su'
l=['']*(d.jd%7)+[*1..(d>>1).jd-d.jd]
56.times{|i|$><<"#{l[i].to_s.rjust 2} #{?\n if i%7>5}"}

```

Bugfix: didn't require the neccessary library (+16) used julian date modulo 7 instead of current week day directly (-3)
used /100 and %100 to parse date instead of regex (-13). Taken from LegoStormtroopr's answer.
removed the parentheses around the argument to `rjust` and `Date.new`(-2)

# Answer
> 5 votes
# Mathematica 203

```
g@d_:=Module[{w={"Mo","Tu","We","Th","Fr","Sa","Su"},c},
c@n_:=" "~ Table ~{n};
Grid@Partition[Join[w,c[Position[w,StringTake[ToString@DayName@d,2]][[1,1]]-1],
Range@DayCount[d,d~DatePlus~{1,"Month"}],c@6],7]]

```

**Testing**

```
g[{2013, 12}]
g[{2014, 1}]
g[{2014, 2}]

```

# Answer
> 4 votes
# Vyxal, 87 bytes

```
k§2vẎṄ,4ȯI:£3<?4ẎIεD4/⌊‟₁/⌊N‟:400/⌊»∧+ż↵`»8τv‹¥Ẏt2Ṡ7%7ε¤w$ẋf»∇ė{»4τ¥Ẏt28+ɾJ7ẇƛƛS2↳;Ṅ;⁋,

```

Try it Online!

-7 thanks to lyxal.

```
=== Part 1: Header ===
k§      # Monday to Sunday
  2vẎ   # Get first two letters of each
     Ṅ, # Join by spaces
=== Part 2: What day does it start? ===
4ȯI                                          # Last two (month) as integer
   :£                                        # Store a copy to register
     3<?4ẎIε                                 # Decrement the year if the month is Jan or Feb
            D                                # Calculate:
             4/⌊‟                            # floor(y/4)
                 ₁/⌊N‟                       # -floor(y/100)
                      :                      # y
                       400/⌊                 # And floor(y/400)
                            »...»8τv‹        # Compressed list of the days (mod 7) at the start of each month
                                     ¥Ẏt     # Get the correct item
                                        2    # Add 2 (1 because first day of month, 1 because it ends on Sunday)
                                         Ṡ7% # Take the sum of the whole thing, mod 7.
=== Part 3: Get the whole month ===
7ε                     # Difference from 7
  ¤w$ẋf                # Copies of the empty string
       »...»4τ         # Compressed list of days in each month, -28
              ¥Ẏt      # Get the correct item
                 28+   # Add 28
                    ɾ  # Make a range out of that
                     J # Add on the empty strings
=== Part 4: Format nicely ===
7ẇ           # Divide into chunks of 7
  ƛ      ;   # Foreach...
   ƛ   ;     # For each item...
    S        # Stringify
     2↳      # Align
        Ṅ    # Join by spaces
          ⁋, # Output joined by newlines

```

# Answer
> 3 votes
# SmileBASIC, 204 bytes

```
INPUT Y$Y$[3]=Y$[3]+"/
DTREAD Y$+"/01"OUT Y,M,,W
W=W-1+!W*7?"Mo Tu We Th Fr Sa Su
FOR I=1TO 30+(1AND M-(M>7))-(M==2)*2+(Y MOD 4<1&&(Y MOD 100||Y MOD 400<1))LOCATE W*3,?STR$(I,2);
W=W+1
IF W>6 THEN W=0?
NEXT

```

Wow, that leap year detector is VERY long...

# Answer
> 2 votes
# PHP, ~~153~~ 147 bytes

```
Mo Di We Th Fr Sa Su
<?=str_pad("",3*$w=date(w,$t=strtotime(chunk_split($argv[1],4,"-")."7")));while($d++<date(t,$t))printf("%2d "."
"[++$w%7],$d);

```

**breakdown**

```
echo"Mo Di We Th Fr Sa Su\n";   // header
echo str_pad("",3*                      // 4. print leading spaces
    $w=date(w,                          // 3. get weekday
    $t=strtotime(                       // 2. convert to unix timestamp
        chunk_split($argv[1],4,"-")."7" // 1. import, split to year-month-, append day 7
)));
while($d++<date(t,$t))                  // 5. loop $d through days of month:
    printf("%2d "."\n"[++$w%7],$d);         // print date, plus a linebreak for sundays

```

# Answer
> 1 votes
## JavaScript (239)

```
h=prompt();y=h.slice(i=0,4);m=h[4]+h[5]-1;d=new Date(y,m);a='MoTuWeThFrSaSu'.match(/../g);for(p=0;p<(d.getDay()||7)-1;p++)a.push('  ');while(d.setDate(++i)&&d.getMonth()==m)a.push(9<i?i:' '+i);while(c=a.splice(0,7).join(' '))console.log(c)

```

Output:

```
(for 198210)                (for 201312)

Mo Tu We Th Fr Sa Su        Mo Tu We Th Fr Sa Su
             1  2  3                           1
 4  5  6  7  8  9 10         2  3  4  5  6  7  8
11 12 13 14 15 16 17         9 10 11 12 13 14 15
18 19 20 21 22 23 24        16 17 18 19 20 21 22
25 26 27 28 29 30 31        23 24 25 26 27 28 29
                            30 31

```

# Answer
> 1 votes
# C (gcc), 242 bytes

Not the most elegant solution, I suspect.

Input in the form of an integer with the four high digits forming the year, and the low two digits the month.

```
X=100,W;f(d){int m=d%X,y=d/X,i=0,M=" >8><><>><><>"[m]/2+(m==2&(!(y%4)&&(y%X|!(y%400))));for(m+=m<3?y--,10:-2,W=(((1+(26*m-2)/10-2*y/X+5*(y%X)/4+y/X/4)%7)+6)%7,printf("Mo Tu We Th Fr Sa Su\n%*s",3*W,"");i<M;)printf("%2d%c",++i,W++%7^6?32:10);}

```

Try it online!

# Answer
> 0 votes
# APL(NARS), 183 chars

```
L←{(0=400∣⍵)∨(0≠25∣⍵)∧0=4∣⍵}⋄C←{Y←(30+2741⊤⍨12/2)+(¯2+L⍵[2])×2=⍳12⋄d←7∣+/Y[⍳⍵[1]-1],{1+L⍵}1900..⍵[2]-1⋄7 7⍴(,/7 2⍴'MoTuWeThFrSaSu'),(d⍴⊂''),{2 0⍕⍵}¨(⍳Y[⍵[1]]),12⍴⊂''}∘{(100∣⍵),⌊⍵÷100}

```

Input ok only from 1900. Test & how to use it:

```
    C 201312
 Mo Tu We Th Fr Sa Su
                    1
  2  3  4  5  6  7  8
  9 10 11 12 13 14 15
 16 17 18 19 20 21 22
 23 24 25 26 27 28 29
 30 31
    C 202312
 Mo Tu We Th Fr Sa Su
              1  2  3
  4  5  6  7  8  9 10
 11 12 13 14 15 16 17
 18 19 20 21 22 23 24
 25 26 27 28 29 30 31

```

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


title: Maximal linear sublists

text:
# Question
Title: Maximal linear sublists
In this challenge you will write code to take a list of positive integers and output all maximal linear sublists.

* A sublist is is a list which can be created by deleting values from the the input list. Sublists have more structure than just lists. They in a way "remember" which values are deleted.
* Similarly we say that sublist A is a sublist of sublist B if A can be formed by deleting elements of B.
* A linear list (or sublist) is one such that all consecutive values have the same difference.
* A maximal linear sublist is a sublist which is linear, and is not a sublist of any other linear sublist.

For example if we receive the input list `[1,3,5,3]` then the maximal linear sublists are:

```
[1,3,5,3]
 ^ ^ ^
[1,3,5,3]
 ^     ^
[1,3,5,3]
   ^   ^
[1,3,5,3]
     ^ ^

```

Note that the first sublist does have a sublist with the values `[1,3]`, but there is another sublist of values `[1,3]` which is maximal.

# Task

Given a list of positive integers you should output all the maximal linear sublists. Despite the previous emphasis, to simplify things you should output the sublists as lists, i.e. just output the values in a list form.

You give your outputs in any order, but there should not be duplicates, other than sublists who coincidentally have the same values.

This is . The goal is to minimize the size of your source code as measured in bytes.

## Test cases

```
[] -> []
[19] -> [19]
[1,1,2] -> [1,2], [1,2], [1,1]
[1,3,5,3] -> [1,3], [3,3], [5,3], [1,3,5]
[1,2,3,4,3] -> [1,2,3], [3,3], [4,3] [1,2,3,4]
[1,2,3,3] -> [1,2,3], [3,3], [1,2,3]
[1,2,3,4] -> [1,2,3,4]

```

# Answer
# Jelly, 18 bytes

```
JŒPịIEɗƇ⁸fƑⱮS¥ÐṂ`ị

```

A monadic Link that accepts a list of integers and yields a list of the maximal linear sublists.

**Try it online!** Or see the test-suite.

### How?

```
JŒPịIEɗƇ⁸fƑⱮS¥ÐṂ`ị - Link: list of integers, A
J                  - indices of A
 ŒP                - powerset
      ɗƇ⁸          - keep those for which:
   ị               -   index back into A
    I              -   forward differences
     E             -   all equal?
             ¥ÐṂ`  - keep those minimal under:
           Ɱ       -   map with:
          Ƒ        -     is invariant under?:
         f         -       filter keep
            S      -   sum
                 ị - index back into A

```
> 4 votes

# Answer
# Python3, 252 bytes

```
E=enumerate
def f(l):
 q,T=[([a],[],[i])for i,a in E(l)],[]
 while q:
  a,c,I=q.pop(0)
  T+=[(a,I)]
  for j,k in E(l):
   if j>max(I)and(c==[]or a[-1]-k==c):q+=[(a+[k],a[-1]-k,I+[j])]
 return[a for a,b in T if not any(not{*b}-{*B}for A,B in T if B!=b)]

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 149 bytes

```
a=>(o=[...Array(1<<a.length).keys(g=n=>[x,y]=a[F]((_,i)=>n>>i&1))][F='filter'](n=>!g(n).some(p=v=>p-(p=v)+y-x)))[F](p=>o.every(q=>p&q-p|q==p)).map(g)

```

Try it online!

## Commented

### Helper function

```
g =                  // g is a helper function (actually defined in the
n =>                 // scope of the main function) taking an integer n
                     // and returning a sublist of a[]
[x, y] =             // save the first two entries in global variables
  a.filter((_, i) => // for each value at index i in a[]:
    n >> i & 1       //   keep it only if the i-th bit of n is set
  )                  // end of filter()

```

### Main function

```
a => (               // a[] = input array
  o = [              // build the range going from 0 to 2**N - 1
    ...Array(        // where N is the length of a[]
      1 << a.length  // (i.e. all possible bit-masks of length N)
    ).keys()         //
  ].filter(n =>      // for each value n in that range:
    !g(n)            //   build the sublist for the bit-mask n
    .some(p = v =>   //   for each value v in this sublist:
      p - (p = v) +  //     discard the sublist if the difference
      y - x          //     between v and the previous value is not
                     //     equal to those of the first 2 entries
    )                //   end of some()
  )                  // end of filter(); save the result in o[]
).filter(p =>        // for each value p in o[]:
  o.every(q =>       //   for each value q in o[]:
    p & q - p |      //     make sure that either at least one bit
    q == p           //     set in p is not set in q, or q = p
  )                  //   end of every()
)                    // end of filter()
.map(g)              // translate the bit-masks back to sublists

```
> 1 votes

# Answer
# Charcoal, ~~58~~ 53 bytes

```
Ｆ⮌ＥＸ²Ｌθ⌕Ａ⮌⍘ι²1Ｆ›⬤υ⁻ικ⊙ι∧›λ¹↨Ｅ⁴§θ§ι⁻λ↔⊖μ±¹⊞υιＥυ⭆¹Ｅι§θν

```

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

```
Ｆ⮌ＥＸ²Ｌθ⌕Ａ⮌⍘ι²1

```

Loop over the sublists of the indices of the list's elements from largest to smallest.

```
Ｆ›⬤υ⁻ικ⊙ι∧›λ¹↨Ｅ⁴§θ§ι⁻λ↔⊖μ±¹

```

If this isn't a sublist of an already found list but is linear, then...

```
⊞υι

```

... save this as a new maximal linear sublist.

```
Ｅυ⭆¹Ｅι§θν

```

Convert the lists of indices to lists of elements and pretty-print them.

Linearity is determined by taking a sliding window of size `3` and computing `x[1]-x[0]+x[1]-x[2]` which should be `0` in all cases.

This answer could be written as a single statement instead of four but it would still be ~~58~~ 53 bytes.
> 1 votes

# Answer
# 05AB1E, ~~22~~ 20 bytes

```
ā<æʒè¥Ë}©ʒ®€æ€`»sðý¢}è

```

Try it online or verify all test cases.

**Explanation:**

```
ā            # Push a list in the range [1, input-length]
 <           # Decrease each by 1 to make them 0-based indices: [0,length)
  æ          # Get the powerset of this
   ʒ         # Filter it by:
    è        #  Index each into the (implicit) input-list
     ¥       #  Get their forward differences
      Ë      #  Check if all are the same
   }©        # After the filter: store the list in variable `®`
   ʒ         # Then filter once again:
    ®        #  Push list of lists `®`
     €æ      #  Get the powerset of each inner list
       €`    #  Then flatten it one level down
         s   #  Swap so the current list we're filtering is at the top
          .¢ #  Count how many times this sublist occurs in the larger list of lists
             #  (only 1 is truthy in 05AB1E)
   }è        # After the filter: index each value into the (implicit) input-list
             # (after which the resulting list of lists is output implicitly)

```

~~Unfortunately, almost all of 05AB1E builtins are vectorized, hence the need for the `»` and `ðý`.~~ -2 bytes, because luckily with the count builtin `¢`, there is a non-vectorized alternative . :)
> 1 votes

---
Tags: code-golf, subsequence
---