title: Counting and spelling up

text:
# Question
Title: Counting and spelling up
Write a program that takes as its input a string that outputs a string with the following properties.

* If a character in the string is an uppercase letter (ASCII 41-5A), then the character is replaced by a string containing every letter up to and including the original letter in upper case. For example, if the input string is `I`, then the output would be `ABCDEFGHI`.
* Similarly, if a character is a lowercase letter (ASCII 61-7A), then the character is replaced in the same way. `i` would be replaced by `abcdefghi`.
* If a character is a number (ASCII 30-39), then the character is replaced by every number starting from `0` and counting up to the number.
* If the input contains concatenated individual characters, then the replacement sequences are concatenated together.
* All other characters are printed without modification.

*Sample inputs* (separated by blank lines)

```
AbC123

pi=3.14159

Hello, World!

```

*Sample outputs*

```
AabABC010120123

abcdefghijklmnopabcdefghi=0123.0101234010123450123456789

ABCDEFGHabcdeabcdefghijklabcdefghijklabcdefghijklmno, ABCDEFGHIJKLMNOPQRSTUVWabcdefghijklmnoabcdefghijklmnopqrabcdefghijklabcd!

```

This is code golf, fellas. Standard rules apply. Shortest code in bytes wins.

---

To see the leaderboard, click "Show code snippet", scroll to the bottom and click "► Run code snippet". Snippet made by Optimizer.

```
/* Configuration */

var QUESTION_ID = 61940; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43444; // 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 "http://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 "http://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}

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

#language-list {
  padding: 10px;
  width: 290px;
  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="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<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
> 11 votes
# Pyth, 19 bytes

```
sXzsJ+rBG1jkUTs._MJ

```

Try it online: Demonstration or Test Suite

### Explanation

```
sXzsJ+rBG1jkUTs._MJ
      rBG1            the list ["abc...xyz", "ABC...XYZ"]
     +    jkUT        appends the string "0123456789"
    J                 save this list of 3 strings in J
   sJ                 join the strings in J
               ._MJ   create all prefixes of the strings in J
              s       and combine them to one list
 XzsJ         s._MJ   translate the input string, chars from sJ
                      get translated to the correct prefix,
                      chars that don't appear in sJ don't get translated
s                     join all resulting translation strings

```

# Answer
> 8 votes
# Python 2.7, ~~100~~ ~~98~~ 96 bytes

```
a=[]
for c in raw_input():d=ord(c);a+=range(max(d&96|1,48),d)*c.isalnum()+[d]
print bytearray(a)

```

# Answer
> 7 votes
# TeaScript, 24 bytes ~~26~~ ~~28~~

TeaScript is JavaScript for golfing

```
xl(#(i=lN()1)h(ii(l)+1))

```

Pretty short

Try it online

### Explanation

```
x.l(#            // Loops through each character of the string

     (i=l.N()1)  // Determines whether a character is alphanumeric
                 // Will return A-Z, a-z or 0-9 depending on result
                 // Assigns to variable i

     .h(         // Get characters up to...
        i.i      // where the character is in "i"
     ) + 1       // Increased by one
)

```

# Answer
> 6 votes
# Ruby, ~~137~~ ~~87~~ ~~82~~ ~~76~~ ~~67~~ 55 bytes

Ungolfed, but you can see the pattern.

```
$><<gets.gsub(/[a-z0-9]/i){[*" 0Aa"[$&.ord/32]..$&]*""}

```

Edit: golfed down to only one regex.

Edit 2: had a lot of extra spaces.

Edit 3: Thanks to manatwork for golfing 12 bytes!

# Answer
> 4 votes
# Haskell, ~~95~~ ~~91~~ ~~86~~ 60 bytes

```
c#(a:o:r)|c<a||c>o=c#r|1<2=[a..c]
c#_=[c]
f=((#"AZaz09")=<<)

```

Usage example: `f "pi=3.14159"` -\> `"abcdefghijklmnopabcdefghi=0123.0101234010123450123456789"`

How it works: copy every char c in the input string unless c is in-between any of `A`/`Z`, `a`/`z` or `0`/`9` and if so take the list of `[<first char in pair> ... <c>]`.

Edit: @Zgarb saved many many bytes. Thanks!

# Answer
> 4 votes
# JavaScript (ES6), ~~143~~ 138 bytes

Uses string comparisons to test which characters to use.

```
s=>s.replace(/[A-Z0-9]/gi,c=>(a=btoa`Ó]·ã»óÖq×£Y§¢«²Û¯Ã³`,(c>'Z'?a:a.toUpperCase()).split``.filter(x=>x<=c&(x>'9'|c<'A')).join``))

```

Online demo. Tested in Firefox and Chrome.

Edit: Saved 5 bytes by replacing `a='0123456789abcdefghijklmnopqrstuvwxyz'` with

```
a=btoa`Ó]·ã»óÖq×£Y§¢«²Û¯Ã³`

```

# Answer
> 3 votes
# Python 2, ~~145~~ ~~140~~ ~~133~~ ~~103~~ 102 Bytes

A not-so-sleek anonymous function using list comprehension. I feel like the logic should be much shorter, I'll try and figure something out.

```
lambda k:''.join([c,`map(chr,range(48+17*(c>'@')+32*(c>'`'),ord(c)+1))`[2::5]][c.isalnum()]for c in k)

```

Should be given a name to be used, i.e. `f=...`

# Answer
> 3 votes
# PHP, 146 bytes

**Golfed**

```
function f($n,&$l){for(;$c=$n[$r],$b=0,$d=ord($c);$r++,$b?:$l.=$c)foreach([58=>48,91=>65,123=>97] as $m=>$i)while($d<$m&&$d>=$i)$b=$l.=chr($i++);}

```

**Revision 1:** put ord ranges directly into foreach. incremented ord range maxes and changed `$d<=$m` to `$d<$m`. using `for` to iterate chars instead of `foreach` and `str_split`. Removed all `{}` by moving code into `for`

**Ungolfed**

```
function f($input,&$output){
foreach (str_split($input) as $char){
  $ord = ord($char);
  $ords = [57=>48,90=>65,122=>97];
  $b = 0;
  foreach ($ords as $max=>$min){
     while ($ord<=$max&&$ord>=$min){
         $b = $max;
         $output .= chr($min);
         $min++;
     }
  }
  $b ?: $output.=$char;
}
};

$output = NULL;
$input = "pi=3.141592";
f($input,$output);
echo $output;

```

**Explanation:** split string into array. If ascii value falls into a range (for a-z,A-Z,0-9), then increment a counter from the min of the range to the char's ascii value, appending each value until you reach the char's ascii value.

I passed in  `&$var` so output is done by reference rather than a `return`

# Answer
> 2 votes
# JavaScript (ES6), ~~340~~ ~~258~~ ~~273~~ 271 bytes

```
a=s=>{s=s.split``;Q=x=>x.toUpperCase();A="ABCDEFGHIJKLMNOPQRSTUVWXYZ";D="0123456789";f="";for(i=0;i<s.length;i++){j=s[i];c="to"+(Q(j)==j?"Upper":"Lower")+"Case";j=Q(j);if(q=A.search(j)+1)f+=g=A.slice(0,q)[c]();else if(q=D.search(j)+1)f+=g=D.slice(0,q);else f+=j}return f}

```

# Answer
> 2 votes
## Python, 143 bytes

```
lambda s:''.join(map(chr,sum(map(lambda a,r=range:r(65,a+1)if 64<a<97else r(97,a+1)if 96<a<123else r(48,a+1)if 47<a<58else[a],map(ord,s)),[])))

```

Try it online

# Answer
> 2 votes
# Scala, 111 91 bytes

```
val f=(_:String).flatMap(x=>if(x.isDigit)('0'to x)else if(x.isUpper)('A'to x)else('a'to x))

```

# Answer
> 2 votes
## Perl 6, 101 bytes

Here is a first pass at it:

```
sub MAIN($_ is copy){
  s:g/<[0..9]>/{(0..$/).join}/;
  s:g/<[a..z]>/{('a'..~$/).join}/;
  s:g/<[A..Z]>/{('A'..~$/).join}/;
  .say
}

```

```
sub MAIN($_ is copy){s:g/<[0..9]>/{(0..$/).join}/;s:g/<[a..z]>/{('a'..~$/).join}/;s:g/<[A..Z]>/{('A'..~$/).join}/;.say}

```

**119**

---

Using `.trans` on `$_`to remove `is copy`.

```
sub MAIN($_){
  .trans(
    /\d/       => {(0..$/).join},
    /<[a..z]>/ => {('a'..~$/).join},
    /<[A..Z]>/ => {('A'..~$/).join}
  ).say
}

```

```
sub MAIN($_){.trans(/\d/=>{(0..$/).join},/<[a..z]>/=>{('a'..~$/).join},/<[A..Z]>/=>{('A'..~$/).join}).say}

```

**106**

---

Act on `@*ARGS` directly instead of defining a `MAIN` sub.
(otherwise identical to previous example)

```
@*ARGS[0].trans(/\d/=>{(0..$/).join},/<[a..z]>/=>{('a'..~$/).join},/<[A..Z]>/=>{('A'..~$/).join}).say

```

**101**

# Answer
> 2 votes
# PowerShell, 155 Bytes

```
($args-split''|%{$b=$_;switch([int][char]$_){{$_-in(65..90)}{[char[]](65..$_)}{$_-in(97..122)}{[char[]](97..$_)}{$_-in(48..57)}{0..$b}default{$b}}})-join''

```

*Technically* a one-liner, and PowerShell is all about those ;-)

Splits the input, pipes that into a `ForEach-Object` loop, switches on the integer value of the cast character, then generates new `char[]` of the appropriate ranges. Note that we have to spend bytes to set a temp variable `$b` because the act of casting the input `$_` in the switch statement means that we can't just keep using `$_` or we'll get funky output.

EDIT - I should point out that this will toss off errors since the first object being fed into `%{...}` is a null object. Since STDERR is ignored by default, this shouldn't be an issue. If it's a problem, change the first bit to be `($args-split''-ne''|...` to eliminate the null object.

# Answer
> 2 votes
# Julia, ~~102~~ ~~98~~ ~~90~~ 84 bytes

```
s->join([(i=Int(c);join(map(Char,(64<c<91?65:96<c<123?97:47<c<58?48:i):i)))for c=s])

```

This creates an unnamed function that accepts a string and returns a string.

Ungolfed:

```
function f(s::AbstractString)
    # For each character in the input, get the codepoint and construct
    # a range of codepoints from the appropriate starting character to
    # the current character, convert these to characters, and join them
    # into a string
    x = [(i = Int(c);
          join(map(Char, (isupper(c) ? 65 :
                          islower(c) ? 97 :
                          isdigit(c) ? 48 : i):i))
         ) for c in s]

    # Join the array of strings into a single string
    return join(x)
end

```

# Answer
> 2 votes
# Perl 5, ~~66~~ ~~61~~ (51 Bytes + 1) 52

Combining regexes with conditional operators worked out nice in this case.
~~With a join~~ Using map to combine the ranges into an array.

```
say map{(/\d/?0:/[A-Z]/?A:/[a-z]/?a:$_)..$_}split//

```

### Test

```
$ echo "A0C1.a3c_2!" |perl -M5.010 -n count_and_spell_up.pl
A0ABC01.a0123abc_012!

```

**Explanation**

```
say                # print output
  map{             # loop through the array that's at the end of the other mustache.
                   # outputs an array.
     (
        /\d/?0            # if $_ is a digit then 0
          :/[A-Z]/?A      # else, if it's an uppercase character then A
             :/[a-z]/?a   # else, if it's a lowercase character then a
               :$_        # else the current character
     )..$_         # generate a sequenced string of characters
                   # that ends with the magic variable $_
                   # ($_ is currently a character from the array)
  }split//     # split the magic variable $_ (currently the input string)
               # to an array of characters

```

# Answer
> 2 votes
## C (269 bytes)

(line break added for clarity)

```
#include<stdio.h>
#define F(x,y,z)if(c>=T[0][x]&&c<=T[1][y]){z}
#define L(x,y)for(i=0;i<x;++i){y}
main(){int c,i,n;char o,*T[]={"0Aa","9Zz"};while((c=getchar())!=EOF)
{F(0,2,L(3,F(i,i,o=T[0][i],n=++c-o;L(n,putchar(o++));break;))else putchar(c);)}}

```

## Ungolfed

```
#include<stdio.h>
int main(void)
{
  int c, i, n;
  char output;
  char *char_table[] = {"0Aa", "9Zz"};

  while ((c = getchar()) != EOF) {
    if (c < '0' || c > 'z') {
      putchar(c);
    } else {
      for (i = 0; i < 3; ++i) {
        if (c >= char_table[0][i] && c <= char_table[1][i]) {
          output = char_table[0][1];
          n = c - output;
          break;
        }
      }
      for (i = 0; i <= n; ++i) {
        putchar(output);
        ++output;
      }
    }
  }
  return(0);
}

```

# Answer
> 1 votes
# JavaScript (ES7), 125 bytes

There were already two JS answers focusing on encoding the strings, so I decided to go for a more algorithmic approach using `String.fromCharCode()`:

```
x=>x.replace(/[^\W_]/g,z=>(c=z.charCodeAt(),f=c<65?48:c<97?65:97,String.fromCharCode(...[for(i of Array(c-f).keys())i+f])+z))

```

A bonus of using this method is that it takes any amount of char codes, so `join`ing the list is not necessary. This turned out shorter than any other technique, so I'm happy with the result.

# Answer
> 1 votes
# MUMPS, 131 bytes

```
u(l,h) i l'>a,a'>h f j=l:1:a s o=o_$C(j),f=0
    q
t(s) f i=1:1:$L(s) s a=$A(s,i),f=1 d u(48,57),u(65,90),u(97,122) s:f o=o_$C(a)
    q o

```

I did manage to save a good few bytes here thanks to MUMPS's dynamic scoping. Here's a roughly-equivalent ungolfed version, which I sure would love to syntax highlight, if only support for the MUMPS Prettify module were available.

```
convert(str) ;
    new asciiCode,flag,i,output
    for i=1:1:$LENGTH(str) do
    . set asciiCode=$ASCII(str,i)
    . set flag=1
    . do helper(48,57)
    . do helper(65,90)
    . do helper(97,122)
    . if 'flag do
    . . set output=output_$CHAR(asciiCode)
    quit
helper(low,high) ;
    if low'>asciiCode,asciiCode'>high do
    . for code=low:1:asciiCode do
    . . set output=output_$CHAR(code)
    . . set flag=0
    quit

```

# Answer
> 1 votes
# Perl 6, ~~78~~ 77 bytes

```
@*ARGS[0].trans(/\d/=>{[~] 0..$/},/<:L>/=>{[~] samecase("a",~$/)..~$/}).say

```

# Answer
> 0 votes
# Mathematica, 102 bytes

```
FromCharacterCode@Flatten[Which[64<#<91,65,96<#<123,97,47<#<58,48,1>0,#]~Range~#&/@ToCharacterCode@#]&

```

Oh well...

# Answer
> 0 votes
# CJam, ~~32~~ 31 bytes

```
q_'[,_el^A,s+26/ff{_@#)<}:s\.e|

```

Try it online in the CJam interpreter.

### How it works

```
q_    e# Push two copies of the user input.
'[,   e# Push the string of all ASCII characters up to Z.
_el   e# Push a copy and convert it to lowercase.
^     e# Perform symmetric difference this keeps only letters.
A,s+  e# Append the string "0123456789".
26/   e# Split the result into chunks of length 26.
ff{   e# For each character from input: For each chunk:
  _@  e#   Copy the chunk and rotate the character on top of it.
  #   e#   Push the index of the character in the string (-1 for not found).
  )<  e#   Increment and keep that many characters from the left of the chunk.
      e#   This pushes "" for index -1.
}
:s    e# Flatten the resulting arrays of strings.
      e# The results will be empty strings iff the character wan't alphanumeric.
\     e# Swap the result with the input string.
.e|   e# Perform vectorized logical OR.

```

# Answer
> 0 votes
# Python 2, ~~135~~ 117 bytes

```
s=''
for c in raw_input():
 b=ord(c);e=b+1
 if c.isalnum():
  b=max(b&96,47)+1
 for i in range(b,e):s+=chr(i)
print s

```

# Answer
> 0 votes
## PHP - 291 bytes

Pass the string to `GET["s"]`.

```
<?php $s=$_GET["s"];$m="array_map";echo implode($m(function($v){$i="in_array";$l="implode";$r="range";global$m;$a=ord($v);if($i($a,$r(48,57)))$v=$l($m("chr",$r(48,$a)));if($i($a,$r(65,90)))$v=$l($m("chr",$r(65,$a)));if($i($a,$r(97,122)))$v=$l($m("chr",$r(97,$a)));return$v;},str_split($s)));

```

# Answer
> 0 votes
# C#, ~~251~~ ~~201~~ ~~184~~ ~~157~~ 154 Bytes

```
using System;class c{static void Main(string[] i){foreach(var c in i[0])for(var x=c>64&c<91?'A':c>96&c<123?'a':c>47&c<58?'0':c;x<=c;)Console.Write(x++);}}

```

edit: Strike! Shorter than PowerShell ;)

# Answer
> 0 votes
# APL (Dyalog Extended), 37 bytes

```
(⊃,/){⎕A∊⍨⌈⍵:⍵…⍨'A'××⍵⋄⍵∊⎕D:'0'…⍵⋄⍵}¨

```

Try it online!

A train that accepts a string as right argument.

# Answer
> 0 votes
# 05AB1E, 9 bytes

```
žKD₂ô€η˜‡

```

Try it online.

**Explanation:**

```
žK         # Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  D        # Duplicate it
   ₂ô      # Split the copy into parts of size 26: ["abc...xyz","ABC...XYZ","012...789"]
     €     # Map over each inner string:
      η    #  Get a list of its prefixes
       ˜   # Flatten this list of lists of strings
           #  ["a","ab","abc",...,"A","AB","ABC",...,"0","01","012",...,"0123456789"]
        ‡  # Transliterate all characters in the (implicit) input-string from
           # "abc...xyzABC...XYZ012...789" to these prefixes at the same positions
           # (after which the result is output implicitly)

```

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


title: Interlaced Rotations

text:
# Question
Title: Interlaced Rotations
# Challenge

Given a square matrix of characters (single-byte printable ASCII characters), rotate each "ring" of the matrix in opposite directions.

Let's take an example:

```
1 2 3 4 5
6 7 8 9 A
B C D E F
G H I J K
L M N O P

```

Then, the outermost ring is rotated clockwise 90 degrees, like so:

```
1 2 3 4 5    L G B 6 1
6       A    M       2
B       F => N       3
G       K    O       4
L M N O P    P K F A 5

```

The second ring is rotated counterclockwise 90 degrees:

```
7 8 9    9 E J
C   E => 8   I
H I J    7 C H

```

The final ring is rotated clockwise 90 degrees, but since it is a single number (letter in our example), then it is not really affected.

The final result is:

```
L G B 6 1
M 9 E J 2
N 8 D I 3
O 7 C H 4
P K F A 5

```

If the matrix has an even side length, the innermost ring will be a 2x2 square and should still be rotated.

# Input

A list of lists in any reasonable standard format. For example, a newline-delimited space-delimited string or a list of space-delimited strings is acceptable, but a list of the values as rings around the matrix is not acceptable. The characters are not necessarily unique.

# Output

A list of lists in any reasonable standard format. Same rules as the input.

# Test Cases

```
1 2 3    7 4 1
4 5 6 => 8 5 2
7 8 9    9 6 3

1 2 3 4 5 6    Y S M G A 1
A B C D E F    Z E K Q W 2
G H I J K L => ! D O I V 3
M N O P Q R    @ C P J U 4
S T U V W X    # B H N T 5
Y Z ! @ # $    $ X R L F 6

```

# Credits

Heavily inspired by a related challenge that rotates each element counterclockwise one position (not by 90 degrees).

# Answer
> 10 votes
# Haskell, 94 bytes

An anonymous function taking and returning a list of `String`s.

Use as `(cycle[t.r,r.t,r.t,r.t]?)["123", "456", "789"]`.

```
(cycle[t.r,r.t,r.t,r.t]?)
(g:h)?(a:b)=g$a:h?t(r b)
_?a=a
r=reverse;t=zipWith(:)`foldr`repeat[]

```

Try it online!

# How it works

* `r` is `reverse`. `t` is one byte shorter than importing `Data.List.transpose`. `t.r` rotates a list of lists 90 degrees clockwise, and `r.t` rotates it counterclockwise.
* The operator `?` takes two arguments, a list of functions and a matrix as a list of strings.
    + An empty matrix is just returned.
    + Otherwise, `?` strips the first function `f` off the list of functions, and the first line `a` off the matrix.
    + Then it rotates the remainder `b` of the matrix clockwise, and recurses with that and the remaining functions. This gradually strips the matrix from the outside in, one ring each four steps.
    + Then it prepends the original line `a` to the result, and applies the function `f` to it to adjust the orientation of the matrix.
* The anonymous function calls `?` with the input matrix as a list of strings, and an infinite list of functions, which repeats cyclically every four steps.
    + For most of the steps the function is counterclockwise rotation, which undoes the implicit clockwise rotation done by `?` when recursing.
    + However, the first step and every fourth step afterwards is instead clockwise rotation.
        - This function is applied when a ring of the matrix is complete, causing each ring to be 180 degrees rotated with respect to the next one.
        - By luck, this is also the correct transformation to apply to the final, completed matrix to get the final result.

# Answer
> 7 votes
# Python 2, 104 bytes

```
def f(x):l=len(x)-1;r=range(l+1);return[[[x[l-i][j],x[i][l-j]][min(i,j,l-i,l-j)%2]for i in r]for j in r]

```

Try it online!

`x[l-i][j]` are the coordenates of a clockwise turn, `x[i][l-j]` for a counterclowise turn. `min(i,j,l-i,l-j)%2` is used to pick the right direction

# Answer
> 4 votes
# Mathematica, 113 bytes

```
r=Reverse;(l=Length[s=#];Table[s[[i+1;;l-i,i+1;;l-i]]=r/@r@s[[i+1;;l-i,i+1;;l-i]],{i,⌊l/2⌋}];r/@Transpose@s)&

```

it is better to input as char string like "E" for special letters like E,I...

**input**

> \[{{1, 2, 3, 4, 5, 6}, {A, B, C, D, "E", F}, {G, H, "I", J, K, L}, {M, N, O, P, Q, R}, {S, T, U, V, W, X}, {Y, Z, "!", "@", "#", "&"}}\]

**output**

> {{Y, S, M, G, A, 1}, {Z, "E", K, Q, W, 2}, {"!", D, O, "I", V, 3}, {"@", C, P, J, U, 4}, {"#", B, H, N, T, 5}, {"&", X, R, L, F, 6}}

# Answer
> 3 votes
# Octave, 86 bytes

```
@(a){k=a;k(x=2:end-1,x)=0;a=rot90(a);a(m)=rot90(a,-2)(m=~mod(bwdist(+k,'ch'),2));a}{5}

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 35 bytes (SBCS)

Full program. Prompts for APL matrix expression. Requires 0-based indexing.

```
⍉⌽m⊣{(b↓e↓m)←⌽⊖b↓m↓⍨e←-b←2⍴⍵}¨⍳≢m←⎕

```

Try it online!

`m←⎕` prompt for matrix and assign to `m`

tally the number of rows in it

**ɩ**ndices zero through one less than that

`{` apply the following lambda to each element (denoted  in the code) of that:

`2⍴⍵`**r**eshape the index to a two-element list

`b←` assign to `b` (for **b**eginning)

`-` negate that

`e←` assign to `e` (for **e**nd)

`m↓⍨` drop that many (negative, so trailing) rows and columns from `m`

`b↓` drop that many leading rows and columns from that

flip upside down

mirror

`(``m)←` assign to the following sub-array of `m`:

`e↓` drop the appropriate number of rows and columns from the end (bottom right)

`b↓` drop the appropriate number of rows and columns from the beginning (top left)

`m⊣` ignore the pass-through values of all the assignments, in favour of the updated value of `m`

mirror

transpose

# Answer
> 2 votes
# APL (Dyalog Unicode), 81 bytes

```
{u⊃+/{⌽[1+2|⍵]∘⍉w×1@(y/⍨∨/¨(⍵,x)∘∊¨y←,∘.,⍨(⍵-1)↓⍳x←1+|⍵-≢w)⊢0×w}¨⍳⌈.5×≢w←⍵}u←⎕UCS

```

Try it online!

A 2-train which takes the matrix as its right argument.

The idea behind this is to peel the matrix into its rings, like so:

```
┌──────┬──────┬──────┬──────┐
│123456│123456│      │      │
│ABCDEF│A    F│ BCDE │      │
│GHIJKL│G    L│ H  K │  IJ  │
│MNOPQR│M    R│ N  Q │  OP  │
│STUVWX│S    X│ TUVW │      │
│YZ!@#$│YZ!@#$│      │      │
└──────┴──────┴──────┴──────┘

```

Then each of these rings are rotated left/right based on their index.

My algorithm for getting the rings has a lot of room for improvement (Porting the python solution may be shorter).

## Explanation

`⎕UCS` convert the matrix to its unicode values

`u←⎕UCS` store conversion function as u

`{...}` apply the following function on the matrix:

`w←⍵` store argument as w

`⍳⌈.5×≢` range `1..ceil(length(w)/2)`

---

**Getting the rings**

`{...}¨` for each value `i` in the range:

`0×w` to the input, converted to zeroes,

`1@(...)` replace the following coordinates with 1s:

`1+|⍵-≢⍵` upper limit: `length(w) - i`

`(⍵-1)↓⍳` create range from i to that

`,∘.,⍨` get all points in that range

`y←` store in `y`

`∨/¨(⍵,x)∘∊¨` check which ones are part of the ring, and get a list of booleans

`y/⍨` filter `y` using the boolean array

multiply `w` with that (vectorizes)

`⌽[1+2|⍵]∘⍉` Rotate right if `i` is odd, otherwise left

---

Finally,

`+/` sum all the matrices (vectorizes)

unwrap

`u` convert back to character matrix.

# Answer
> 2 votes
# Jelly, 19 18 bytes

```
ŒJUC;L‘_ɗ@ṂḂʋ¦€œịṁ

```

Try it online!

## Explanation

```
ŒJUC;L‘_ɗ@ṂḂʋ¦€œịṁ   Main monadic link
ŒJ                   Multidimensional indices
  U                  Reverse each
              €      For each
            ʋ          (
    ;                    Join with
        ɗ                (
     L   @                 Length of the input
      ‘                    Increment
       _                   Subtract the argument
                         )
          Ṃ              Minimum
           Ḃ             Parity
            ʋ          )
             ¦         At the obtained index
   C                   subtract it from 1
               œị    Index into the input
                 ṁ   Reshape to be the same as the input

```

# Answer
> 2 votes
# , 98 bytes

```
f=function(m,r=T,d=length(m)^.5){n=t(m)[d:1,]
if(r)n[]=rev(n)
if(d>2)n[e,e]=f(m[e<-3:d-1,e],!r)
n}

```

Try it online!

**How?**
At each recursive step, rotate the matrix clockwise by transposing it and reversing the rows. Then, if it should be an anticlockwise rotation, reverse all the elements. Finally, replace the 'internal matrix' with the results of a recursive call, with the rotation set to the opposite direction.

```
interlaced_rotate=
f=function(m,r=T,       # recursive function:
                        # m=matrix
                        # r=direction of rotation (TRUE=clockwise, FALSE=anticlockwise)
d=length(m)^.5){        # d=length of matrix side
  n=t(m)[d:1,]          # n=m rotated clockwise by transposing & reversing rows
  if(r)n[]=rev(n)       # if it's an anticlockwise rotation, reverse the elements
  if(d>2)               # if the 'internal matrix' has a side-length of >1:
    n[e,e]=             # replace it with
    f(m[e<-3:d-1,e],!r) # a recursive call, reversing the direction
n}                      # finally, return n

```

---
Tags: code-golf, matrix
---


title: Output the qwerty keyboard

text:
# Question
Title: Output the qwerty keyboard
Given a character, output (to the screen) the entire qwerty keyboard layout (with spaces and newlines) that follows the character. The examples make it clear.

Input 1

```
f

```

Output 1

```
g h j k l
z x c v b n m

```

Input 2

```
q

```

Output 2

```
w e r t y u i o p
a s d f g h j k l
z x c v b n m

```

Input 3

```
m

```

Output 3

(Program terminates without output)

Input 4

```
l

```

Output 4

```
z x c v b n m

```

**Shortest code wins.** (in bytes)

P.S.

Extra newlines, or extra spaces at the end of a line are accepted.

# Answer
> 20 votes
## CJam, ~~42~~ 40 bytes

```
"wertyuiop asdfghjkl zxcvbnm"q/W=S%Sf*N*

```

Test it here.

### Explanation

```
"we...nm"
     e# Push the letters in order, without q. We don't need q, because it will never
     e# be part of the output.
q/   e# Split the string around the input. If the input is "q", the entire string
     e# will go into a single chunk.
W=   e# Select the last chunk.
S%   e# Split the string around spaces, discarding empty segments (only relevant for the
     e# first segment if the input is "p" or "l").
Sf*  e# Join each line by spaces.
N*   e# Join the lines by linefeeds.

```

# Answer
> 11 votes
# Pyth, 33 bytes

```
jjL\ cec."`zÈ´ýß44,ûtKÕÀ@"z\`

```

Note that some characters are unprintable. Try it online in the Pyth Compiler.

### How it works

```
jjL\ cec."`z…"z\`

        ."`z…"     Unpack …, with lowest character '`' and highest character `z`.
       c      z    Split at occurrences of the input (z).
      e            Retrieve the last resulting chunk.
     c         \`  Split into rows, at backticks.
 jL\               Separate the characters of each row by spaces.
j                  Separate the rows by linefeeds.

```

# Answer
> 10 votes
# Perl, 56 bytes

```
#!perl -p
'qwertyuiop
asdfghjkl
zxcvbnm'=~/$_
?/;$_=$';s/\B/ /g

```

Counting the shebang as 3, input is taken from stdin. If a leading newline isn't a concern for inputs `p` and `l`, then `/$_\n?/` could be replaced with a bare `$_` to save 4.

---

**Sample Usage**

```
$ echo g|perl qwerty.pl
h j k l
z x c v b n m

$ echo v|perl qwerty.pl
b n m

```

# Answer
> 6 votes
# GS2, ~~38~~ 37 bytes

```
♦wertyuiop asdfghjkl zxcvbnm♣B3$,■♪2◙

```

The source code uses the CP437 encoding. Try it online!

### Test run

```
$ base64 -d > qwerty.gs2 <<< BHdlcnR5dWlvcCBhc2RmZ2hqa2wgenhjdmJubQVCMyQs/g0yCg==
$ wc -c qwerty.gs2
37 qwerty.gs2
$ echo -n f | gs2 qwerty.gs2
g h j k l
z x c v b n m

```

### How it works

```
♦                                      Begin string literal.
 wertyuiop asdfghjkl zxcvbnm
                            ♣          End string literal.
                             B         Swap the string with the input.
                              3        Split the string at the input character.
                               $       Select the last chunk.
                                ,      Split the selected chunk at spaces.
                                 ■     Map over the resulting array:
                                  ♪      Push ' '.
                                   2     Join the characters, separating by ' '.
                                    ◙    Push a linefeed.

```

# Answer
> 6 votes
# C#, 112 bytes ~~105~~ ~~110~~

Count went up by 5 bytes, but more correct! Thanks @MartinBüttner!!

```
void c(char i){System.Console.Write(@"q w e r t y u i o p
a s d f g h j k l
z x c v b n m".Split(i)[1].Trim());}

```

Un-golfed

```
void c(char i)
{
    System.Console.Write(@"q w e r t y u i o p
    a s d f g h j k l
    z x c v b n m".Split(i)[1].Trim());
}

```

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

```
x=>[...`qwertyuiop
asdfghjkl
zxcvbnm`].join` `.split(x)[1]

```

Uses the same technique as most other answers. Suggestions welcome!

# Answer
> 4 votes
## Python, 83 bytes

```
lambda c,s="q w e r t y u i o p\na s d f g h j k l\nz x c v b n m":s[s.index(c)+2:]

```

Try it online

# Answer
> 4 votes
# TeaScript, ~~50~~ ~~45~~ 44 bytes

TeaScript is JavaScript for golfing.

```
`qwertyuiop
asdfghjkl
zxcvbnm`.s×[1]s(b)j(p)

```

### Ungolfed and explanation

```
`qwertyuiop
asdfghjkl
zxcvbnm`.s(x)[1]s(b)j(p)

      // Implicit: x = input string
`...` // Take the qwerty string,
.s(x) // and split it at the input.
[1]   // Take the second item from this,
s(b)  // split it into chars,
j(p)  // and join the result with spaces.
      // Implicit: output final expression

```

# Answer
> 4 votes
# Ruby, ~~63~~ 57 bytes

Takes the character as command line argument: `ruby keyboard.rb e`

```
"qwertyuiop
asdfghjkl
zxcvbnm".scan$*[0]
puts$'.chars*' '

```

# Answer
> 3 votes
# JavaScript ES6, 73

```
f=x=>[...(k=`qwertyuiop
asdfghjkl
zxcvbnm`).slice(k.search(x)+1)].join` `

```

If a leading newline is not allowed when parameter is `p` or `l`, then **83**

```
f=x=>(k=`q w e r t y u i o p
a s d f g h j k l
z x c v b n m`).slice(k.search(x)+2)

```

# Answer
> 3 votes
# Sed, 59 characters

(58 characters code + 1 character command line option.)

```
s/./&qwertyuiop\nasdfghjkl\nzxcvbnm/
s/(.).*\1//
s/\w/& /g

```

Sample run:

```
bash-4.3$ echo -n 'f' | sed -r 's/./&qwertyuiop\nasdfghjkl\nzxcvbnm/;s/(.).*\1//;s/\w/& /g'
g h j k l
z x c v b n m

```

# Answer
> 3 votes
# Ruby, ~~86~~ ~~87~~ ~~83~~ ~~71~~ 66

```
puts"qwertyuiop
asdfghjkl
zxcvbnm ".split($*[0])[1].gsub /./,'\& '

```

The extra space after `m` is to prevent the program from crashing if the input is 'm'.

Thanks to @manatwork for ~16 bytes of tips

# Answer
> 2 votes
# PHP, 88 bytes

```
<?=$m[1&ereg("$argn.(.*)",'q w e r t y u i o p
a s d f g h j k l
z x c v b n m',$m)];

```

Requires the `-F` command line option, counted as 3. Default .ini setting are assumed (you may disable your local .ini with `-n`).

---

**Sample Usage**

```
$ echo g|php -F qwerty.php
h j k l
z x c v b n m

$ echo v|php -F qwerty.php
b n m

```

# Answer
> 2 votes
# Prolog (SWI), ~~153~~ 133 bytes

**Edit:** Cut 20 bytes with tips from @Fatalize

**Code**

```
b([A,_|T],[H]):-A=H,writef('%s',[T]);b(T,[H]).
p(X):-name(X,C),b(`q w e r t y u i o p \r\na s d f g h j k l \r\nz x c v b n m`,C),!.

```

**Explanation**

```
p(X):-name(X,C),                                                               % Get charcode of input
      b(`q w e r t y u i o p \r\na s d f g h j k l \r\nz x c v b n m`,C),!.    % Get keyboard chars as charcodes and call b
b([A,_|T],[H]):-A=H,                                                           % If list head is input element
                writef('%s',[T]);                                              % Interpret list as charcodes and print as string
                b(T,[H]).                                                      % Else remove first element of list and try again

```

**Examples**

```
>p(f).
g h j k l
z x c v b n m

>p(q).
w e r t y u i o p
a s d f g h j k l
z x c v b n m

```

# Answer
> 2 votes
# Japt, ~~49~~ ~~42~~ ~~41~~ ~~40~~ 38 bytes

**Japt** is a shortened version of **Ja**vaScri**pt**. Interpreter

```
`qØÆyuiop\n?dfghjkl\nzxcvbnm`qU g1 ¬qS

```

The `?` should be the unprintable Unicode char U+0086.

### How it works

```
          // Implicit: U = input char
`...`     // Take the compressed string and decompress it.
qU g1     // Split the string at the input and take the second item.
¬qS       // Split into chars, then join with spaces.
          // Implicit: output final expression

```

Now beating CJam! :) Suggestions welcome!

### Non-competing version, 12 bytes

```
;Dv qU g1 ¬¸

```

As of Jan 11, I've added a cool new feature to Japt: If the program contains a leading comma, the variables `ABCDEFGHIJL` are redefined to various values. `D` is set to `"QWERTYUIOP\nASDFGHJKL\nZXCVBNM"`, so `;Dv` is enough to replace the string here.

# Answer
> 2 votes
# Befunge, 122 bytes

```
"m n b v c x z"25*"l k j h g f d s a"v
v1-")"g2-"U"~"q w e r t y u i o p"*25<
>-:#v_$>:#,_@ZVD0FHJ:LNP^\<>,2B48X.T6R
^1$\<

```

It has been tested here: Befunge-93 Interpreter.

### How it works

* `'q w e r t y u i o p\na s d f g h j k l\nz x c v b n m'` is pushed on the stack.
* The number of values to discard (hardcoded in `@ZVD0FHJ:LNP^\<>,2B48X.T6R`) N is pushed.
* First N values are discarded and the remaining values are printed.

### Note

I picked the encoding so the string starts with `@` in order to overlap with the program. This string is generated with the following python code:

```
import string
letters = string.ascii_lowercase
base = 'q w e r t y u i o p a s d f g h j k l z x c v b n m'
print(''.join(chr(base.index(x) + 32 + 9 + 3) for x in letters))

```

# Answer
> 1 votes
## Python 2, ~~58~~ ~~67~~ 63 bytes ##

```
lambda x:" ".join("qwertyuiop\nasdfghjkl\nzxcvbnm".split(x)[1])

```

Takes input as a string or char. Splits the string at the input and prints off everything after the split.

(First time code-golfing, please be gentle :P )

EDIT: Didn't see the additional spaces required between characters, added now

EDIT 2: Modified to be an anonymous lambda function and removing the additional split arg, saving 4 bytes

# Answer
> 1 votes
# Mumps - 102 Bytes

Golfed script:

```
S A="qwertyuiopasdfghjklzxcvbnm",B=0 R P F I=1:1:$L(A) S Q=$E(A,I) W:B Q," " X:"qpl"[Q "W !" S:Q=P B=1

```

Ungolfed and commented:

```
 S A="qwertyuiopasdfghjklzxcvbnm" ; Need the qwerty order
 S B=0 ; boolean flag for printing, default to false.
 R P   ; read from stdin into P
 F I=1:1:$L(A) D   ; Count I from 1 to length of qwerty variable; do all of the following:
 . S Q=$E(A,I)     ; Extract 1 letter (at position I) from A and save in Q.
 . W:B Q," "       ; If our print flag (B) is true, print the letter in Q & a space.
 . X:"qpl"[Q "W !" ; If Q is q, p or l, write a cr/lf
 . S:Q=P B=1       ; If Q == P (stdin) change our print flag from false to true.

```

The rule allowing extra newlines saved me almost 10 bytes...

# Answer
> 1 votes
# JavaScript, 88 bytes

```
function s(d){alert("qw e r t y u i o p\na s d f g h j k l\nz x c v b n m".split(d)[1])}

```

(no need in the space after the first char, as it never gets to the output)

Alerts the keyboard when you call `s("some letter")`. Can be also made with `document.write()` or `console.log()`, but hey, it's longer :P

Demo:

```
function s(d){alert("qw e r t y u i o p\na s d f g h j k l\nz x c v b n m".split(d)[1])}

s(prompt("Enter the key"));
```

# Answer
> 1 votes
# Java - 107 bytes

```
void q(char c){System.out.print("qwertyuiop\nasdfghjkl\nzxcvbnm ".split(""+c)[1].replaceAll("\\w","$0 "));}

```

Ungolfed with wrapper-class reading from System.in

```
public class Qwerty {

    public static void main(String[] args) {
        new Qwerty().q(new java.util.Scanner(System.in).next().charAt(0));
    }
    void q(char c) {
        System.out.print("qwertyuiop\nasdfghjkl\nzxcvbnm ".split(""+c)[1].replaceAll("\\w","$0 "));
    }
}

```

If spaces at *start-of-line* were acceptable, we could go down to 99 bytes:

```
void q(char c){System.out.print("qwertyuiop\nasdfghjkl\nzxcvbnm ".split(""+c)[1].replace(""," "));}

```

# Answer
> 1 votes
# Ruby, ~~59 57~~  67 bytes

Added spaces between letters

```
puts"qwertyuiop\nasdfghjkl\nzxcvbnm".split(gets.chop)[-1].chars*' '

```

# Answer
> 1 votes
# 8086 machine code + DOS, 61 bytes

Hexdump (with ASCII view on the right):

```
B8 1E 01 8B F8 CD 21 B1 1F F2 AE 8B F7 AC 8A D0 ......!.........
B4 02 CD 21 80 E2 20 74 02 CD 21 E2 F0 C3 71 77 ...!.. t..!...qw
65 72 74 79 75 69 6F 70 0D 0A 61 73 64 66 67 68 ertyuiop..asdfgh
6A 6B 6C 0D 0A 7A 78 63 76 62 6E 6D 0D          jkl..zxcvbnm.

```

Assembly source code (can be assembled with tasm):

```
    .MODEL TINY

    .CODE
    org 100h

    MAIN PROC

    mov ax, offset qwerty ; sets ah=1 (coincidence)
    mov di, ax      ; di points to the string
    int 21h         ; reads a char from keyboard into al

    mov cl, 31      ; cx is the length of the string
    repne scasb     ; look for the char
    mov si, di      ; si now points beyond the found char

myloop:
    lodsb           ; load a char
    mov dl, al
    mov ah, 2
    int 21h         ; output the char

    and dl, 20h     ; if it's a letter, set it to a space
    jz print_done   ; if it's not a letter, don't print a space
    int 21h         ; if it's a letter, print a space
print_done:
    loop myloop     ; repeat until end of string

    ret

qwerty db 'qwertyuiop',13,10,'asdfghjkl',13,10,'zxcvbnm',13

    MAIN ENDP
    END MAIN

```

Two fun things here:

1. The offset of the `qwerty` string is `0x011e`. The upper byte of it is 1, which is the DOS function number for character input. This saves 1 byte in the code.
2. All lower-case letters have bit 5 set. When doing an `AND` with `0x20`, they are all turned into a space, which is then printed. If the previous char was an end-of-line byte, it gets turned into 0, and no space is output. This is used to avoid the nonsensical sequence `0d 20 0a 20` at end of line.

One almost-fun thing:

I tried to search for the input char starting at address 0 (that decreased program size by 2 bytes), instead of the usual place (start of the string). This almost worked; however, it failed for input `t`, because the code itself contains the byte `t` (as part of the encoding of a conditional jump). So for `t`, it would output a few junk bytes:

# Answer
> 1 votes
# O 2.2, ~~48~~ 46 characters

```
"qwertyuiop
asdfghjkl
zxcvbnm
"i/r;s{n.U=ST?}d

```

Sample run:

```
bash-4.3$ ./o keyboard.o <<< 'f'
g h j k l
z x c v b n m

```

## O, 61 characters

```
"qwertyuiop\nasdfghjkl\nzxcvbnm\n"i/r;""/rl{.o"\n"={}{' o}?}d

```

Sample run:

```
bash-4.3$ java xyz.jadonfowler.o.O keyboard.o <<< 'f'
g h j k l
z x c v b n m

```

# Answer
> 1 votes
**SQL (MS T-SQL), 172 bytes**

```
CREATE PROC c @I CHAR(1) AS DECLARE @S CHAR(49) SET @S = 'w e r t y u i o p' + CHAR(13) + 'a s d f g h j k l' + CHAR(13) + 'z x c v b n m' PRINT RIGHT(@S,LEN(@S)-CHARINDEX(@I,@S))

```

Ungolfed:

```
CREATE PROC c                           -- Create a procedure named "c"
    @I CHAR(1)                          -- Which is invoked with a single character input (@I)
AS

DECLARE @S CHAR(49) = 'w e r t y u i o p' + CHAR(13) + 'a s d f g h j k l' + CHAR(13) + 'z x c v b n m' -- Initialise the entire output omitting "q " as @S
PRINT RIGHT(@S,LEN(@S)-CHARINDEX(@I,@S))    -- Use the charindex funtion to effectively substring @S

```

I'm new here, only just discovered this site. No idea if I've posted correctly or if T-SQL is allowed but I know the procedure above works.

# Answer
> 1 votes
# Hassium, 114 Bytes

```
func main(){k="qwertyuiop\nasdfghjkl\nzxcvbnm\n"foreach(l in k.substring(k.index(input())))print(l!="\n"?l+" ":l)}

```

Run online and see expanded with test case here

# Answer
> 1 votes
# Japt `-hR`, 12 bytes

```
;Dv qU ®·®¬¸

```

Try it

# Answer
> 1 votes
# Husk, 38 bytes

```
↓2↓≠←⁰¶mJ' ¶¨qw²yuiop₄sdfghjkl¶zxcvbnm

```

Try it online!

# Answer
> 1 votes
# Husk, ~~29~~ 35 bytes

*Edit +6 bytes when I realised that the letters need to be separated by spaces*

```
¶mJ' ¶!2x¨qw²yuiop₄sdfghjkl¶zxcvbnm

```

Try it online!

# Answer
> 1 votes
# K (ngn/k), 53 bytes

```
{` 0:1_*|x\"\n"/" "/'$$`qwertyuiop`asdfghjkl`zxcvbnm}

```

Try it online!

Uses `"\n"/" "/'$$`...`...`...` to (slightly) compress `"q w e r t y u i o p\na s d f g h j k l\nz x c v b n m"`.

It then splits that string on the input character, taking the remainder that occurs after that character.

# Answer
> 1 votes
# JavaScript, 77 bytes

```
alert(`w e r t y u i o p
a s d f g h j k l
z x c v b n m`.split(prompt())[1])

```

### Fiddle

# Answer
> 0 votes
# Gema, 56 characters

```
?=@subst{\\A\*?=\;\?=\? ;qwertyuiop\nasdfghjkl\nzxcvbnm}

```

Sample run:

```
bash-4.3$ echo -n 'f' | gema '?=@subst{\\A\*?=\;\?=\? ;qwertyuiop\nasdfghjkl\nzxcvbnm}'
g h j k l
z x c v b n m

```

# Answer
> 0 votes
# , 32 chars / 79 bytes

```
⟦ɘƄ瀛ذ鸊ް΀ꀆဓƘ᳀ᘁ堍怍訁码聮Ęݠⶰ䀀#]ø⬭Čï⎖1

```

`Try it here (Firefox only).`

At least I'm winning in char count... (Byte count's a different story.)

Oh yeah, just realized that I implemented index shortcuts (`⎖1` instead of `[1]`) awhile back. Silly me!

# Answer
> 0 votes
# C++, ~~129, 112~~ 97 bytes

```
#include<string>
#include<cstdio>
void o(char c){puts(strstr("qwertyuiopasdfghjklzxcvbnm",&c));}

```

Ungolfed:

```
#include<string>
#include<cstdio>
void o(char c)
{
    puts(strstr("qwertyuiopasdfghjklzxcvbnm",&c));
}

```

# Answer
> 0 votes
## Batch, 206 + 2 = 208 bytes

Because this uses delayed expansion you need to invoke it with `CMD /V /C keyboard.cmd <letter>`, so adding ~~1~~2 for the `/V` switch.

```
@echo off
set a=q w e r t y u i o p
set b=a s d f g h j k l
set c=z x c v b n m
if not "!a:*%1 =!"=="!a!" echo !a:*%1 =!
if not "!a:*%1=!!b:*%1 =!"=="!a!!b!" echo !b:*%1 =!
if not %1==m echo !c:*%1 =!

```

# Answer
> 0 votes
## Python, 109 bytes

I know its a bit large but its all I know how to do right now!

```
def kb(c):
 s = "q w e r t y u i o p \n a s d f g h j k l \n z x c v b n m"
 a = s.split(c)
 print(a[1])

```

# Answer
> 0 votes
# PHP, 83 bytes

```
<?=trim(explode($argv[1],"qw e r t y u i o p
a s d f g h j k l
z x c v b n m")[1]);

```

Takes the letter from the command line, like:

```
$ qwerty.php y

```

# Answer
> 0 votes
# Bash, 80 bytes

```
x="qwertzuiop\nasdfghjkl\nyxcvbnm"&&echo -e ${x#*$1}|sed 's/./& /g'

```

Try it yourself, either replace *$1* with desired character or make a #!/bin/bash script.

Here are some samples from cygwin:

```
$x="qwertzuiop\nasdfghjkl\nyxcvbnm"&&echo -e ${x#*q}|sed 's/./& /g'
w e r t z u i o p
a s d f g h j k l
y x c v b n m

$x="qwertzuiop\nasdfghjkl\nyxcvbnm"&&echo -e ${x#*m}|sed 's/./& /g'

$x="qwertzuiop\nasdfghjkl\nyxcvbnm"&&echo -e ${x#*h}|sed 's/./& /g'
j k l
y x c v b n m

```

It's not the shortest, but I'm still proud of it!

# Answer
> 0 votes
# Bash, 74 bytes

Took a different approach than @Cajova\_Houba's answer, so I posted it separately. Ended up not being too much shorter because I initially forgot to deal with space-separating the output.

```
cut -d"$1" -f2<<<"qwertzuiop asdfghjkl yxcvbnm"|tr ' ' "\n"|sed 's/./& /g'

```

Takes input as a command line argument, or just replace `$1` manually and run it straight from terminal.

# Answer
> 0 votes
# Haskell, 79 bytes

```
drop 2.snd.(`span`"q w e r t y u i o p\na s d f g h j k l\nz x c v b n m").(/=)

```

Try it online!

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

```
f(c){puts(strchr("qwertyuiop\nasdfghjkl\nzxcvbnm",c)+1);}

```

Try it online!

---
Tags: code-golf, keyboard
---


title: The Written Digits Sequence

text:
# Question
Title: The Written Digits Sequence
Here's a reasonably trivial sequence which is not in the Online Encyclopedia of Integer Sequences.

Start with an empty sequence then define each term as the number of characters required to write out, in English, all of the digits of the sequence so far without spaces.\*

For reference the number of characters of all of the (base ten) digits in English are:

```
zero   one    two    three  four   five   six    seven  eight  nine
4      3      3      5      4      4      3      5      5      4

```

(Which is the start of both A52360 and A5589.)

This makes the first entry \\$a(0) = 0\\$ since there are zero digits present in the empty sequence.

This makes the second entry \\$a(1) = 4\\$ as it takes four characters to write "zero", the only digit present so far.

This makes the third entry \\$a(2) = 8\\$ as it takes four more characters to write the "four" for a total of eight to write "zerofour".

This makes the fourth entry \\$a(3) = 13\\$ as it takes five more characters to write "eight" for a total of thirteen to write "zerofoureight".

This makes the fifth entry \\$a(4) = 21\\$ as it takes eight more characters to write "onethree" for a total of twenty-one to write "zerofoureightonethree".

...and so on. Here are the first 100 entries:

```
0, 4, 8, 13, 21, 27, 35, 44, 52, 59, 67, 75, 84, 93, 102, 112, 121, 130, 142, 152, 162, 171, 182, 193, 205, 216, 225, 235, 247, 259, 270, 282, 293, 305, 318, 331, 344, 357, 371, 384, 398, 412, 422, 432, 444, 456, 467, 479, 492, 503, 516, 526, 536, 548, 561, 571, 583, 597, 610, 620, 630, 642, 652, 662, 671, 682, 693, 705, 718, 731, 744, 757, 771, 784, 798, 812, 823, 836, 849, 862, 873, 888, 903, 916, 926, 936, 948, 961, 971, 983, 997, 1010, 1024, 1038, 1055, 1070, 1086, 1101, 1114, 1127

```

* We could define it for other languages and/or other bases or with spaces of course

### The challenge

Given \\$n\\$ output, in as few bytes of code as possible, any of:

* The first \\$n\\$ terms of the sequence (should work for non-negative integers)
* The value of \\$a(n)\\$ (should work for non-negative integers)
* The \\$n\\$th term of the sequence (should work for positive integers - i.e. value of \\$a(n-1)\\$)

---

This is so the shortest answer in bytes wins for each language, and the shortest answer in bytes wins. Don't let golfing languages stop you from entering in your favourite language be it a practical one or an esoteric one!

# Answer
# Perl 6, 45 bytes

```
{({[+] @_.join.uninames>>.comb X-6}...*)[$_]}

```

Try it online!

No need for fancy moduloing when you can get the name of the digit directly! Anonymous code block that returns the nth value of the sequence, or you can pass in a range to get a list of values

### Explanation:

```
{(                                     )[$_]}  # Index input into:
  {                               }...*        # An infinite sequence
                                               # Where each element is
   [+]   # The sum of
       @_.join  # All previous elements joined together
              .uninames  # The unicode names for each character
                         # These are names in the form "DIGIT ONE"
                       >>.comb  # Split each to lists of characters
                               X-6  # Subtract 6 from each

```
> 12 votes

# Answer
# JavaScript (ES6), ~~69~~ ~~68~~ ~~61~~ 58 bytes

Returns \\$a(n)\\$.

```
f=(n,s=0)=>n?f(n-1,[...s+''].map(d=>s+=(d+10)%23%3+3)|s):s

```

Try it online!

### How?

A digit \\$d\\$ is converted to a number \\$n\\$ of letters with:

$$n=(((d \times 100 + 10) \bmod 23) \bmod 3)+3$$

```
 d | *100 | +10 | MOD 23 | MOD 3 | +3 | word
---+------+-----+--------+-------+----+-------
 0 |    0 |  10 |   10   |   1   |  4 | zero
 1 |  100 | 110 |   18   |   0   |  3 | one
 2 |  200 | 210 |    3   |   0   |  3 | two
 3 |  300 | 310 |   11   |   2   |  5 | three
 4 |  400 | 410 |   19   |   1   |  4 | four
 5 |  500 | 510 |    4   |   1   |  4 | five
 6 |  600 | 610 |   12   |   0   |  3 | six
 7 |  700 | 710 |   20   |   2   |  5 | seven
 8 |  800 | 810 |    5   |   2   |  5 | eight
 9 |  900 | 910 |   13   |   1   |  4 | nine

```

Because the number is split into digit characters, we can process \\$d\times 100+10\\$ by just adding \\$10\\$ (as a string concatenation).
> 8 votes

# Answer
# Stax, ~~14~~ 13 bytes

```
┴♥7[╘⌂←─üTJ‼√

```

Run and debug it

The key insight here is that digit `d` requires `((4 - 2 * d) // 3) % 3 + 3` letters to spell. (That's python integer division, and python-style non-negative modulus)
> 7 votes

# Answer
# Pip, 21 bytes

```
Lai+:$+4335443554@^Pi

```

Takes input \\$n\\$ as a command-line argument and outputs the first \\$n\\$ terms. Try it online!

### Explanation

```
Lai+:$+4335443554@^Pi
                       a is 1st cmdline arg; i is 0 (implicit)
La                     Loop (a) times:
                   Pi   Print i
                  ^     Split it into a list of characters (i.e. digits)
       4335443554@      Use each digit to index into this number, giving the length of the
                        name of the digit (0 -> 4, 1 -> 3, etc.)
     $+                 Sum the results
  i+:                   Increment i by that amount

```
> 5 votes

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

```
ÎFD•Qb₁ñ•sSèOO

```

Try it online!

**Explanation**

```
Î                # initialize stack with 0 and input
 F               # input times do:
  D              # duplicate the current number
         sSè     # and use one copy to index into
   •Qb₁ñ•        # 433544355
            OO   # sum digits and sum the stack

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 57 bytes

```
Nest[#+Tr@StringLength@IntegerName@IntegerDigits@#&,0,#]&

```

Try it online!

`Tr@StringLength@IntegerName@IntegerDigits@#&` lists the digits of `#`, converts each of them to an English name, counts the length, and sums the results. Lots of things thread over lists, it's very exciting. Then we just iteratively apply the definition.

TIO complains that it doesn't have an Internet connection, but I'm not sure why, because it figures out the right answer anyway. Maybe it's checking for updates to the names of integers?

Outputs the value of \\$a(n)\\$, but we could change it to give the entire list \\$a(0), a(1), \dots, a(n)\\$ by changing `Nest` to `NestList`.
> 4 votes

# Answer
# Clean, 82 bytes

```
import StdEnv,Text
$a=iter a(\n=n+sum[3+indexOf{c}" 9810324765"rem 3\\c<-:""<+n])0

```

Try it online!
> 4 votes

# Answer
# APL (Dyalog Unicode), ~~29~~ 28 bytes

```
{{⍵++/3+3|⌊3÷⍨4-2×⍎¨⍕⍵}⍣⍵⊢0}

```

Try it online!

Dfn. Prints \\$f(input)\\$

Thanks to the guys @The APL Orchard for helping with this one:

@ngn for 2 bytes; @H.PWiz for ~~3~~ 4 bytes.

Now using @recursive's formula.

### How:

```
{{⍵++/3+3|⌊3÷⍨4-2×⍎¨⍕⍵}⍣⍵⊢0} ⍝ Main fn

 {                     }⍣⍵⊢0 ⍝ Starting with 0, repeat (⍣) the inner fn input times
      3+3|⌊3÷⍨4-2×⍎¨⍕⍵      ⍝ @recursive's formula
  ⍵++/                       ⍝ Sum with the input.

```
> 4 votes

# Answer
# Python 2, 71 bytes

```
f=lambda n,k=0:n and f(n-1,k+sum(632179420>>3*int(d)&7for d in`k`))or k

```

Try it online!
> 3 votes

# Answer
# Python 2, 61 bytes

```
n=0
exec"for c in`n`:n+=(4-2*int(c))/3%3+3\n"*input()
print n

```

Try it online!

Uses recursive's digit count mapping.

---

**Python 2, 63 bytes**

```
f=lambda n:n and f(n-1)+sum((4-2*int(c))/3%3+3for c in`f(n-1)`)

```

Try it online!

A recursive function version. It takes exponential time to run because it has two recursive calls to `f(n-1)`.
> 3 votes

# Answer
# Pyth, 21 bytes

```
u+Gs@L+L3jC\᯻3jGTQ0

```

Try it online here.

```
u+Gs@L+L3jC\᯻3jGTQ0   Implicit: Q=eval(input()), T=10

u                Q0   Starting at 0, repeat the following Q times, with current value as G:
          C\᯻           Get character code 7163
         j   3          Convert the above to base 3, yields [1, 0, 0, 2, 1, 1, 0, 2, 2]
      +L3               Add 3 to each to generate digit length dictionary
              jGT       Get digits of G (convert to base 10)
    @L                  Lookup each value in the above in the dictionary, modular indexing
   s                    Take the sum
 +G                     Add G to the above

```
> 3 votes

# Answer
# MathGolf, 17 bytes

```
0\{_▒♀*♂+L%3%3+Σ+

```

Try it online!

This uses Arnauld's method. Outputs the nth element of the sequence.. If the empty string is okay for `a(0)`, then we could remove the `0\` at the beginning.

### Explanation:

```
0\                 Setup 0 as the counter
  {                Loop input times
   _▒              Duplicate counter and split to list of digits
     ♀*            Multiply each element by 100
       ♂+          Add 10
         L%        Modulo by 23
           3%      Modulo by 3
             3+    Add 3
               Σ   Sum list
                +  And add to counter

```
> 3 votes

# Answer
# Ruby, 54 bytes

```
->n{s=0;n.times{s+=s.digits.sum{|d|4+392[d]-70[d]}};s}

```

Try it online!
> 2 votes

# Answer
# Java (JDK), 95 bytes

```
n->{int l=0;while(n-->0)l+=(""+l).chars().map(x->"4335443554".charAt(x-48)-48).sum();return l;}

```

Try it online!
> 2 votes

# Answer
# Vyxal, 13 bytes

```
0?(»Þ([ǒ»Ȯİ∑Ṡ

```

Try it Online!

A port of the 05AB1E answer

## Explained

```
0?(»Þ([ǒ»Ȯİ∑Ṡ
0?              # Push 0 followed by the input number
  (             # Input number of times:
   »Þ([ǒ»       #     Push the number 433544355
         Ȯİ     #     And get the indexes corresponding to the numbers in the second last item on the stack
           ∑Ṡ   #     Sum that list and then the stack

```
> 2 votes

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

```
f=(a,b=1,s=4)=>a?b<a?f(a,++b,s+=[...s+''].reduce((q,w)=>+'4335443554'[w]+q,0)):s:0

```

Try it online!
> 1 votes

# Answer
# Jelly, 13 bytes

```
ṃ“vẋç’ḃ5¤S+Ɗ¡

```

Try it online!

0-indexed.

Full program; takes input from STDIN.
> 1 votes

# Answer
# Red, 99 95 bytes

```
func[n][d:"4335443554"s: 0 repeat i n[print s foreach c form s[s: s - 48 + do d/(-47 + do c)]]]

```

Try it online!

Just a straightforward solution.
> 1 votes

# Answer
# , 37 bytes

```
(+1#.|(3+3|23|10+100*]),.&.":)@]^:[&0

```

Try it online!

Uses Arnauld's method

## Explanation:

The argument is `n`

```
                                 ^:    - apply the verb on the left hand site
                                   [   - n times
                                    &0 - to a starting value 0
 (                             )@]     - calculate for the current value of the argument
                         ,.&.":        - convert to string and then each char to digit
        (3+3|23|10+100*])              - map each digit to its word length
       |                               - a filler for the fork
    1#.                                - sum the lengths
   +                                   - add them to the current value

```
> 1 votes

# Answer
**Edited after 1st comment.**

Prints all terms

# Scala, 76 bytes

```
def^(n:Int)=(1 to n).scanLeft(0)((y,_)=>y+(y+"").map(x=>(x*9+1)%13%3+3).sum)

```

Try it online!

Prints nth term

# Scala, 72 bytes

```
def^(n:Int)=Stream.iterate(0)(x=>x+(x+"").map(x=>(x*9+1)%13%3+3).sum)(n)

```

# Scala, 69 bytes

```
def^(n:Int)=(0/:(1 to n))((y,_)=>y+(y+"").map(x=>(x*9+1)%13%3+3).sum)

```

# Scala, 67 bytes

```
def s(b:Int):Stream[Int]=b#::s(b+(b+"").map(x=>(x*9+1)%13%3+3).sum)

```

# Scala, 67 bytes

```
val s:Stream[Int]=0#::s.map(x=>x+(x+"").map(x=>(x*9+1)%13%3+3).sum)

```

Try it online!
> 1 votes

---
Tags: code-golf, sequence, arithmetic, integer
---


# Question
Title: Is this a winning *Frustration* configuration?
Frustration is a solitaire card game which is played by calling out the sequence:

“Ace”, “Two”, “Three”, ... , "Nine", "Ten", “Jack”, “Queen”, “King”, “Ace”, “Two”, etc.

With each call, you simultaneously flip over a card from a shuffled deck of 52 cards. You win the game if you get through the entire deck without ever calling out the rank of the card being flipped over.

### Challenge

Given a string or list of characters representing an ordered deck of cards, return "Truthy" if the deck is a winning *Frustration* configuration, and return "Falsy" otherwise

### Input

Input will be a single string (or a list of characters, or a list of codepoints) consisting solely of the following 13 characters (you may choose to take the letters as uppercase or lowercase):

```
A 2 3 4 5 6 7 8 9 T J Q K

```

Each character will be repeated 4 times in the input. An example of a valid input is:

```
A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK

```

You may assume that the input is always valid (ie. it will contain exactly 52 characters and the 13 characters mentioned above will be repeated exactly 4 times each)

### Output

Output one of two distinct "Truthy" and "Falsy" values. The values you choose **must** be consistent (ie. different "Truthy" inputs must produce the same "Truthy" output and different "Falsy" inputs must produce the same "Falsy" output)

### Examples

The input `KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ` would be a winning *Frustration* configuration (hence a "Truthy" input) because none of the cards in the sequence match the name called out when flipping that card over.

The input `2K3A456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ` would **not** be a winning *Frustration* configuration (hence a "Falsy" input) because the 3rd card flipped over matches the name called out when flipping it (`3`).

### Test Cases (one per line)

**Truthy**

```
KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ
2A2A2AKQKQK3Q456789345678934567893456789A2JJJJTQKTTT
KQJT98675432AKQJT98675432AKQJT98675432AKQJT98675432A
55667987TAQK8TAQK8TAQK8TAQK325476979965432JJJJ234234
JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQKQ

```

**Falsy**

```
A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK
2A2A2AKQKQKQ3456789345678934567893456789A2JJJJTQKTTT
KQJT98765432AKQJT98765432AKQJT98765432AKQJT98765432A
8TAQK8TAQK8TAQK8TAQK234567999765432JJJJ2342345566797
JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQQK

```

### Scoring

This is . Shortest answer in bytes wins

# Answer
> 13 votes
# Python 2, ~~45~~ 42 bytes

*-5 bytes thanks to @ovs*

```
lambda s:all(map(cmp,s,'A23456789TJQK'*4))

```

Try it online!

# Answer
> 8 votes
# Perl 5 -p, 29 bytes

```
$_^="A23456789TJQK"x4;$_=/\0/

```

Try it online!

Perl allows XOR on strings, how awesome is that?!

# Answer
> 6 votes
# Jelly, 14 bytes

```
QṢ“ṡ=2E’œ?ṁn⁸Ạ

```

A monadic Link accepting a list of characters which yields `0` or `1`.

**Try it online!**

### How?

```
QṢ“ṡ=2E’œ?ṁn⁸Ạ - Link: list of characters, D
Q              - de-duplicate D
 Ṣ             - sort
  “ṡ=2E’       - base 250 integer = 3,832,012,820
        œ?     - nth permutation
          ṁ    - mould like (D)
           n   - not equal? (vectorises):
            ⁸  -   chain's left argument, D
             Ạ - all?

```

# Answer
> 5 votes
# Bash \+ Core utilities, 48 bytes

```
egrep "`echo \([^A ][^{{2..9},T,J,Q,K} ]\){4}`"

```

Try the test cases online!

Input is on stdin.

Output is the exit code: `0` for truthy, `1` for falsy.

# Answer
> 4 votes
# Retina 0.8.2, 57 bytes

```
([^A][^2][^3][^4][^5][^6][^7][^8][^9][^T][^J][^Q][^K]){4}

```

Try it online! Link includes test cases. Explanation: Simply matches a string of 52 bytes that doesn't match the specified character at each given position.

# Answer
> 4 votes
# Haskell, 37 bytes

```
and.zipWith(/=)(cycle"A23456789TJQK")

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 19 bytes

-2 bytes thanks to EdgyNerd,

-1 byte thanks to Grimmy.

```
'A8L>"TJQK"JJ4×ø€Ëà

```

Try it online!

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

```
Inner[Equal,#,Characters[#<>#<>#<>#&@"A23456789TJQK"],Or]&

```

Try it online! Pure function. Takes a list of characters as input and returns `True` or `False` as output. Note that this function checks for losing configurations (since `Equal` and `Or` are shorter than `Unequal` and `And`), so `False` is the truthy value and `True` is the falsy value.

# Answer
> 2 votes
## JavaScript (ES6), 48 bytes

With the input being a string:
`t=>![...t].some((v,i)=>"A23456789TJQK"[i%13]==v)`

With the input as an array of char it's down to 43 bytes:
`t=>!t.some((v,i)=>"A23456789TJQK"[i%13]==v)`

```
var f=
t=>![...t].some((v,i)=>"A23456789TJQK"[i%13]==v);

[
"KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ",
"2A2A2AKQKQK3Q456789345678934567893456789A2JJJJTQKTTT",
"KQJT98675432AKQJT98675432AKQJT98675432AKQJT98675432A",
"55667987TAQK8TAQK8TAQK8TAQK325476979965432JJJJ234234",
"JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQKQ"
].map(v=>console.log(v,f(v)));

[
"A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK",
"2A2A2AKQKQKQ3456789345678934567893456789A2JJJJTQKTTT",
"KQJT98765432AKQJT98765432AKQJT98765432AKQJT98765432A",
"8TAQK8TAQK8TAQK8TAQK234567999765432JJJJ2342345566797",
"JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQQK"
].map(v=>console.log(v,f(v)));
```

# Answer
> 2 votes
# Java (JDK), 63 bytes

```
s->s.matches("A23456789TJQK".repeat(4).replaceAll(".","[^$0]"))

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 44 bytesSBCS

```
{A T J Q K←10+¯9 0 1 2 3⋄~∨/(13|⍳52)=13|⍎¨⍵}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 19 bytes

```
⬤θ¬⁼ι§⁺⪫…²χωTJQKA⊖κ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean; `-` for truthy, nothing for falsy. Explanation:

```
 θ                  Input string
⬤                   All characters satisfy
    ι               Current character
  ¬⁼                Not equal to
        …²χ         Digits from 2 to 9
       ⪫   ω        Joined together
      ⁺     TJQKA   Suffixed with picture cards
     §              Indexed by
                 ⊖κ Current index incremented

```

# Answer
> 1 votes
# Perl 5, 36 bytes

```
sub f{('A23456789TJQK'x4^pop)!~/\0/}

```

Try it online!

`'A23456789TJQK' x 4` results in the 52 byte string of `A23456789TJQK` repeated four times.

This string is bitwise XOR-ed (operator `^`) by the equal length input string from `pop`.

Any equal byte (char) at the same positions in the two strings results in a null-byte from xor.

And `!~` (not regex-match) returns true if no null-byte `\0` exists. Otherwise false.

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

```
i;f(char*s){for(i=0;i<52&&s[i]-"A23456789TJQK"[i++%13];);i-=52;}

```

Outputs zero for truthy and non-zero for falsy.

Try it online!

# Answer
> 1 votes
# , 26 bytes

```
1 e.(52$'A23456789TJQK')&=

```

Try it online!

0 is truthy, 1 is falsy.

Straightforward as possible, posted mostly as a straw man because I thought it was interesting that there didn't seem to be a trick to compress 'A23456789TJQK' that was shorter than the literal.

# Answer
> 1 votes
# K (oK), 24 bytes

```
~|/(52#"A23456789TJQK")=

```

Try it online!

* `(52#"A23456789TJQK")` build the frustration sequence
* `(...)=` compare it to the input
* `~|/` do none (i.e. not any) match?

# Answer
> 0 votes
# Pyth, ~~24~~ 20 bytes

```
!sqV*X1"ATJQK"jkr2T4

```

Try it online!

* `X1"ATJQK"jkr2T` Construct the string "A23456789TJQK". Inserting the range 2-9 at position 1 of "ATJQK" is one byte shorter than using the full string literal
* `* ... 4` Duplicate that string 4 times
* `V` Vectorize the above string and the input string as inputs to the following function:

+ `q` (arg1) == (arg2)
* `!s` Return true if the result sums to 0 (ie. none of the cards from the input match the above string)

# Answer
> 0 votes
# GolfScript, 29 bytes

```
"A23456789TJQK"4*]zip{1/~=},!

```

Try it online!

```
"A23456789TJQK"4*               # Push this string repeted 4 times
                 ]zip           # Zip the input and the previous string
                     {    },    # Find all elements that pass this test
                      1/        # Divide in groups of 1      "XY" -> ["X" "Y"]
                        ~=      # Are they equal?
                            !   # Is it an empty array?

```

Outputs `1` for truthy and `0` for falsy.

# Answer
> 0 votes
# Japt `-e`, 16 bytes

```
kVg"tjqk"i9õ ¬ha

```

Try it

# Answer
> 0 votes
# x86 machine code, ~~33~~ 32 bytes

Replace `xx xx xx xx` with the address of `.Llut`.

Machine code:

```
00000034: bb xx xx xx xx 6a 34 59 89 c8 d4 0d d7 ae 74 02  .....j4Y......t.
00000044: e2 f6 c3 41 4b 51 4a 54 39 38 37 36 35 34 33 32  ...AKQJT98765432

```

Commented assembly:

```
        .intel_syntax noprefix
        .section .text
        .globl frustration
        // Input: EDI: 52 byte string to test
        // Clobbers: EAX, ECX, EBX, EDI
        // Output: ECX: Zero for true, non-zero for false
frustration:
        // Load the lookup table into EBX.
        mov     ebx, offset .Llut
        // Set ECX to 52 for our loop iterator
        push    52
        pop     ecx
.Lloop:
        // Copy ECX to EAX
        mov     eax, ecx
        // Convert to the LUT index. Read the .Llut comment before
        // questioning my math. ;)
        //
        // AL = AL % 13, AH = AH / 13
        aam     13
        // Load the corresponding card rank into AL.
        // AL = EBX[AL]
        xlatb
        // Compare to the byte in EDI, increment EDI
        scas    al, byte ptr [edi]
        // If it was equal, return. ECX will be nonzero.
        // Note that loopne wouldn't work: it decrements first, so it
        // won't work for the last card. :(
        je      .Lfalse
        // Loop for 52 iterations
        loop    .Lloop
        // At this point, ECX is zero from the loop, our "truthy" value
.Lfalse:
        ret
.Llut:
        // We store our LUT in a slightly unsual order.
        // This is because we are looping from 52->0, and using
        // the index mod 13 to get the index. However, we read
        // forwards, and we decrement AFTER the modulo.
        //
        // This means we need to reverse, then rotate one byte.
        //  0  52  0
        //  1  51 12
        //  2  50 11
        // ....
        // 12  40  1
        .ascii "AKQJT98765432"

```

Try it online!

The function takes the string pointer in `edi` and returns, in `ecx`, either zero for a win, or non-zero for a loss.

Doesn't follow standard calling convention.

I finally found a good use for both `aam` and `xlatb`, I feel accomplished.

See the comments for details.

This could use 2 fewer bytes on 16-bit, but that is solely because the LUT address is 2 bytes smaller. No fancy 16-bit tricks, so I'll leave it at x86 because it is easily testable on TIO.

I'd love to trim down this LUT a bit, but I'm not currently sure how. The LUT is 13 bytes plus a 5 byte `mov`, making more than half of the code.

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


title: FizzBuzz Reverse Solver

text:
# Question
Title: FizzBuzz Reverse Solver
> **Synopsis:** Given the output of a generalised FizzBuzz program, return the list of factors and words used for the program.

## Challenge Description

Imagine a generalised FizzBuzz program that takes in as input a list of factors and words to use and the number to start from. For instance, if the input of this program was

```
3 2,Ninja 5,Bear 7,Monkey

```

The program would print out numbers from `3` to `100`, replacing numbers divisible by `2` with `Ninja`, numbers divisible by `5` with `Bear`, and numbers divisible by `7` with `Monkey`. For numbers that are divisible then more than one of those terms, the program will concatenate the words, printing things such as `NinjaBear` or `BearMonkey` or `NinjaMonkey` or `NinjaBearMonkey`. Here's the output of that input:

```
3
Ninja
Bear
Ninja
Monkey
Ninja
9
NinjaBear
11
Ninja
13
NinjaMonkey
Bear
Ninja
17
Ninja
19
NinjaBear
Monkey
Ninja
23
Ninja
Bear
Ninja
27
NinjaMonkey
29
NinjaBear
31
Ninja
33
Ninja
BearMonkey
Ninja
37
Ninja
39
NinjaBear
41
NinjaMonkey
43
Ninja
Bear
Ninja
47
Ninja
Monkey
NinjaBear
51
Ninja
53
Ninja
Bear
NinjaMonkey
57
Ninja
59
NinjaBear
61
Ninja
Monkey
Ninja
Bear
Ninja
67
Ninja
69
NinjaBearMonkey
71
Ninja
73
Ninja
Bear
Ninja
Monkey
Ninja
79
NinjaBear
81
Ninja
83
NinjaMonkey
Bear
Ninja
87
Ninja
89
NinjaBear
Monkey
Ninja
93
Ninja
Bear
Ninja
97
NinjaMonkey
99
NinjaBear

```

Note that whenever the program needs to combine words together, it always goes from **lowest number to highest number**. So it won't print out something like `MonkeyBear` (since Monkey is a higher number than Bear is).

Your program should take in the *output* of the generalised FizzBuzz program as *input*, and *output* the *input* given to the generalised FizzBuzz program. In other words, write a "reverse program" for the generalised FizzBuzz program. For instance, given the code block above as input, your program should output `3 2,Ninja 5,Bear, 7,Monkey`.

There are some rules that the words will always follow:

* It will always be possible to tell exactly what the factors and words are from the input.
* Each word will begin with a capital letter and will not contain any other capital letters, or numbers.
* Each factor is unique.

## Sample Inputs and Outputs

Input:

```
Calvins
7
Hobbies
9
10
11
Calvins
13
14
15
Hobbies
17
Calvins
19
20
21
22
23
CalvinsHobbies
25
26
27
28
29
Calvins
31
Hobbies
33
34
35
Calvins
37
38
39
Hobbies
41
Calvins
43
44
45
46
47
CalvinsHobbies
49
50
51
52
53
Calvins
55
Hobbies
57
58
59
Calvins
61
62
63
Hobbies
65
Calvins
67
68
69
70
71
CalvinsHobbies
73
74
75
76
77
Calvins
79
Hobbies
81
82
83
Calvins
85
86
87
Hobbies
89
Calvins
91
92
93
94
95
CalvinsHobbies
97
98
99
100

```

Output:

```
6 6,Calvins 8,Hobbies

```

Input:

```
FryEggman
7
Am
Fry
The
11
FryAmEggman
13
14
FryThe
Am
17
FryEggman
19
AmThe
Fry
22
23
FryAmEggman
The
26
Fry
Am
29
FryTheEggman
31
Am
Fry
34
The
FryAmEggman
37
38
Fry
AmThe
41
FryEggman
43
Am
FryThe
46
47
FryAmEggman
49
The
Fry
Am
53
FryEggman
The
Am
Fry
58
59
FryAmTheEggman
61
62
Fry
Am
The
FryEggman
67
Am
Fry
The
71
FryAmEggman
73
74
FryThe
Am
77
FryEggman
79
AmThe
Fry
82
83
FryAmEggman
The
86
Fry
Am
89
FryTheEggman
91
Am
Fry
94
The
FryAmEggman
97
98
Fry
AmThe

```

Output:

```
6 3,Fry 4,Am 5,The 6,Eggman

```

Input:

```
DeliciousTartApplePie
DeliciousCreamPancakeStrawberry
DeliciousProfiterole
DeliciousCream
DeliciousPancake
DeliciousCreamStrawberryTart

```

Output:

```
95 1,Delicious 2,Cream 3,Pancake 4,Strawberry 5,Tart 19,Apple 95,Pie 97,Profiterole

```

You can get the code I used to generate the inputs here.

# Answer
> 11 votes
# Pyth, 73 bytes

```
jd+J-101lK.zjL\,Sm,_-F>2+_Jf}d@KTUKd{smtcdf-@dTGUdf>T\:K

```

That was certaintly a tough one. I think I've covered all the edge cases, including everything in @MartinBüttner's example, and the no repeat factors example.

NinjaBearMonkey, Deliciousness

At the high level, the program first finds all of the words by chopping up the alphabetical strings on capital letters.

Then, the rows are mapped to whether or not each string appears in the row, and each possible factor is tested to see if it produces the same ordering. If it does, the factor is added to a gobal list, which is check to see if the factor was already present. If it was not already present, the factor is used. The strings are ordered by first appearance in the input, which disambiguates the ordering of strings that each appear only once in the same row.

After that, it's just formatting and printing.

# Answer
> 5 votes
# Scala, 350 characters

```
(s:String)⇒{def g(a:Int,b:Int):Int=if(b==0)a.abs else g(b,a%b);val(j,q)=(s.lines:\100→Map.empty[String,Int]){case(l,(n,m))⇒if(l(0).isDigit)(n-1,m)else(n-1,m++(Seq(Seq(l(0)))/:l.tail){case(x,c)⇒if(c.isUpper)Seq(c)+:x else (x(0):+c)+:x.tail}.map{t⇒val w=t.mkString;w→g(m.getOrElse(w,n),n)})};s"${j+1}"+q.map{case(k,v)=>s" $v,$k"}.toSeq.sorted.mkString}

```

not winning... but nice question.

### tested results:

```
scala> (s:String)⇒{def g(a:Int,b:Int):Int=if(b==0)a.abs else g(b,a%b);val(j,q)=(s.lines:\100→Map.empty[String,Int]){case(l,(n,m))⇒if(l(0).isDigit)(n-1,m)else(n-1,m++(Seq(Seq(l(0)))/:l.tail){case(x,c)⇒if(c.isUpper)Seq(c)+:x else (x(0):+c)+:x.tail}.map{t⇒val w=t.mkString;w→g(m.getOrElse(w,n),n)})};s"${j+1}"+q.map{case(k,v)=>s" $v,$k"}.toSeq.sorted.mkString}
res0: String => String = <function1>

scala> res0("""DeliciousTartApplePie
     | DeliciousCreamPancakeStrawberry
     | DeliciousProfiterole
     | DeliciousCream
     | DeliciousPancake
     | DeliciousCreamStrawberryTart""")
res1: String = 95 1,Delicious 2,Cream 3,Pancake 4,Strawberry 5,Tart 95,Apple 95,Pie 97,Profiterole

scala> res0("""FryEggman
     | 7
     | Am
     | Fry
     | The
     | 11
     | FryAmEggman
     | 13
     | 14
     | FryThe
     | Am
     | 17
     | FryEggman
     | 19
     | AmThe
     | Fry
     | 22
     | 23
     | FryAmEggman
     | The
     | 26
     | Fry
     | Am
     | 29
     | FryTheEggman
     | 31
     | Am
     | Fry
     | 34
     | The
     | FryAmEggman
     | 37
     | 38
     | Fry
     | AmThe
     | 41
     | FryEggman
     | 43
     | Am
     | FryThe
     | 46
     | 47
     | FryAmEggman
     | 49
     | The
     | Fry
     | Am
     | 53
     | FryEggman
     | The
     | Am
     | Fry
     | 58
     | 59
     | FryAmTheEggman
     | 61
     | 62
     | Fry
     | Am
     | The
     | FryEggman
     | 67
     | Am
     | Fry
     | The
     | 71
     | FryAmEggman
     | 73
     | 74
     | FryThe
     | Am
     | 77
     | FryEggman
     | 79
     | AmThe
     | Fry
     | 82
     | 83
     | FryAmEggman
     | The
     | 86
     | Fry
     | Am
     | 89
     | FryTheEggman
     | 91
     | Am
     | Fry
     | 94
     | The
     | FryAmEggman
     | 97
     | 98
     | Fry
     | AmThe""")
res2: String = 6 3,Fry 4,Am 5,The 6,Eggman

```

# Answer
> 4 votes
# Python 2, ~~366~~ ~~340~~ 331 bytes

This program receive input via stdin.

New approach:

Calculate the factor of only one occurrence's words by the distance from the end of the line. For example (from the last sample): `DeliciousTartApplePie` Pie is calculate as: `[95,19,5,1][0]` and Apple is: `[95,19,5,1][1]`.

```
import sys
import re
d=[(i,re.findall('[A-Z][a-z]*',l)[::-1])for i,l in enumerate(sys.stdin)]
e=101-len(d)
print e," ".join(`x`+','+`y`[1:-1]for x,y in sorted({next((j-i for j,t in d if j>i and w in t),[x for x in range(i+e,0,-1)if(i+e)%x==0][d[i][1].index(w)]):w for w,i in{w:i for i,l in d[::-1]for w in l}.items()}.iteritems()))

```

Old approach:

```
import sys
import re
l=[(i,re.findall('[A-Z][a-z]*',l))for i,l in enumerate(sys.stdin)]
e=101-len(l)
d={}
for i,s in l:
 for w in s[::-1]:
  if w not in d.values():
   d[next((j-i for j,t in l[i+1:]if w in t),next(m for m in range(i+e,0,-1)if(i+e)%m==0and m not in d))]=w
print e," ".join(`x`+','+`y`[1:-1]for x,y in sorted(d.iteritems()))

```

# Usage:

```
python FizzBuzzReverseSolver.py < Sample1.txt

```

# Explanation (of Old approach):

* In general, the program creates a list of line number and list of words (e.g. `[(0, []), (1, ['Ninja']), (2, ['Bear']), ...]`.
* For each word in every line (starting from the end of the line):
    + Find the next occurrence of the word and insert the difference and the word to a predefined dictionary.
    + If it doesn't found, insert the biggest factor of the line number (including itself) that doesnt already exist in the dictionary and the word to the dictionary.

# Answer
> 1 votes
# 05AB1E, 65 bytes

```
|ā¤тα©+øUáεDS.uÅ¡J¦}˜ÙDεVXʒнYå}€θ0š¥θ}øí.¡н}εRεćÑRNèš]€`{',ý®>šðý

```

Try it online.

**Explanation:**

Step 1: Pair all input-lines with their corresponding value:

```
|            # Get all inputs as a list of strings
 ā           # Push a list in the range [1,length] (without popping the list itself)
  ¤          # Push its last/largest value (without popping)
   тα        # Get the absolute difference with 100
     ©       # Store this value in variable `®` (without popping)
      +      # Add it to each value in the [1,length]-list
ø            # Create pairs with the list of strings

```

Try just step 1, one builtin at a time.

Step 2: Get all unique words:

```
U            # Pop and store the paired-list in variable `X`
 á           # Only leave the letters of each string in the (implicit) input-list
             # (note that it'll use the entire list as input after we've used `|` once)
  ε          # Map each string to:
   D         #  Duplicate the string
    S        #  Convert the copy to a list of characters
     .u      #  Check for each character whether it's uppercase
       Å¡    #  Split at the truthy indices (while keeping them)
         J   #  Join each inner list of characters back to a string
          ¦  #  Remove the leading item, which is always an empty string
  }˜         # After the map: flatten the list of lists
    Ù        # And uniquify it

```

Try just step 2, one builtin at a time.

Step 3: Map each word to a list of pairs containing that word:

```
D            # Duplicate the list of words
 ε           # Map over each:
  V          #  Pop and store the current word in variable `Y`
   X         #  Push the paired-list `X`
    ʒ        #  Filter it by:
     н       #   Where its first item (the string)
      Yå     #   Contains word `Y`
    }        #  Close the filter

```

Try just step 3.

Step 4: Convert each to the step-size, and pair it with the words:

```
     €       #  Map over each inner list
      θ      #   And only leave the last item (the value)
       0š    #  Prepend a 0 to this list
         ¥   #  Get the deltas/forward-differences
          θ  #  And only leave the last one
 }ø          # After the map: pair each together with its word

```

Try just step 4, one builtin at a time.

Step 5: Fix any duplicated items (i.e. `Apple` & `Pie` both having value `95` now for the last test case):

```
í            # Reverse each pair
 .¡          # Then group all pairs by:
   н         #  Their first item (the value)
  }ε         # After the group-by, map over each list of pairs:
    R        #  Reverse the list of pairs
     ε       #  Map over each pair:
      ć      #   Extract head; pop and push remainder-list and first item separated
       Ñ     #   Pop this value, and get all its divisors
        R    #   Reverse this list
         Nè  #   Index the map-index into it
           š #   And prepend this value back to the list
   ]€`       # After both maps: flatten the list of lists of pairs one level down

```

Try just step 5, one builtin at a time.

Step 6: Print the output, including starting item:

```
{            # Sort this list of pairs (based on their first item, the value)
 ',ý        '# Join each pair with "," delimiter
    ®>       # Push value `®`, and increase it by 1
      š      # Prepend it in front of the list
       ðý    # Join the list by spaces
             # (after which it is output implicitly as result)

```

Try just step 6, one builtin at a time.

---
Tags: code-golf, fizzbuzz
---


title: Validate 2Col syntax!

text:
# Question
Title: Validate 2Col syntax!
As a couple of people may have noticed lately, I've largely abandoned development of Braingolf because it's boring and uninspired, and moved on to 2Col which is a little more interesting, and not designed to be a golfing language.

The defining feature of 2Col is that every line of code must be exactly 2 characters long, excluding the newline. This means that the length of a 2Col program can always be calculated as `3n-1` where `n` is the number of lines in the program.

So here's my challenge: Given 2Col code as a string, output truthy if it is valid 2Col code (Every line is exactly 2 characters and it conforms with the `3n-1` formula), and falsey otherwise.

## Input

Input should be taken as a single string, or an array of characters.

## Output

A truthy value if the input string is valid layout, and a falsey value otherwise.

Your code should be consistent in which truthy/falsey values it uses

## Testcases

```
======
F!
$^
----
truthy
======

======
*8
+1
Sq
----
truthy
======

======
nop
xt
----
falsey
======

======
+1
+1
#^

----
falsey
======

======
<empty string>
----
falsey
======

======
ye
----
truthy
======

======
no<space>
----
falsey
======

======
test
----
falsey
======

======
puzzle
----
falsey
======

```

## Scoring

This is so fewest bytes wins!

# Answer
> 6 votes
# Brachylog (2), 4 bytes

```
ṇl₂ᵐ

```

Try it online!

Full program (because this is a ; Brachylog full programs output `false.` if there was an assertion failure, `true.` without one).

## Explanation

```
ṇl₂ᵐ
ṇ     Split input into lines
   ᵐ  For each line:
 l₂     Assert that that line has length 2

```

Subscripts on `l` are one of Brachylog's newest features (although still older than the challenge), and this is a good challenge to use them on.

# Answer
> 3 votes
# JavaScript (ES6), ~~24~~ ~~28~~ ~~25~~ 24 bytes

Fixed program and shaved of three bytes thanks to @PunPun1000

Shaved off one byte thanks to @Shaggy

```
s=>/^(..\n)*..$/.test(s)

```

Returns true if valid and false if not.

```
f=
s=>/^(..\n)*..$/.test(s)

t=
`22
22
22
22
22`

console.log(f(t));
console.log(f(t.slice(0, -1)));
```

# Answer
> 2 votes
# Haskell, ~~23~~ ~~52~~ 32 bytes

```
all((==2).length).lines.(++"\n")

```

I got my inspiration from some other solutions, clever trick adding that `"\n"`.

# Answer
> 2 votes
# Cubix, 20 bytes

Returns 1 for truthy and nothing for falsey

```
@1OuABq>;;?w-!$@;U_N

```

Cubified

```
    @ 1
    O u
A B q > ; ; ? w
- ! $ @ ; U _ N
    . .
    . .

```
* `ABq` slurp in all the input, reverse it and push the EOI(-1) to the bottom of the stack
* `>;;` Step into the loop and remove items from the stack
* `?` Test for EOI(-1).
    + If found `1uO@` push 1 to the stack, u-turn onto integer output and halt
    + Otherwise `_` reflect back onto the `?` which redirects to the `w` lane shift
* `N-!$@;U` push line feed (10) onto the stack, subtract, test result, skip the halt if false, remove the result and u-turn
* `;;>` remove the line feeds from the stack and redirect into the loop.

Try it online!

# Answer
> 2 votes
# Python, 51

```
lambda s:all(len(l)==2for l in(s+"\n").splitlines())

```

Test case runner:

```
tcs = {
    "F!\n$^": 1,
    "*8\n+1\nSq": 1,
    "nop\nxt": 0,
    "+1\n+1\n#^\n": 0,
    "": 0,
    "ye": 1,
    "no ": 0,
    "test": 0,
    "puzzle": 0
}
f = lambda s:all(len(l)==2for l in(s+"\n").splitlines())
for tc, expected in tcs.items():
    assert f(tc) == expected

```

# Answer
> 1 votes
# JavaScript (ES6), ~~35~~ 24 bytes

```
s=>!/^.?$|.../gm.test(s)

```

---

## Try it

```
f=
s=>!/^.?$|.../gm.test(s)
oninput=_=>o.innerText=f(i.value)
o.innerText=f(i.value=`F!
$^`)
```

```
<textarea id=i></textarea><pre id=o>
```

# Answer
> 1 votes
# Japt, ~~7~~ 6 bytes

```
·eÈÊ¶2

```

Try it online

---

## Explanation

```
     :Implicit input of string "U"
·    :Split to array on newline
eÈ   :Maps over the array, checking that every item's ...
Ê    :length ...
¶2   :Equals 2
     :Implicit output of result

```

# Answer
> 1 votes
# Jelly, 6 bytes

```
ỴL€=2Ṃ

```

Try it online!

**Explanation:**

```
ỴL€=2Ṃ
Ỵ       Split at newlines
 L€     Length of each...
   =2   ...equals two.
     Ṃ  Minimum.

```

# Answer
> 1 votes
# Retina, 10 bytes

```
^..(¶..)*$

```

Try it online! Outputs `1` or `0` as appropriate.

# Answer
> 1 votes
# Java (OpenJDK 8), 25 bytes

```
s->s.matches("(..\n)*..")

```

Try it online!

Checks if the input string has any number of lines followed by a line feed and a final line without one (ensures at least one line)

# Answer
> 1 votes
# J-uby, ~~19~~ 18 bytes

```
:=~&/^(..\n*)..$/m

```

`:=~&` makes an anonymous function that takes `x` and returns `0` if it matches the regex `/^(..\n*)..$/m`, or `nil` otherwise.

# Answer
> 1 votes
# 05AB1E, 6 bytes

```
¶¡D2ùQ

```

Try it online!

```
¶¡D2ùQ   Argument s
¶¡       Split s on newlines
  D      Duplicate
   2ù    Keep only elements of length 2
     Q   Compare

```

# Answer
> 0 votes
# Bash + GNU utilities, 13

```
grep -qv ^..$

```

This sets the shell return value (accessible in `$?`) to 0 for false and 1 for true. This is actually the opposite sense compared to normal shell convention, so to make that right you'd need to do:

# Bash + GNU utilities, 15

```
! grep -qv ^..$

```

# Answer
> 0 votes
# Ruby, 22 bytes

```
->s{s=~/^(..\n*)..$/m}

```

# Answer
> 0 votes
# Jelly, 5 bytes

```
ỴẈ=2Ȧ

```

Try it online!

A small improvement over the other jelly answer.

## Explanation

```
ỴẈ=2Ȧ Main Link: takes string on the left
Ỵ     split on newlines
 Ẉ    length(vectorizes)
  =2  equals 2? (vectorizes)
    Ȧ are all elements truthy?

```

---
Tags: code-golf, string, decision-problem
---


title: Where is that snake going?

text:
# Question
Title: Where is that snake going?
Write a function (using as few bytes as possible) that takes a bi-dimensional array of any number of columns and rows in which:

* `0` represents empty block,
* `1` represents snake block.

The function must return the number of possible paths the snake traveled.

**Example 1:**

Input:

```
[
  [1,1,1,1,1],
  [0,0,0,0,1],
  [0,0,0,0,1],
]

```

Output: `2`

In the example above, the function will return `2` because the answer is either one of:

**Example 2:**

Input:

```
[
  [1,1,1,1],
  [0,0,1,1],
  [0,0,1,1],
]

```

Output: `6`

In this example the function will return `6` because the answer is either one of:

**Note:**

When assessing the input, you can assume that:

* The arrays representing columns will always have the same sizes (so the arrays are rectangular);
* There exists at least 1 valid path;
* The snake cannot walk through the edges (as can happen in some versions of snake);
* The snake will always have at least 2 blocks;
* The snake cannot move diagonally;
* The paths are directed. (so, two paths ending at different positions but otherwise looking exactly the same are not the same path, it’ll add up to the total)

# Answer
# Wolfram Language (Mathematica), 16+83=99 bytes

Library import statement (16 bytes):

```
<<Combinatorica`

```

Actual function body (83 bytes):

```
Length@HamiltonianCycle[MakeGraph[#~Position~1~Join~{1>0},##||Norm[#-#2]==1&],All]&

```

Try it online!

---

Note that the question just ask for the number of Hamiltonian path in the graph.

However, (for some reason) the `HamiltonianPath` function doesn't really work with directed graph (example). So, I used the workaround described in this Mathematica.SE question:

* Add an vertex (called `True`) that is connected to all other vertices.
* Count the number of Hamiltonian cycle on the resulting graph.

The graph is constructed using `MakeGraph` (annoyingly there are no directly equivalent built-in), using the boolean function `##||Norm[#-#2]==1&`, which returns `True` if and only if one of the arguments is `True` or the distance between the two vertices are `1`.

---

`Tr[1^x]` cannot be used instead of `Length@x`, and `<2` cannot be used instead of `==1`.

---

`HamiltonianPath` can be used if the graph is undirected, with the function body takes **84** bytes (exactly 1 byte more than the current submission):

```
Length@HamiltonianPath[MakeGraph[#~Position~1,Norm[#-#2]==1&,Type->Undirected],All]&

```

Try it online!
> 11 votes

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

```
ŒṪŒ!ạƝ€§ÐṂL

```

Try it online!

---

## Explanation.

```
ŒṪ               Positions of snake blocks.
  Œ!             All permutations.
                 For each permutation:
    ạƝ€             Calculate the absolute difference for each neighbor pair
       §            Vectorized sum.
                 Now we have a list of Manhattan distance between snake
                    blocks. Each one is at least 1.
        ÐṂL      Count the number of minimum values.
                    Because it's guaranteed that there exists a valid snake,
                    the minimum value is [1,1,1,...,1].

```
> 10 votes

# Answer
# JavaScript (ES6), ~~154~~ 134 bytes

```
m=>m.map((r,Y)=>r.map(g=(_,x,y,r=m[y=1/y?y:Y])=>r&&r[x]&&[-1,0,1,2].map(d=>r[r[x]=0,/1/.test(m)?g(_,x+d%2,y+~-d%2):++n,x]=1)),n=0)|n/4

```

Try it online!

## How?

### Method

Starting from each possible cell, we flood-fill the matrix, clearing all cells on our way. Whenever the matrix contains no more **1**'s, we increment the number **n** of possible paths.

Each valid path is counted 4 times because of the direction chosen on the last cell, which actually doesn't matter. Therefore, the final result is **n / 4**.

### Recursive function

Instead of calling the recursive function **g()** from the callback of the second **map()** like this...

```
m=>m.map((r,y)=>r.map((_,x)=>(g=(x,y,r=m[y])=>...g(x+dx,y+dy)...)(x,y)))

```

...we define the recursive function **g()** *directly as the callback* of **map()**:

```
m=>m.map((r,Y)=>r.map(g=(_,x,y,r=m[y=1/y?y:Y])=>...g(_,x+dx,y+dy)...))

```

Despite the rather long formula `y=1/y?y:Y` which is needed to set the initial value of **y**, this saves 2 bytes overall.

### Commented code

```
m =>                           // given the input matrix m[][]
  m.map((r, Y) =>              // for each row r[] at position Y in m[][]:
    r.map(g = (                //   for each entry in r[], use g() taking:
      _,                       //     - the value of the cell (ignored)
      x,                       //     - the x coord. of this cell
      y,                       //     - either the y coord. or an array (1st iteration),
                               //       in which case we'll set y to Y instead
      r = m[y = 1 / y ? y : Y] //     - r = the row we're currently located in
    ) =>                       //       (and update y if necessary)
      r && r[x] &&             //     do nothing if this cell doesn't exist or is 0
      [-1, 0, 1, 2].map(d =>   //     otherwise, for each direction d,
        r[                     //     with -1 = West, 0 = North, 1 = East, 2 = South:
          r[x] = 0,            //       clear the current cell
          /1/.test(m) ?        //       if the matrix still contains at least one '1':
            g(                 //         do a recursive call to g() with:
              _,               //           a dummy first parameter (ignored)
              x + d % 2,       //           the new value of x
              y + ~-d % 2      //           the new value of y
            )                  //         end of recursive call
          :                    //       else (we've found a valid path):
            ++n,               //         increment n
          x                    //       \_ either way,
        ] = 1                  //       /  do r[x] = 1 to restore the current cell to 1
      )                        //     end of map() over directions
    ),                         //   end of map() over the cells of the current row
    n = 0                      //   start with n = 0
  ) | n / 4                    // end of map() over the rows; return n / 4

```
> 10 votes

# Answer
# Python 2, ~~257~~ ~~246~~ ~~241~~ ~~234~~ ~~233~~ ~~227~~ ~~214~~ 210 bytes

```
lambda b:sum(g(b,i,j)for j,l in e(b)for i,_ in e(l))
e=enumerate
def g(b,x,y):d=len(b[0])>x>-1<y<len(b);c=eval(`b`);c[d*y][d*x]=0;return d and b[y][x]and('1'not in`c`or sum(g(c,x+a,y)+g(c,x,y+a)for a in(1,-1)))

```

Try it online!

---

Saved

* -8 bytes, thanks to Kevin Cruijssen
* -14 bytes, thanks to user202729
> 8 votes

# Answer
# Python 2, 158 bytes

```
E=enumerate
g=lambda P,x,y:sum(g(P-{o},*o)for o in P if x<0 or abs(x-o[0])+abs(y-o[1])<2)+0**len(P)
lambda L:g({(x,y)for y,r in E(L)for x,e in E(r)if e},-1,0)

```

Try it online!
> 5 votes

# Answer
# Haskell, 187 155 bytes

```
r=filter
l=length
(a,b)?(x,y)=abs(a-x)+abs(b-y)==1
l#x=sum[p!r(/=p)l|p<-x]
p![]=1
p!l=l#r(p?)l
f x|l<-[(i,j)|i<-[0..l x-1],j<-[0..l(x!!0)-1],x!!i!!j>0]=l#l

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Extended), 28 bytes

```
+/×/1=2(1⊥∘|-)/x[⌂pmat≢x←⍸⎕]

```

Try it online!

A full program that accepts a matrix.
> 1 votes

---
Tags: code-golf, grid, binary-matrix
---