title: Exploded view of a string

text:
# Question
Title: Exploded view of a string
Don't you love those exploded-view diagrams in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

# The challenge

Write a program or function that

1. inputs a string containing only **printable ASCII characters**;
2. dissects the string into **groups of non-space equal characters** (the "pieces" of the string);
3. outputs those groups in any convenient format, with some **separator between groups**.

For example, given the string

```
Ah, abracadabra!

```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr

```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

# Rules

The **input** should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains **at least one non-space character**.

The **output** should consist of **characters** (even if the input is by means of ASCII codes). There has to be an unambiguous **separator between groups**, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator **between characters** of each group is **optional**. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

* The groups may be strings separated by newlines, as shown above.
* The groups may be separated by any non-ASCII character, such as `¬`. The output for the above input would be the string:

```
!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr

```
* The groups may be separated by *n*\>1 spaces (even if *n* is variable), with chars between each group separated by a single space:

```
!  ,    A   a a a a a    b b  c       d   h  r r

```
* The output may also be an array or list of strings returned by a function:

```
['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']

```
* Or an array of char arrays:

```
[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]

```

Examples of formats that are not allowed, according to the rules:

* A comma can't be used as separator (`!,,,A,a,a,a,a,a,b,b,c,d,h,r,r`), because the input may contain commas.
* It's not accepted to drop the separator between groups (`!,Aaaaaabbcdhrr`) or to use the same separator between groups and within groups (`! , A a a a a a b b c d h r r`).

The groups may appear in **any order** in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and `A` and `a` are different characters (grouping is **case-sentitive**).

Shortest code in bytes wins.

# Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

* Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr

```
* Test case 2:

```
\o/\o/\o/
///
\\\
ooo

```
* Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p

```
* Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y

```

# Answer
> 12 votes
# Jelly, 5 bytes

```
ḟ⁶ṢŒg

```

Try it online!

It does return an array, just that when it is printed to STDOUT, the separator is gone.

This is indeed a function that can be called as such (in Jelly, each line is a function).

```
ḟ⁶ṢŒg
ḟ⁶      filter out spaces
  Ṣ     sort
   Œg   group

```

# Answer
> 24 votes
# Python 3.5+, ~~77~~ ~~46~~ ~~44~~ 41 bytes

```
lambda s:[a*s.count(a)for a in{*s}-{' '}]

```

Pretty simple. Goes through the unique characters in the string by converting it to a set (using Python 3.5's extended iterable unpacking), then uses a list comprehension to construct the exploded diagrams by counting the number of times each character occurs in the string with `str.count`. We filter out spaces by removing them from the set.

The order of the output may vary from run to run; sets are unordered, so the order in which their items are processed, and thus this answer outputs, cannot be guaranteed.

This is a lambda expression; to use it, prefix `lambda` with `f=`.

~~Try it on Ideone!~~ Ideone uses Python 3.4, which isn't sufficient.

Usage example:

```
>>> f=lambda s:[a*s.count(a)for a in{*s}-{' '}]
>>> f('Ah, abracadabra!')
[',', 'A', 'aaaaa', 'd', '!', 'bb', 'h', 'c', 'rr']

```

*Saved 3 bytes thanks to @shooqie!*

# Answer
> 11 votes
# Retina, 13 bytes

```
O`.
!`(\S)\1*

```

The sorting is very easy (it's a builtin), it's separating the letters that takes 9 bytes. Try it online!

The first line s`O`rts all matches of the regex `.` (which is every character), giving us  `!,Aaaaaabbcdhrr`.

Match is the default stage for the last line of a program, and `!` makes it print a linefeed-separated list of matches of the regex. The regex looks for one or more instances of a non-space character in a row.

# Answer
> 9 votes
# Perl 6, 28 bytes

```
*.comb(/\S/).Bag.kv.map(*x*)

```

Note that Bag like a Hash or Set is unordered so the order of results is not guaranteed.

## Explanation:

```
# Whatever lambda ｢*｣

# grab the characters
*.comb(
  # that aren't white-space characters
  /\S/
)
# ("A","h",",","a","b","r","a","c","a","d","a","b","r","a","!")

# Turn into a Bag ( weighted Set )
.Bag
# {"!"=>1,","=>1,"A"=>1,"a"=>5,"b"=>2,"c"=>1,"d"=>1,"h"=>1,"r"=>2}

# turn into a list of characters and counts
.kv
# ("!",1,",",1,"A",1,"a",5,"b",2,"c",1,"d",1,"h",1,"r",2)

# map over them 2 at a time
.map(
  # string repeat the character by the count
  * x *
)
# ("!",",","A","aaaaa","bb","c","d","h","rr")

```

# Answer
> 8 votes
# Vim, ~~50~~, 46 bytes

```
i <esc>:s/./&\r/g
:sor
qq:%s/\v(.)\n\1/\1\1
@qq@qD

```

Explanation/gif will come later.

# Answer
> 7 votes
# Brachylog, ~~14~~ 7 bytes

**7 bytes thanks to Fatalize.**

```
:@Sxo@b

```

Try it online!

```
:@Sxo@b
:@Sx     remove spaces
    o    sort
     @b  group

```

# Answer
> 7 votes
## Pyth, 6

```
.gk-zd

```

Try it here or run a Test Suite.

Pretty simple, `-zd` removes spaces from the input, and `.gk` groups each remaining element by its value. Unfortunately, I haven't found a way to make use of auto-fill variables. Note that the output is shown as Python strings, so certain characters (read: backslashes) are escaped. If you want it to be more readable, add a `j` to the beginning of the code.

# Answer
> 7 votes
## Haskell, 38 bytes

```
f s=[filter(==c)s|c<-['!'..],elem c s]

```

Basically nimi's solution, but explicitly checking only letters appearing in the string.

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

```
s=>[...s].sort().join``.match(/(\S)\1*/g)

```

# Answer
> 5 votes
# 2sable, 7 bytes

Code:

```
Úð-vyÃ,

```

Explanation:

```
Ú       # Uniquify the string, aabbcc would result into abc
 ð-     # Remove spaces
   vy   # For each character...
     Ã  #   Keep those in the string, e.g. 'aabbcc', 'a' would result into 'aa'
      , #   Pop and print with a newline

```

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

# Answer
> 5 votes
## Haskell, 40 bytes

```
f x=[v:w|d<-['!'..],v:w<-[filter(==d)x]]

```

Usage example: `f "Ah, abracadabra!"`-\> `["!",",","A","aaaaa","bb","c","d","h","rr"]`.

The pattern `v:w` matches only list with at least one element, so all characters not in the input are ignored.

Also 40 bytes:

```
import Data.List
group.sort.filter(>' ')

```

# Answer
> 4 votes
# C# ~~125~~ 98 Bytes

```
using System.Linq;s=>s.GroupBy(c=>c).Where(g=>g.Key!=' ').Select(g=>new string(g.Key,g.Count())));

```

## Explanation

```
//Using anonymous function to remove the need for a full signature
//And also allow the implicit return of an IEnumerable
s =>

    //Create the groupings
    s.GroupBy(c => c)

    //Remove spaces
    .Where(g=> g.Key!=' ')

    //Generate a new string using the grouping key (the character) and repeating it the correct number of times
    .Select(g => new string(g.Key, g.Count()));

```
* Thanks to @TheLethalCoder who suggested the use of an anonymous function, which also allowed me to remove the `ToArray` call and just implicitly return an IEnumerable which collectively saves 27 bytes

# Answer
> 4 votes
# R, ~~198~~ ~~189~~ ~~96~~ 95 bytes

```
for(i in unique(a<-strsplit(gsub(" ","",readline()),"")[[1]]))cat(rep(i,sum(a==i)),"\n",sep="")

```

**Ungolfed :**

```
a<-strsplit(gsub(" ","",readline()),"")[[1]] #Takes the input from the console

for(i in unique(a)) #loop over unique characters found in variable a

cat(rep(i,sum(a==i)),"\n",sep="") # print that character n times, where n was the number of times it appeared

```

~~This solution is currently not entirely working, when `\` are involved.~~
*Now it is !*

Thank **a lot** you to @JDL for golfing out *102* bytes !

# Answer
> 4 votes
# Ruby, 41 + 1 = 42 bytes

+1 byte for `-n` flag.

```
gsub(/(\S)(?!.*\1)/){puts$1*$_.count($1)}

```

Takes input on stdin, e.g.:

```
$ echo 'Ah, abracadabra!' | ruby -ne 'gsub(/(\S)(?!.*\1)/){puts$1*$_.count($1)}'
A
h
,
c
d
bb
rr
aaaaa
!

```

# Answer
> 4 votes
## \>\<\>, 49 bytes

```
i:0(?v
84}0~/&{!*
v!?: <}/?=&:&:<
>&1+&}aol1-?!;^

```

Very spaciously wasteful in the output, but i assume is still allowed given the lenience of the rules

Explanation:

```
i:0(?v           Collects text from input
84}0~/&{!*       adds 32 (first ascii starting at space) to register and 0 to stack
v!?: <}/?=&:&:<  checks all characters to the current register, if equal:
       o         prints the character and continues looping
>&1+&}aol1-?!;^  when all characters are checked, adds 1 to register, prints a newline,
                 checks the stack length to halt the program if 0, and starts looping again

```

fit some things in pretty tight, even using jumps to get around some functions so i could run the pointer vertically.

Basically this puts each ASCII character on its own newline, and if none of that character exists, the line will be blank

Try it online

Edit: i was wrong there was an error in the code what would cause it to never complete if there was a space in the input

# Answer
> 4 votes
# Swift, ~~105~~ 91 bytes

Thanks to @NobodyNada for 14 bytes :)

Yeah, I'm pretty new to Swift...

```
func f(a:[Character]){for c in Set(a){for d in a{if c==d && c != " "{print(c)}}
print("")}}

```

Characters within a group are separated by a single newline. Groups are separated by two newlines.

# Answer
> 4 votes
## PowerShell v2+, 44 bytes

```
[char[]]$args[0]-ne32|group|%{-join$_.Group}

```

Takes input `$args[0]` as a command-line argument literal string. Casts that as a `char`-array, and uses the `-n`ot `e`qual operator to pull out spaces (ASCII `32`). This works because casting has a higher order precedence, and when an array is used as the left-hand operator with a scalar as the right-hand, it acts like a filter.

We pass that array of characters to `Group-Object`, which does exactly what it says. Note that since we're passing *characters*, not strings, this properly groups with case-sensitivity.

Now, we've got a custom object(s) that has group names, counts, etc. If we just print that we'll have a host of extraneous output. So, we need to pipe those into a loop `|%{...}` and each iteration `-join` the `.Group` together into a single string. Those resultant strings are left on the pipeline, and output is implicit at program completion.

### Example

```
PS C:\Tools\Scripts\golfing> .\exploded-view-of-substrings.ps1 'Programming Puzzles and Code Golf'
PP
rr
ooo
gg
aa
mm
i
nn
u
zz
ll
ee
s
dd
C
G
f

```

# Answer
> 3 votes
# Mathematica, 36 bytes

Built-in functions `Gather` and `Characters` do most of the work here.

```
Gather@Select[Characters@#,#!=" "&]&

```

# Answer
> 3 votes
# Pyth, 5 bytes

```
.gksc

```

Try it here!

Takes input as a Python string (i.e. wrapped in quotes, escaped quotes and slashes as necessary).

Explanation:

```
    c    Split (implied) input on whitespace
   s     Sum together
.gk      Group by value

```

If you guarantee at least one space in the input, there's a 4-byte solution:

```
t.gk

```

Try it here!

Explanation:

```
 .gk (Q)  groups the characters in the string by their value
           this sorts them by their value, which guarantees that spaces are first
t         Remove the first element (the spaces)

```

# Answer
> 3 votes
# Dyalog APL, 11 bytes

Function returning list of strings.

```
(⊂∩¨∪)~∘' '

```

`(⊂∩¨∪)` the intersection of the entirety and its unique characters

`~∘' '` except spaces

TryAPL online!

# Answer
> 3 votes
# Thunno 2, 3 bytes

```
ðoÑ

```

Try it online!

`ðo` removes spaces from the string. `Ñ` is a built-in for "group by". There is no body so it just groups identical characters together.

# Answer
> 3 votes
# JavaScript (Node.js), 59 bytes

Here's some JS solutions without regex. Uses linebreak as separators between groups.

```
s=>[...s].sort().map(c=>b==(b=c)?c:`
`+c,b=0).join``.trim()

```

Try it online!

---

Alternative that might not be supported by some browsers because of `at(-1)` (**62 bytes**) :

```
s=>[...s].sort().map(c=>a+=a.at(-1)==c?c:`
`+c,a="")&&a.trim()

```

Try it:

```
f=s=>[...s].sort().map(c=>a+=a.at(-1)==c?c:`
`+c,a="")&&a.trim()

;[
  `Ah, abracadabra!`,
  `\\o/\\o/\\o/`,
  `A man, a plan, a canal: Panama!`,
  `"Show me how you do that trick, the one that makes me scream" she said`
].forEach(s=>console.log(f(s)))
```

---

Alternative funny solution (**67 bytes**) :

```
s=>[...s].sort().map(a=c=>c!=' '?a[c]=[a[c]]+c:0)&&Object.values(a)

```

Try it online!

# Answer
> 3 votes
# \>\<\> (Fish), ~~53~~ ~~50~~ 46 bytes

```
l'~')?v0
v?(0:i<]r+1r[
\~rvol-1
^?:<;?('!'l~oa

```

Try it

Finally beat the current fish answer. Note the link pre-populates the stack to make it faster but this is unnecessary for the correctness of the program.

Each element of the stack stores how often the nth character appears in the input.

The top row pushes `ord('~')` 0s to the stack.

The second row reads the input. Use `[r1+r]` to get the nth element of the stack, add 1 to it, then put it back into place.

The left (red) half of the third row reverses the stack so the higher valued items are on the top. Now we know that the length of the stack is the character code of the count the top element represents. This allows very convenient printing.

The left (grey) half of the bottom row checks if the count of the nth character is 0. If so go to the right half of the third row.

The right (blue) half of the bottom row prints a line break `ao`. Then pops the top of the stack. If we now have less than `ord('!')` items on the stack only spaces remain and we exit (since we shouldn't print spaces)

The right half of the third row runs if there is more than one occurrence of the top character. If so, we subtract one occurrence, then print the length of the stack as a character.

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

-1 byte from @doug's improvement

```
{.x" "_=x}

```

Try it online!

Returns characters in order of appearance in original input.

* `=x` group the input, returning a dictionary mapping distinct values to the indices in which they appear in the input
* `" "_` remove the space character
* `.x` index back into the input using the indices returned above, and return just the values of the dictionary (i.e. the list of repeated characters)

# Answer
> 3 votes
# Japt `-R`, 6 bytes

```
ñ x ó¥

```

Try it

# Answer
> 3 votes
# , 65 bytes

```
cat(strrep(z<-names(y<-table(strsplit(readline(),""))),y)[z>" "])

```

Attempt This Online!

Full program that accepts input by reading a line from the terminal, and outputs a space-separated string of character-groups. The input & output are chosen to be directly comparable to the earlier R answers of Billywob and Frédéric.

Nevertheless, we could also golf a little further within the original rules, by writing a function that accepts input as an array of characters, and outputs an array of strings:

# , 49 bytes

```
function(x)strrep(z<-names(y<-table(x)),y)[z>" "]

```

Attempt This Online!

Note that this could be further shortened to 42 bytes using a version of R that is more-recent than the challenge to allow us to exchange `function` for `\`.

# Answer
> 2 votes
# Processing, 109 bytes

```
void s(char[] x){x=sort(x);char l=0;for(char c:x){if(c!=l)println();if(c!=' '&&c!='\n'&&c!='\t')print(c);l=c;}}

```

Its the brute force approach, sort the array, then loop through it. If it doesn't match the last character printed, print a newline first. If it is whitespace, skip the printing step.

# Answer
> 2 votes
# Octave, 61 bytes

```
@(x)mat2cell(y=strtrim(sort(x)),1,diff(find([1 diff(+y) 1])))

```

This is an anoymous function that takes a string as input and outputs a cell arrray of strings.

Try at Ideone.

### How it works

* `sort` sorts the input string. In particular, spaces will be at the beginning.
* `strtrim` removes leading spaces.
* `diff(+y)` computes consecutive differences between characters (to detect group boundaries)...
* ... so `diff(find([1 diff(+y) 1])` gives a vector of group sizes.
* `mat2cell` then splits the sorted string into chunks with those sizes.

# Answer
> 2 votes
# Javascript (using external Library - Enumerable) (~~78~~ 67 bytes)

```
 n=>_.From(n).Where(y=>y!=' ').GroupBy(x=>x).WriteLine(y=>y.Write())

```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: This is what Enumerable was made to do! Load the string into the library, which converts it to a char array. Filter out the white space entries. Group by char. Write each group to a line, according to the specified predicate. That predicate says to join all the elements of the current group into a string, without a delimiter.

# Answer
> 2 votes
## Perl6, ~~48~~ ~~47~~ 45

```
slurp.comb.Bag.kv.map:{$^a.trim&&say $a x$^b}

```

Thanks to manatwork for the improvements.

# Answer
> 2 votes
## Bash + coreutils, ~~53~~ ~~50~~ 45 bytes

```
sed 's: ::g;s:\(.\)\1*:& :g'<<<`fold -1|sort`

```

There is no separator between the characters of a group and the groups are separated by space. There is one trailing group separator, but as I understood that's acceptable.

**Run:**

```
./explode_view.sh <<< '\o /\ o /\ o k'

```

**Output:**

```
// \\\ k ooo

```

# Answer
> 2 votes
# MATL, 7 bytes

```
Xz!t7XQ

```

**MATL Online Demo**

# Answer
> 2 votes
## Ruby, 35 bytes

```
->s{(?!..?~).map{|x|s.scan x}-[[]]}

```

Tried to turn the problem upside down to save some bytes. Instead of starting with the string, start with the possible character set.

# Answer
> 2 votes
# Japt `-R`, 3 bytes

```
¸¬ü

```

Try it

```
¸¬ü     :Implicit input of string
¸       :Split on spaces
 ¬      :Join
  ü     :Group & sort
        :Implicit output joined with newlines

```

# Answer
> 2 votes
# Zsh, 35 bytes

Try it online!

```
for x (${(us::)1// })<<<${1//[^$x]}

```

Input via argument `$1`. Expression `${(us::)1// }` splits `$1` to array of unique chars, and removes spaces. Iterate over the unique array. For each `x`, print `$1`, removing non-`x` chars.

~~45 bytes~~: `A=(${(s::)1});for x (${(u)A})<<<${(Mj::)A#$x}`

# Answer
> 2 votes
# Arturo, 26 bytes

```
$=>[sort&--` `|chunk=>[&]]

```

Try it!

Takes input as a list of characters.

```
$=>[           ; a function where input is assigned to &
    sort       ; sort
    &--` `     ; input with spaces removed
    |          ; then
    chunk=>[&] ; split into groups of equal contiguous characters
]              ; end function

```

# Answer
> 1 votes
# Ruby, 46 bytes

Try it online!

```
->s{(s.chars-[' ']).uniq.map{|c|c*s.count(c)}}

```

My original full program version, 48 bytes after adding the `n` flag:

```
p gsub(/\s/){}.chars.uniq.map{|c|c*$_.count(c)}

```

# Answer
> 1 votes
# Python, 107

Could be shortened by lambda, but later

```
x=sorted(input())
i=0
while i<len(x):x[i:]=['  '*(x[i]!=x[i-1])]+x[i:];i-=~(x[i]!=x[i-1])
print("".join(x))

```

# Answer
> 1 votes
## CJam, 10 bytes

```
{S-$e`::*}

```

An unnamed block that expects the string on top of the stack and replaces it with a list of strings.

Try it online!

### Explanation

```
S-  Remove spaces.
$   Sort.
e`  Run-length encode, gives pairs [R C], where R is the run-length and
    C is the character.
::* Repeat the C in each pair R times.

```

# Answer
> 1 votes
## Pyke, ~~16~~ 9 bytes

```
d-}F/i*d+

```

Try it here!

# Answer
> 1 votes
# Common Lisp, 123

```
(lambda(s &aux(w(string-trim" "(sort s'char<))))(princ(elt w 0))(reduce(lambda(x y)(unless(char= x y)(terpri))(princ y))w))

```

Ungolfed:

```
(lambda (s &aux (w (string-trim " " (sort s 'char<))))
  (princ (elt w 0))
  (reduce
    (lambda (x y)
      (unless (char= x y) (terpri))
      (princ y))
  w))

```

Not the most golf friendly language. This could probably be modified to return list of lists instead of printing string.

# Answer
> 1 votes
# Emacs, 36 keystrokes

`C-SPACE` `C-E``M-x``sort-r``TAB``RETURN``.``RETURN``.``RETURN``C-A``C-M-S-%``\(\(.\)\2*\)``RETURN``\1``C-Q``C-J``RETURN``!`

### Result

`A man, a plan, a canal: Panama!` --\>

```
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p

```

### Explanation

1. `C-SPACE` `C-E`
2. `M-x` `sort-r``TAB` `RETURN` `.``RETURN` `.``RETURN`
3. `C-A`
4. `C-M-S-%` `\(\(.\)\2*\)``RETURN``\1` `C-Q` `C-J``RETURN` `!`

1. Select the input line;
2. Call `sort-regexp-fields` with arguments `.` and `.`;
    * Argument #1: *Regexp scpecifying records to sort*
    * Argument #2: *Regexp scpecifying key within records*
3. Return at line start;
4. Apply regexp substitution `\(\(.\)\2*\)` -\> `\1\n` on all matches.

# Answer
> 1 votes
# PHP, 67 bytes

Space as separator

PHP5 using deprecated `ereg_replace` function.

```
for(;++$i<128;)echo ereg_replace("[^".chr($i)."]","",$argv[1])." ";

```

PHP7, 73 bytes

```
for(;++$i<128;)echo str_repeat($j=chr($i),substr_count($argv[1],$j))." ";

```

Using built in is worse :(

```
foreach(array_count_values(str_split($argv[1]))as$a=>$b)echo str_repeat($a,$b)." ";

```

# Answer
> 1 votes
# Perl, 31 bytes

Includes +1 for `-p`

Run with input on STDIN:

```
explode.pl <<< "ab.ceaba.d"

```

`explode.pl`:

```
#!/usr/bin/perl -p
s%.%$&x s/\Q$&//g.$/%eg;y/
//s

```

If you don't care about spurious newlines inbetween the lines the following 24 bytes version works too:

```
#!/usr/bin/perl -p
s%.%$&x s/\Q$&//g.$/%eg

```

# Answer
> 1 votes
# Oracle SQL 11.2, 123 bytes

```
SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))GROUP BY c;

```

Un-golfed

```
SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)
FROM (SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
GROUP BY c

```

# Answer
> 1 votes
# S.I.L.O.S 265

The (non competing) code better input format is at the bottom, feel free to try it online!

```
def : lbl
loadLine :
a = 256
:a
:s
x = get a
z = x
z - 32
z |
if z u
a + 1
GOTO s
:u
if x c
GOTO e
:c
b = x
b + 512
c = get b
c + 1
set b c
a + 1
if x a
:e
a = 512
b = 768
l = 10
:Z
j = a
j - b
if j z
z = get a
c = a
c - 512
:3
if z C
printChar l
a + 1
GOTO Z
:C
printChar c
z - 1
GOTO 3
:z

```

Input for the above is a series of command line arguments representing ascii values, terminated with a zero.Try it online!.

---

For a more reasonable method of input we must up the byte count (and use features that were nonexistent before the writing of this challenge).
For 291 bytes we get the following code.
```
\
def : lbl
loadLine :
a = 256
:a
:s
x = get a
z = x
z - 32
z |
if z u
a + 1
GOTO s
:u
if x c
GOTO e
:c
b = x
b + 512
c = get b
c + 1
set b c
a + 1
if x a
:e
a = 512
b = 768
l = 10
:Z
j = a
j - b
if j z
z = get a
c = a
c - 512
:3
if z C
printChar l
a + 1
GOTO Z
:C
printChar c
z - 1
GOTO 3
:z

```

Feel free to test this version online!. The backslash is unnecessary but is there to show the important leading line feed.

# Answer
> 1 votes
## ARM machine code on Linux, 60 bytes

Hex Dump:

```
b590 4c0d f810 2b01 b11a 58a3 3301 50a3 e7f8 6222 2704 2001 f1ad 0101 2201 237f 5ce5 b135 700b df00 3d01 d8fc 250a 700d df00 3b01 d8f4 bd90 000200bc

```

This function basically creates an array of size 128, and whenever it reads a character from the input string it increment's the value at that characters position. Then it goes back through the array and prints each character array\[character\] times.

Ungolfed Assembly (GNU syntax):

```
.syntax unified
.bss @bss is zero-initialized data (doesn't impact code size)
countArray:
    .skip 128 @countArray[x] is the number of occurances of x

.text
.global expStr
.thumb_func
expstr:
    @Input: r0 - a NUL-terminated string.
    @Output: Groups of characters to STDOUT
    push {r4,r7,lr}
    ldr r4,=countArray @Load countArray into r4
    readLoop:
        ldrb r2,[r0],#1 @r2=*r0++
        cbz r2,endReadLoop @If r2==NUL, break
        ldr r3,[r4,r2] @r3=r4[r2]
        adds r3,r3,#1 @r3+=1
        str r3,[r4,r2] @r4[r2]=r3
        b readLoop @while (true)
    endReadLoop:
    @Now countArray[x] is the number of occurances of x.
    @Also, r2 is zero
    str r2,[r4,#' ] @'<character> means the value of <character>
    @What that just did was set the number of spaces found to zero.
    movs r7,#4 @4 is the system call for write
    movs r0,#1 @1 is stdout
    sub r1,sp,#1 @Allocate 1 byte on the stack
    @Also r1 is the char* used for write
    movs r2,#1 @We will print 1 character at a time
    movs r3,#127 @Loop through all the characters
    writeLoop:
        ldrb r5,[r4,r3] @r5=countArray[r3]
        cbz r5,endCharacterLoop @If we're not printing anything, go past the loop
        strb r3,[r1] @We're going to print byte r3, so we store it at *r0
        characterLoop:
            swi #0 @Make system call
            @Return value of write is number of characters printed in r0
            @Since we're printing one character, it should just return 1, which
            @means r0 didn't change.
            subs r5,r5,#1
            bhi characterLoop
        @If we're here then we're done printing our group of characters
        @Thus we just need to print a newline.
        movs r5,#10 @r5='\n' (reusing r5 since we're done using it as a loop counter
        strb r5,[r1]
        swi #0 @Print the character

        endCharacterLoop:
        subs r3,r3,#1
        bhi writeLoop @while (--r3)
    pop {r4,r7,pc}
.ltorg @Store constants here

```

Testing script (also assembly):

```
.global _start
_start:
    ldr r0,[sp,#8] @Read argv[1]
    bl expstr @Call function
    movs r7,#1 @1 is the system call for exit
    swi #0 @Make system call

```

# Answer
> 1 votes
# Scala, 53 bytes

```
def?(s:String)=s.filter(_!=' ').groupBy(identity).map{_._2.mkString}

```

When run with REPL:

```
scala> ?("Ah, abracadabra!")
res2: scala.collection.immutable.Iterable[String] = List(!, A, aaaaa, ,, bb, c, h, rr, d)

scala> print(res2.mkString("\n"))
!
A
aaaaa
,
bb
c
h
rr
d

```

EDIT: Forgot to filter spaces

# Answer
> 1 votes
## Clojure, 46

```
#(partition-by identity(sort(re-seq #"\S" %)))

```

Long and descriptive function names for simplest of things, yeah.

# Answer
> 1 votes
# PowerShell, 65

@TimmyD has the shorter answer but I don't have enough rep to comment. Here's my answer in 65 bytes.

I didn't think to use `group` and I didn't know that you could stick `-join` in front of something instead of `-join""` on the end and save two characters (using that would make my method 63).

```
([char[]]$args[0]-ne32|sort|%{if($l-ne$_){"`n"};$_;$l=$_})-join""

```

My method sorts the array, then loops through it and concatenates characters if they match the preceding entry, inserting a newline if they do not.

# Answer
> 1 votes
# Clojure (55 bytes)

```
(defn f[s](map(fn[[a b]](repeat b a))(frequencies s)))

```

Test Cases:

```
(f "Ah, abracadabra!")
;;=> ((\space) (\!) (\A) (\a \a \a \a \a) (\b \b) (\c) (\d) (\h) (\,) (\r \r))

(f "\\o/\\o/\\o/")
;;=> ((\\ \\ \\) (\o \o \o) (\/ \/ \/))

(f "A man, a plan, a canal: Panama!")
;;=> ((\space \space \space \space \space \space) (\!) (\A) (\a \a \a \a \a \a \a \a \a) (\c) (\, \,) (\l \l) (\m \m) (\n \n \n \n) (\P) (\p) (\:))

(f "\"Show me how you do that trick, the one that makes me scream\" she said")
;;=> ((\space \space \space \space \space \space \space \space \space \space \space \space \space \space) (\a \a \a \a \a) (\" \") (\c \c) (\d \d) (\e \e \e \e \e \e \e) (\h \h \h \h \h \h) (\i \i) (\k \k) (\,) (\m \m \m \m) (\n) (\o \o \o \o \o) (\r \r) (\S) (\s \s \s \s) (\t \t \t \t \t \t) (\u) (\w \w) (\y))

```

# Answer
> 1 votes
# Java 8, ~~121~~ ~~120~~ ~~110~~ 103 Bytes

```
s->s.chars().distinct().filter(c->c!=32)
    .forEach(c->out.println(s.replaceAll("[^\\Q"+(char)c+"\\E]","")))

```

Above lambda can be consumed with Java-8 `Consumer`. It fetches distinct characters and replaces other characters of the String to disassemble each character occurrence.

# Answer
> 1 votes
# Elixir, 70 bytes

```
def f(s), do: '#{s}'|>Enum.group_by(&(&1))|>Map.delete(32)|>Map.values

```

# Answer
> 1 votes
## R, 67 bytes

Even though there's already an R-answer by @Frédéric I thought my solution deserves it's own answer because it's conceptually different.

```
for(i in unique(x<-strsplit(readline(),"")[[1]]))cat(x[x%in%i]," ")

```

The program prints the ascii characters in order of appearence in the string where groups are separated by two white spaces and chars within groups by one white space. A special case is if the string has whitespaces in itself, then at one specific place in the output there will be `4+number of white spaces in string` white spaces separating two groups E.g:

`Ah, abracadabra!` =\> `A h , a a a a a b b r r c d !`

### Ungolfed

Split up the code for clarity even though assignment is done within the unique functions and changed to order of evaluation:

```
x<-strsplit(readline(),"")[[1]]) # Read string from command line and convert into vector

for(i in unique(x){              # For each unique character of the string, create vector
  cat(x[x%in%i]," ")             # of TRUE/FALSE and return the elements in x for which
}                                # these are matched

```

# Answer
> 1 votes
**C, 178**

```
#define F for
#define i8 char
#define R return
z(i8*r,i8*e,i8*a){i8*b,c;F(;*a;++a)if(!isspace(c=*a)){F(b=a;*b;++b)if(r>=e)R-1;else if(*b==c)*b=' ',*r++=c;*r++='\n';}*r=0;R 0;}

```

z(outputArray,LastPointerOkinOutputarray,inputArray) return -1 on error 0 ok Note:Modify its input array too...

```
#define P printf
main(){char a[]="A, 12aa99dd333aA,,<<", b[256]; z(b,b+255,a);P("r=%s\n", b);}

/*
 178
 r=AA
 ,,,
 1
 2
 aaa
 99
 dd
 333
 <<
 */

```

# Answer
> 1 votes
## Racket 243 bytes

```
(let*((l(sort(string->list s)char<?))(g(λ(k i)(list-ref k i))))(let loop((i 1)(ol(list(g l 0))))(cond((= i(length l))
(reverse ol))((equal?(g l(- i 1))(g l i))(loop(+ 1 i)(cons(g l i)ol)))(else(loop(+ 1 i)(cons(g l i)(cons #\newline ol)))))))

```

Ungolfed:

```
(define (f s)
  (let*((l (sort (string->list s) char<?))
        (g (λ (k i)(list-ref k i))) )
    (let loop ((i 1)
               (ol (list (g l 0))))
      (cond
        ((= i (length l)) (reverse ol))
        ((equal? (g l (- i 1)) (g l i))
         (loop (+ 1 i) (cons (g l i) ol)))
        (else (loop (+ 1 i) (cons (g l i) (cons #\newline ol))))
        ))))

```

Testing:

```
(display (f "Ah, abracadabra!"))

```

Output:

```
(
 !
 ,
 A
 a a a a a
 b b
 c
 d
 h
 r r)

```

# Answer
> 1 votes
# Nibbles, 1.5 bytes (3 nibbles)

```
=~|

```

```
=~|     # full program
=~|$$$  # with implicit args added;
  |     # filter
   $    # the input
    $   # by itself (=remove spaces),
=~      # now group the remaining characters by
     $  # themselves

```

# Answer
> 1 votes
# Factor, 37 bytes

```
[ " " without [ ] collect-by values ]

```

Attempt This Online!

* `" " without` remove spaces
* `[ ] collect-by` group letters by letter
* `values` discard the keys

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
ðK{γ

```

Outputs as a list.

Try it online or verify all test cases.

`ðK` could alternatively be `ðм` or `#J` for the same byte-count.

**Explanation:**

```
ðK    # Remove all spaces from the (implicit) input-string
  {   # Sort the remaining characters
   γ  # Group adjacent equal characters together in substrings
      # (after which the resulting list is output implicitly)

ðм    # (Vectorized) remove all spaces from the (implicit) input-string

#     # Split the (implicit) input-string by spaces (no-op if the input doesn't contain
      # any spaces)
 J    # Join this list back together to a string (or no-op, by joining the stack
      # consisting of just the single string if the input didn't contained any spaces)

```

# Answer
> 1 votes
# Bash +coreutils, 55 bytes

```
for x in `fold -1|tee a|sort|uniq`;{ grep $x a|rs -g0;}

```

Try it online!

# Answer
> 0 votes
# Javascript (ES5): 50 48 bytes

As a function:

```
function(i){return i.split("").sort().join(" ")}

```

The important code, replace the empty string with the search string (29 bytes):

```
"".split("").sort().join(" ")

```

# Answer
> 0 votes
# PowerShell - 86

I imagine I could get this smaller, but I'll work on it later. This assumes that `$d` contains the string to explode.

```
$s="";$i=0;[Array]::Sort(($a=$d-split""));$a|%{$s+=$_;if($a[++$i]-cne$_){$s+="`n"}};$s

```

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


title: Chinese color mixing

text:
# Question
Title: Chinese color mixing
# Objective

Given two Chinese ideographs meaning basic colors, output the ideograph that means the color resulting from mixing them.

# Basic colors

The basic colors are:

* 靑(U+9751; blue)
* 赤(U+8D64; red)
* 黃(U+9EC3; yellow)
* 白(U+767D; white)
* 黑(U+9ED1; black)

# Mixed colors

* Mixing 靑(blue) and 赤(red) yields 靘(U+9758; purple).
* Mixing 赤(red) and 黃(yellow) yields 熏(U+718F; orange).
* Mixing 黃(yellow) and 白(white) yields 硅(U+7845; beige).
* Mixing 白(white) and 黑(black) yields 黻(U+9EFB; grey).
* Mixing 黑(black) and 靑(blue) yields 黯(U+9EEF; deep blue).
* Mixing 靑(blue) and 黃(yellow) yields 綠(U+7DA0; green).
* Mixing 黃(yellow) and 黑(black) yields 騮(U+9A2E; brown).
* Mixing 黑(black) and 赤(red) yields 紫(U+7D2B; wine red).
* Mixing 赤(red) and 白(white) yields 紅(U+7D05; pink).
* Mixing 白(white) and 靑(blue) yields 碧(U+78A7; sky blue).

*(This scheme of color terms is historical, and it doesn't reflect the modern usage of Chinese.)*

To summarize in Unicode points:

```
9751, 8D64, 9758
8D64, 9EC3, 718F
9EC3, 767D, 7845
767D, 9ED1, 9EFB
9ED1, 9751, 9EEF
9751, 9EC3, 7DA0
9EC3, 9ED1, 9A2E
9ED1, 8D64, 7D2B
8D64, 767D, 7D05
767D, 9751, 78A7

```

# Rules

I/O format is flexible. In particular, I/O in Unicode points is okay, and outputting trailing whitespace is permitted.

Mixing colors is commutative. It is assumed that the two inputted basic colors are different.

In any case, an input not fitting into your format falls in *don't care* situation.

# Examples

* Given 靑 and 白, output 碧.
* Given 赤 and 白, output 紅.

# Answer
# Nibbles, ~~31~~ 30 bytes (60 nibbles)

*Edit: -1 byte thanks to xigoi*

```
=%!=$@90:`D 40960 $ 1c179f3cec8cb05803cd69a25df3d95bf5d7758

```

Attempt This Online!

Port of SuperStormer's Python answer \- upvote that.
Input and output as Unicode points.

```
=%!=$@90:`D 40960 $
         `D         # interpret the appended data
            40960   # in base 40960
                    # (so generates 10x 2-byte values);
        :         $ # append the input
=                   # and index into this list using
  !=                # absolute difference
    $@              # of inputs
 %    90            # modulo-90

```

---

# Nibbles, 44 bytes (88 nibbles)

```
=%!=$@90.`/3`D256+' '$ c78287c79465c9888ec7666fc79680c78165c7948bc99b8fc99b9bc97d7858

```

Attempt This Online!

Input and output as Chinese characters.
> 4 votes

# Answer
# Python, 60 bytes

*-1 byte thanks to Neil*

```
lambda a,b:' 碧紅騮熏綠硅紫黯黻靘'[abs(a-b)%90%11]

```

Attempt This Online!

Takes input in Unicode codepoints (integers), and returns a string.

### Explanation

Basically, the idea is to "hash" the 2 input values and index into a string of possible outputs. `abs(a-b)%90%11` resulted in 10 different indexes for the 10 possible inputs. Generation script
> 19 votes

# Answer
# Wenyan (文言), 237 bytes

-33 bytes thanks to @tsh.

```
吾有一術名之曰色欲行是術必先得二數曰「甲」曰「乙」乃行是術曰加甲以乙除其以百六六所餘幾何除其以十一所餘幾何夫『靘黯碧熏硅硅紫紅黻綠』之其乃得矣是謂「色」之術也

```

Expects two code points.

Based on @Arnauld's Javascript answer, but uses `(a+b)%166%11` instead of `a*b%25%11`, because Wenyan is 1-indexed.

You can try it on this Online IDE. Here is a full test program:

```
吾有一術名之曰色欲行是術必先得二數曰「甲」曰「乙」乃行是術曰加甲以乙除其以百六六所餘幾何除其以十一所餘幾何夫『靘黯碧熏硅硅紫紅黻綠』之其乃得矣是謂「色」之術也

有數三萬八千七百三十七。名之曰「靑」。
有數三萬六千一百九十六。名之曰「赤」。
有數四萬零六百四十三。名之曰「黃」。
有數三萬零三百三十三。名之曰「白」。
有數四萬零六百五十七。名之曰「黑」。

施「色」於「靑」於「赤」。書之。
施「色」於「赤」於「黃」。書之。
施「色」於「黃」於「白」。書之。
施「色」於「白」於「黑」。書之。
施「色」於「黑」於「靑」。書之。
施「色」於「靑」於「黃」。書之。
施「色」於「黃」於「黑」。書之。
施「色」於「黑」於「赤」。書之。
施「色」於「赤」於「白」。書之。
施「色」於「白」於「靑」。書之。

```
> 17 votes

# Answer
# JavaScript (ES6), 50 bytes

Expects two code points as `(a)(b)`.

```
a=>b=>"紫騮靘熏X綠黻紅硅黯碧"[a*b%25%11]

```

Try it online!

### How?

Short modulo chains exist for all simple commutative operations (addition, multiplication, XOR and even OR). The benefit of using a multiplication is that no parentheses are required.

It's also interesting to note that we still have enough information when reducing both code points modulo 9:

```
a=>b=>"XX碧紫紅黯靘黻X綠X硅騮XX熏"[a%9^b%9]

```

Try it online! (53 bytes)
> 12 votes

# Answer
# 05AB1E, 33 bytes

```
α90%•MÚöć'wSlé∞‘cP₃$«¢Γå"α•5ô0šsè

```

I/O as codepoint integers.

Port of *@SuperStormer*'s Python answer.

Try it online or verify all test cases.

**Explanation:**

```
α        # Get the absolute difference of the two (implicit) input codepoint-integers
 90%     # Modulo-90
•MÚöć'wSlé∞‘cP₃$«¢Γå"α•
        '# Push compressed integer 30887320053947029071321603078932043406874069938744
 5ô      # Split it into parts of size 5
   0š    # Prepend a dummy 0
     s   # Swap so the earlier abs(a-b)%90 is at the top of the stack
      è  # 0-based modular index it into this list
         # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•MÚöć'wSlé∞‘cP₃$«¢Γå"α•` is `30887320053947029071321603078932043406874069938744`.

---

Since I was curious: using the actual unicode characters would result in an 18-character program, but it would be 40 bytes in UTF-8 encoding:

```
α90%" 碧紅騮熏綠硅紫黯黻靘"è

```

Input as codepoint integers, output as Chinese character.

Try it online.
> 5 votes

# Answer
# Charcoal, ~~55~~ 51 bytes

```
Ｆ²⊞υ﹪﹪℅Ｓ³¹¦⁵℅Ｉ§⪪§⪪”)‴φ<ΦηA∧⌊✂⮌.\`Ｐ⁷⸿⁼DT⟦8'Ｒ＆Ｃ”¶⌊υ⁵⌈υ

```

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

```
Ｆ²⊞υ﹪﹪℅Ｓ³¹¦⁵

```

Input the code points and reduce them modulo `31` and `5` to get them into the range `0-4`.

```
℅Ｉ§⪪§⪪”)‴φ<ΦηA∧⌊✂⮌.\`Ｐ⁷⸿⁼DT⟦8'Ｒ＆Ｃ”¶⌊υ⁵⌈υ

```

Look up the resulting character in a compressed lookup table.

A port of @SuperStormer's method is also 51 bytes:

```
§ 碧紅騮熏綠硅紫黯黻靘﹪↔⁻℅Ｓ℅Ｓ⁹⁰

```

Attempt This Online! Link is to verbose version of code. (TIO unnecessarily quotes the string literal, costing three bytes.)
> 2 votes

# Answer
# C (gcc), 61 bytes

```
f(a,b){a=L" 碧紅騮熏綠硅紫黯黻靘"[abs(a-b)%90%11];}

```

Try it online!

Port of @SuperStormer's Python submission

Thanks to @Neil for knowing how to print multibyte characters, and to @Kevin Cruijssen for pointing out that my byte count was wrong.
> 2 votes

# Answer
# Scala 3, 51 bytes

```
a=>b=>"黻綠黯熏紅紫硅碧騮靘"(a*b%6231%10)

```

Attempt This Online!

Same modulo trick as @SuperStormer but uses multiplication instead.
> 2 votes

# Answer
# Wolfram Language(Mathematica), 105 bytes

Port of @SuperStormer's Python answer in Mathematica.

---

Golfed version, Try it online!

105 bytes, it can be golfed much more.

```
f[a_,b_]:=FromCharacterCode@ToCharacterCode["碧紅騮熏綠硅紫黯黻靘"][[Mod[Mod[Abs[a-b],90],11]]]

```

Ungolfed version. Try it online!

```
f[a_, b_] :=
  FromCharacterCode[
   ToCharacterCode["碧紅騮熏綠硅紫黯黻靘"][[((Abs[a - b]~Mod~ 90 )~Mod ~11)]]];

repl = {{"靑", "赤", "靘"}, {"赤", "黃", "熏"}, {"黃", "白", "硅"}, {"白", "黑",
    "黻"}, {"黑", "靑", "黯"}, {"靑", "黃", "綠"}, {"黃", "黑", "騮"}, {"黑",
    "赤", "紫"}, {"赤", "白", "紅"}, {"白", "靑", "碧"}};

Table[a = repl[[i, 1]]; b = repl[[i, 2]]; c = repl[[i, 3]];
  res = f[ToCharacterCode[a][[1]], ToCharacterCode[b][[1]]];
  Print[a, " ", b, " ", c, " ", res], {i, Length[repl]}];

```
> 2 votes

# Answer
# Ruby, 53 bytes

```
->n{"紅熏紫 碧綠黯硅靘  黻騮"[n.sum%23%13]}

```

Try it online!

A function which Takes a string with the two input codepoints, finds a checksum (which for some reason is always even) and performs a mod-fold to hash it down to a number 0..12. This is then used as in index to look up in a string. The output is then returned as a single character.

The imperfect hash means there are 3 wasted spaces in the string, but that only counts as 3 bytes total (the Chinese characters on the other hand are 3 bytes each.)
> 2 votes

# Answer
# Thunno 2, 32 bytes

```
ṛ90%»æḳṫƈe:÷/ċWƊ&ıZbȥƙNỵ`@»Ṙ⁵0Ƥi

```

Try it online!

Port of @SuperStormer's Python answer. I/O as codepoints.

Just in case you're wondering:

## Thunno 2, 39 bytes (UTF-8)

```
-A90%" 碧紅騮熏綠硅紫黯黻靘"i

```

Try it online!

Input as codepoints, outputs the character.

#### Explanation

```
ṛ90%»...»Ṙ⁵0Ƥi  # Implicit input
ṛ               # Absolute difference
 90%            # Mod 90
    »...»Ṙ      # Compressed number
          ⁵     # Split into chunks of length 5
           0Ƥ   # With a 0 prepended
             i  # Index into the list
                # Implicit output

```
> 1 votes

# Answer
# Vyxal, 33 bytes

```
ε90%»æ↲‡ẇf;ƈ0£Xġ'ɾ[c₆⟨OɖaA»S5ẇ0pi

```

Try it Online!

Port of @SuperStormer's Python answer. I/O as codepoints.

#### Explanation

```
ε90%»...»S5ẇ0pi  # Implicit input
ε                # Absolute difference
 90%             # Mod 90
    »...»S       # Compressed number
          5ẇ     # Split into chunks of length 5
            0p   # With a 0 prepended
              i  # Index into the list
                 # Implicit output

```
> 1 votes

# Answer
# Go, 78 bytes

```
func(a,b rune)rune{return[]rune("紫騮靘熏X綠黻紅硅黯碧")[a*b%25%11]}

```

Attempt This Online!

Port of @Arnauld's answer.
> 1 votes

---
Tags: code-golf, unicode
---


# Question
Title: "Print this diamond" gone beautifully wrong
Write a function (or a whole program) that outputs (or prints) the following ASCII art:

### Output:

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

```

This is , so the shortest solution in bytes wins!

#### Allowed:

* Any number of **trailing spaces** on each line
* An equal number of *additional* **leading spaces** on each line (meaning of additional: without counting the already mandatory leading spaces shown in the output above)
* *Additional* **newlines** at the beginning and/or at the end. These additional lines can contain any number of spaces

---

I'm late to the party, but as some of you may have recognized, this challenge is inspired by the bugged output in *Carcigenicate*'s answer in Clojure for the Print this diamond challenge.

This answer also led to a chain of 3 challenges from *Kevin Cruijssen* : It was just a bug, It was just an input-bug, and I done did made a spaceship maw!

But i wanted to see something more "pulsar-y", as this is what i find most beautiful in the original answer!

I hope you will generate beautifully bugged ASCII arts while doing this challenge :)

# Answer
> 8 votes
# Python 3, 80 bytes

```
i=8
while i+9:k=abs(i);print(f"{(' '*k).join(str((10**(9-k)//9)**2)):^41}");i-=1

```

Try it online!

Uses the classic arithmetic trick where, for example,

```
(10**9//9)**2 == 111111111**2 == 12345678987654321

```

## Python 3, 79 bytes

```
f=lambda k=8,c=1:(s:=[f"{(' '*k).join(str(c*c)):^41}"])[k:]or s+f(k-1,c*10+1)+s

```

Try it online!

Recursive function that generates a list of lines when called with no inputs. The idea is to start with the center line, then repeatedly sandwich what we have between two copies of a new line.

## Python 3, 79 bytes

```
f=lambda p=8*' ',c=1:(s:=f"{p.join(str(c*c)):^41}\n")+(p and f(p[1:],c*10+1)+s)

```

Try it online!

Recursive function that generates the whole multiline string, with a trailing newline, when called with no input.

# Answer
> 7 votes
# Thunno 2, 14 bytes

```
9Rƒıṅ8_ṣjⱮ;ⱮØC

```

Try it online!

~~Seems like the compressed list part (`¿qJŒḣ“ɲþẇɦɠ¿i`) could be golfed a bit with a formula, but I couldn't find it.~~

~~I found the formula \\$(n-6)(n-5)\\$ for the leading spaces.~~

I don't need that any more. Port of Kevin Cruijssen's 05AB1E answer.

*-5 by porting @KevinCruijssen's 05AB1E answer*

#### Explanation

```
9Rƒıṅ8_ṣjⱮ;ⱮØC  # Full program
9Rƒ             # Prefixes of [1..9]
   ı      ;     # Map over:
    ṅ8_         #  8 - iteration index
       ṣj       #  Join by that many spaces
         Ɱ      #  Palindromise
           Ɱ    # Palindromise
            ØC  # Center
                # Implicit output

```

Old:

```
9RⱮı65d-pṣnRⱮn9_ṣj+  # Full program
9RⱮı                 # Map over [1,2,...,8,9,8,...,2,1]:
    65d-pṣ           #  Push (n-6) * (n-5) spaces
          nRⱮ        #  Push [1,2,...,n,...2,1]
             n9_ṣj   #  Join by (9-n) spaces
                  +  #  Prepend the leading spaces
                     # Implicit output, joined on newlines

```

# Answer
> 6 votes
# Ruby, ~~71~~ 69 bytes

Function outputting an array of lines. A synthesis of my old answer with Level River St's answer as per their suggestions.

-2 bytes by switching to Ruby 2.7+ (TIO is on 2.5.5)

```
->{(-8..8).map{([*1...x=9-k=_1.abs,*x.downto(1)]*(' '*k)).center 41}}

```

Attempt This Online!

# Ruby, 77 bytes

Recursion, ahoy! Function outputting an array of lines.

```
f=->x=1{s=([*1...x,*x.downto(1)]*(' '*(9-x))).center 41;x<9?[s,*f[x+1],s]: s}

```

Try it online!

# Answer
> 6 votes
# Vyxal, 12 bytes

```
9ƛɾ9n-Ij;∞øṗ

```

Try it Online!

Uses the strangely specific `øṗ` (Flip Brackets Vertical Palindromise, Center, Join on Newlines) builtin.

```
9ƛ      ;         for n in [1...9]:
  ɾ9n-Ij            join [1..n] by 9-n spaces
         ∞        palindromize the list
          øṗ      palindromize and center all the strings and join by \n

```

# Answer
> 5 votes
# Charcoal, 17 bytes

```
Ｅ⁹⪫⮌…·¹⊕ι× ⁻⁸ι‖Ｏ¬

```

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

```
Ｅ⁹⪫⮌…·¹⊕ι× ⁻⁸ι

```

For `n` from `1` to `9`, output the numbers from `n` down to `1` joined with `9-n` spaces, but doing everything `0`-indexed.

```
‖Ｏ¬

```

Reflect both left and down to complete the diamond gone beautifully wrong.

# Answer
> 5 votes
# Pip `-l`, 23 bytes

```
QPZJ RZJ:R\,_JsX9-_M\,9

```

Attempt This Online!

### Explanation

```
QPZJ RZJ:R\,_JsX9-_M\,9
                    \,9  ; Range from 1 to 9, inclusive
                   M     ; Map this function to each:
          \,_            ;   Range from 1 to fn arg, inclusive
         R               ;   Reversed
             J           ;   Join on this string:
              sX         ;   A number of spaces equal to
                9-_      ;   9 minus fn arg
      ZJ:                ; Transpose list of strings, filling gaps with spaces
     R                   ; Reverse list of lines
  ZJ                     ; Transpose again
QP                       ; Quad-palindromize
                         ; Autoprint, joining on newlines (-l flag)

```

Here's the step-by-step evolution, using size 5 instead of 9 and showing spaces using periods:

```
\,5

1
2
3
4
5

R\,_JsX5-_M

1
2...1
3..2..1
4.3.2.1
54321

ZJ:

12345
....4
...33
..2.2
.1.21
.....
..11.

R

..11.
.....
.1.21
..2.2
...33
....4
12345

ZJ

......1
..1...2
1..2..3
1.2.3.4
..12345

QP

......1......
..1...2...1..
1..2..3..2..1
1.2.3.4.3.2.1
..123454321..
1.2.3.4.3.2.1
1..2..3..2..1
..1...2...1..
......1......

```

# Answer
> 4 votes
# Ruby, 83 bytes

Updated per suggestion from @ValueInk

```
(-8..8).map{|i|puts (((-8+c=i.abs)..8-c).map{|j|"#{9-c-j.abs}"}*(" "*c)).center 41}

```

Try it online!

# Ruby, 86 bytes

```
(-8..8).map{|i|puts (((-8+c=i.abs)..8-c).map{|j|(9-c-j.abs).to_s}*(" "*c)).center(41)}

```

Try it online!

# Answer
> 4 votes
# Jelly, 20 bytes

```
9Rjạ9⁶xƊƊ€Uz⁶ZUŒBŒḄY

```

A full program that prints the diamond.

**Try it online!**

### How?

```
9Rjạ9⁶xƊƊ€Uz⁶ZUŒBŒḄY - Main Link: no arguments
9                    - 9
         €           - for each {i in [1..9]}:
        Ɗ            -   last three links as a monad f(i):
 R                   -     range -> [1..i]
       Ɗ             -     last three links as a monad f(i):
   ạ9                -       absolute difference with 9 -> 9-i
     ⁶               -       space character
      x              -       repeat -> ' '*(9-i)
  j                  -     join -> e.g. "1      2      3"
          U          - reverse each
           z⁶        - transpose with space character as filler
             Z       - transpose
              U      - reverse each
               ŒB    - bounce each
                 ŒḄ  - bounce
                   Y - join with newline characters
                     - implicit, smashing print

```

# Answer
> 3 votes
# Vyxal, 16 bytes

```
9ɾKėƛ÷$8εIj∞;∞øĊ

```

Try it Online!

Port of ~~my Thunno 2 answer~~ Kevin Cruijssen's 05AB1E answer.

*-1 thanks to @lyxal*
*-3 by porting @KevinCruijssen's 05AB1E answer*

#### Explanation

```
9ɾKėƛ÷$8εIj∞;∞øĊ  # Full program
9ɾK               # Prefixes of [1..9]
   ėƛ       ;     # Enumerate and map over:
     ÷$8ε         #  Absolute difference between 8 and the iteration index
         Ij       #  Join by that many spaces
           ∞      #  Palindromise
             ∞    # Palindromise
              øĊ  # Center
                  # Implicit output

```

Old:

```
9ɾ∞ƛ65f-ΠInɾ∞n9εIj+  # Full program
9ɾ∞ƛ                 # Map over [1,2,...,8,9,8,...,2,1]:
    65f-ΠI           #  Push (n-6) * (n-5) spaces
          nɾ∞        #  Push [1,2,...,n,...2,1]
             n9εIj   #  Join by (9-n) spaces
                  +  #  Prepend the leading spaces
                     # Implicit output, joined on newlines

```

# Answer
> 3 votes
# Swift, 156 bytes

`String(repeating:count)` is nice for practical code, but so long for code golf...

```
let f={(1...$0)+(1..<$0).reversed()}
f(9).map{n in print(.init(repeating:" ",count:(n-6)*(n-5))+f(n).map{"\($0)"+String(repeating:" ",count:9-n)}.joined())}

```

Try it on SwiftFiddle!

Port of @TheThonnu's various answers. `f` is a shorthand for counting from 1 to n and back. I put the joining spaces inside the `map` callback rather than passing them to `joined` because the latter would involve an extra argument label (`joined(separator:)`).

# Answer
> 3 votes
# Scala, 214 bytes

Port of @Level River St's Ruby answer in Scala.

---

Golfed version. Try it online!

```
object M extends App{(-8 to 8).map{i=>val c=i.abs
println((" "*(20-((-8+c)to(8-c)).map{j=>(9-c-j.abs).toString}.mkString(" "*c).length/2)+((-8+c)to(8-c)).map{j=>(9-c-j.abs).toString}.mkString(" "*c)).slice(0,41))}}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    (-8 to 8).map { i =>
      val c = i.abs
      val line = ((-8 + c) to (8 - c)).map { j =>
        (9 - c - j.abs).toString
      }.mkString(" " * c)
      println(center(line, 41))
    }
  }

  def center(s: String, width: Int): String = {
    val padSize = width - s.length
    if(padSize <= 0) s
    else (" " * (padSize/2)) + s + (" " * (padSize - padSize/2))
  }
}

```

# Answer
> 3 votes
# 05AB1E, ~~16~~ 15 bytes

```
9Lηε8N-ð×ýû}û.c

```

Try it online.

**Explanation:**

```
9L           # Push a list in the range [1,9]
  η          # Pop and push its prefixes: [[1],[1,2],[1,2,3],...]
   ε         # Map over each prefix:
    8N-      #  Push 8 minus the 0-based map index
       ð×    #  Pop and push a string of that many spaces
         ý   #  Join the list with those spaces (or empty string for N=8) as delimiter
          û  #  Palindromize this string
   }û        # After the map: palindromize the list of lines as well
     .c      # Join the list by newlines,
             # and add leading spaces where necessary to centralize the lines
             # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Perl 5, 65 bytes

```
$a=-1-abs,print map/\D|0/?$":$_,map$a+10+abs()/$a,-20..20for-8..8

```

Try it online!

I'd count it `63+1` (instead of `65`), the `+1` for `-E` and `say` instead of `print`, can't figure out how to get it in TIO which also doesn't add 1 for `-l` switch. But it beats direct competitors anyway :), it's strange nobody used this strategy.

# Answer
> 2 votes
# Python 3, 107 bytes

```
R=range
for n in[*R(1,9),*R(9,0,-1)]:print((n-6)*(n-5)*' '+((9-n)*' ').join(map(str,[*R(1,n),*R(n,0,-1)])))

```

Try it online!

Port of my Thunno 2 answer.

*-5 thanks to @Neil*

# Answer
> 2 votes
# JavaScript (V8), 102 bytes

A full program.

```
for(n=17;n--;print(s))for(q=n<9?n:16-n,x=9-q,i=s=''.padEnd(20-q*x);~q;)s+=`${++i>q?1+q--:i}`.padEnd(x)

```

Try it online!

---

# C (gcc), 116 bytes

*-1 thanks to @c--*

```
q;x;i;main(n){for(n=17;n--;i=!puts(""))for(q=n<9?n:16-n,x=9-q;~q;q-=i>q)printf("%*d",i>1?x:x+12-q*x+q,++i>q?1+q:i);}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 21 bytes

```
9Lûε65S-Pð×yLûy9αð×ý«

```

Try it online!

Port of my Thunno 2 answer. Unfortunately 05AB1E doesn't have the "push n spaces" built-in that Thunno 2 and Vyxal have.

Output as a list of lines. TIO footer joins by newlines.

*-2 thanks to @KevinCruijssen*

#### Explanation

```
9Lûε65S-Pð×yLûy9αð×ý«  # Implicit input
9Lûε                   # Map over [1,2,...,8,9,8,...,2,1]:
    65S-P×J            #  Push (n-6) * (n-5) spaces
           yLû         #  Push [1,2,...,n,...2,1]
              y9αð×ý   #  Join by (9-n) spaces
                    «  #  Prepend the leading spaces
                       # Implicit output

```

# Answer
> 2 votes
# Retina, 60 bytes

```

9*

$`;$'¶
v`( *;)( *)
$.1$2
P`.+
%`^.
$^$<'
L$`9
$>`$^$`

```

Try it online! Explanation:

```

9*

```

Insert 9 spaces.

```

$`;$'¶

```

Generate a `9×9` square of spaces, but with `;`s on the main diagonal.

```
v`( *;)( *)
$.1$2

```

Use the spaces before the `;` to generate the numbers from `n` down to `1` on the `n`th row, spaced using the spaces after the `;`.

```
P`.+
%`^.
$^$<'

```

Reflect horizontally.

```
L$`9
$>`$^$`

```

Reflect vertically (actually around the central `9` but it comes to the same thing).

92 bytes in Retina 0.8.2:

```

9$*

$`;$'¶
(?=( *;)( *)).
$.1$2
.+
$&12$*
(.(.{20})).*
$2$1
%20O^$`.

¶.+¶$
$&$`
9>O^$`

```

Try it online! Explanation:

```

9$*

```

Insert 9 spaces.

```

$`;$'¶

```

Generate a `9×9` square of spaces, but with `;`s on the main diagonal.

```
(?=( *;)( *)).
$.1$2

```

Use the spaces before the `;` to generate the numbers from `n` down to `1` on the `n`th row, spaced using the spaces after the `;`.

```
.+
$&12$*
(.(.{20})).*
$2$1
%20O^$`.

```

Reflect horizontally by prefixing each line with a copy of the 20 characters after the first and then reversing those 20 characters.

```
¶.+¶$
$&$`
9>O^$`

```

Reflect vertically by duplicating all the lines except the last and then reversing only the duplicates.

# Answer
> 2 votes
# Zsh, 108 bytes

```
for c ({1..9} {8..1}){w=$[(10**c/9)**2];printf \\n%$[(5-c)*(6-c)]s
for x (${(s::)w})printf %-$[9-$#w/2]s $x}

```

Try it online!

Adapted from @Donat's "bash diamond" code and my "spaceship maw" solution.

# Answer
> 2 votes
# , 45 bytes

```
8({.~#-@+41-:@-#)@dlb@(9&-":1+]-|@i:)@-|@i:@8

```

Try it online!

Meh.

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

```
i,c=8;main(j){for(;--i/j?i=j=9-abs(c--):1;)printf("%*c",i-j?j-10:11*i-i*i-31,i-j?48+j-abs(i):10);}

```

Try it online!

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

```
j;main(z,x){for(;z<10;putchar(x>20?10:x%z|(x=58-z-abs(x/z))<49?32:x))x=j%43-21,z=abs(j++/43-8)+1;}

```

Try it online!

# Answer
> 1 votes
# JavaScript (V8), 98 bytes

I don't know if it's very polite to answer my own challenge, but here it is!

```
for(z of(z=9,s=(n=1,p="".padEnd(9-z))=>n<z?n+p+s(n+1,p)+p+n:z)())print("".padEnd((6-z)*(5-z))+s())

```

Try it online!

---

This is the combined works of *Donat*'s recent Javascript answer to the challenge "Print this diamond"
and *The Thonnu*'s formula: **(n−6)(n−5) for the leading spaces**.
*@Donat*, don't hesitate if you want to post this as your own answer, this is mostly your work after all :)

# Answer
> -1 votes
# Vyxal, 278 Bytes

```
»×ẏ∴⁺¢ɽƒ3∴ĿṘ€ȯLdd2)"lY∇λµ≠Ḟw⅛!ḋ₌₁ẊṘ?
‡₄¥D‹Ḣ€ɾȯḟǑLdẇm₁≤ɖ↵$hḭ«€X⇧0A2&/•p[₀‟₃5Ǔ≈Π>ḋṠßĠ-⋏↳ĖOUḃ`∑ß∨(V⋏⋎ṁ7Ż≥×h'D℅p×>¥D↲‛℅ddlʀɾ⌐D%₆₄⁋ŻṘġȧ₅ḣ'ɾp0Ḋ¢lǐ⟨6K⌊∵¶⟨Ḣ,g#;¬‛^4⟨β•qrṠg₅Þf⋎→__↑¢[ẏNcḟ≠H꘍C¼↔Π꘍∧≬ǏḭḞǔṄꜝ⌐ø₇µ`ʁȯ⁋√ÞVe↲ <†∧↔⊍n÷PḂė?ġ¦$₌$e⋎\]↵⇩ṁn€⋏+₀ǒ&Ċ⌐∩ṁṗ½VḃḞβ#WżL∵ṖðǓmẊOur,8‹»`1
23456789`τ

```

Compressed number converted to custom string base.

Try it online!

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


title: Continuously Count Consecutive Cases

text:
# Question
Title: Continuously Count Consecutive Cases
## Background

Imagine that I'm creating a really long necklace, consisting of only two characters, `A` and `B`. You must count the number of occurrences of the substring `AB` in the string.

However, since it's a necklace, you must also consider if the last character and the first character join to make `AB`. For example, in `BBBA`, there would be 1 occurrence of `AB`, as the final `A` would join to the first `B`.

Finally, since I'm not finished making the chain, you must continually accept an input. Every successive input after the first is intended to be appended to the current necklace. You must also provide the output for the entire appended necklace after each input. Due to I/O limitations however, these inputs will be given as an array.

## Your Task

* Sample input: An array consisting of strings consisting of **any two different characters of your choosing**, only. You must clarify in your answer what the substring you're checking for is (which is of length two, and contains both of the distinct characters you're using). You may not use a boolean array.
* Output: The number of occurrences of the substring, as an array of outputs.

**Explained Examples**

```
Input => Output
ABABA => 2
ABABA => 4

The chain at the second output would be ABABAABABA, which contains 4 ABs.

```

```
Input => Output
BA => 1
BABA => 3
BB => 3
BAAAAB => 4

The chain at the second output would be BABABA, which contains 3 ABs including the A at the end and the B at the start.
The chain at the third output would be BABABABB, which contains 3 ABs
The chain at the fourth output would be BABABABBBAAAAB, which contains 4 ABs

```

**Test Cases**

```
Input => Output
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
AB => 1
AAA => 1
B => 2
AB => 3
//
BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB => 1
A => 2
B => 2
A => 3
A => 3
B => 3
//
BABABABABABAB => 6
A => 7

```

This is , so shortest answer wins. (# of bytes)

# Answer
> 6 votes
# Vyxal, 5 bytes

```
¦ƛǏ₀O

```

Try it Online!

Uses the characters `1` and `0`, checks for substring `10`.

## Explained

```
¦ƛǏ₀O
¦ƛ     # To each prefix of the input:
  Ǐ    #   Append the first character to the end
   ₀O  #   And count the number of instances of "10" in that

```

Created with the help of Luminespire.

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

```
k=>{for(let i=1;i<=k.length;i++)console.log(((s=k.slice(0,i).join('')).match(/01/g)||[]).length+!(+s.at(-1)-~-s[0]))}

```

Uses `0` instead of A and `1` instead of B.

I could probably get rid of the first/last character special case by appending the first character at the end like Vyxal did using `(k.slice(0,i).join('')+k[0][0]).match(/01/g)` instead of `(s=k.slice(0,i).join('')).match(/01/g)` but I can't be bothered to rewrite my terrible explanation

# Explained

```
// Take k ['01010', '01010']
// Convert it to s '01010'
// Then in the next loop s='0101001010'
// In s, count the occurences of 01
// Then count special case of first/last characters

// k has length N
k=>{for(let i=1;i<=k.length;i++) // Loop 'i' from 1 to N inclusive
console.log( // Output:

  (
    (s=k.slice(0,i).join('')) // Get bracelet up to current 'i'
    .match(/01/g)             // List of occurences of '01'
      ||[]                    // Default to empty list
  ).length                    // Get length
+
  !(+s.at(-1)-~-s[0]) // Is +s.at(-1)-~-s[0] equal to 0?
                      // (implicitly) convert to number

)}

```

## But what is `!(+s.at(-1)-~-s[0])`?

`s.at(-1)` is the last element of s, and for the rest... well... I just threw a bunch of random stuff in there until it worked; please don't tell my coding teacher

## With test cases

```
const f=

k=>{for(let i=1;i<=k.length;i++)console.log(((s=k.slice(0,i).join('')).match(/01/g)||[]).length+!(+s.at(-1)-~-s[0]))}

`
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
AB => 1
AAA => 1
B => 2
AB => 3
//
BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB => 1
A => 2
B => 2
A => 3
A => 3
B => 3
//
BABABABABABAB => 6
A => 7
`.slice(1,-1).replaceAll('A','0').replaceAll('B','1').split('\n//\n').forEach(testCase => {
    const parts = testCase.split('\n').map(x=>x.split(' => '));
    const input_ = parts.map(x=>x[0]);
    console.log('\n\nInput:',input_,'\nExpected output:');
    parts.forEach(x=>console.log(+x[1]));
    console.log('Output:');
    f(input_);
});

```

# Answer
> 3 votes
# 05AB1E (legacy), 6 bytes

```
ηJεĆT¢

```

I/O as a list. Uses characters `1` and `0` for `A` and `B` respectively.

Uses the legacy version of 05AB1E, because the new version of 05AB1E has a bug with multi-digit integers and the count builtin `¢`, so it would require an additional `§` after the `T`.

Try it online! or verify all test cases.

**Explanation:**

```
η       # Get the prefixes of the (implicit) input-list
 J      # Join each inner list together to a single string
  ε     # Map over each string:
   Ć    #  Enclose; append its first character at the end
    T¢  #  Count how many times "10" occurs in this string
        # (after which the list of counts is output implicitly as result)

```

# Answer
> 3 votes
# Scala, ~~139~~ 61 bytes

Port of @Gábor Fekete's Python answer in Scala.

---

Golfed version. Attempt This Online!

Saved 78 bytes thanks to the comment of @corvus\_192

```
var c="";def f(i:Any)={c+=i;(c+c(0))sliding 2 count(_=="AB")}

```

Ungolfed version. Attempt This Online!

```
import scala.collection.mutable.ArrayBuffer

object Main {

  var c: ArrayBuffer[String] = ArrayBuffer()

  def f(i: String): Int = {
    if (c.isEmpty) {
      c += i
    }
    else {
      c = ArrayBuffer(c.head + i)
    }
    (c.head + c.head(0)).sliding(2).count(_ == "AB")
  }

  def main(args: Array[String]): Unit = {
    val cases = Array(
      ("ABABA", 2),
      ("ABABA", 4),
      ("//", 0),
      ("BA", 1),
      ("BABA", 3),
      ("BB", 3),
      ("BAAAAB", 4),
      ("//", 0),
      ("AB", 1),
      ("AAA", 1),
      ("B", 2),
      ("AB", 3),
      ("//", 0),
      ("BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB", 1),
      ("A", 2),
      ("B", 2),
      ("A", 3),
      ("A", 3),
      ("B", 3),
      ("//", 0),
      ("BABABABABABAB", 6),
      ("A", 7)
    )

    for (caseValue <- cases) {
      caseValue._1 match {
        case "//" =>
          println("=" * 15)
          c = ArrayBuffer()
        case _ =>
          val t = f(caseValue._1)
          println(caseValue._1 + " " + caseValue._2 + " ; result: " + t)
      }
    }
  }
}

```

# Answer
> 2 votes
# Charcoal, 19 bytes

```
ＷＳ«≔⁺ωιωＩ№⁺ω§ω⁰ABＤ⎚

```

Try it online! Link is to verbose version of code. Fully interactive version, so when run from the command line it will prompt for the next piece of necklace and output the count of `AB`s so far. Explanation:

```
ＷＳ«

```

Keep accepting pieces but stop when an empty piece is entered.

```
≔⁺ωιω

```

Concatenate the piece to the necklace so far.

```
Ｉ№⁺ω§ω⁰ABＤ⎚

```

Output the number of `AB`s so far.

# Answer
> 2 votes
# Dyalog APL, 21 bytes

```
{∇⍵,⍞⊣⎕←+/'AB'⍷⍵,⊃⍵}⍞
                    ⍞  # Take a line from standard input, and pass it to the following function:
      ⎕←               #   print
        +/             #   how many times
          'AB'         #   the string AB
              ⍷        #   appears in
               ⍵,⊃⍵    #   the string formed by concatenating the input and its first element
     ⊣                 #   , then,
 ∇                     #   call the same function
  ⍵,⍞                  #   passing the input concatenated with another line from standard input

```

Created with the help of Luminespire.

# Answer
> 2 votes
# Python, ~~67~~ ~~65~~ 55 bytes

```
lambda i,c=[]:c.extend(i)or''.join(c+c[:1]).count('AB')

```

Attempt This Online!

Using the default `list` argument to memorize the previous inputs.

edit: changed `extend` to `append` to save 2 bytes

edit: with the help of @Albert.Lang and @Jonathan Allan golfed an additional 10 bytes

# Answer
> 2 votes
# Swift 5.7 `-enable-bare-slash-regex`, 95 bytes

```
{var x=""
return $0.map{x+=$0
return x.ranges(of:/AB/).count+("B"==x.first&&"A"==x.last ?1:0)}}

```

Try it on SwiftFiddle! Without the `-enable-bare-slash-regex` flag, the regex literal `/AB/` would be spelled `#/AB/#` on macOS, or `try!Regex("AB")` on Linux, so the flag is obvious. SwiftFiddle enables it by default on Swift 5.7 and later.

The code should be fairly straightforward: append the new element to what's been seen so far, then count the ranges that match `/AB/`, and check whether it starts with "B" and ends with "A".

# Answer
> 2 votes
# Ruby `-nl`, ~~40~~ 38 bytes

```
a="#{a}#$_"
p (a+a[0]).scan('AB').size

```

Attempt This Online!

```
ruby -nl                     # -n loops program over each line of input
                             # -l automatically trims trailing newlines

a="       "                  # Set a to...
   #{a}                      #  a, if already set (empty string otherwise)
       #$_                   #  plus most recent line of input
  (a+a[0])                   # Get a plus its first character
          .scan('AB').size   #  and count all instances of AB
p                            # Print that number

```

# Answer
> 2 votes
# Nibbles, 6 bytes

```
`\$:/,`=+$$~

```

Attempt This Online!

Works with any two distinct characters.

```
`\$:/,`=+$$~
             For each p in
`\ :          prefixes of
  $            the input
     ,        length of
      `=  $    group runs of identical elements in
        +$      p concatenated
    /      ~  floor-divided by 2

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
;\ŒgẈ:2

```

Attempt This Online!

Port of my Nibbles answer.

```
;\ŒgẈ:2
;\      Concatenate all prefixes
        For each concatenated prefix:
  Œg     Group runs of equal elements
    Ẉ    Length
     :2  Floor divide by two

```

# Answer
> 1 votes
# Excel, 80 bytes

```
=MAP(SCAN("",A1#,LAMBDA(a,b,a&b)),LAMBDA(c,ROWS(TEXTSPLIT(RIGHT(c)&c,,"AB"))-1))

```

Input is *vertical* spilled range `#A1`.

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
ƒıJẹTc

```

Attempt This Online!

Uses `1` and `0`, and checks for the substring `10`, like Vyxal and 05AB1E.

#### Explanation

```
ƒıJẹTc  # Implicit input
ƒı      # Map over prefixes
  Jẹ    #  Join and append first character
    Tc  #  Count occurrences of "10"
        # Implicit output

```

# Answer
> 1 votes
# Pyth, 11 bytes

```
m/shBsd`T._

```

Try it online!

Uses characters "1" and "0" for "A" and "B" respectively.

### Explanation

```
m/shBsd`T._Q    # implicitly add Q
                # implicitly assign Q = eval(input())
         ._Q    # prefixes of Q
m               # map over lambda d
     sd         #   concatenate list of strings
   hB           #   bifurcate into [str, first_char(str)]
  s             #   concatenate list of strings
 /     `T       #   count occurrences of "10"

```

# Answer
> 1 votes
# Perl 5 `-pl`, 28 bytes

```
$,.=$_;$_=chop.$,;$_=s/AB//g

```

Try it online!

# Answer
> 1 votes
# Jelly, ~~9~~ 8 bytes

```
;\µṙ1<)§

```

Try it online!

Something cleverer still feels possible. Takes input as shown in the test cases, since counting substring occurrences is actually pretty expensive anyways.

```
;\          Scan by concatenate, creating a list of each cumulative necklace.
  µ   )     For each:
   ṙ1       rotate left once, and
       §    count how many
     <      are less than in the corresponding original positions.

```

# Answer
> 1 votes
# Scala 3, 65 bytes

```
_.scanLeft("")(_+_).tail.map(s=>(s+s(0))sliding 2 count(_=="AB"))

```

Attempt This Online!

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


title: Ordinal string check

text:
# Question
Title: Ordinal string check
# Description :

Given a string as input, check if it is a valid ordinal number in English or not. If it is valid return truthy value otherwise return falsy value. (Suggested by @Arnauld. Thanks . Also by @JoKing)

For users who want to know about *ordinal numbers* go here :

https://www.mathsisfun.com/numbers/cardinal-ordinal-chart.html (Suggestion by : qwr)

# Possible inputs :

```
21st ---> true
12nd ---> false
1nd ---> false
....

```

This is a **code golf** challenge so shortest code in each language will be the winner.

# Examples :

```
console.log('12th' , true) // This evaluates to true
console.log('1st' , true) // also evaluates to true
console.log('21nd' , false) // returns false
console.log('11st' , false) // returns false
console.log('111199231923819238198231923213123909808th' , true) // true
```

Since a lot of people asked the question regarding whether input will be only valid strings or not :

All inputs will always be valid. i.e they will be in the form of string and consist of a digit (or number of digits) along with one of the four suffixes :

`st` , `nd` , `rd` , `th`

# Answer
# Python,  ~~56~~  53 bytes

-3 thanks to (use unique letter inclusion instead of penultimate character equality)

```
lambda v:'hsnrhhhhhh'[(v[-4:-3]!='1')*int(v[-3])]in v

```

An unnamed function.

**Try it online!**

### How?

Since all input (here `v`) is guaranteed to be of the form `\d*[st|nd|rd|th]` we can just test whether a character exists in `v` which we expect to be there if it were correct (`s`, `n`, `r`, or `h`, respectively) - that is `<getExpectedLetter>in v`.

The last digit usually determines this:

```
v[-3]: 0 1 2 3 4 5 6 7 8 9
v[-2]: h s n r h h h h h h

```

...except when the penultimate digit is a `1`, when all should end with `th` and hence our expected character must be `h`; to evaluate this we can take a slice (to avoid an index error occurring for inputs with no -4th character) `v[-4:-3]`. Since `0` maps to `h` already we can achieve the desired effect using multiplication prior to indexing into `'hsnrhhhhhh'`.
> 4 votes

# Answer
# Bash + GNU utilities, 54

Regex matching seems to be a straightforward way to go. I'm pretty sure this expression could be shortened more:

```
egrep '((^|[^1])(1st|2nd|3rd)|(1.|(^|[^1])[^1-3])th)$'

```

Input from STDIN. Output as a shell return code - 0 is truthy and 1 is falsey.

Try it online!
> 3 votes

# Answer
this is under the assumption that the input is valid ordinal pattern. if its not the case changes need to be made

# JavaScript (Node.js),97 92 78 bytes

```
s=>("tsnr"[~~((n=(o=s.match(/(\d{1,2})(\D)/))[1])/10%10)-1?n%10:0]||'t')==o[2]

```

Try it online!

### Explanation

```
s=>
   ("tsnr"                                // all the options for ordinal - 4-9 will be dealt afterwards
      [~~(                                //floor the result of the next expression
        (n=(                              //save the number (actually just the two right digits of it into n
          o=s.match(/(\d{1,2})(\D)/))[1]) //store the number(two digits) and the postfix into o (array)
        /10%10)-1                         //if the right most(the tenths digit) is not 1 (because one is always 'th')
          ?n%10:0]                        //return n%10 (where we said 0-3 is tsnr and afterwards is th
            ||'t')                        // if the result is undefined than the request number was between 4 and 9 therefor 'th' is required
    ==o[2]                                // match it to the actual postfix

```

### \_____________________________________________________________________

port of @Herman Lauenstein

# JavaScript (Node.js), 48 bytes

```
s=>/1.th|(^|[^1])(1st|2nd|3rd|[^1-3]th)/.test(s)

```

Try it online!
> 3 votes

# Answer
# Java 8, ~~54~~ 51 bytes

```
s->s.matches(".*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).")

```

**Explanation:**

Try it online.

```
s->  // Method with String parameter and boolean return-type
  s.matches(".*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).")
     //  Validates if the input matches this entire regex

```

Java's String#matches implicitly adds `^...$`.

**Regex explanation:**

```
^.*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).$
^                                          Start of the regex
 .*1.                                       If the number ends in 11-19:
     th                                      it must have a trailing th
       |                                    If not:
        (.*    )?                            Optionally it has leading digits,
           [^1]                              excluding a 1 at the end
                 (1s|2n|3r         .      followed by either 1st, 2nd, 3rd,
                          |[^1-3]t).      0th, 4th, 5th, ..., 8th, or 9th
                                    $   End of the regex

```
> 3 votes

# Answer
# Retina, ~~35~~ 31 bytes

-4 bytes thanks to @Asone Tuhid

Thanks to @Leo for finding a bug

```
1.th|(^|[^1])(1s|2n|3r|[04-9]t)

```

Outputs `1` for true and `0` for false. This assumes the input is in ordinal format with a valid suffix (ends with `st`, `nd`, `rd` or `th`).

Try it online!
> 2 votes

# Answer
# Pyth, ~~49~~ 60 bytesSBCS

```
Js<2zK%J100I||qK11qK12qK13q>2z"th".?qz+J@c."dt8¸*£tÎðÎs"2J

```

**Test suite**

SE ate some unprintables in the code (and in the below explanation) but they're present in the link.

Explanation:
```
Js<2zK%J100I||qK11qK12qK13q>2z"th".?qz+J@c."dt8¸*£tÎðÎs"2J # Code
Js<2z                                                         # J= the integer in the input
     K%J100                                                   # K=J%100
           I||qJ11qJ12qJ13                                    # IF K is 11, 12, or 13:
                          q>2z"th"                            #  Print whether the end of the input is "th"
                                  .?                          # Otherwise:
                                    qz                        #  Print whether the input is equal to
                                      +J                      #   J concatenated with
                                        @                   J #    The object at the Jth modular index of
                                          ."dt8¸*£tÎðÎs"   #     The string "thstndrdthththththth"
                                         c                 2  #      Chopped into strings of length 2 as a list

```
Python 3 translation:
```
z=input();J=int(z[:-2]);K=J%100
if K==11or K==12or K==13:print(z[-2:]=="th")
else:print(z==str(J)+["thstndrdthththththth"[2*i:2*i+2] for i in range(10)][J%10])

```
> 2 votes

# Answer
# Python 2, ~~92~~ ~~82~~ ~~74~~ 68 bytes

-8 thanks to *Chas Brown*
-6 thanks to *Kevin Cruijssen*

```
lambda s:(a+'t'*10+a*8)[int(s[-4:-2]):][:1]==s[-2:-1]
a='tsnr'+'t'*6

```

Constructs a big string of `th`s, `st`s, `nd`s, and `rd`s for endings `00` to `99`. Then checks to see if it matches.
> 2 votes

# Answer
# Jelly,  ~~25~~  22 bytes

-3 bytes thanks to an observation made in a comment made by on my Python entry.

```
ḣ-2VDṫ-’Ạ×ɗ/«4ị“snrh”e

```

A monadic link.

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

### How?

```
ḣ-2VDṫ-’Ạ×ɗ/«4ị“snrh”e - Link: list of characters   e.g. "213rd" or "502nd" or "7th"
ḣ-2                    - head to index -2                "213"      "502"      "7"
   V                   - evaluate                         213        502        7
    D                  - cast to decimal list            [2,1,3]    [5,0,2]    [7]
     ṫ-                - tail from index -1                [1,3]      [0,2]    [7]
           /           - reduce with:                                          (no reduction since already length 1)
          ɗ            -   last 3 links as a dyad:
       ’               -     decrement (the left)           0         -1        x
        Ạ              -     all? (0 if 0, 1 otherwise)     0          1        x
         ×             -     multiply (by the right)        0          2        x
            «4         - minimum of that and 4              0          2        4
              ị“snrh”  - index into "snrh"                 'h'        'n'      'h'
                     e - exists in? (the input list)        0          1        1

```
> 2 votes

# Answer
# Perl 5 `-n`, 57 bytes

```
/..$/;say$&eq(th,st,nd,rd,(th)x6)[$_%100-$_%10-10&&$_%10]

```

Try it online!
> 1 votes

# Answer
# Haskell, 100 bytes

```
f('1':_:a@[_,_])=a=="th"
f(a:b)|length b>2=f b
f(a:"th")|a>'3'=1>0
f x=elem x$words"0th 1st 2nd 3rd"

```

Try it online!
> 1 votes

# Answer
# GeoGebra, 56 bytes

```
s="1nd"
b=Ordinal(FromBase(Take(s,1,Length(s)-2),10))==s

```

Try It On GeoGebra!

Input is `s`, Output is `b`. `b` is `true` if `s` is a valid ordinal, `false` otherwise.

I just realized that GeoGebra has string support, so I had to try it.

### Explanation:

```
Ordinal(FromBase(Take(s,1,Length(s)-2),10))==s
                 Take(s,1,Length(s)-2)                s without the last two characters
        FromBase(                     ,10)            Convert the string to a number
Ordinal(                                  )           Convert the number to ordinal form
                                           ==s        Is it equal to s?

```
> 1 votes

# Answer
# Vyxal, 7 bytes

```
₌Ǎ⌊∆o$c

```

Try it Online!

Because we have a built-in for that.

## Explained

```
₌Ǎ⌊∆o$c
₌Ǎ⌊     # Push the letters and numbers of the input
∆o      # Push the corresponding ordinal string
$c      # are the letters of the string contained in the ordinal string?

```
> 1 votes

# Answer
# Factor \+ `math.text.english`, 37 bytes

```
[ 2 cut* swap dec> ordinal-suffix = ]

```

## Explanation

```
                ! "121th"
2 cut*          ! "121" "th"
swap            ! "th" "121"
dec>            ! "th" 121
ordinal-suffix  ! "th" "st"
=               ! f

```
> 1 votes

# Answer
# Scala, 51 bytes

Port of @Kevin Cruijssen's Java answer in Scala.

Try it online!

```
s=>s.matches(".*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).")

```
> 1 votes

# Answer
# Python 2, ~~94~~ ~~82~~ ~~77~~ ~~73~~ 70 bytes

```
lambda s:'tsnrthtddh'[min(4,int(s[-3])*(('0'+s)[-4]!='1'))::5]==s[-2:]

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 24 bytes

```
0ìþR2£`≠*.•’‘vê₅ù•sèsáнQ

```

Try it online! or as a Test suite

**Explanation**

```
0ì                         # prepend 0 to input
  þ                        # remove letters
   R                       # reverse
    2£                     # take the first 2 digits
      `≠                   # check if the 2nd digit is false
        *                  # and multiply with the 1st digit
         .•’‘vê₅ù•         # push the string "tsnrtttttt"
                  sè       # index into this string with the number calculated
                    sáн    # get the first letter of the input
                       Q   # compare for equality

```
> 0 votes

# Answer
# Ruby, ~~42~~ 39 bytes

Lambda:

```
->s{s*2=~/1..h|[^1](1s|2n|3r|[4-90]t)/}

```

Try it online!

User input:

```
p gets*2=~/1..h|[^1](1s|2n|3r|[4-90]t)/

```

Try it online!

Matches:

* `1(anything)(anything)h` \- `12th`
* `(not 1)1s` \- (`1st`)
* `(not 1)2n` \- (`2nd`)
* `(not 1)3r` \- (`3rd`)

Because `[^1]` (`not 1`) doesn't match the beginning of a string, the input is duplicated to make sure there's a character before the last.

---

# Ruby `-n`, 35 bytes

```
p~/1..h|([^1]|^)(1s|2n|3r|[4-90]t)/

```

Try it online!

Same idea as above but instead of duplicating the string, this also matches the start of the string (`^`).
> 0 votes

# Answer
# Excel, 63 bytes

```
=A1&MID("thstndrdth",MIN(9,2*RIGHT(A1)*(MOD(A1-11,100)>2)+1),2)

```

---

`(MOD(A1-11,100)>2)` returns `FALSE` when `A1` ends with `11`-`13`

`2*RIGHT(A1)*(MOD(A1-11,100)>2)+1` returns `1` if it's in `11`-`13` and `3`,`5`,`7`,etc. otherwise

`MIN(9,~)` changes any returns above `9` into `9` to pull the `th` from the string

`MID("thstndrdth",MIN(~),2)` pulls out the first `th` for inputs ending in `11`-`13`, `st` for `1`, `nd` for `2`, `rd` for `3`, and the last `th` for anything higher.

`=A1&MID(~)` prepends the original number to the ordinal.

---

Posting as wiki since I am not the author of this. (Source)
> 0 votes

# Answer
# Wolfram Language (Mathematica), 122 bytes

Unlike most of the other answers on here, this will actually return false when the input is not a "valid ordinal pattern", so it will correctly return false on input like "3a23rd", "monkey" or "╚§+!". So I think this works for the entire set of possible input strings.

```
StringMatchQ[((d=DigitCharacter)...~~"1"~(e=Except)~d~~(e["1"|"2"|"3",d]~~"th")|("1st"|"2nd"|"3rd"))|(d...~~"1"~~d~~"th")]

```

Try it online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), ~~65~~ 59 bytes

```
SpokenString@p[[#]]~StringTake~{5,-14}&@@ToExpression@#==#&

```

Try it online!

Of course Mathematica has a built-in (although undocumented) for converting to ordinal number. Source.

(for the 65-byte version: according to that it seems that v9 and before doesn't need calling `Speak` before so it may be possible to save some more bytes)

Also check out KellyLowder's answer for a non-builtin version.
> 0 votes

# Answer
# PCRE (Perl-compatible regular expression), 29 bytes

```
1.th|(?<!1)(1s|2n|3r)|[4-90]t

```

We accept `th` after any "teen" number, or after any digit other than 1..3. For 1..3, we use a negative lookbehind to accept `st`, `nd`, or `rd` only when not preceded by `1`.

## Test program

```
#!/usr/bin/bash

ok=(✓ ❌)

for i
do grep -Pq '1.th|(?<!1)(1s|2n|3r)|[4-90]t' <<<"$i"; echo $i ${ok[$?]}
done

```

### Results

```
1st ✓
1th ❌
2nd ✓
2th ❌
3rd ✓
3th ❌
4st ❌
4th ✓
11th ✓
11st ❌
12nd ❌
12th ✓
13th ✓
13rd ❌
112nd ❌
112th ✓
21nd ❌
32nd ✓
33rd ✓
21th ❌
21st ✓
11st ❌
111199231923819238198231923213123909808th ✓

```
> 0 votes

# Answer
# x86 machine code, 65 bytes

```
00000000: 31c0 4180 3930 7cfa 8079 0161 7ef4 8079  1.A.90|..y.a~..y
00000010: ff31 7418 31db 8a19 83eb 308a 9300 0000  .1t.1.....0.....
00000020: 0031 db43 3851 010f 44c3 eb0a 31db 4380  .1.C8Q..D...1.C.
00000030: 7901 740f 44c3 c374 736e 7274 7474 7474  y.t.D..tsnrttttt
00000040: 74                                       t

```

Assembly:

```
section .text
	global func
func:					;the function uses fastcall conventions
					;ecx=first arg to function (ptr to input string)
	xor eax, eax			;reset eax to 0
	read_str:
		inc ecx			;increment ptr to string

		cmp byte [ecx], '0'
		jl read_str		;if the char isn't a digit, get next digit
		cmp byte [ecx+1], 'a'
		jle read_str		;if the char after the digit isn't a letter, get next digit
		cmp byte [ecx-1], '1'
		je tens 		;10-19 have different rules, so jump to 'tens'
		xor ebx, ebx		;reset ebx to 0
		mov bl, byte [ecx]  	;get current digit and store in bl (low byte of ebx)
		sub ebx, 0x30		;convert ascii digit to number
		mov dl, [lookup_table+ebx] ;get correct ordinal from lookup table
		xor ebx, ebx		;reset ebx to 0
		inc ebx			;set ebx to 1
		cmp byte [ecx+1], dl	;is the ordinal correct according to the lookup table?
		cmove eax, ebx		;if the ordinal is valid, set eax (return reg) to 1 (in ebx)
		jmp end			;jump to the end of the function and return

		tens:
		xor ebx, ebx		;reset ebx to 0
		inc ebx			;set ebx to 1
		cmp byte [ecx+1], 't'	;does it end in th?
		cmove eax, ebx		;if the ordinal is valid, set eax (return reg) to 1 (in ebx)

	end:
	ret				;return the value in eax
section .data
	lookup_table db 'tsnrtttttt'

```

Try it online!
> 0 votes

# Answer
# PHP, 60 bytes

boring: regexp once more the shortest solution

```
<?=preg_match("/([^1]|^)(1st|2nd|3rd|\dth)$|1\dth$/",$argn);

```

empty output for falsy, `1` for truthy.

Run as pipe with `-nF` or try it online. (TiO wrapped as function for convenience)
> 0 votes

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