title: Are these identifiers equivalent?

text:
# Question
Title: Are these identifiers equivalent?
In the language Nim, the rules for differentiating identifiers are slightly more relaxed than most other languages. Two identifiers are equivalent or address the same variable if they follow **these rules**:

* the first character of both **are the same** *(case sensitive)*
* both strings are the same *(case **in**sensitive)* after removing **all instances** of the characters `-` and `_`

## Challenge

Write a **program/function** that takes **two strings** that represent Nim identifiers and output a truthy or falsey value based on **whether or not they are equivalent** by the rules above.

### Specifications

* Standard I/O rules **apply**.
* Standard loopholes are **forbidden**.
* The strings will **only contain ASCII printables**. You **do not** need to check if it's a valid identifier.
* The strings may be taken as two separate inputs, list of strings, etc. (you know the drill)
* Empty strings **need not** be handled.
* The output **must be consistent** for both truthy and falsey values.
* This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**.
* Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise.
* Built-in functions that perform this task are **allowed** but including a solution that doesn't rely on a built-in is encouraged.
* Explanations, even for "practical" languages, are **encouraged**.

## Test cases

```
Input                                    Output

count, Count                             falsey
lookMaNoSeparator, answer                falsey
_test, test                              falsey
test, tset                               falsey
aVariableName, a_variable_name           truthy
numbers_are_cool123, numbersAreCool123   truthy
symbolsAre_too>_>, symbols_areTOO>>      truthy

```

## Ungolfed reference implementation

This is written in Nim, itself.

```
import strutils, re

proc sameIdentifier(a, b: string): bool =
  a[0] == b[0] and
    a.replace(re"_|–", "").toLower == b.replace(re"_|–", "").toLower

```

# Answer
> 8 votes
## JavaScript (ES6), ~~62~~ 61 bytes

*Saved 1 byte thanks to @JohanKarlsson*

Takes input in currying syntax `(a)(b)`. Returns a boolean.

```
a=>b=>(r=s=>s[0]+s.replace(/-|_/g,'').toUpperCase())(b)==r(a)

```

### Test cases

```
let f =

a=>b=>(r=s=>s[0]+s.replace(/-|_/g,'').toUpperCase())(b)==r(a)

console.log(f("count")("Count"))                           // falsey
console.log(f("lookMaNoSeparator")("answer"))              // falsey
console.log(f("_test")("test"))                            // falsey
console.log(f("aVariableName")("a_variable_name"))         // truthy
console.log(f("numbers_are_cool123")("numbersAreCool123")) // truthy
```

# Answer
> 6 votes
# Python 3, 76 bytes

```
lambda a,b:f(*a)==f(*b)
f=lambda f,*r:[f+k.lower()for k in r if~-(k in'-_')]

```

Try it online!

-1 byte thanks to notjagan
-3 bytes thanks to Wheat Wizard

# Answer
> 4 votes
# Actually, 15 bytes

```
⌠p"-_"(-Σùo⌡M═Y

```

Try it online!

Fun fact: this works with any number of inputs (it always returns truthy for less than 2 inputs).

Explanation:

```
⌠p"-_"(-Σùo⌡M═Y
⌠p"-_"(-Σùo⌡M    for each input:
 p                 separate the first character
  "-_"(-           remove all dashes and underscores from the rest of the string
        Σù         concatenate the list from the last operation and lowercase the string
          o        append it to the first character
             ═Y  are none of the elements unique?

```

# Answer
> 4 votes
## C++, ~~288~~ 248 bytes

-5 bytes thanks to Zacharý

```
#include<string>
#include<algorithm>
#define E(a,v)a.erase(std::remove(a.begin(),a.end(),v),a.end());
#define F(a)for(auto&c:a)c=toupper(c);
int e(std::string&a,std::string&b){if(a[0]!=b[0])return 0;E(a,45)E(b,45)E(a,95)E(b,95)F(a)F(b)return a==b;}

```

Thanks you, Preprocessor. Also, this code takes advantage of the fact that in C++ the rule to cast int to bool is `int_var!=0`

# Answer
> 3 votes
# Jelly, 11 bytes

```
ḟ⁾-_Œl,Ḣµ€E

```

Try it online!

-2 bytes thanks to Erik the Outgolfer
-1 byte thanks to Jonathan Allan

# Answer
> 3 votes
# Pyth, 13 bytes

```
qFm[hd-r0d"-_

```

Try it online!

# Explanation

```
qFm[hd-r0d"-_
  m              For each value in the input (which is a list of two strings):
   [             Create a list consisting of
    hd               the first character of each value
      -r0d"-_        and the lowercase version of the value without "-" or "_"
qF               Fold over equivalence; checks to see if both lists are the same

```

# Answer
> 3 votes
# Ruby, ~~86~~ ~~64~~ ~~63~~ ~~61~~ 51 bytes

```
f=->x{x[0]+x.upcase.delete("-_")}
->x,y{f[x]==f[y]}

```

Try it online!

This ~~feels really long~~ still feels a bit long. I would appreciate the help of any Ruby gurus out there in making this at least a bit shorter.

# Answer
> 3 votes
# 05AB1E, 12 bytes

```
εćs„-_SKl«}Ë

```

Try it online!

-1 thanks to Adnan.

Theoretically, `εćs„-_-«}Ë` should've worked for 10 bytes, but unfortunately this behavior is deprecated for now.

# Answer
> 2 votes
# CJam, 20 bytes

```
{_"-_"f-:el:=\:c:=*}

```

Takes input in the form of \["string1","string2"\].

Try it Online (testing version)

```
{
_      e# make copy of input
"-_"f- e# remove all "-" and "_" from both words in copy
:el    e# convert words in copy to lowercase
:=     e# 1 if both words in copy are equal, 0 if not
\      e# move original version of input to top of stack
:c     e# convert each word in original input to only 1st character
:=     e# 1 if both characters from original input are equal, 0 if not
*      e# multply the two numbers we obtained. If and only if both are 1 (true) we return 1 (true)
}

```

# Answer
> 2 votes
# Haskell, ~~85~~ ~~78~~ ~~76~~ ~~71~~ 68 bytes

*2 bytes saved thanks to Ørjan Johansen*

```
import Data.Char
s(a:x)=a:[toLower a|a<-x,all(/=a)"-_"]
x!y=s x==s y

```

Try it online!

Errors on the empty string.

# Answer
> 2 votes
# Python 2, 72 bytes

```
lambda x,y:r(x)==r(y)
r=lambda x:x[0]+x[1:].lower().translate(None,"-_")

```

Try it online!

Won't work with Python 3 because of the new `translate` syntax.

# Answer
> 2 votes
# Excel, 105 bytes

```
=AND(CODE(A1)=CODE(B1),SUBSTITUTE(SUBSTITUTE(A1,"_",""),"-","")=SUBSTITUTE(SUBSTITUTE(B1,"_",""),"-",""))

```

CODE() returns numeric code of first character.

String comparison in Excel is case insensitive.

# Answer
> 2 votes
# Husk, 13 bytes

```
¤=§,←(m_ω-"-_

```

Try it online!

Builds for each string a pair consisting of the first character of the string and the whole string lowercased and with all occurrences of -/\_ removed. Then checks if the two pairs are equal.

A particularity is that `-` in Husk is set difference (i.e. it removes only the first occurrence found): in order to remove all occurrences, the fixed point of `-"-_` is found with `ω-"-_`.

# Answer
> 2 votes
# Japt, ~~14~~ 25 bytes

```
g ¥Vg ©Uu k"_-" ¥Vu k"_-"

```

~~Checks case-insensitive string equality by removing all characters in word 2 from word 1, and removing the `-_` characters; that results in an empty string (`""`) if the words are equal.~~
*Thanks Ørjan Johansen for pointing out the problem with this.*

Checks first-char equality and if the uppercased inputs are equal after removing `_-`.

Try it online!

## Explanation

Implicit input: `U` and `V` are input strings

```
g ¥Vg

```

Check if first letter of `U` (implicit) equals (`¥`) the first char of `V`.

```
©Uu k"_-" ¥Vu k"_-"

```

And (`©`) check if `U`, uppercased (`u`) and with `_-` removed (`k`), equals (`¥`) the same for `V`. Implicitly return the boolean result.

# Answer
> 2 votes
# , 76 bytes

```
function(l)(g=substr(l,1,1))[1]==g[2]&(h=tolower(gsub('-|_','',l)))[1]==h[2]

```

Anonymous function that takes input as a list of two strings. Takes advantage of the fact that R's string operations, while quite long in # of characters, are vectorized. Additionally wrapping an assignment in parentheses will bind the variable, so `(g=substr(l,1,1))` retains a variable to be reused later in the line and similarly for `h`.

R returns the last evaluated expression as function output.

Ungolfed:

```
function(l){
  g <- substr(l,1,1)
  h <- tolower(gsub("_|-","",l))
  (g[1]==g[2])&(h[1]==h[2])
}

```

Try it online! (all test cases)

# Answer
> 2 votes
# Vyxal 3, 10 bytes

```
…≈¿ᶴ-_½-ʀ≈

```

Try it Online!

# Answer
> 1 votes
# Perl 5, 67 bytes

```
s/.//,push@a,$&,y/_-//dr for<>;say($a[0]eq$a[2]&&lc$a[3]eq lc$a[1])

```

Try it online!

Takes the identifiers as input on separate lines.

**Explanation:**

```
s/.//,             # remove the first character
push@a,            # storage space, even positions are first character
                   # odd positions are remainder
$&,                # implicit variable holding last matched pattern (first char)
y/_-//dr           # Remove _ and - from remainder of input
for<>;             # iterate over all input lines
say                # output
($a[0]eq$a[2]&&    # check that first character is identical and
lc$a[3]eq lc$a[1]) # so is the lowercase version of the rest

```

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

-6 bytes thanks to @notjagan: check the length of set of all reduced names is 1 or not.

```
lambda*l:len({x[0]+re.sub('-|_','',x[1:].lower())for x in l})<2
import re

```

Try it online!

# Answer
> 1 votes
# Retina, 28 bytes

```
T`L\_-`l_`(?<=.).+
^(.*)¶\1$

```

Try it online!

# Answer
> 1 votes
# Charcoal, 29 bytes

```
∧⁼§θ⁰§η⁰⁼↧⪫⪪⪫⪪θ_ω-ω↧⪫⪪⪫⪪η_ω-ω

```

Try it online!

This prints a `-` for truthy and nothing for falsey.

Link to the verbose version. It first compares the first character of both input strings (`⁼§θ⁰§η⁰`) and then compares the rest of both strings after removing the underscores and the hyphens (`⪫⪪⪫⪪θ_ω-ω`) and converting to lowercase ().

# Answer
> 1 votes
# C#, ~~101~~ 89 bytes

```
string g(string s)=>string.Concat(s.ToUpper().Split('-','_'));f=>s=>f[0]==s[0]&g(f)==g(s)

```

*Saved 12 bytes thanks to @kusi581.*

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

```
a->b->a.charAt(0)==b.charAt(0)&&a.replaceAll("_|-","").equalsIgnoreCase(b.replaceAll("_|-",""))

```

Try it online! Pretty straight forward.

# Answer
> 1 votes
# Pyke, 13 bytes

```
F'hl1"-_"-)Xq

```

Try it online!

```
F         )   -  for i in input():
 'hl1         -   i[0], i.lower()
     "-_"-    -         ^.remove("-_")
           Xq - equal(^)

```

# Answer
> 1 votes
# C (gcc), ~~126~~ 114 bytes

```
#define p(s)do++s;while(*s==45||*s==95);*s>95?*s-=32:0;
f(char*a,char*b){while(*a&&*a==*b){p(a)p(b)}return*a==*b;}

```

Try it online!

With whitespace and comments:

```
#define p(s)                   // Define helper macro p           \
    do ++s;                    // Increment pointer at least once \
    while (*s==45 | *s==95);   // and past any '-' or '_'         \
    *s>95 ? *s -= 32 : 0;      // If lowercase letter, convert to upper

f(char* a, char* b) {          // Define main function f
    while (*a && *a == *b) {   // Loop until end of either string
                               // or a difference found
        p(a)                   // Transform pointer and one char
        p(b)                   // via helper p above
    }
    return *a==*b;             // Test chars equal (on success, both '\0')
}

```

# Answer
> 1 votes
# Dyalog APL, ~~47~~ ~~32~~ ~~28~~ ~~27~~ ~~26~~ 22 bytes

-4 bytes thanks to Kritixi Lithos

```
{(=/⊃¨⍵)∧≡/819⌶⍵~'-_'}

```

Takes input as a list of the strings.

Try it online!

### How?

```
{(=/⊃¨⍵)∧≡/819⌶⍵~'-_'}
               ⍵~'-_'   Remove '-' and '_'
           819⌶         Lowercase
         ≡/             Equality between elements
        ∧               And
 (=/⊃¨⍵)                The first element of each element is equal

```

# Answer
> 1 votes
# Common Lisp, 98 bytes

```
(lambda(x y)(and(eql(elt x 0)(elt y 0))(string-equal(#1=remove #\-(#1##\_ y))(#1##\-(#1##\_ x)))))

```

Try it online!

Ungolfed (super straightforward!) version:

```
(defun f(x y)
  (and (eql (elt x 0) (elt y 0))         ; check if initial characters are identical
       (string-equal                     ; string comparison (case insensitive)
         (remove #\- (remove #\_ y))     ; remove from both strings the unwanted chars
         (remove #\- (remove #\_ x)))))

```

# Answer
> 1 votes
# Brachylog, 17 bytes

```
hᵛ&{{¬∈"_-"&ụ}ˢ}ᵛ

```

Try it online!

Outputs through predicate success/failure.

```
h                    The first element
 ᵛ                   is the same for each element of the input,
  &                  and
   {           }ᵛ    for each element of the input the following are the same:
    {      &ụ}ˢ      every element uppercased which satisfies the condition that
     ¬∈              it is not an element of
       "_-"          the string "_-".

```

# Answer
> 0 votes
# Erlang 113 bytes

```
A=fun(L)->string:to_lower(lists:flatten(string:tokens(L,"-_")))end,fun([C|D],[C|E])->A(D)==A(E);(_,_)->a==b end.

```

a pair of anonymous functions that compare the two lists. meant to be pasted in the erlang shell.

more readable:

```
A=fun(L) ->
    string:to_lower( % case insensitive
        lists:flatten( % squash all characters back into one list
            string:tokens(L,"-_") % return a list of list of characters
        )
    )
end.
fun([C|D],[C|E]) -> % are the first characters exactly the same?
    A(D)==A(E); % does the rest compare correctly?
   (_,_) -> % first chars not the same
    a==b % shorter than 'false'
end.

```

# Answer
> 0 votes
# Clip, 25 bytes

```
&=(x(y=AxAy[Aa--m.L`a'-'_

```

**Explanation**:

`x`, `y` and `z` may be referenced in a Clip program to implicitly take up to three inputs. Since this program only references `x` and `y`, it takes two inputs which are assigned to `x` and `y`.

```
 =(x(y                    First characters of x and y are equal
&                         And
      =AxAy               A(x) == A(y)
           [Aa            Function A, takes parameter a
                m.L`a     Map all elements of a to lower case
              --     '-'_ Remove all occurrences of '-' and '_'

```

Takes two strings from standard input, outputs `1` and `0` for true and false respectively.

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


title: Make me a square!

text:
# Question
Title: Make me a square!
# Task

Given one non-whitespace printable character, make a 3x3 square representation of that input. For example, if the input is `#`, then the output is:

```
###
# #
###

```

# Rules

* The output format is strict, although a trailing newline is allowed. It means that the space in the middle is required, and also that the two newline characters separating the three lines are required.

# Testcases

Input: `#`

Output:

```
###
# #
###

```

Input: `A`

Output:

```
AAA
A A
AAA

```

Input: `0`

Output:

```
000
0 0
000

```

# Scoring

This is . Shortest answer in bytes wins.

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, 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 > b.lang) return 1;
    if (a.lang < b.lang) 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="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
# Charcoal, ~~5~~ 3 bytes

```
Ｂ³Ｓ

```

Try it online! Edit: Saved 40% thanks to @carusocomputing. Explanation:

```
Ｂ   Draw a box
³   3×3 (second dimension is implicit if omitted)
Ｓ   Using the input character

```
> 33 votes

# Answer
# Carrot, 11 bytes

```
###
# #
###

```

Try it online!

The program is in caret-mode, where `#`s are replaced with the input.
> 50 votes

# Answer
# Python 2, 32 bytes

```
lambda s:s+s.join(s+'\n \n'+s)+s

```

Try it online!
For `s='a'` : the middle `s+'\n \n'+s` generates `a\n \na` and `s.join` turns it in `a**a**\n**a** **a**\n**a**a` (bold `a`s are the ones that `.join` adds), because `.join` accepts a string as an iterable, then it is surrounded with the two missing characters
> 19 votes

# Answer
# MATL, 5 bytes

```
3Y6*c

```

Try it online!

### Explanation

```
3Y6   % Push predefined literal: [true true true; true false true; true true true]
*     % Implicitly input a character. Multiply element-wise by its code point
c     % Convert to char. Implicitly display. Char 0 is displayed as space

```
> 16 votes

# Answer
# 05AB1E, 8 bytes

```
4×ð«û3ô»

```

Try it online!

```
INPUT    # ['R']                 | Implicit Input: 'R'
---------#-----------------------+-------------------------------
4×       # ['RRRR']              | Repeat string 4 times.
  ð      # ['RRRR',' ']          | Push space onto top of stack.
   «     # ['RRRR ']             | Concatenate last 2 items.
    û    # ['RRRR RRRR']         | Palindromize.
     3ô  # [['RRR','R R','RRR']] | Split into 3 pieces.
       » # ['RRR\nR R\nRRR']     | Join with newlines
---------#-----------------------+-------------------------------
OUTPUT   # RRR                   | Implicitly print the top
         # R R                   | of the stack on exit.
         # RRR                   |

```

---

Original idea using 30 as a binary number (unfinished, someone else try this in another lang):

# 05AB1E, 12 bytes

```
30bûTIð«‡3ô»

```

Try it online!
> 15 votes

# Answer
# Python 3.6, 33 bytes

```
lambda c:f'{3*c}\n{c} {c}\n{3*c}'

```

Try it online!
> 11 votes

# Answer
## RPL (Reverse Polish Lisp), 60 characters

```
→STR 1 4 START DUP NEXT " " + SWAP + 4 ROLLD + + SWAP 2 PICK

```

(Note that "→" is a single character on the HP48 and compatible calculators)

Would visually represent what you want by having three items on the stack:

```
3.: "###"
2.: "# #"
1.: "###"

```

If you insist to return it as one string, one has to add the newline characters as well and combine the strings, left as exercise to the next tester.

Explanation:

* `→STR`: Make the last object in the stack into a string. (So the input can be anything, e.g. a number.)
* `1` `4`: Push the number `1` and `4` to the stack.
* `START [...] NEXT`: Like a for loop but without access to the counter variable. Takes two numbers from the stack (here, we just have pushed `1` and `4`) and executes the code `[...]` the corresponding times (here, four times).
* `DUP`: Duplicate the last entry in the stack.
* `" "`: Push the string  (i.e. the string with one whitespace) to the stack.
* `+`: Take two objects from the stack and return them added together, for strings: Concatenated.
* `4`: Push the number `4` to the stack.
* `ROLLD`: Takes the last element (here: `4` that we just have pushed) from the stack and rolls the next element as far down the stack as the number we just took from the stack specifies.
* `SWAP`: Swaps the two last stack elements.
* `2`: Push `2` to the stack.
* `PICK`: Takes an element (here: The `2` we just pushed to the stack), interprets it as a number n, and copies the nth element from the stack.
> 9 votes

# Answer
# JavaScript, 28 bytes

```
c=>c+c+c+`
${c} ${c}
`+c+c+c

```

---

## Try it

```
f=
c=>c+c+c+`
${c} ${c}
`+c+c+c
o.innerText=f(i.value="#")
i.oninput=_=>o.innerText=f(i.value)
```

```
<input id=i maxlength=1><pre id=o>
```
> 7 votes

# Answer
# Jelly, 8 bytes

1 byte thanks to Erik the Outgolfer.

```
x4,`Ks3Y

```

Try it online!
> 7 votes

# Answer
# sed, ~~28~~ 18 bytes

```
s:.:&&&\n& &\n&&&:

```

Try it online!
> 5 votes

# Answer
# Brain-Flak, ~~76~~ 70 + 1 = 71 bytes

*Requires the `-c` flag*

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

```

Try it online!
> 5 votes

# Answer
# Java 7, ~~56~~ 55 bytes

-1 Thanks to Leaky Nun for pointing out the space I missed

```
String a(char s){return"...\n. .\n...".replace('.',s);}

```

Simply replaces the periods with the given character, for input #:

```
...       ###
. .  =>   # #
...       ###

```

Try it online!
> 5 votes

# Answer
# PHP, 32 Bytes

```
<?=strtr("000
0 0
000",0,$argn);

```

Try it online!
> 5 votes

# Answer
# Pyth, 7 bytes

```
jc3.[9d

```

Try this online.

Explanation:

```
jc3.[9d Expects quoted input.
  3     3
     9  9
      d ' '
        Q (eval'd input) as implicit argument
   .[   Pad B on both sides with C until its length is a multiple of A
 c      Split B to chunks of length A, last chunk may be shorter
j       Join A on newlines

```
> 5 votes

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

*-1 byte thanks to carusocomputing.*

```
Ð¶¹ðJû

```

Explanation:

```
         # Implicit input                  # ['R']
 Ð       # Repeat string three times       # ['R', 'R', 'R']
  ¶      # Push newline character          # ['R', 'R', 'R', '\n']
   ¹     # Push first input                # ['R', 'R', 'R', '\n', 'R']
    ð    # Push space                      # ['R', 'R', 'R', '\n', 'R', ' ']
     J   # Join stack                      # ['RRR\nR ']
      û  # Palindromize ("abc" -> "abcba") # ['RRR\nR R\nRRR']
         # Implicit output                 # []

```

Uses the **CP-1252** encoding. Try it online!
> 5 votes

# Answer
# Brain-Flak, ~~61~~, 59 bytes

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

```

Try it online!

This is 58 bytes of code `+1` byte for the `-c` flag which enables ASCII input and output.

Explanation:

```
(((
   (
    (
     (

      #Duplicate the input 3 times
      ((({})))

#Push 10 (newline)
<([][][]())>

     #Push the input again
     )

#Push 32 (space)
<(([][][]()){})>

    #Push the input again
    )

#Push 10 (newline)
<([]()()())>)

#Push input 3 times
)))

```
> 4 votes

# Answer
# C (gcc), ~~49~~ 47 bytes

*Saved 2 bytes thanks to 2501!*

```
j;f(i){for(j=12;j;)putchar(--j%4?j-6?i:32:10);}

```

Try it online! has a trailing newline
> 4 votes

# Answer
# Python 3, 34 bytes

```
lambda s:s*3+"\n"+s+" "+s+"\n"+s*3

```

Try it online!
> 3 votes

# Answer
# Octave, 36 bytes

```
x=repmat(input(0),3);x(5)=32;disp(x)

```

Try it online!

### Explanation

This creates a 3x3 char matrix with the input char repeated, and sets its 5th entry in column-major order (i.e. its center) to `32` (ASCII for space).
> 3 votes

# Answer
# Pyke, 5 bytes

```
dQA.X

```

Try it online!
> 3 votes

# Answer
# Ruby, ~~27~~ 25 bytes

Saved 2 bytes thanks to Level River St

```
->x{[s=x*3,x+" "+x,s]*$/}

```

Try it online!
> 3 votes

# Answer
# Brainfuck, 40 bytes

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

```

Try it online! *Requires an implementation that can access left of the starting position.*

Also see: Graviton's brainfuck answer which takes a different approach (but is longer).

---

## Explanation:

Brainfuck can do a lot of cool tricks with its limited instruction set. Unfortunately, this answer doesn't use any of them, because it's cheaper (in terms of bytes) to just hardcode everything.

```
+++++[->++<<++++++>]                         Sets the cells to |5*6|>0<|5*2|
,                   Takes input character into the middle cell | 30|>#<| 10|
...                                Print the top of the square | 30|>#<| 10| ###
>.                                   Print a newline character | 30| # |>10|    \n
<.                               Print another input character | 30|>#<| 10| #
<++.                  Add 30+2 for a space character and print |>32| # | 10|  _
>.                   And just print the 5 remaining characters | 32|>#<| 10|   #
>.                                                             | 32| # |>10|    \n
<...                                                           | 32|>#<| 10| ###

```

\# = input character, _ = space (ASCII 32), \n = newline (ASCII 10)

---

Results in this beautiful box (for input '+'):

```
+++
+ +
+++

```
> 3 votes

# Answer
# Vim, 9 keystrokes

Assuming the input char is present in a buffer, vim makes this straightforward

```
x3pY2plr<space>

```

There is probably some magic vim commands of use here (there always seem to be some) so improvement suggestions are welcome. Only one keystroke behind V!
> 3 votes

# Answer
# Pyth, 11 bytes

```
jc++K*z4dK3

```

Try it online!

**Explanation:**

```
jc++K*z4dK3    expects a single char as input

j              joins on new line
 c        3    chops array into 3 sized pieces
  +            joins +K*z4d and K
   +           joins K*z4 and d
    K          initialize variable K as *z4
     *z4       duplicate the input 4 times
        d      variable initialized to string " "
         K     calls variable K, in this case *z4

```
> 3 votes

# Answer
# AWK, ~~28~~ ~~26~~ 25 bytes

```
$0=$0$0$0RS$0FS$0RS$0$0$0

```

Try it online!
> 3 votes

# Answer
# StupidStackLanguage, 28 bytes

```
jfffavvflflqvvvviifblflflfff

```

Try it online!

## Explanation

```
j # Get the input (x)
fff # first 3
avv # new line
fl # print new line
fl # first x
qvvvviifb # space
lf # second x
lf # new line
lfff # last 3 x's

```
> 3 votes

# Answer
# \>\<\>, ~~24~~ 23 bytes

```
i:o:o:oao:o84*o:a0!.<o$

```

Try it online!
> 2 votes

# Answer
# CJam, ~~11~~ 10 bytes

```
r9*4St3/N*

```

Try it online!

Explanation:

```
r9*4St3/N* e# Expects single char (token) as input
r          e# Get input token (C)
 9*        e# Repeat C 9 times
   4St     e# Set the 5th char of C to be a space
      3/   e# Split into parts of length 3
        N* e# Join by newlines

```
> 2 votes

# Answer
# , 8 bytes

```
x3p2Ùlr

```

Try it online!
> 2 votes

# Answer
# J-uby, ~~22~~ 20 bytes

-2 bytes thanks to @Jordan

```
:tr&"...
. .
..."&?.

```

### Explanation

`String#tr` is Ruby's character-wise replace method. The first `&` binds `:tr` to `"...\n. .\n..."`, and the second partially applies `'.'` to it. Effectively, this is `->s{"...\n. .\n...".tr('.',s)}`
> 2 votes

# Answer
# C#,50 bytes

```
a=>Console.Write(a+a+a+"\n"+a+" "+a+"\n"+a+a+a);

```

Test Case:

```
var f = new Action<string>(
a=>Console.Write(a+a+a+"\n"+a+" "+a+"\n"+a+a+a);
);
f("#");

```
> 2 votes

# Answer
# Windows batch, 37 bytes

```
@echo %1%1%1
@echo %1 %1
@echo %1%1%1

```

Simply outputs the first command-line argument in a square form.
> 2 votes

# Answer
# Z80 or 8080 Assembly, 21 bytes machine code

Assume a memory mapped I/O device:

```
              Z80                  8080
3A xx xx    ld  a, (input)      lda  input       ; get input character
11 0A 20    ld  de, 200ah       lxi  d, 200ah   ; space & newline
21 yy yy    ld  hl, output      lxi  h, output  ; get output address
77          ld  (hl), a         mov  m, a       ; output character * 3
77          ld  (hl), a         mov  m, a
77          ld  (hl), a         mov  m, a
73          ld  (hl), e         mov  m, e       ; output newline
77          ld  (hl), a         mov  m, a       ; output character
72          ld  (hl), d         mov  m, d       ; output space
77          ld  (hl), a         mov  m, a       ; output character
73          ld  (hl), e         mov  m, e       ; output newline
77          ld  (hl), a         mov  m, a       ; output character * 3
77          ld  (hl), a         mov  m, a
77          ld  (hl), a         mov  m, a
76          halt                hlt             ; or C9 ret

```

No interpreter needed!

Hexdump:

```
0000: 3A 00 FF 11 0A 20 21 01 FF 77 77 77 73 77 72 77
0010: 73 77 77 77 76
```

where the input address is at FF00h and the output address is mapped at FF01h. The actual addresses will depend on the actual hardware. Of course this assumes the I/O is memory mapped. If it is I/O mapped, it would take several extra bytes because Z80 & 8080 I/O instructions are two bytes each. This also assumes the output device interprets 0Ah as a newline and doesn't require a CR (0Dh) which would add an extra 4 bytes to the program.
> 2 votes

# Answer
# Emacs, 15 keystrokes

The current buffer must only contain the input character, and the cursor must be at the start of the line.

```
C-k C-y C-y C-y C-a C-k C-y RET C-y C-b BACKSPACE SPC C-e RET C-y

```
> 2 votes

# Answer
# 05AB1E, ~~7~~ 6 bytes using the canvas and compressed integers.

```
3IŽ9¦Λ

```

Try it online!
> 2 votes

# Answer
# Python 3, 31 bytes

```
lambda s:3*s+f'\n{s} {s}\n'+3*s

```

Try it online!
> 2 votes

# Answer
# MAWP, 29 bytes

```
|!;!;!;25W;!;84W;!;25W;!;!;;.

```

Try it!

-6 bytes from Dion's straightformard solution.

# MAWP, 35 bytes

```
%|7[1A~!~]////25W//84W//25W////~[;]

```

Manually shifting the stack was more practical than trying to loop through it and make a box.

Try it!
> 2 votes

# Answer
# Swift3, 50 bytes

```
[1,2,3].map{$0==2 ? print(c+" "+c) : print(c+c+c)}

```

This uses the ternary operator to print different strings, depending on the row.

Try it online
> 1 votes

# Answer
# Aceto, 19 bytes

```
nppk
pKLp
pppn
,kpp

```

Read a single character (`,`), then activate sticky mode (`k`). Print it three times, a newline and then the character again (`pppnp`).

Deactivate sticky mode (`K`), then load the empty string from quick storage (`L`), print it (`p`), activate sticky mode again (`k`), and print the rest (`pnppp`).
> 1 votes

# Answer
## C#, 74 71 66 bytes

```
m=>{System.Console.WriteLine("{0}{0}{0}\n{0} {0}\n{0}{0}{0}",m);};

```

golfed 5 bytes thanks to an anon
> 1 votes

# Answer
# brainfuck, 48 bytes

Great simple challenge.

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

```

Try it online!

# Explanation

```
,...              : take input, print it 3 times
>++++++++++.      : print ASCII with index 10 (new line)
<.>               : print input.
+[->+>+++<<]>>-.  : add 1 to 10, triple it, subtract one and print it (space)
<<<.>>-.<<...     : print input, newline, and input 3 times

```
> 1 votes

# Answer
# MATL, 8 bytes

```
4Y"0yv3e

```

Unlike my other MATL answer, this builds the output manually, without using any predefined literal.

Try it at MATL Online!

### Explanation

Consider input `'^'` as an example.

```
      % Implicitly input one char.
4Y"   % Repeat 4 times. Gives a string.     STACK: '^^^^'
0     % Push 0. Char 0 is shown as space.   STACK: '^^^^', 0
y     % Duplicate from below.               STACK: '^^^^', 0, '^^^^'
v     % Concatenate everything vertically.  STACK: ['^';'^';'^';'^';0'^';'^';'^';'^';'^']
3e    % Reshape into a 3-row char matrix.   STACK: ['^^^';'^ ^';'^^^']
      % Implicitly display.

```
> 1 votes

# Answer
# \>\<\>, 19 bytes

```
i:o:o:oao:$o" "|;o~

```

Try it online!
> 1 votes

# Answer
## R, 44 bytes

```
cat(y<-rep(scan(,''),4),' ',y,sep='',fill=3)

```

Test and output:

```
> cat(y<-rep(scan(,''),4),' ',y,sep='',fill=3)
1: #
2:
Read 1 item
###
# #
###
>

```
> 1 votes

# Answer
## C#, 30 bytes

```
s=>s+s+s+$"\n{s} {s}\n"+s+s+s;

```

Compiles to a `Func<string, string>`.

Using `Replace` for 32 bytes.

```
c=>@"###
# #
###".Replace('#',c);

```

Compiles to a `Func<char, string>`.
> 1 votes

# Answer
# Retina, 18 bytes

```
:`$
$_$_
*2=`.

```

Half of this code looks like trailing empty lines, I like that :)

Try it online!

### Explanation

There are three stages in this program, each of them prints a line of the output, in sequence.

```
:`$
$_$_

```

Add two more copies of the input at the end and print the resulting string.

```
*2=`.

```

There's a single space in the second line. This stage replaces the second character of the string with a space, prints the result, and then reverts the string to what it was before (thanks to the `*`)

```

```

The two final empty lines are a replacement stage with no effect. This is only needed because a final stage with no printing modifier implicitly prints the resulting string.
> 1 votes

# Answer
# R, ~~43~~ 40 bytes

`cat(gsub("y",scan(,""),"yyy\ny y\nyyy"))`

Saved 3 bytes thanks to Giuseppe.

Explanation: create a box using the character "y" and then substitute the input character.
> 1 votes

# Answer
# ///, 27 bytes

```
/\\\#//\#\#\#
\#\ \#
\#\#\#

```

Try it online!

Since there is no other way to take input in ///, it is hard-coded.

```
/\\\#/INPUT HERE/\#\#\#
\#\ \#
\#\#\#

```

Version that takes input in Itflabtijtslwi (28 bytes):

```
GG\\\#GG\#\#\#
\#\ \#
\#\#\#

```

Try it online!
> 1 votes

# Answer
## QBIC, ~~23~~ 20 bytes

Brute-forcing this is shorter than fancy string-flips...

```
?;+A+A?A+@ `+A?A+A+A

```

---

Original answer:

```
A=;+A+A+@┘`+A?A+@ `+_fA

```

Explanation:

```
A=;     ; gets a cmd line parameter and assigns it to A$
        This overrides that value by
  +A+A    appending itself two times
  +@┘`    Then a literal newline
  +A      And another copy of the input char
?       PRINT
  A       The combined A$ ("###\n#")
  +@ `    a space
  +_fA    and then the flipped version of A$

```
> 1 votes

# Answer
# Japt, ~~11~~ 9 bytes

```
³+R+U+S ê

```

Try it online

---

## Explanation

```
    :Implicit input of string U
³   :Repeat input 3 times
+R  :Append newline
+U  :Append input
+S  :Append space
ê   :Duplicate string, excluding last character, reverse it and append it to original

```

---

## Alternative, 9 bytes

I can't decide which version I prefer.

```
[U³RUS]¬ê

```

Try it online

---

## Alternative, 10 bytes

I really liked this version, but sadly it came in at a byte too big.

```
NpU²RUS ¬ê

```

Try it online
> 1 votes

# Answer
# Javascript (ES6), 32 bytes

```
i=>`###
# #
###`.replace(/#/g,i)

```
> 1 votes

# Answer
# Cubix, 26 bytes

```
./v.o;@?/i:::Ns:Ss:Nu/:::s

```

This is the first piece of Cubix code I've ever written...I was originally going to try to answer the Try to make a cube challenge, but I figured I'd answer the original (easier) question first. Cubix is pretty cool!

Try it online! and also Watch the interpeter!
> 1 votes

# Answer
# Syms, 21 bytes

```
{}<[[[++~[{& &}~[>~>>

```

Try it online!
> 1 votes

# Answer
# Perl 5, 23 + 1 (-p) = 24 bytes

The brute force way seems to be the shortest.

```
$_.="$_$_
$_ $_
$_$_$_"

```

Try it online!
> 1 votes

# Answer
# K (oK), 8 bytes

**Solution:**

```
3 3#5$4#

```

Try it online!

**Example:**

```
> 3 3#5$4#"@"
("@@@"
 "@ @"
 "@@@")

```

**Explanation:**

Evaluated right-to-left. Build `'AAAA'`, then `'AAAA '` and then shape into the 3x3 grid required.

```
3 3#5$4# / the solution
      4# / take 4 of whatever is to the right
    5$   / right pad with whitespace to length 5
3 3#     / shape into 3x3 grid

```

**Bonus:**

The solution is a polyglot for **q/kdb+**:

```
q)3 3#5$4#"*"
"***"
"* *"
"***"

```
> 1 votes

# Answer
# Pepe, 54 bytes

```
REEeREEEeeReeerREeeeeEeEeReeereeeEeeeeeReeeREEeeReReee

```

Try it

**Explanation:**

```
REEe        # Input as str
REEEee      # Duplicate it
Reee        # Output whole stack
rREeeeeEeEe # Insert linefeed (10) to the stack
Reee        # Output whole stack
reeeEeeeee  # Print space (' ')
Reee        # Output whole stack
REEee       # Go to next position
ReReee      # Pop it (space) and output the whole stack

```
> 1 votes

# Answer
# Dart, 30 bytes

```
f(s)=>'$s$s$s\n$s $s\n$s$s$s';

```

Try it online!
> 1 votes

# Answer
# *Acc!!*, 58 bytes

```
N
Count i while 11-i {
Write _+i%4/3*(10-_)+i%6/5*(32-_)
}

```

Try it online!

### How?

Let's lay out the desired output in a line, substituting `_` for the newlines, and look at patterns and indices.

```
###_# #_###
01234567890

```

We need newlines at indices 3 and 7, a space at index 5, and the input character at all other indices. To put it a different way, for index `i`, we want newline when `i%4 == 3`, space when `i%6 == 5`\*, and the input character otherwise.

So, after reading the input character into the accumulator with `N`, we run a `Count` loop from 0 up to but not including 11. Iff `i%4` is 3, `i%4/3` is 1, and we output `_+(10-_)` i.e. 10 i.e. newline. Iff `i%6` is 5, `i%6/5` is 1, and we output `_+(32-_)` i.e. 32 i.e. space. Otherwise, we output `_` i.e. the accumulator value i.e. the input character. Fortunately, the two modulo cases are never true at the same time; this would happen at index 11, but we stop at index 10.

---

* The modulo operation would seem unnecessary here, but (as far as I can tell) it is the shortest way to test `i == 5` in *Acc!!*, which doesn't have a comparison operator.
> 1 votes

# Answer
## `d` `n`, 8 bytes

```
º±▀σ\g┘╒

```

Uncompressed:

```
4*:' S++3,

```

Explanation:

```
4*         Repeat input 4 times
  :' S++   Put space in middle, append input * 4
        3, Chop into 3 equal pieces
Flag: n Join with newlines

```

## `d`, ~~13~~ ~~11~~ 9 bytes

Here's a version without chopping or similar built-ins.

```
↨i`♣T'@└µ

```

## Explanation

Uncompressed is:

```
' a++bab++E

```

```
          E % Foreach in the string:
' a++       % (implicit) input, the space, and input
     bab++  % Output the string created by the input,
            % the current item, and the input
            % With a newline
            % The None isn't outputted

```
> 1 votes

# Answer
# Keg, 11 bytes

```
???
? ?
???

```

It really just replaces the `?`s with the input!

Alterate 11 byter

```
¿3*:&
? ?
&

```
> 1 votes

# Answer
# naz, 46 bytes

```
1x1f0m9a1a1o0x1r2x1v3o1f1v1o0m4a8m1o1v1o1f1v3o

```

Strictly speaking, the above program outputs the exact byte stream required to make the square, though the top of the square will be misaligned given that the interpreter linked above always prepends `output:` to program output.

**Explanation** (with `0x` commands removed)

```
1x1f0m9a1a1o     # Function 1
                 # Reset the register, add 10 and output (produces a newline)
1r2x1v           # Read the first byte of input and store it in variable 1
3o               # Output the byte 3 times
1f               # Call function 1
1v1o0m4a8m1o1v1o # Output variable 1, output 32 (space), then output variable 1
1f               # Call function 1
1v3o             # Output variable 1 3 times

```
> 1 votes

# Answer
# GolfScript, 15 bytes

```
...n\." "\.n\..

```

**Explanation**

At the beginning of the program, the input is put onto the stack. Each `.` copies the top of stack. Each `n` pushes a newline onto the stack. `" "` pushes a space. `\` swaps the top two elements. At the end of the program, the stack is output to the standard output.

Try it Online
> 1 votes

# Answer
# TI-BASIC, 14 + 6 = 20 bytes

This submission uses two programs, the main one and a helper program called `prgmΘ`.

```
prgmΘ:Disp Ans+" "+Ans:prgmΘ         ;main program

Disp Ans+Ans+Ans                     ;helper program "prgmΘ"

```

Input is a string stored in Ans.
> 1 votes

# Answer
# GolfScript, 13 bytes

```
4*.' '\++3/n*

```

Try it online!

## Explanation

```
              # input #
4*            # ["####"]
  .           # ["####","####"]
   ' '        # ["####","####"," "]
      \       # ["####"," ","####"]
       ++     # ["#### ####"]
         3/   # [["###" "# #" "###"]]
           n* # [["###\n# #\n###"]]

```
> 1 votes

# Answer
# Husk, 6 bytes

Husk is *way* easier to use than Pyth.

```
C3w½*8

```

Try it online!

# Explanation

```
    *8 Repeat the input 8 times. "!" -> "!!!!!!!!"
   ½   Halve the input. "!!!!!!!!" -> ["!!!!","!!!!"]
  w    Join with spaces. ["!!!!","!!!!"] -> "!!!! !!!!"
C3     Split into chunks of 3. ["!!!","! !","!!!"]

Husk automatically outputs lists joined with newlines

```
> 1 votes

# Answer
# , <sup>~~12~~</sup> 9 bytes

```
3 3$4j1#]

```

Try it online!

*-3 thanks to FrownyFrog*
> 1 votes

# Answer
# 1+, ~~40~~ 38 bytes

```
,";";";(|11+""*")++";^";()**;";^;";";;

```

Longer than I thought. Ungolfed, but it's a start.
> 1 votes

# Answer
# Poetic, 208 bytes

```
BOX,OR SQUARE
i was creating a side,i built a box
i looked,it was four-sided
i am somewhat weirdly earnest,however,about n*n squares having a"no-holes-in-a-drawing"shape
i am trying to produce regular squares

```

Try it online!
> 1 votes

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

```
{`0:x,x,x,"\n",x," ",x,"\n",x,x,x}

```

Try it online!

The straightforward (although long) answer.
> 1 votes

# Answer
# Vyxal `j`, 40 bits<sup>v2</sup>, 5 bytes

```
4*ð+∞²

```

Try it Online!

Bitstring:

```
0100101010111010101000100000000000001010

```

optimal encoding for a 6 byter
> 1 votes

# Answer
# Braingolf, ~~34~~ 20 bytes

```
...#
<.># <.>#
<..&@

```

Little disappointed that this isn't easily golfed. At least it's shorter than JavaScript

### Explanation:

For input `#`

```
                   | [35]
...                | [35,35,35,35]
   #<newline>      | [35,35,35,35,10]
<.>                | [35,35,35,35,10,35]
   #<space>        | [35,35,35,35,10,35,32]
     <.>           | [35,35,35,35,10,35,32,35]
        #<newline> | [35,35,35,35,10,35,32,35,10]
<..                | [35,35,35,10,35,32,35,10,35,35,35]
   &@              | Print entire stack

35 = # ASCII value
10 = <newline> ASCII value
32 = <space> ASCII value

Output:
###
# #
###

```
> 0 votes

# Answer
# Retina, 21 bytes

```
.
$&$&$&¶$& $&¶$&$&$&

```

Try it online!
> 0 votes

# Answer
# Befunge, 26 bytes

```
~:::25*\:84*\:25*\::>:#,_@

```

Try it online!

Explanation

```
~::          Take input and put bottom row in stack (: is duplicate)
:25*\:84*\   Create second row (25* is 10 or newline, 84* is 32 or space)
:25*\::      Create top row
>:#,_@       Print out stack until the stack is empty

the \ after the numbers is to switch the stack around since you need the input on
top of the stack to duplicate it

```
> 0 votes

# Answer
# `bash`, ~~43~~ 38 bytes

```
read -sN1 x
echo "$x$x$x
$x $x
$x$x$x"

```
> 0 votes

# Answer
# Scala, 23 bytes

```
a=>a*3+s"\n$a $a\n"+a*3

```

Accepts and returns a `String`. The `s` before a string literal allows you to use `$`-prefixed variables in it, or even `${expressions}`. `*` repeats a `String`, like in Python.

Try it online!
> 0 votes

# Answer
## VBScript, 72 bytes

```
n=chr(10):msgbox replace("###"&n&"# #"&n&"###","#",wscript.arguments(0))

```

VBScript sucks ;-)
> 0 votes

# Answer
# Foo, 40 bytes

```
&<character as ascii value>&3(-1<$c>)$c13<$c$c32$c$c13>&3(-1<$c>)

```

As Foo cannot take input, you should replace `<character as ascii value>` with the ASCII value of the character.

Try it online!
> 0 votes

# Answer
# Common Lisp, SBCL, 50 bytes

```
(format t"~@?
~a ~:*~a
~@*~@?""~3@{~a~:*~}"(read))

```

## Explanation

```
format              ;printing function
~@?                 ;execute format string given as argument
~a ~:*~a            ;print current argument (will be result of (read))
                    ;then print space, go back one argument (to again use
                    ;result of (read) and print it
~@*~@?              ;go back to first argument, then execute format string
                    ;given as this argument
"~3@{~a~:*~}"       ;loop three times printing argument number 2
                    ;~:* makes it keep going back to argument number 2
(read)              ;take input

```

Ideas for improvement are welcomed.
> 0 votes

# Answer
# Excel VBA, 27 Bytes

Anonymous VBE immediate window function that takes input from cell `[A1]` on the `Application.ActiveSheet` object and outputs a 'square' to the VBE immediate window.

```
a=[A1]:?a;a;a:?a" "a:?a;a;a

```
> 0 votes

# Answer
# Swift, 54 bytes

```
var s=readLine()!,a=s+s+s+"\n";print(a+s+" "+s+"\n"+a)

```
> 0 votes

# Answer
# Sinclair ZX80/ZX81 (without sanity check), ~55 Bytes (listing)

```
 1 INPUT A$
 2 PRINT A$;A$;A$
 3 PRINT A$;" ";A$
 4 PRINT A$;A$;A$

```

### With sanity check (ZX80 with 8K ROM or ZX81)

```
 1 INPUT A$
 2 IF NOT LEN A$ OR LEN A$>1 THEN GOTO 1
 3 PRINT A$;A$;A$
 4 PRINT A$;" ";A$
 5 PRINT A$;A$;A$

```

Line two of the latter version makes sure that there is a single character entered. So in the first example, it is possible to enter nothing and simply press `NEW LINE`.
> 0 votes

# Answer
# PowerShell, 26 Bytes

```
param($c)$c*3;"$c $c";$c*3

```

takes a char/length 1 string - then prints it 3 times, it twice with a separating space, and it 3 times again.
> 0 votes

# Answer
# braingasm, 18 bytes

```
,...10..32..10....

```

Yeah... read a byte, print it three times, then print a newline (`10`), then the byte again, then a space (`32`), that byte again, another newline and that byte three more times...
> 0 votes

# Answer
# Haskell, ~~45~~ 44 bytes

-1 byte thanks to Laikoni

Naive approach

```
f s=putStrLn$s:s:s:'\n':s:' ':s:'\n':s:s:[s]

```

For some reason

```
f s=putStr$s:s:s:'\n':s:' ':s:'\n':s:s:[s]

```

won't output the last line on repl.it, but if it's still valid it shaves off 2 bits for a total of 42

And

```
f s=print$s:s:s:'\n':s:' ':s:'\n':s:s:[s]

```

will print the answer as "sss\ns s\nsss" instead of properly linebreaking. If that's valid it shaves off 3 bits for a total of 41

There is a solution with replace that's 42 bits long ... but that's without counting the bytes needed to import the necessary module. For reference:

```
import Data.String.Utils
f s=putStrLn$replace "." s "...\n. .\n..."

```
> 0 votes

# Answer
# Ruby, 23+1 = 24 bytes

Uses the `-n` flag for +1 byte.

```
puts$_*3,$_+' '+$_,$_*3

```

Try it online!
> 0 votes

# Answer
# OCaml, 53 bytes

```
let f c=String.map(function '#'->c|c->c)"###
# #
###"

```

It's pretty bad. OCaml does not even have a replace function

# Bash, 26 bytes

```
echo "$1$1$1
$1 $1
$1$1$1"

```

5 bytes less boring
> 0 votes

# Answer
# Python 2, 34 bytes

```
lambda n:3*n+'\n'+n+" "+n+'\n'+3*n

```

Try it online!
> 0 votes

# Answer
# UGL, 23 Bytes

```
j"\n"++l*I3l++i" "il*i3

```

try it online (write the code to stdin. you can also use the link at the top of the answer to try online, that accepts ctrl+v)

Equivalent Python code:

```
cur_inp = ""
def inp():
    global cur_inp
    cur_inp = input()
    return cur_inp
"\n".join([inp*3]+[cur_inp+" "+cur_inp]+[cur_inp*3])

```

Using Python's string multiplication.
> 0 votes

# Answer
# Burlesque, 20 bytes

```
3.*3.*{1 1}' D!)\[un

```

Try it online!

```
3.*       # Make a list of 3 instances     {A A A}
3.*       # Again                          {{A A A} {A A A} {A A A}}
{1 1}' D! # Set value at 1,1 to a space    {{A A A} {A   A} {A A A}}
)\[       # Concatenate each internal list {"AAA" "A A" "AAA"}
un        # Join array with newlines

```

# Burlesque, 23 bytes

```
495b2"1"x/r~'0' r~3coun

```

Try it online!

Just for a bit of variety

```
495b2   # Read the number 495 as binary (111101111)
"1"x/r~ # Replace 1s with input char
'0' r~  # Replace 0 with space
3co     # Chunks of 3
un      # Separate by newlines

```
> 0 votes

# Answer
# APL (Dyalog Extended), 15 bytes

```
(' ',⍞)[⊤7 5 7]

```

Try it online!

Indexes into a binary matrix.

Requires `⎕IO←0`(0-indexing)
> 0 votes

# Answer
# Vyxal, 7 bytes

```
D¶?ðWṅ∞

```

Try it Online!

Using the canvas builtin is the same byte count:

# Vyxal, 7 bytes

```
3»«₁»ø∧

```

Try it Online!
> 0 votes

# Answer
# Gema, 22 characters

```
*=*$0$0\n$0 $0\n$0$0$0

```

(Frustratingly inefficient. In Gema the `*` (and `?`) have order numbers, so in `***=***` each `*` on right side matches the `*` on left side with same order number. ☹)

Sample run:

```
bash-5.2$ echo -n 'M' | gema '*=*$0$0\n$0 $0\n$0$0$0'
MMM
M M
MMM

```

Try it online!
> 0 votes

# Answer
# AWK, 24 bytes

```
sub(/./,"&&&\n& &\n&&&")

```

Attempt This Online! or try some more test cases.

This is one byte shorter than `$0=$0$0$0RS$0FS$0RS$0$0$0`.

This is basically regex substitution that takes one char and puts it into the box shape. `sub` without the 3rd argument takes and modifies `$0` in-place. Since the substitution always succeeds, the `sub` call evaluates to true and the modified `$0` is printed (the default action).

`sub($0,...)` doesn't work because some chars don't form a valid regex, such as `[`.
> 0 votes

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


title: aaabbabbc

text:
# Question
Title: aaabbabbc
One element of the list `aa, ab, ba, bb, c` has been removed, and the remainder shuffled and joined with no separator. Find the missing element.

For example, if the input was `aaabbac`, this is made by concatenating `aa ab ba c`, so the output would be `bb`.

## Rules

* Standard I/O rules apply.
* You must take input as a string (or equivalent in your language), and you must use the characters `abc` as in the question; you cannot substitute them for others.
* This is code golf, shortest code in bytes wins.

## Test cases

```
cbbbaab  -> aa
bbbaabc  -> aa
cabbabb  -> aa
baaacbb  -> ab
bbcaaba  -> ab
caababb  -> ab
bbcabaa  -> ba
abcaabb  -> ba
abcbbaa  -> ba
bacaaab  -> bb
aacabba  -> bb
caaabba  -> bb
bbabaaba -> c
aaabbabb -> c
abaabbba -> c

```

# Answer
# Python,  ~~55~~  51 bytes

```
lambda a:'%x'%(-int(a.replace('c','0c'),16)%255-39)

```

Attempt This Online!

Explain:

* Observe that 'a', 'b', 'c' are base 16 digits.
* I learnt from Albert.Lang's solution that we can use int(a.replace('c',''),x)%(x\*x-1) to extract sum of character at odd and even position.
* Replace 'c' with '0c' allow us to subtract by 39 to get 'c' without affecting other output cases (Original idea is to replace 'c' with '33', by xnor).
* Finally, '%x'% is used to convert int back to base 16.

Logs:

* Saved 4 bytes thank to xnor's suggests.

# Python,  ~~94~~ 92 bytes

```
lambda a:('c'in a)*''.join(chr(390-sum(map(ord,a.replace('c','')[i::2])))for i in(0,1))or'c'

```

Attempt This Online!

Logs:

* Saved 2 bytes thank to Jonathan Allan's tip.
> 30 votes

# Answer
# JavaScript (ES6), 59 bytes

```
s=>(s+"aaabbabbc").replace(q=/c|../g,s=>(q[s]^=1)?o=s:0)&&o

```

Try it online!

## Commented

```
s =>              // s = input string
(s + "aaabbabbc") // append all the patterns to s
.replace(         // replace:
  q =             //   we use q as an object to keep track of
                  //   encountered patterns
  /c|../g,        //   a pattern is either 'c' or 2 characters
  s =>            //   for each matched pattern s:
    (q[s] ^= 1) ? //     if this is the first time we see it:
      o = s       //       save it into o
    :             //     else:
      0           //       do nothing
) && o            // end of replace(); return o (i.e. the last
                  // pattern seen for the first time)

```

---

# JavaScript (ES6), 52 bytes

Porting Phan Trọng Nhân's excellent answer is definitely shorter.

```
s=>(216-`0x${s}`.replace('c','0c')%255).toString(16)

```

Try it online!

---

# JavaScript (ES6), 64 bytes

My original answer.

```
s=>"b__c__aab"[q=s.replace(/c|../g,s=>'0x'+s|0)%9]+["ab"[q%7%5]]

```

Try it online!

## How?

### Identifying the missing pattern

We look for the relevant patterns in the input string with `/c|../g` and replace each of them with its decimal value when parsed as hexadecimal.

This gives:

| original pattern | replaced with |
| --- | --- |
| aa | 170 |
| ab | 171 |
| ba | 186 |
| bb | 187 |
| c | 12 |

For instance, `"abbabbc"` is turned into `"17118618712"`.

It is a well known fact that \\$n \bmod 9\\$ is the sum of the decimal digits of \\$n\\$ modulo \\$9\\$. (Obviously, the order of the digits doesn't matter.)

Because each decimal pattern described above has a different remainder modulo \\$9\\$, we can identify the missing one by just reducing the entire transformed string modulo \\$9\\$:

| \\$q=n \bmod 9\\$ | missing pattern |
| --- | --- |
| 0 | ba |
| 3 | c |
| 6 | ab |
| 7 | aa |
| 8 | bb |

### Output

We use a 9-character lookup string for the first character:

```
"b__c__aab"[q=...]

```

We could also use the following trick, which is unfortunately just as long:

```
"bac"[7/(q=...)|0]

```

And we use a shorter lookup string with a modulo chain for the 2nd character, wrapped into brackets so that *undefined* is turned into an empty string for \\$q=3\\$:

```
["ab"[q%7%5]]

```
> 18 votes

# Answer
# Stax, 11 bytes

```
ù¢╓┘0ï<ΣEZ1

```

Run and debug it

Unpacked (13 bytes):

```
'c|^2/M{{SkmT

```

Explanations:

```
'c|^         Set xor with "c" without deduplication or changing of order.
2/           Split into 2 character chunks.
M            Transpose (aka zip).
{{Skm        Map by reduce by xor of the character codes.
             The two lines work like reducing by vectorized xor.
T            Trim on the right. For some reasons null bytes are also
             printed as spaces and are also removed.

```

~~The difficult part is to find the right language that had all the required features.~~ Many languages have them but they may not be the default behavior of the most obvious operator, so I thought they don't. The most important one is set xor (set symmetric difference) without deduplication. Others are splitting to equally sized chunks, and doing mathematics on character values. But Stax doesn't have map and reduce operators with block starters omitted for a single character operation.

# Vyxal, 87 bitsv2, ~~11~~ 10.875 bytes

```
\cÞ⊍C2ẇƒ꘍C∑Ǎ

```

Try it Online!

Bitstring:

```
011010100001110110101010000101011001101011111101101001000110111010111001101110101010000

```

Explanations:

```
\cÞ⊍         Set xor with "c" without deduplication or changing of order.
C            Convert characters to numbers.
2ẇ           Split into 2 character chunks.
ƒ꘍           Reduce by automatically vectorized xor.
C            Convert back to characters.
∑            Concatenate.
Ǎ            Remove non-letters, i.e. the null byte if the answer is "c".

```
> 15 votes

# Answer
# Jelly, ~~15~~ 14 bytes

```
ḟ”cQp`ḟs2$Ʋȯ”c

```

Try it online!

*Thanks to @JonathanAllan for saving a byte!*

A full program taking a string as its argument and printing the missing piece. (It can also be used as a monadic link, but will return a Jelly string if the result is one of the `ab` permutations and a single character for `c`.)

## Explanation

```
ḟ”cQp`ḟs2$Ʋȯ”c
ḟ”c            | Filter out "c"
         Ʋ     | Following as a monad:
  Q            | - Uniquify
   p`          | - Cartesian product with itself
     ḟ         | - Filter out
      s2$      |   - The c-less input split into twos
           ȯ”c | Or "c"

```

## Alternative approach: Jelly, 10 bytes

```
œ^”cs2œ^"/

```

Try it online!

This is a translation of @jimmy23013’s clever Stax answer; I’ve not replaced my main one since I wanted to preserve my different approach, but this is clearly shorter!

`œ^”cŒœœ^/€` would also work for ten.
> 11 votes

# Answer
# Python, 55 bytes

```
lambda a:f'{int("cc"+(30*a).strip("ab"),16)%255%192:x}'

```

Attempt This Online!

This produces 15 (= base - 1) on frame and (if `c` is present) 15 off frame copies of the input. The sum will therefore be 0 modulo 0x11 x 0x0f. `.strip("ab")` removes one set of on frame copies of all but c. Adding 0xcc which is the sum of the four possible non c terms mod 0xff yields the missing item unless it is c which is dealt with separately.

# Python, 57 bytes

```
lambda s:" aabbcbaba"[int(s.replace("c",""),14)%195%8::5]

```

Attempt This Online!

### How?

First get rid of the evil frame-shifting "c". Afterwards read as base 14 and add all pairs by reducing modulo 195. Further reduce and produce the answer by indexing into a magic string.
> 10 votes

# Answer
# Vyxal, 106 bitsv2, 13.25 bytes

```
‛ab2↔\cpṖ'ḣ∑?=;hh

```

Try it Online!

Bitstring:

```
1010100100110111101010010101000011000010000011011100110001101010100111101011100111001010011100110100101110

```

## Explained

```
«F^ǒ⇩v«2ẇṖ'ḣ∑?=;hh
         Ṗ          # Permutations of
«F^ǒ⇩v«             # The string "aaabbabbc"
       2ẇ           # split into chunks of size 2
          '    ;    # Filtered by:
           ḣ        #   the permutation with the head removed
            ∑       #   joined into a single string
             ?=     #   equals the input.
                hh  # Get the first item of the first item in that list.

```

Created with the help of Luminespire.
> 6 votes

# Answer
# 9.4, 25 bytes

```
(]>.&XOR&.dfh _2]\-.)&'c'

```

Attempt This Online!

`dfh` and `hfd` were recently modified to have each other as inverses. ATO doesn't have the change yet.

# , 26 bytes

```
12(hfd@>.XOR)_2 dfh\-.&'c'

```

Attempt This Online!

The XOR of three of `aa, ab, ba, bb` interpreted as hexadecimal (or any base that is a greater power of 2) is the missing one, and the XOR of all four is zero. When all four are present, the XOR value is replaced with 12 before converting back to hexadecimal.

```
12(hfd@>.XOR)_2 dfh\-.&'c'    input: a string
                    -.&'c'    remove 'c'
             _2 dfh\          convert each chunk of 2 with "hex->int"
  (      XOR)                 reduce by bitwise XOR
12     >.                     max with 12; if the result is 0, use 12 instead
   hfd@                       convert with "int->hex"

```

# Vyxal, 99 bitsv2, 12.375 bytes

```
\co2ẇHƒ꘍12∴k6τ

```

Try it Online!

Bitstring:

```
011010100001111110010011010110100010110000110101011111111011101001101110100010100100100101011011010

```

Literal translation of the J solution above.

```
\co2ẇHƒ꘍12∴k6τ
\co               remove 'c'
   2ẇ             chunks of 2
     H            convert each with "hex->int"
      ƒ꘍          reduce by bitwise XOR
        12∴      max with 12
            k6τ   into base "lower hex digits"; convert with "int->hex"

```
> 6 votes

# Answer
# TypeScript's Type System, ~~144~~ 142 bytes

```
type F<S,X=0>=S extends`c${infer R}`?F<R,X|"c">:S extends`${infer A}${infer B}${infer R}`?F<R,X|`${A}${B}`>:Exclude<"aa"|"ab"|"ba"|"bb"|"c",X>

```

Try it at the TypeScript playground.

This is only so long because it has to check for "c" separately because TypeScript annoyingly doesn't let you `infer` part of a string that is a union of strings of variable length. I also have a different idea that might be shorter, but it's not at all obvious how to accomplish it in TS types so it might take me a while to figure out.
> 5 votes

# Answer
# Jelly,  ~~20 18~~  17 bytes

-3 thanks to Nick Kennedy reminding me to golf the magic table.

```
⁾abp`”cṭŒ!F=¥Þ⁸ṪṪ

```

A full program that accepts the flattened, redacted permutation and prints the missing item.

**Try it online!** Or see all twenty four of each of the five choices here.

#### How?

Brute force...

```
⁾abp`”cṭŒ!F=¥Þ⁸ṪṪ - Link: list of characters, X
⁾ab               - "ab"
   p`             - Cartesian product with itself -> ["aa","ab","ba","bb"]
     ”cṭ          - tack 'c' character -> ["ab","ba","bb","aa",'c']
        Œ!        - all permutations
             Þ    - sort by:
            ¥ ⁸   -   last two links as a dyad - f(Permutation, X):
          F       -     flatten the Permutation
           =      -     equals X (vectorised)
               Ṫ  - tail -> permutation with matching prefix
                Ṫ - tail -> the missing pair
                  - implicit print

```

---

### Non-brute-force 21 bytes

I quite like this non-brute force method at **21 bytes** though (maybe it can be improved upon?)...

```
ḟ”cOḤÐoS;Ḥ$%5Qị“bbaac

```

A full program that accepts the flattened, redacted permutation and prints the missing item.

**Try it online!** Or see all twenty four of each of the five choices here.

#### How?

```
ḟ”cOḤÐoS;Ḥ$%5Qị“bbaac - Main Link: list of characters
ḟ”c                   - remove any 'c' character
   O                  - cast to ordinal values ('a' -> 97, 'b' -> 98)
     Ðo               - apply to odd indices (first, third, ...):
    Ḥ                 -   double
       S              - sum
        ;Ḥ$           - concatenate double this value -> [sum, 2×sum]
           %5         - modulo five -> [sum%5, (2×sum)%5]
             Q        - deduplicate
              ị“bbaac - index into "bbaac"

```

#### Examples:

**1. missing "c"** `"aaabbbba"`

-\> `"aaabbbba"` (removed `'c'`; no change)
-\> `[97,97,97,98,98,98,98,97]` (cast to ordinals)
-\> `[194,97,194,98,196,98,194,97]` (double values at odd indices)
-\> `1170` (sum those)
-\> `[1170, 2340]` (concatenate double itself)
-\> `[0, 0]` (modulo five)
-\> `[0]` (deduplicate)
-\> `"c"` (index into "bbaac" - Note that indexing is one-based and modular)

**2. missing "bb"** `"aaacbba"`

-\> `"aaabba"` (removed `'c'`)
-\> `[97,97,97,98,98,97]` (cast to ordinals)
-\> `[194,97,194,98,196,97]` (double values at odd indices)
-\> `876` (sum those - i.e. \\$1170 - (2 \times 98) - 98 = 876\\$)
-\> `[876, 1752]` (concatenate double itself)
-\> `[1, 2]` (modulo five)
-\> `[1, 2]` (deduplicate; no change)
-\> `"bb"` (index into "bbaac")
> 5 votes

# Answer
# Ruby, 41 bytes

```
->s{"%x"%(726-s.scan(/c|../).sum(&:hex))}

```

Try it online!

`0xaa+0xab+0xba+0xbb+0xc` is 726.
> 5 votes

# Answer
# Retina 0.8.2, ~~29~~ 23 bytes

```
$
¶aaabbbbac
D`c|..
1A`

```

Try it online! Link includes test cases. Explanation:

```
$
¶aaabbbbac

```

Append another copy of the whole list on a separate line.

```
D`c|..

```

Remove duplicate elements from the copy.

```
1A`

```

Remove the original input.
> 4 votes

# Answer
# Go, 209 bytes

```
import."strings"
func f(s string)string{r,S:=ReplaceAll(s,"c",""),map[string]int{"aa":0,"ab":0,"ba":0,"bb":0}
for i:=0;i<len(r);i+=2{k:=r[i:i+2]
if S[k]<1{S[k]++}}
for k,v:=range S{if v<1{return k}}
return"c"}

```

Attempt This Online!

### Explanation

```
import."strings"
func f(s string)string{
// remove "c" from the input. guaranteed to be even length
r:=ReplaceAll(s,"c","")
// map to keep track of seen pairs
S:=map[string]int{"aa":0,"ab":0,"ba":0,"bb":0}
// for each pair of chars...
for i:=0;i<len(r);i+=2{
// get the pair
k:=r[i:i+2]
// if pair is not seen yet, increment the counter
if S[k]<1{S[k]++}}
// for each pair...
for k,v:=range S{
// if not seen, return that pair
if v<1{return k}}
// otherwise return "c"
return"c"}

```
> 4 votes

# Answer
# Uiua, ~~31~~ 29 bytes

Two bytes saved by replacing `"ab"` with `⊝.`

```
⊔⊡⊗0⊐⊃∊'⊂⊙"c"∩(↯~2)⊞⊟.⊝.▽≠@c.

```

Try it online!

Interestingly, since Uiua has an autoformatter that runs during execution, afterwards it is 30 bytes. (Specifically, `'⊂⊙"c"` is turned into `(⊂⊙"c")`)

## Explanation

```
                          ▽≠@c. # Remove all c from the string
                     ⊞⊟.⊝.      # construct "ab" and generate all pairs of its elements
               ∩(↯~2)           # Simultaneously:
                                  # flatten the table into an array of 2-char strings
                                  # chunk the input (sans c) into 2-char strings
     ⊐⊃∊                        # Both find which of aa,ab,ba,bb are in chunked input...
        '⊂⊙"c"                  # ...and add c to the array of aa,ab,ba,bb
  ⊗0                            # Index of pair that was not found (4 if all were found)
⊔⊡                              # Select from aa,ab,ba,bb,c

```
> 4 votes

# Answer
# Uiua, 27 bytes

```
?"c"⍜(-@a)(◿2/+↯~2▽<2.)=8⧻.

```

Try it online!

**Explanation:**

For the cases where 'c' is in the string, this uses a little trick by converting 'a' to 0 and 'b' to 1, then the XOR of the three pairs results in the missing pair.

```
?"c"                    =8⧻.   # If the string length is 8, return "c"
    ⍜(-@a)(           )       # Subtract char 'a' from the string to get an
                               # array where a=0, b=1, c=2. Then perform the
                               # following and add char 'a' back at the end:
                   ▽<2.        # Remove any 2s (char 'c')
                ↯~2            # Reshape to pairs
            ◿2/+               # XOR by adding the pairs and taking modulo 2

```

**Example:**

Input: "cbbbaab"

| Operation | Stack (top on left): |
| --- | --- |
|  | "cbbbaab" |
| `⧻.` | 7 "cbbbaab" |
| `=8` | 0 "cbbbaab" |
| `?"c"` | "cbbbaab" |
| `⍜(-@a)(` | \[2 1 1 1 0 0 1\] |
| `▽<2.` | \[1 1 1 0 0 1\] |
| `↯~2` | \[\[1 1\] \[1 0\] \[0 1\]\] |
| `/+` | \[2 2\] |
| `◿2` | \[0 0\] |
| `)` | "aa" |
> 4 votes

# Answer
# Perl 5 (`-p`), ~~32~~, 29 bytes

```
$_=s/c//?eval s/..\K\B/^/gr:c

```

Try it online!

If `c` can't be removed returns `c` otherwise bitwise xor 2 char strings.

-3 bytes thanks to Kjetil S, changing `(?!$)` (negative lookahead end anchor) with `\B` (non-word-boundary)
> 4 votes

# Answer
# Java (SE), 164 bytes

`b->{if(b.contains("c"))l:for(var c:"aa ab ba bb".split(" ")){for(int i=0;i<6;i+=2)if(c.contains(b.replace("c","").substring(i,i+2)))continue l;return c;}return"c";}`

**Try it online!**

**Formatted:**

```
    static Function<String, String> f1 = b -> {
        if (b.contains("c"))
            l:for (var c : "aa ab ba bb".split(" ")) {
                for (int i = 0; i < 6; i += 2)
                    if (c.contains(b.replace("c", "").substring(i, i + 2)))
                        continue l;
                return c;
            }
        return "c";
    };

```

**Logs:**

* Golfing tips for I/O defaults respected (lambda function `b`) Thanks @corvus\_192 !
* `String` replaced with `var` at one place (-3 bytes)
* `System.out.println`s replaced with `return`s (-31 bytes) Thanks @ceilingcat !
* `return "c";` replaced with `return"c";` (-1 byte)
> 4 votes

# Answer
# Charcoal, ~~19~~ 15 bytes

```
⌊⁻⪪”&∨O⊕”²⪪⁻Ｓc²

```

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

```
   ”...”        Compressed string `aaabbbbac`
  ⪪     ²       Split into pairs of characters
 ⁻              Remove elements from
           Ｓ    Input string
          ⁻ c   Remove the `c`
         ⪪   ²  Split into pairs of characters
⌊               Take the minimum
                Implicitly print

```

If all of the `a`/`b` pairs were successfully removed then the only remaining element is the trailing `c` otherwise the minimum element is the missing `a`/`b` pair.
> 3 votes

# Answer
# Python, 83 bytes

```
lambda a:min({'aa','ab','bb','ba','c'}-{a.replace('c','')[i:i+2]for i in[0,2,4,6]})

```

Attempt This Online!

* -17 bytes thanks to Neil
> 3 votes

# Answer
# Ruby, 64 bytes

```
->s{a=%w[aa ab ba bb c];a.find{[*(a-[_1]).permutation].join[s]}}

```

Attempt This Online!
> 3 votes

# Answer
# Python 3.8, 82 bytes

```
lambda a:("cbbaa"*469)[(k:=sum(map(ord,(r:=a.replace('c',''))+r[::2])))::k][r==a:]

```

An unnamed function that accepts the flattened, redacted permutation and returns the missing item.

**Try it online!**

A port of my non-brute-force Jelly solution.
> 3 votes

# Answer
# Google Sheets, 80 bytes

`=substitute(regexreplace("aa|ab|ba|bb|c",regexreplace(A1,"(c|..)","$1|"),),"|",)`

Put the input in cell `A1` and the formula in `B1`.

Nothing clever here, just two replaces, plus removal of hardcoded separators.

Translation to JavaScript (90 bytes, non-competing):

```
s=>(r=(x,y,z)=>x.replace(RegExp(y,'g'),z||''))(r('aa#ab#ba#bb#c',r(s,'(c|..)','$1|')),'#')

```
> 3 votes

# Answer
# Python 3, 73 bytes

```
b,*l=0,{'c'},{0}
for c in input():l[b]^={c};b^=c<'c'
print(str(l)[3::10])

```

Try it online!

**71 bytes**

```
b=k=62
for c in input():k^=ord(c)*b;b^=c<'c'
print("babbaac"[k%7:][:2])

```

Try it online!
> 3 votes

# Answer
# , 31 30 29 bytes

```
(e.~{];,@{@;~@-.-._2<\-.)&'c'

```

Try it online!

*-1 thanks to ovs*

* `,@{@;~@-.` All valid 2 char pairs, constructed by the crossing the input with itself after removing 'c'. This will contain dups but is guaranteed to have all the valid pairs.
* `-.` Minus
* `_2<\-.` All 2 char input pairs, formed after removing 'c'
    + At this point we will either have our answer or the empty list (in the case that 'c' itself is missing)
* `];` Prepend 'c'
    + Now we will have an answer that looks like `c;ab` (in the case we're missing a 2 char sequence) or simply `c` (in the case we're missing 'c')
* `e.~{` If 'c' is an element of the input, take the 2nd element. Otherwise take the first (ie, return 'c' itself).

## , 30 bytes

```
(-.~,&;(,{;~'ab')-._2<\-.)&'c'

```

Try it online!

A similar alternate solution that has unboxed output and no conditional logic. Feels slightly cleaner to me despite being 1 byte longer.
> 3 votes

# Answer
# Python, 86 bytes

```
lambda s:[*{'aa','ab','ba','bb'}-{*map(str.__add__,*[filter('c'.__ne__,s)]*2)},'c'][0]

```

Attempt This Online!

No magic numbers here, just another approach to solving in Python, this one a straightforward-ish golfing of removing each of the pairs in the string (with `'c'` removed) from the initial set, and if none are left, defaulting to `'c'`.
> 3 votes

# Answer
# Uiua, 38 characters (62 bytes)

`("c";|⊢▽¬∊,⊃(↯¯1_2▽∊,)(/⊂⊞⊂.)"ab")∊@c.`

Uiuapad

```
("c";|⊢▽¬∊,⊃(↯¯1_2▽∊,)(/⊂⊞⊂.)"ab")∊@c.
(    |                              )∊@c.  # Is 'c' a member of the string?
 "c";                                      # If not, just return 'c'
            ⊃            (/⊂⊞⊂.)"ab"       # Else, generate the list L = ["aa" "ab" "ba" "bb"]
            ⊃(↯¯1_2▽∊,)                   # And filter out any the c's from the string (by keeping only members of "ab") and reshape it into a n×2 matrix
      ⊢▽¬∊,                               # Return the element of L which does not appear in this matrix.

```
> 3 votes

# Answer
# 05AB1E, 14 bytes

```
'cK2ôH.«^12Mhl

```

Port of *@Bubbler*'s J & Vyxal answer, so make sure to upvote that answer as well!

Try it online or verify all possible I/O test cases.

**Explanation:**

```
'cK            '# Remove a potential "c" from the (implicit) input-string
   2ô           # Split it into pairs
     H          # Convert each string-pair from hexadecimal to a base-10 integer
      .«        # Reduce this list by:
        ^       #  Bitwise-XORing
         12     # Push 12
           M    # Push the largest value on the stack
            h   # Convert it from a base-10 integer to (uppercase) hexadecimal
             l  # Convert it to lowercase
                # (after which the result is output implicitly)

```
> 3 votes

# Answer
# AWK, ~~67~~ 64 bytes

```
patsplit($0,l,/c|[ab]./){$0="aaabbbbac";for(k in l)sub(l[k],a)}1

```

Attempt This Online!

Removed a semicolon by moving `patsplit` out to the pattern part (-1), and golfed the regex a bit (-2).

previous answer, 67 bytes:

```
{patsplit($0,l,/c|[ab]{2}/);$0="aaabbbbac";for(k in l)sub(l[k],a)}1

```

Attempt This Online!

* `patsplit($0,l,/c|[ab]{2}/)`: Split `$0` (the input string) into valid chunks and store as a list in `l`. `/c|../` doesn't work because regex matching is done in favor of longer length across all alternatives.
* `$0="aaabbbbac"`: Replace `$0` with this fixed string.
* `for(k in l)sub(l[k],a)`: For each chunk in `l`, find and remove once from `$0`. An uninitialized variable `a` is used in place of an empty string.
* `1`: An all-match pattern. This causes `$0` to be printed as a default action.

Replacing **without** splitting `"aaabbbbac"` into chunks first works because

* there is only one place to be replaced for `ab` and `ba`, and
* for `aa` and `bb`, it doesn't matter which part of the runs is removed.
> 3 votes

# Answer
# APL+WIN, ~~69~~, ~~63~~, 57 bytes.

A bit more golfing saves another 6 bytes.

Prompts for string:

```
((8=⍴i)/'c'),(~s∊⊂[2]((⍴v),2)⍴v←(i←⎕)~'c')/s←,'ab'∘.,'ab'

```

Try it online! Thanks to Dyalog Classic
> 2 votes

# Answer
# Vyxal v2.21.12, 14 bytes

```
\cẆǒf«H₴Ǐ3F«ǒ⊍

```

Try it Online! (code modified to work on current version)

I'm using an older version of Vyxal because for some reason `ǒ` was modified in a recent version. Also, yes there's another Vyxal answer, but this one's shorter in regular SBCS bytes.

```
  Ẇ            # Split (keeping delimiter) on
\c             # "c"
   ǒf          # Cut each into chunks of length 2
     «H₴Ǐ3F«   # Compressed string "abaabbbac"
            ǒ  # Cut into chunks of length 2
             ⊍ # Take the set difference

```
> 2 votes

# Answer
# Nekomata, 12 bytes

```
ĕ<ĭÐŤʳXH"c"I

```

Attempt This Online!

The `xor` trick is borrowed from this answer by Bubbler.

```
ĕ<ĭÐŤʳXH"c"I
ĕ                   Pick one char out from the input string
 <                  Check that all remaining chars are less than the picked char
                    If this does not fail, which means the input contains 'c':
  ĭÐ                    Uninterleave the remaining chars into a pair of strings
    Ť                   Transpose
     ʳX                 Reduce by xor (chars are converted to code points implicitly)
       H                Convert from code points
           I        Otherwise:
        "c"             Return "c"

```
> 2 votes

# Answer
# C#, 93 bytes

```
x=>"aa ab ba bb c".Split().Except(x.Replace("c","").Chunk(2).Select(z=>""+z[0]+z[1])).First()

```

Explanation

```
x =>                         // input string
   "aa ab ba bb c".Split()   // construct array with the four pairs + c
   .Except(                  // remove from it...
       x.Replace("c","")     // remove c from input
       .Chunk(2)             // split into chunks of size 2 (each chunk is a char[])
       .Select(              // transform each item
           z=>""+z[0]+z[1]   // convert char[] to string
       )
   ).First();                // first item remaining. this is c if all pairs were removed

```

Try it online!

Uses `.Chunk` which isn't supported on tio.run.
> 2 votes

# Answer
# C# (without Implicit global usings), 241 bytes

```
var v=new System.Collections.Generic.List<string>();int i=0;while(v.Count<4){if(args[0][i]=='c')v.Add("c");else{v.Add(args[0].Substring(i,2));i++;}i++;}foreach(var k in"aa|ab|ba|bb|c".Split('|'))if(!v.Contains(k))System.Console.WriteLine(k);

```

This is my first golf, and the language isn't very golfable... be indulgent :-)

I didn't find a online compiler which handle input arguments correctly ; so to test this, paste it in a Visual Studio .cs file.
> 2 votes

# Answer
# Java (JDK), 118 bytes

Adaptation of *Arnauld*'s first JS answer
(this could probably be outgolfed with the new base-16 trick)

```
s->{var r="";for(var e:("aaabbabbc"+s).split("(?<=\\G..|c)"))r=r.contains(e)?r.replace(e,""):r+e+" ";return r.trim();}

```

Try it online!

---

We concatenate the string of all possible values with the string parameter, so that the whole resulting string contains every value twice, except for the "missing" value which will only appear once.
Then we use a regex to split the whole string into either `pairs of characters`, or `the character "c" alone`.
We parse the resulting array, and in a string accumulator we add any unseen value (with a space separator) and remove every value already seen. At the end, the accumulator contains only the missing value, and lots of spaces that we trim.
> 2 votes

# Answer
# AWK, 123 120 bytes

```
a["aa"];a["ab"];a["ba"];a["bb"];{if(!sub(/c/,z))$0="c";else{for(i=1;i<6;i+=2)delete a[substr($0,i,2)];for(k in a)$0=k}}1

```

Try it online!

---

Ungolfed :

```
a["aa"];a["ab"];a["ba"];a["bb"]
{
    if($0!~/c/)$0="c"
    else{
        sub(/c/,"",$0)
        for(i=1;i<6;i+=2) delete a[substr($0,i,2)]
        for(k in a)$0=k
    }
}
1

```
> 1 votes

# Answer
# Gema, ~~96~~ 65 characters

```
c=@set{c;}
??=@set{??;}
\Z=${aa;aa}${ab;ab}${ba;ba}${bb;bb}${c;c}

```

Sample run:

```
bash-5.2$ echo -n 'aaabbac' | gema 'c=@set{c;};??=@set{??;};\Z=${aa;aa}${ab;ab}${ba;ba}${bb;bb}${c;c}'
bb

```

Try it online! / Try all test case online!
> 1 votes

# Answer
# Swift, 187 bytes

Short version:

```
func m(_ s: String)->String{var t:Set=["aa","ab","ba","bb","c"];let s=s.map({String($0)});var i=0;while i<s.count{var x=s[i];if x != "c"{i+=1;x+=s[i];};t.remove(x);i+=1};return t.first!}

```

Verbose version:

```
func m2(_ s: String) -> String {
    var t:Set = ["aa","ab","ba","bb","c"]
    let s = s.map({String($0)})
    var i = 0
    while i < s.count {
        var x = s[i]
        if x != "c" {
            i += 1
            x += s[i]
        }
        t.remove(x)
        i += 1
    }
    return t.first!
}

```
> 0 votes

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


title: Swap letter and digit runs

text:
# Question
Title: Swap letter and digit runs
Given an input string containing only alphanumeric ASCII characters and starting with a letter, swap each letter run with the digit run which follows.

A *run* is a sequence of consecutive letters or digits. Note that in the case where the input string ends with a run of letters, this run is left untouched.

**Walk-through example**

For instance, given the input string `uV5Pt3I0`:

1. Separate runs of letters and runs of digits: `uV 5 Pt 3 I 0`
2. Identify pairs of runs: `(uV 5) (Pt 3) (I 0)`
3. Swap pairs of runs: `(5 uV) (3 Pt) (0 I)`
4. Concatenate: `5uV3Pt0I`

**Examples**

```
uV5Pt3I0 -> 5uV3Pt0I
J0i0m8 -> 0J0i8m
abc256 -> 256abc
Hennebont56Fr -> 56HennebontFr
Em5sA55Ve777Rien -> 5Em55sA777VeRien
nOoP -> nOoP

```

This is so the shortest answer in bytes wins. Explanations are encouraged.

# Answer
> 9 votes
# Jelly, 9 bytes

```
~ṠŒg⁸ṁṭ2/

```

Try it online!

### How it works

```
~ṠŒg⁸ṁṭ2/  Main link. Argument: s (string)

~          Apply bitwise NOT.
           Bitwise operators attempt to cast to int, so if c is a digit, this
           yields ~int(c), a negative number.
           If c cannot be cast to int, ~ will yield 0.
 Ṡ         Take the sign.
           We've now mapped digits to -1, non-digits to 0.
  Œg       Group consecutive equal elements.
    ⁸ṁ     Mold s as the result, grouping run of digits and runs of non-digits.
       2/  Reduce all pairs of runs by...
      ṭ        tack, appending the first run of the pair to the second run.

```

# Answer
> 15 votes
# Retina, 15 bytes

```
(\D+)(\d+)
$2$1

```

This replaces the regex `(\D+)(\d+)` with `$2$1`. Let's break that down if you don't know what that means.

The `\D` means 'match anything that isn't a number'. `\d` means 'match everything that is a number'. The `+` sign means 'match this at least once but try to match it as many times as possible'. The brackets define a group. The first group is `(\D+)` and the second is `(\d+)`

In the second line we say that we want to put whatever was matched by the second group, followed by whatever was matched by the first group. This effectively swaps the letter and digit runs.

Try it online!

# Answer
> 7 votes
# JavaScript (ES6), 34 bytes

```
s=>s.replace(/(\D+)(\d+)/g,"$2$1")

```

---

## Try it

```
o.innerText=(f=
s=>s.replace(/(\D+)(\d+)/g,"$2$1")
)(i.value="uV5Pt3I0");oninput=_=>o.innerText=f(i.value)
```

```
<input id=i><pre id=o>
```

# Answer
> 7 votes
## Haskell, ~~58~~ 56 bytes

*Thanks to @Laikoni for shaving off 2 bytes*

```
f""=""
f s|(a,(b,y))<-span(<':')<$>span(>'9')s=b++a++f y

```

Try it online!

Ungolfed:

```
f "" = ""
f string | (letters, afterLetters) <- span (> '9') string
         , (numbers, afterNumbers) <- span (< ':') afterLetters
         = numbers ++ letters ++ f afterNumbers

```

# Answer
> 6 votes
# Pyth, 15 bytes

```
ss_Mc:z"(\d+)"3 2

```

**Explanation**

```
     :z"(\d+)"3      # Split the input z onto matches of numbers (\d+)
    c           2    # Split the resulting list in pieces of length 2
  _M                 # Reverse each pair
ss                   # Concatenate

```

Test suite.

# Answer
> 6 votes
# Japt (v2.0a0), 16 bytes

```
q/(\d+/ ò mw c q

```

Test it online!

Note: this is an unstable alpha, so if this link breaks, you can use a slightly longer version in v1.4.4: Test it online!

### Explanation

```
q/(\d+/ ò mw c q  : Implicit input              "uV5Pt3I0"
q                 : Split input on
 /(\d+/           :   runs of digits, keeping each run. (This compiles to the regex /(\d+)/g)
                  : This gives                  ["uV","5","Pt","3","I","0",""]
        ò         : Take every pair of items.   [["uV","5"],["Pt","3"],["I","0"],[""]]
          m       : Map each pair by
           w      :   reversing.                [["5","uV"],["3","Pt"],["0","I"],[""]]
             c    : Flatten into one array.     ["5","uV","3","Pt","0","I",""]
               q  : Join into a single string.  "5uV3Pt0I"
                  : Implicit: output result of last expression

```

# Answer
> 6 votes
# Python 2, 49 bytes

Every non-regex solution I tried was longer. :P

```
lambda s:re.sub('(\D+)(\d+)',r'\2\1',s)
import re

```

Try it online!

# Answer
> 5 votes
# CJam, ~~32~~ ~~30~~ 28 bytes

```
q{i_64>X\:X^{])[}&c}/]]2/Wf%

```

CJam has no regex and no "split into digits and letters" or whatnot, so this was kind of painful.

Try it online!

### Explanation

```
q      e# Read the input.
{      e# Do the following for every char c:
 i     e#  Get c's codepoint.
 64>   e#  Check if it's greater than 64 (i.e. if it's a letter), pushing 1 or 0.
 X     e#  Push X (variable predefined to 1).
 \:X   e#  Store whether c was a letter or digit into X.
 ^{    e#  If (old X) XOR (new X) is 1:
  ]    e#   Close the current array.
  )    e#   Pull out its last character.
  [    e#   Open a new array.
 }&    e#  (end if)
 c     e#  Turn the codepoint back into a character. This also shoves it into the new array,
       e#  in case one was opened.
}/     e# (end for)
]      e# Close the final array, since it hasn't been closed yet.
]      e# Wrap the whole stack into an array.
2/     e# Split elements into groups of 2.
Wf%    e# Reverse each group.
       e# Implicitly flatten and print.

```

# Answer
> 4 votes
# Gema, 11 characters

```
<L><D>=$2$1

```

Sample run:

```
bash-4.4$ gema '<L><D>=$2$1' <<< 'Em5sA55Ve777Rien'
5Em55sA777VeRien

```

# Answer
> 3 votes
# Java 8, 38 bytes

```
s->s.replaceAll("(\\D+)(\\d+)","$2$1")

```

Not much to explain. Uses the same method as *@Okx*'s Retina answer, which can't be any shorter in Java.

Try it here.

# Answer
> 2 votes
# Jelly, 12 bytes

```
e€ØDŒg⁸ṁs2Ṛ€

```

Try it online!

Explanation:

```
e€ØDŒg⁸ṁs2Ṛ€ Accepts a string
e€ØD         Check if each char is in ['0'..'9']
    Œg       Split runs of 0s and 1s (respectively letter and digit runs)
      ⁸ṁ     Replace with input, keeping the split
        s2   Get pairs of runs, last left alone if letter run
          Ṛ€ Swap each pair

```

# Answer
> 2 votes
# Japt, ~~18~~ 14 bytes

```
r"(%D+)"pv ÏiZ

```

Try it

```
r"(%D+)"pv ÏiZ     :Implicit input of string
r                  :Replace
 "(%D+)"           :Literal string
        p          :Append
         v         :  Lowercase resulting in the Regex /(\D+)(\d+)/g
           Ï       :Pass each match through a function
            i      :  To the first matched group prepend
             Z     :  The second matched group

```

# Answer
> 2 votes
# Sed, 29 bytes

```
s/([^0-9]+)([0-9]+)/\2\1/g

```

Run with -r.

Uses capture groups and replaces them in the opposite order.

# Answer
> 2 votes
# PHP, no regex, 73 bytes

```
for(;a&$c=$argn[$i++];$p=$c)$c<A?print$c:$s=($p<A?!print$s:$s).$c;echo$s;

```

Run as pipe with `-nR` or test it online.

**breakdown**

```
for(;a&$c=$argn[$i++];  # loop through input
    $p=$c)                  # 2. remember character
    $c<A                    # 1. if digit
        ?print$c            # then print it
        :$s=($p<A           # else if previous character was digit
            ?!print$s           # then print and reset string
            :$s                 # else do nothing
        ).$c;                   # append current character to string
echo$s;                 # print remaining string

```

# Answer
> 1 votes
## Clojure, ~~104~~ 88 bytes

Oh regex is really handy... anyway (TIO):

```
#(apply str(flatten(map reverse(partition-all 2(partition-by(fn[i](< 47(int i)58))%)))))

```

`partition-by` splits into consecutive runs based on the return value of that function, `partition-all` splits into partitions of 2 (the pairs we'll be swapping), `map reverse` reverses them, `flatten` gets rid of nested list structure and finally we'll output a string. If `partition` was used instead of `partition-all` and we had odd number of chunks then the last one would be discarded.

Original used verbose but fun `(juxt second first)` and `(set"0123456789")` instead of `reverse` and ASCII integer ranges.

```
#(apply str(flatten(map(juxt second first)(partition-all 2(partition-by(comp not(set"0123456789"))%)))))

```

# Answer
> 1 votes
# PHP, 45 bytes

```
<?=preg_replace("#(\D+)(\d+)#","$2$1",$argn);

```

Try it online!

# Answer
> 1 votes
# C#, 71 bytes

```
s=>System.Text.RegularExpressions.Regex.Replace(s,@"(\D+)(\d+)","$2$1")

```

Just a shame regular expressions are so long in C#.

Try it online!

Full/Formatted version:

```
using System;

class P
{
    static void Main()
    {
        Func<string, string> f = s => System.Text.RegularExpressions.Regex.Replace(s, @"(\D+)(\d+)", "$2$1");

        Console.WriteLine(f("uV5Pt3I0"));
        Console.WriteLine(f("J0i0m8"));
        Console.WriteLine(f("abc256"));
        Console.WriteLine(f("Hennebont56Fr"));
        Console.WriteLine(f("Em5sA55Ve777Rien"));
        Console.WriteLine(f("nOoP"));

        Console.ReadLine();
    }
}

```

# Answer
> 1 votes
# QuadR, 15 bytes

```
(\D+)(\d+)
\2\1

```

Try it online!

### Explanation blatantly stolen from Okx:

This replaces the regex `(\D+)(\d+)` with `\2\1`. Let's break that down if you don't know what that means.

The `\D` means 'match anything that isn't a number'. `\d` means 'match everything that is a number'. The `+` sign means 'match this at least once but try to match it as many times as possible'. The brackets define a group. The first group is `(\D+)` and the second is `(\d+)`

In the second line we say that we want to put whatever was matched by the second group, followed by whatever was matched by the first group. This effectively swaps the letter and digit runs.

# Answer
> 1 votes
# PowerShell, 40 bytes

```
$args|%{$_ -replace '(\D+)(\d+)','$2$1'}

```

Try it online!

---

PowerShell is pretty ideal for this, seeing that it supports regex search-and-replace out of box. Props go to @Okx for the regex solution.

# Answer
> 1 votes
# Pip, 17 bytes

```
aR-C+XL.C+XD{c.b}

```

Takes input as a command-line argument. Try it online!

### Explanation

This uses the standard regex-replacement strategy, somewhat golfed.

The regex is `-C+XL.C+XD`, which evaluates to ``(?i)([a-z]+)(\d+)``:

```
   XL       Preset regex variable for lowercase letter: `[a-z]`
  +         Apply + to the regex: `[a-z]+`
 C          Wrap the regex in a capturing group: `([a-z]+)`
-           Apply the case-insensitive flag: `(?i)([a-z]+)`
        XD  Preset regex variable for digit: `\d`
       +    Apply + to the regex: `\d+`
      C     Wrap the regex in a capturing group: `(\d+)`
     .      Concatenate the two regexes: `(?i)([a-z]+)(\d+)`

```

The replacement is `{c.b}`, a callback function that concatenates the second group (`c`) and the first group (`b`). (The first argument to the function, `a`, contains the whole match.)

This is three bytes shorter than the naive `aR`(\D+)(\d+)``\2\1``.

# Answer
> 1 votes
# brainfuck, 98 bytes

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

```

Try it online!

### Explanation

This program maintains a queue of letters than haven't been output yet, and outputs them when appropriate.

The key to this program is `>>----[---->+<<<-[>]>]`. The three cells right of the input cell start out at zero. If the input is a code point between 1 and 63 inclusive, this moves the pointer one space right and places the input two spaces right of this new position. Otherwise, the pointer moves two spaces right, the cell one space right of the new position becomes 63, and the same 63 is subtracted from the input cell. This neatly divides the input into letters (65-122) and digits (48-57).

```
,[                       Take first input byte and start main loop
  >>                     Move two cells to the right
  ----[---->+<<<-[>]>]   (See above)
  >>                     Move two cells to the right
                         This cell contains the input if it was a digit, and 0 if input was a letter
  [                      If input was a digit:
   .                     Output digit immediately
   [[-]<]                Zero out digit and working cell
   <<[-]+>>              Set flag so we know later that we've output a digit
  ]
  <                      Move one cell left
                         This cell contains 63 if input was a letter, and 0 if input was a digit
  [                      If input was a letter:
   [-<<<+>>>]            Add 63 back to input letter
   <<<<                  Move to flag
   [                     If a digit has been output since the last letter read:
    -                    Clear flag
    <[<]>                Move to start of queue
    [.[-]>]              Output and clear all queued letters
   ]
   >[-<+>]>              Move input to end of queue
  ]
,]                       Repeat until no input remains
<[-]                     Clear flag if present
<[<]>                    Move to start of queue
[.>]                     Output all queued letters

```

# Answer
> 1 votes
# Ruby, 31 bytes

```
->x{x.gsub /(\D+)(\d+)/,'\2\1'}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 40 bitsv2, 5 bytes

```
⁽±Ḋ2ẇvṘ

```

Try it Online!

Bitstring:

```
1111001101110011001010001110010110010110

```

# Answer
> 0 votes
# Mathematica, 129 bytes

```
(n=NumberString;l=Length;s=Riffle[a=StringCases[#,n],b=StringSplit[#,n]];If[l@a==0,s=#,If[l@a<l@b,AppendTo[s,b[[-2;;]]]]];""<>s)&

```

# Answer
> 0 votes
# Scala, 89 bytes

A port of @Julian Wolf's Haskell answer in Scala.

---

Golfed version. Try it online!

```
s=>s match{case""=>"";case s=>{val(l,a)=s.span(_>'9');val(n,a2)=a.span(_<':');n+l+f(a2)}}

```

Ungolfed version. Try it online!

```
object Main extends App {

  def f(string: String): String = {
    string match {
      case "" => ""
      case str =>
        val (letters, afterLetters) = str.span(_ > '9')
        val (numbers, afterNumbers) = afterLetters.span(_ < ':')
        numbers + letters + f(afterNumbers)
    }
  }

  println(s"uV5Pt3I0         -> ${f("uV5Pt3I0")}")
  println(s"J0i0m8           -> ${f("J0i0m8")}")
  println(s"abc256           -> ${f("abc256")}")
  println(s"Hennebont56Fr    -> ${f("Hennebont56Fr")}")
  println(s"Em5sA55Ve777Rien -> ${f("Em5sA55Ve777Rien")}")
  println(s"nOoP             -> ${f("nOoP")}")

}

```

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