title: N-gram histogram

text:
# Question
Title: N-gram histogram
Given a text and a number `N`, output, in a human readable format, the set of the character N-grams with their respective percentages.

**The smallprint**

* The text can be read from a file, stdin, passed as string parameter to a function or any other common way i forgot to mention
* The number `N` can be hardcoded, but only if it needs to be changed in one single place to change the functionality, the number counts as one byte regardless of the number of digits (`T=input();N=100;f(T,N)` would count as 20 bytes, not 22)
* No case sensitivity and all non-letter characters are treated the same. Inputs `Abra Cadabra!` and `aBRa#caDAbrA5` should produce the same output. The character for non-letter can be any printable non-letter, not necessarily contained in the input
* You may assume `N < text.length`
* Output can be written to a file or displayed on screen. If you use a function you can `return` the result instead of printing as long as it is human readable (a JSON object or array like in the examples below is fine, a custom class or a sparse matrix with `27^N` entries - not so much)

**Examples** with `text = 'Abra Kadabra!'`
`N = 1`

```
a 0.385
b 0.154
r 0.154
_ 0.154
k 0.076923
d 0.076923

```

`N = 12`

```
abra_kababra 0.5
bra_kadabra_ 0.5

```

`N = 2` (dont worry about number format or rounding as long as it sums up to `0.99 < x < 1.01`)

```
ab 0.1666666
br 0.16666
ra 0.1666
a. 0.166667
.k 0.0833333
ka 0.0833333
ad 8.33333e-2
da 0.0833333

```

a tree structure is fine too

```
{'a':{'b':0.166, '.':0.166, 'd': 0.0833},
 'b':{'r':0.166},
 'r':{'a':0.166},
 '.':{'k':0.0833},
 'k':{'a':0.0833},
 'd':{'a':0.0833}}

```

or a list of lists

```
[['A', 'B', 0.166], ['B', 'R', 0.166], ...]

```

# Answer
> 4 votes
# Pyth, ~~40~~ ~~35~~ 27 character

```
KCm>m?k}kGNrz0dQ{m,bc/KblKK

```

Try it online: Pyth Compiler/Executor

For the input `Abra Kadabra!`, `2` it prints something like (the order is each time different, because of the behavior of set):

```
{(('d', 'a'), 0.08333333333333333), (('r', 'a'), 0.16666666666666666), (('b', 'r'), 0.16666666666666666), (('"', 'k'), 0.08333333333333333), (('a', 'b'), 0.16666666666666666), (('k', 'a'), 0.08333333333333333), (('a', '"'), 0.16666666666666666), (('a', 'd'), 0.08333333333333333)}

```

I use `"` as special character.

## Explanation

```
m?k}kGNrz0         implicit: z = raw_input() # input_string
m      rz0         map each character k of z.lower() to:
  k   N                k                     '"'
 ? }kG                    if k in "a-z" else
We call the result X.

KCm>XdQ             implicit: Q = input() # number N
  m   Q             map each d in [0, 1, 2, ..., Q - 1] to:
   >Xd                  X[d:] # all characters of X starting at position d
 C                  zip - creates all N-grams
K                   store the results in variable K

{m,bc/KblKK
 m        K         map each b in K to:
  ,b                    the pair (b,                    )
     /Kb                             K.count(b)
    c   lK                                      / len(K)
{             set - remove duplicates

```

# Printing in a 'human readable format': 35 character

```
KCm>m?k}kG\_rz0dQjbo_eN{m,sbc/KblKK

```

Try it online: Pyth Compiler/Executor

For the input: `Abra Kadabra!`, `2` it prints:

```
('a_', 0.16666666666666666)
('ab', 0.16666666666666666)
('ra', 0.16666666666666666)
('br', 0.16666666666666666)
('ka', 0.08333333333333333)
('da', 0.08333333333333333)
('_k', 0.08333333333333333)
('ad', 0.08333333333333333)

```

## Explanation (differences)

```
\_ instead of N in m?k}kGNrz0
Uses '_' instead of '"'

s in {m,sbc/KblKK
This combines the individual characters

jbo_eN
  o                 order the elements N by:
   _eN                  the value -N[-1] (by the negative percentage)
jb                  join by newlines - prints each pair in row

```

# Answer
> 3 votes
## J, ~~57~~ ~~55~~ 48 characters.

As a dyadic verb, N goes left, text goes right.

```
[:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\

```

Example

```
2 ([:((a.{~97+~.);"#:#/.~%#)((u:97+i.26)i.tolower)\) 'Abra Kadabra!'

```

yields:

```
┌──┬─────────┐
│ab│0.166667 │
├──┼─────────┤
│br│0.166667 │
├──┼─────────┤
│ra│0.166667 │
├──┼─────────┤
│a{│0.166667 │
├──┼─────────┤
│{k│0.0833333│
├──┼─────────┤
│ka│0.0833333│
├──┼─────────┤
│ad│0.0833333│
├──┼─────────┤
│da│0.0833333│
└──┴─────────┘

```

Thanks to randomra for a nine character improvement.

### Explanation

This is the solution with spaces inserted in the appropriate places:

```
[: ((a. {~ 97 + ~.) ;"#: #/.~ % #) ((u: 97 + i. 26) i. tolower)\

```

First, observe that `"#:` is shorthand for `"1 0` and that `u: 97 + i. 26` is just `'abcdefghijklmnopqrstuvwxyz'`, so without these two tricks we get

```
[: ((a. {~ 97 + ~.) ;"1 0 #/.~ % #) ('abcdefghijklmnopqrstuvwxyz' i. tolower)\

```

And this is how this works. In the following explanation, `x` and `y` are the left and right arguments, `u` and `v` are verbs, and `m` and `n` are nouns.

1. `[: u v`—a *capped fork,* `x ([: u v) y` is equal to `u (x v y)`. This is used instead of `u@v` because `v` is an adverbial phrase and parentheses were needed. In this code, `u` is `(a. {~ 97 + ~.) ;"#: #/.~ % #` and `v` is `((u: 97 + i. 26) i. tolower)\`.
2. `x u\ y`—apply `u` to each *infix* of `y` of length `x`. For example, `3 ]\ 'abcdefg'` where `]` is the identity function yields

```
abc
bcd
cde
def
efg

```
3. `n u v`—a fork with a noun as the left argument. `(n u v) y` is equal to `n u (v y)`. This is used multiple times in the code.
4. `tolower y`–convert all upper case letters in `y` to lower case.
5. `x i. y`–find the *index* of `y`, which is in this case for each item in `y` the lowest index into `x` at which that item can be found or the number of items in `x` if such an item does not exist. In our use case, `x` is the lower case alphabet. `('abcdefghijklmnopqrstuvwxyz' i. tolower) y` translated each (upper case or lower case) letter in `y` into a number from 0 to 25. Non-letters are translated into 26. Notice that the character immediately following `z` in ASCII is `{`.
6. `x u/. y`–applies `u` to `y` *keyed* by `x`. That is, `u` is applied to groups of items of `y` with the same key in `x`. Noticeably, if `x` and `y` are equal, `y u/. y` applies `u` to groups of equal items of `y` and can be used to generate frequency statistics.
7. `# y`–the *tally* of `y`, that is, the number of items in `y`.
8. `u~`–the *reflexive* of `u`, that is, `u~ y` is equal to `y u y`.
9. `u v w`–a *fork,* `(u v w) y` is equal to `(u y) v (w y)`. This, too, is used multiple times in the code.
10. `x % y``x` *divided by* `y`.
11. `#/.~ % #`–the frequency count we want sans what we count.
12. `~. y`–the *nub* of `y`, that is, each distinct item of `y`. For instance, `~. 1 2 3 3 4 6 6 6` yields `1 2 3 4 6`.
13. `(a. {~ 97 + ~.) y`–the *nub* of `y` converted from indices into the alphabet back to letters; 26 is converted into `{` implicitly.
14. `x ; y``x` *linked* to `y`, that is, both put into boxes and the boxes concatenated. For instance, `'abc' ; 1 2 3 4` yields

```
┌───┬───────┐
│abc│1 2 3 4│
└───┴───────┘

```

This is needed because in J, arrays are homogeneous; all items in an array need to have same type. A box hides what is in it and turns heterogeneous arrays into arrays of boxes.
15. `u"n``u` *ranked* `n`. Rank is a slightly complex concept so I won't explain it here, but in this case, `x ;"1 0 y` (for which `x ;"#: y` is just a shorthand) applies `;` to each string in `x` and the corresponding number in `y` as opposed to the entire of `x` and the entire of `y`. This is the difference between

```
┌──┬───────────────────────────────────────────────────────────────────────────┐
│ab│0.166667 0.166667 0.166667 0.166667 0.0833333 0.0833333 0.0833333 0.0833333│
│br│                                                                           │
│ra│                                                                           │
│a{│                                                                           │
│{k│                                                                           │
│ka│                                                                           │
│ad│                                                                           │
│da│                                                                           │
└──┴───────────────────────────────────────────────────────────────────────────┘

```

and the correct output shown above.

# Answer
> 2 votes
# CJam, 53 bytes

```
q~el_'{,97>-'_er_,,\f>1$(W*<f<:L__&_@f{\a/,(}L,df/]z`

```

Without having a look at the other CJam answer, here is a shorter one.

Input goes like:

```
2 "Abra Kadabra!"

```

Output is like:

> \[\["ab" 0.16666666666666666\] \["br" 0.16666666666666666\] \["ra" 0.16666666666666666\] \["a\_" 0.16666666666666666\] \["\_k" 0.08333333333333333\] \["ka" 0.08333333333333333\] \["ad" 0.08333333333333333\] \["da" 0.08333333333333333\]\]

Explanation soon.

Try it online here

# Answer
> 2 votes
# BQN, 56 bytes

```
"A[a{"⊸⍋⊸({2|?+16×¬;'_'}¨)⊸{u⋈˘(≠s)÷˜+´˘⍷⟜˘u←⍷s←↕}

```

Anonymous function that takes a string on the left and the number N on the right. It returns a 2-D array, in which each row contains a length-N substring and a 0-D array containing the substring's frequency. Try it at BQN online!

### Explanation

*Wow* this is ugly--and not just because of BQN's total lack of character/string primitives.

The first half normalizes the string argument by converting lowercase letters to uppercase and non-letters to underscores:

```
"A[a{"⊸⍋⊸({2|?+16×¬;'_'}¨)
"A[a{"⊸⍋                        Classify the characters: 0 if < 'A', 1 if >= A but
                                 < '[', and so forth (meaning, in particular, 1 for
                                 uppercase letters and 3 for lowercase letters)
        ⊸(                   )  With that as the left argument and the original
                                string as the right argument,
          {                }¨   call this function on each number-character pair:
           2|?                  If the number is odd (1 or 3):
                    ¬            1 minus the number
                 16×              times 16
               +                 plus the character
                       ;'_'      Else, underscore

```

Now the actual meat of the function:

```
⊸{u⋈˘(≠s)÷˜+´˘⍷⟜˘u←⍷s←↕}
⊸{                          }  Pass the left argument through the above function
                               before calling this function:
                        ↕    Get all length-(right arg) substrings of (left arg)
                      s←       Save that 2D array of characters as s
                     ⍷         Deduplicate
                   u←          Save that 2D array of characters as u
              ⍷⟜˘            For each row of u, find all occurrences of that
                               substring in the left arg; mark the beginning of
                               an occurrence with a 1, all other positions with a 0
           +´˘                 Sum each row, giving a list of occurrence counts
         ÷˜                    Divide each by
     (≠s)                      the length of s
   ⋈˘                          Pair each with
  u                            the corresponding unique substring

```

# Answer
> 1 votes
# CJam, ~~61~~ 59 bytes

I think the input transformation is quite nifty, but the actual tallying needs work.

```
l~qeu'~),_el&'_er_,,2$f{2$@><\}\W*<:L__&\f{1$a/,(L,d/][};]`

```

Reads `N` on the first line and then treats the remainder of STDIN as the text:

```
2
Abra Kadabra!

```

The result is printed as a nested CJam-style array with upper case letters and `_` for non-letters:

```
[["AB" 0.16666666666666666] ["BR" 0.16666666666666666] ["RA" 0.16666666666666666] ["A_" 0.16666666666666666] ["_K" 0.08333333333333333] ["KA" 0.08333333333333333] ["AD" 0.08333333333333333] ["DA" 0.08333333333333333]]

```

Test it here.

# Answer
> 1 votes
# Haskell, 164 bytes

```
import Data.Char
import Data.List
l=genericLength
c c|isAlpha c=toLower c|1<2='_'
n%i=[(s!!0,l s/l p)|s<-group p]where p=sort[take n s|s<-tails$map c i,length s>=n]

```

Usage: `12 % "Abra Kadabra!"` -\> `[("abra_kadabra",0.5),("bra_kadabra_",0.5)]`

This is longer than I thought. Does anyone know a shorter version of a "split list into sublists of length n" function (my attempt: `[take n s|s<-tails$ i,length s>=n]`)?

How it works:

* map all characters in the input list to lowercase or '\_' if not a letter
* split into a list of substrings of length n
* sort, name the list `p`
* group equal elements (e.g. for n=2 -\> `[["_k"],["a_","a_"],["ab","ab"],["ad"],["br","br"],["da"],["ka"],["ra","ra"]]`
* for each sublist take one of it's elements and pair it with the length divided by the length of p

# Answer
> 1 votes
# Mathematica, ~~124~~ 119 bytes

Could probably golf further.

```
#[[1]]->#[[2]]&/@#/Length@#&@Tally@Partition[Characters@StringReplace[ToLowerCase@#,Except@LetterCharacter->"_"],#2,1]&

```

# Answer
> 1 votes
# Clip 10, 53

```
\[tm[b{(b/)b)mlxt`}q[bm[juj+jtb}R)mlbt]a[!cA}m.U`xS]n

```

Example:

```
C:\Users\~~~~~\Documents>java -jar Clip10.jar ngram.clip
Abra Kadabra!
2
{{"AB", 0.166666666666666}, {"A ", 0.166666666666666}, {"RA", 0.166666666666666}, {"BR", 0.166666666666666}, {"DA", 0.083333333333333}, {" K", 0.083333333333333}, {"KA", 0.083333333333333}, {"AD", 0.083333333333333}}

```

## Explanation

```
 [t                                               ]n .- Assign the second input to t -.
                                            m.U`x    .- Convert the input to upper case -.
                                      a[!cA}     S   .- Replace all non-alphabetic characters with spaces -.
                   [b                ]               .- Assign the modified string to b -.
                     m[juj+jtb}R)mlbt                .- All substrings of length t -.
                  q                                  .- Frequencies (in the form {"A", 1} )-.
   m[b{(b/)bmlxt`}                                   .- Use proportional frequencies
\                                                    .- Make the array pretty -.

```

# Answer
> 1 votes
# APL (Dyalog Classic) with MiServer's `Strings.lc`, 30 bytes

Prompts for text, then for `N`. Prints N-grams and frequencies.

```
(∪,⊢∘≢⎕U2338÷≢)⎕,/'\W'⎕R'_'lc⍞

```

Try it online!

Only 25 characters (but 44 bytes) in Dyalog Unicode:

```
(∪,⊢∘≢⌸÷≢)⎕,/'\W'⎕R'_'lc⍞

```

… because `⎕U2338`, but is not included in the Classic character set.

### Explanation

get text input

`lc`**l**ower**c**ase

`'\W'⎕R'_'` PCRE **R**eplace non-word characters with underscores

`,/` concatenate the characters in each possible position of a sliding window of size

number-input

`(``)` apply the following anonymous tacit function on that (the N-grams):

the unique (N-grams)

`,` followed by

`⊢∘≢⌸` the number occurrences for each unique element (of the N-grams)

`÷` divided by

the tally (of N-grams)

# Answer
> 1 votes
# Ruby, 86 bytes

```
->s,n{s.upcase.gsub(/[^A-Z]/,?_).chars.each_cons(n).tally.map{[_1,_2/(s.size-n+1.0)]}}

```

Attempt This Online!

# Answer
> 1 votes
# Python, 92 bytes

```
lambda s,k:(b:=1+len(s)-k)//b*(a:=[s[i:i+k]for i in range(b)])and{t:a.count(t)/b for t in a}

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 24 bytes

```
„üÿUáмS¡'_ýlDX.VÙDŠ¢DO/ø

```

Inputs in the order `N, text`. Outputs as a list of \[string, decimal\] pairs. A trailing `»` (+1 byte) could be added to pretty-print them to STDOUT.

Try it online or verify all test cases.

**Explanation:**

```
„üÿ       # Push string "üÿ", where `ÿ` is automatically replaced with the first
          # (implicit) input-integer
   U      # Pop and store this string in variable `X`
á         # Only keep all letters of the second (implicit) input-string
 м        # Remove all those letters from the second (implicit) input-string
  S       # Convert the remaining string of characters to a list
   ¡      # Split the second (implicit) input-string on those characters
    '_ý  '# Join it with "_" delimiter
       l  # Convert this string to lowercase
D         # Duplicate the string
 X        # Push string `X` we created earlier
  .V      # Evaluate and execute it as 05AB1E code,
          # creating overlapping substrings of size `N`
    Ù     # Uniquify this list
D         # Duplicate the unique substrings
 Š        # Triple-swap from a,b,b to b,a,b
  ¢       # Pop the string and list, and count how many times each string occurs
   D      # Duplicate the list of counts
    O     # Sum it together
     /    # Divide the individual counts by the sum
      ø   # And pair it with the substrings we've duplicated
»         # (Optional) join each pair by spaces, and then each string by newlines
          # (after which the result is output implicitly)

```

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


title: Reduce using the lowest value

text:
# Question
Title: Reduce using the lowest value
**The challenge**

Create a function which takes an array of numbers and subtract from each element the lowest element in the array that has not yet been subtracted from another.

* After using the lowest value, It can not be used again.
* Numbers in the array are decimal numbers, and not necessarily integers.

**Example:**

```
Input: [6, 4, 7, 8, 9, 2, 1, 4]

Next lowest value:          Output:
[6, 4, 7, 8, 9, 2, 1, 4]    [6, 4, 7, 8, 9, 2, 1, 4]
                   ^         ^
                            6-1 = 5
[6, 4, 7, 8, 9, 2, -, 4]    [5, 4, 7, 8, 9, 2, 1, 4]
                ^               ^
                            4-2 = 2
[6, 4, 7, 8, 9, -, -, 4]    [5, 2, 7, 8, 9, 2, 1, 4]
    ^                              ^
                            7-4 = 3
[6, -, 7, 8, 9, -, -, 4]    [5, 2, 3, 8, 9, 2, 1, 4]
                      ^               ^
                            8-4 = 4
[6, -, 7, 8, 9, -, -, -]    [5, 2, 3, 4, 9, 2, 1, 4]
 ^                                       ^
                            9-6 = 3
[-, -, 7, 8, 9, -, -, -]    [5, 2, 3, 4, 3, 2, 1, 4]
       ^                                    ^
                            2-7 = -5
[-, -, -, 8, 9, -, -, -]    [5, 2, 3, 4, 3,-5, 1, 4]
          ^                                    ^
                            1-8 = -7
[-, -, -, -, 9, -, -, -]    [5, 2, 3, 4, 3,-5,-7, 4]
             ^                                    ^
                            4-9 = -5

Final output: [5, 2, 3, 4, 3, -5, -7, -5]

```

**Test Cases**

`Input: [6, 4, 7, 8, 9, 2, 1, 4] => Output: [5, 2, 3, 4, 3, -5, -7, -5]`

`Input: [4, 7, 4, 9, -10, 8, 40] => Output: [14, 3, 0, 2, -18, -1, 0]`

`Input: [0.25, -0.5, 8, 9, -10] => Output: [10.25, 0, 7.75, 1, -19]`

`Input: [3, 4, 9, 1, 1, 1, -5] => Output: [8, 3, 8, 0, -2, -3, -14]`

---

This is , so the shortest answer in bytes win.

# Answer
# Jelly, 2 bytes

```
_Ṣ

```

Try it online!

or Try all test cases

```
_   # Subtract from...
 Ṣ  # The input array sorted

```
> 15 votes

# Answer
# MATL, 3 bytes

```
tS-

```

Try it online!

```
(implicit input as an array)
t                              # duplicate
 S                             # sort
  -                            # element-wise subtract
(implicit output)

```
> 5 votes

# Answer
# Husk, 4 bytes

```
Ṡz-O

```

Try it online!

**Explanation**

```
      -- input, e.g. [6,4,7,8,9,2,1,4]
   O  -- sort        [1,2,4,4,6,7,8,9]
Ṡz-   -- element wise difference to input: [6-1,4-2,7-4,8-4,9-6,2-7,1-8,4-9]
      -- return result [5,2,3,4,3,-5,-7,-5]

```
> 4 votes

# Answer
# Prolog (SWI), ~~93~~ ~~80~~ 68 bytes

```
[H|T]/[A|B]/[X|Y]:-X is H-A,(T=[],Y=T;T/B/Y).
X*Y:-msort(X,S),X/S/Y.

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 44 bytes

```
a=>[...a].map(x=>x-a.sort((a,b)=>b-a).pop())

```

Try it online!

### Commented

```
a =>                 // given the input array a[]
  [...a]             // create a copy of a[]
  .map(x =>          // for each integer x in the copy:
    x -              //   update x by ...
    a.sort((a, b) => //     sorting the original array in descending order
      b - a          //     (we only need to sort it once, but it's shorter to do it here)
    ).pop()          //     taking the element at the top of a[] and subtracting it from x
  )                  // end of map()

```
> 3 votes

# Answer
# Python 3, ~~42~~ 40 bytes

~~`lambda a:[b-c for b,c in zip(a,sorted(a))]`~~

```
lambda a:[a.pop(0)-b for b in sorted(a)]

```
> 3 votes

# Answer
# Japt, ~~8~~ ~~6~~ 4 bytes

```
í-Uñ

```

Try it here

---

## Explanation

```
           :Implicit input of array U
c          :Flatten (simply creates a 2nd copy of the array because JavaScript's sort mutates the original array)
  í        :Interleave
    Un     :U sorted
   -       :Reduce each pair by subtraction

```
> 3 votes

# Answer
# Ruby, 32 chars

```
->a{a.zip(a.sort).map{|x,y|x-y}}

```
> 3 votes

# Answer
# Java 10, 83 bytes

```
a->{var b=a.clone();java.util.Arrays.sort(b);for(int i=0;i<a.length;a[i]-=b[i++]);}

```

Modifies the input-array instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
a->{                         // Method with double-array parameter and no return-type
  var b=a.clone();           //  Create a copy of the input-array
  java.util.Arrays.sort(b);  //  Sort this copy
  for(int i=0;i<a.length;    //  Loop over the indices
    a[i]-=                   //   Subtract from the `i`'th item in the input-array:
          b[i++]);}          //    The `i`'th item of the sorted array

```
> 3 votes

# Answer
# , 18 bytes

```
(x=scan())-sort(x)

```

Try it online!

Does what it says :)
> 3 votes

# Answer
# Haskell, 34 bytes

```
import Data.List
zipWith(-)<*>sort

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 2 bytes

```
{-

```

Try it online or verify all test cases.

**Explanation:**

```
{     # Sort the input-array
 -    # Subtract all values in this sorted array from the input-array

```
> 2 votes

# Answer
# , 4 bytes

```
-/:~

```

Try it online!

## Explanation:

From the argument subtract `-` the sorted `/:~` argument
> 2 votes

# Answer
# Common Lisp, 46 bytes

```
(lambda(x)(mapcar #'- x(sort(copy-seq x)#'<)))

```

Try it online!
> 2 votes

# Answer
# Coconut, 23 bytes

```
a->map((-),a,sorted(a))

```

Try it online!
> 2 votes

# Answer
# Perl 6, 15 bytes

```
{@^a Z-@a.sort}

```

Try it online!

Anonymous function that takes one list and returns a list.
> 2 votes

# Answer
# Julia 0.6, 12 bytes

```
A->A-sort(A)

```

Try it online!
> 2 votes

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

```
{x-x@<x}

```

Try it online!
> 2 votes

# Answer
# Japt, 9 bytes

```
íNc n
®r-

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
ÿ◙┘¿N

```

Run and debug it

To show how it works, here's the unpacked, commented version.

```
m       for each element execute, then pop and print:
  xo    sort the original input
  i@    index into array using iteration index
  -     subtract

```

Run this one
> 1 votes

# Answer
# SmileBASIC, 49 bytes

```
DEF R A
DIM B[0]COPY B,A
SORT B
ARYOP 1,A,A,B
END

```

The input array is modified in place.

`ARYOP` does operations on entire arrays at once. In this case it subtracts `B` from `A` and stores the result in `A`.
> 1 votes

# Answer
# PHP, 86 bytes

```
function f($a){$b=$a;sort($b);return array_map(function($x,$y){return $y-$x;},$b,$a);}

```

Try it online!
> 0 votes

# Answer
# Tcl, 49 bytes

```
proc S L {lmap n $L m [lsort -r $L] {expr $n-$m}}

```

Try it online!
> 0 votes

# Answer
# Factor, 23 bytes

```
[ dup natural-sort v- ]

```

Attempt This Online!
> 0 votes

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


title: Bleeeet Bleeeet Bl Bleet!

text:
# Question
Title: Bleeeet Bleeeet Bl Bleet!
(Meaning: Convert English to Bleet)

We have praised goats as god for years now.

But if we can't translate English to 'Bleet', the Goat God's language, we cannot communicate with them.

So, to communicate with them, we have researched the activities of goats, and retrieved this pattern, which is the core of the language.

> Say 'Bleet' for the length of each words. That means the amount of 'e's should be (length-3) for words longer than 3 letters.You shall cut down 'Bleet' for words shorter than 'Blt'. For example, 'be' becomes 'bl', but 'cat' and 'boat' becomes 'blt' and 'blet'.

As it seems, they don't actually change non-alphabet characters to 'Bleet'. Our research showed that 'Hello, World!' to Bleet is 'Bleet, Bleet!' not 'Bleeet Bleeet'. Also, The goats are not so intelligent(no offense), so they don't seem to understand non-ascii characters or diacritics at all.

Now, It's time to make a translator to communicate with the goat gods.

## Bleeeeet (Meaning: Examples)

```
Hello, World! => Bleet, Bleet!
lorem ipsum dolor sit amet. => Bleet Bleet Bleet Blt Blet.
We praise the Goat God! => Bl Bleeet Blt Blet Blt!
I have a pen => B Blet B Blt
0123456789_ => 0123456789_
0te_st1 => 0Bl_Bl1

```

# Answer
> 13 votes
## Retina, 31 bytes

```
T`lL`e
(?<!e)e
B
Be
Bl
e(?!e)
t

```

Try it online!

### Explanation

```
T`lL`e

```

Turn all letters into `e`s.

```
(?<!e)e
B

```

Turn the first `e` in each run into `B`.

```
Be
Bl

```

Turn `Be` into `Bl`.

```
e(?!e)
t

```

Turn the last `e` in each run into `t`.

# Answer
> 4 votes
# JavaScript (ES6), ~~79~~ ~~77~~ 74 bytes

```
s=>s.replace(/[A-Z]+/gi,x=>x.replace(/./g,(_,i)=>'Bl'[i]||'et'[+!x[i+1]]))

```

Alternate approach, currently ~~83~~ 78 bytes:

```
s=>s.replace(/[A-Z]+/gi,x=>`Bl${'e'.repeat((l=x.length)>3&&l-3)}t`.slice(0,l))

```

The best I could do recursively was 88 bytes:

```
f=([c,...s],i=0,q=/^[A-Z]/i)=>c?q.test(c)?('Bl'[i]||'te'[+q.test(s)])+f(s,i+1):c+f(s):''

```

# Answer
> 4 votes
# PHP, ~~115~~ ~~88~~ ~~86~~ ~~77~~ 75 bytes

`preg_replace` with arrays (requires PHP 5.4 or later)

```
echo preg_replace(["#[a-z]#i","#(?<!e)e#",_Be_,"#e(?!e)#"],[e,B,Bl,t],$argn);

```

Run with `echo '<string>' | php -nR '<code>'` or test it online.

**breakdown**

```
SEARCH      EXPLANATION             REPLACE     EXAMPLE
            original string                     Hello
[a-z]       every letter            e           eeeee
(?<!e)e     first letter            B           Beeee
Be          first two letters       Bl          Bleee
e(?!e)      last letter if still e  t           Bleet

```

Revision 5: saved 9 bytes with Martin Ender´s regex chain.
(That also fixed cases with non-alphabetic word characters = digits/underscores.)

# Answer
> 3 votes
# Haskell, ~~135~~ 128 bytes

```
b"e"="B"
b"ee"="Bl"
b('e':_:_:e)="Bl"++e++"t"
b e=e
e!(l:t)|elem l$['a'..'z']++['A'..'Z']=('e':e)!t|1<3=b e++l:""!t
e!_=[]
(""!)

```

Try it online! Usage `(""!) $ "some string"`. Without regexes, this turned out to be quite long, maybe some other approach is shorter. Edit: Saved 7 bytes thanks to @nimi!

# Answer
> 2 votes
# PHP, 84 Bytes

```
<?=preg_replace(["#[a-z]#i","#(?<!l)l#","#(?<=l)l#","#e(?!e)#"],[l,B,e,t],$argv[1]);

```

# PHP, 117 Bytes

```
<?=preg_replace_callback("#[a-z]+#i",function($m){return substr(str_pad(Bl,-1+$l=strlen($m[0]),e).t,0,$l);},$argv[1]);

```

# Answer
> 2 votes
# Perl 5, 47 bytes

Saved 15 bytes by using the same technique as Martin Ender's Retina answer. (This answer is basically a port of his answer now)

46 bytes of code + `-p` flag.

```
s/\pl/e/g;s/(?<!e)e/B/g;s/Be/Bl/g;s/e(?!e)/t/g

```

Try it online!

---

Older versions: 62 bytes:

```
s/\pl+/$l=length$&;$_=Bl.e x($l-3).t;chop while$l<y%%%c;$_/ge

```

And 68 bytes:

```
s%\pl+%$_=$&;s/./B/;s/.\K./l/;s/(?<=..).(?=.)/e/g;s/..\K.$/t/;$_%ge

```

# Answer
> 2 votes
# C, ~~120~~ ~~151~~ ~~140~~ ~~111~~ ~~108~~ ~~105~~ ~~104~~ ~~92~~ 90 Bytes

Working for "It's Jimmy's test" --\> Bl'B Bleet'B Blet

```
j;f(char*m){for(;*m=!isalpha(*m++)?j=0,*(m-1):"*Blet"[isalpha(*m)?j^3?++j:j:j>1?4:++j];);}

```

The output is now a side effect by destroying the original string.

```
main(c,v)char**v;{
    char test[] = "The End is near Fellows!";
    f(test);puts(test);
    char test2[] = "We praise the Goat God!";
    f(test2);puts(test2);
    char test3[] = "It's Jimmy's test";
    f(test3);puts(test3);
    char test4[] = "0te_st1";
    f(test4);puts(test4);
    char test5[] = "I have a pen";
    f(test5);puts(test5);
    char test6[] = "_0123456789_";
    f(test6);puts(test6);
}

```

I think it's correct at least now

```
Blt Blt Bl Blet Bleeeet!
Bl Bleeet Blt Blet Blt!
Bl'B Bleet'B Blet
0Bl_Bl1
B Blet B Blt
_012345678_

```

# Answer
> 2 votes
# Python 2.7, 129 118 114 109 95 91 88 bytes

```
import re
s=re.sub
def f(i):print s(r"e\b","t",s("Be","Bl",s(r"\be","B",s("\w","e",i))))

```

Just an `re.sub` chain

### Step by step

Example input: "**We praise the Goat God!**"

---

**Alias sub so we can save bytes on repeated calls**

```
import re
s=re.sub

```

**Replace all word characters with "e"**

`s("\w","e",i)`

Output: `ee eeeeee eee eeee eee!`

**Replace all "e"s which are preceded by a word boundary (Beginning of word) with "B"**

`s(r"\be","B",s("\w","e",i))`

Output: `Be Beeeee Bee Beee Bee!`

**Replace all "Be" with "Bl"**

`s("Be","Bl",s(r"\be","B",s("\w","e",i)))`

Output: `Bl Bleeee Ble Blee Ble!`

**Replace all "e"s which are followed by a word boundary with "t"**

`s(r"e\b","t",s("Be","Bl",s(r"\be","B",s("\w","e",i))))`

Output: `Bl Bleeet Blt Blet Blt!`

# Answer
> 1 votes
# Python 3, 271 bytes

I am aware that this is rather long and I welcome suggestions on how to reduce the length.

```
def f(s):
 b=[];t='';f=[];a=list.append
 for c in s:
  if c.isalpha():t+='e'
  else:
   if t:a(b,t);t=''
    a(b,c)
 if t:a(b,t)
 for i in b:
  i=[*i]
  if i[0]=='e':
   i[0]='B';i[-1]=[i[-1],'t'][len(i)>2]
   if len(i)>2:i[1]='l'
  a(f,''.join(i))
 return ''.join(f)

```

# Answer
> 1 votes
# Python 2, ~~137~~ 114 bytes

```
def f(s,r='',l=-3):
 for c in s+'\0':
	if c.isalpha():l+=1
	else:r+=('Bl%st'%('e'*l))[:l+3*(l>=0)]+c;l=-3
 print r

```

Try it online!

# Answer
> 1 votes
# Pip, 28 bytes

```
aR+XA{Y'eX#a-3\"Bl\yt\"@<#a}

```

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

### Explanation

This was fun--I got to use regex modifiers and string interpolation.

```
                              a is 1st cmdline arg; XA is the regex `[A-Za-z]` (implicit)
aR                            In a, replace
   XA                          the regex XA
  +                            wrapped in (?:  )+
     {                     }  with this callback function:
          #a-3                 Length of argument - 3
       'eX                     Repeat e that many times (empty string if #a-3 is negative)
      Y                        Yank that string into the y variable
              \"Bl\yt\"        An escaped string, which interpolates the value of y
                       @<#a    Take first len(a) characters
                              After the replacement, the string is autoprinted

```

# Answer
> 1 votes
# stacked, 57 bytes

```
'\l+'{!n size 2-:4\^5*1+3/\1<-4 tb 0\,'Blet'\#''join}repl

```

Try it online! Takes input from the top of the stack.

Let **a**(**n**) = A136412(**n** \- 2) = (5 × 4**n** − 2 \+ 1) ÷ 3. Converting **a**(**n**) to base 4 yields:

```
a(3) = 13<sub>4</sub>
a(4) = 123<sub>4</sub>
a(5) = 1223<sub>4</sub>
a(6) = 12223<sub>4</sub>
...

```

Mapping indices 0..3 to the string `Blet`, we get:

```
a(3) = lt
a(4) = let
a(5) = leet
a(6) = leeet
...

```

Now, prepending `B` gives us the desired string, given the length. Mostly. One just needs to handle the special cases for **n** ≤ 2. In my case, this is solved by subtracting (**n** − 2 \< 1) as a numeric boolean (1 for "true" and 0 for "false").

As for the specifics of the answer:

```
'\l+'{! ... }repl
             repl    replace all
'\l+'                alphanumeric strings ("letters")
     {!     }        applying this function to the result.

```

# Answer
> 0 votes
# Java 7, 201 bytes

```
String c(String s){String r="",z="e([^e]|$)";char p=0;int x;for(char c:s.toCharArray()){x=c&~32;p=x>64&x<91?p==66?'l':p>100&p<109?'e':66:c;r+=p;}return r.replaceAll("l"+z,"lt$1").replaceAll(z,"et$1");}

```

Not really happy with it, and can certainly be golfed some more..

**Explanation:**

```
String c(String s){               // Method with String parameter and String return-type
  String r="",                    //  The return-String
         z="e([^e]|$)";           //  Partial regex String that's used twice ('e' followed by non-'e' or nothing)
  char p=0;                       //  The previous character
  int x;                          //  Another temp value
  for(char c : s.toCharArray()){  //  Loop over the characters of the input String
    x = c&~32;                    //   Make every lowercase character uppercase (this returns an integer, hence the integer temp value, which is shorter than a cast to char)
    p = x>64 & x<91 ?             //   If the current character is a letter:
         p == 66 ?                //    And if the previous character is 'B':
          'l'                     //     Set the character value to 'l'
         : p>100&p<109 ?          //    Else if the previous character is either an 'e' or 'l':
            'e'                   //     Set the character value to 'e'
           :                      //    Else:
            66                    //     Set the character value to 'B'
         :                        //   Else (not a letter):
          c;                      //    Set the character to the current character
    r += p;                       //   Append the result-String with this character
  }                               //  End loop
  return r                        //  Return the result-String
    .replaceAll("l"+z,"lt$1")     //   After we've replaced all occurrences of "le." with "lt." (where "." can be anything else, including nothing at the end of a line)
    .replaceAll(z,"et$1")         //   And also replaced all occurrences of "ee." with "et." (where "." can again be anything else)
}                                 // End of method

```

**Test code:**

Try it here.

```
class M{
  static String c(String s){String r="",z="e([^e]|$)";char p=0;int x;for(char c:s.toCharArray()){x=c&~32;p=x>64&x<91?p==66?'l':p>100&p<109?'e':66:c;r+=p;}return r.replaceAll("l"+z,"lt$1").replaceAll(z,"et$1");}

  public static void main(String[] a){
    System.out.println(c("Hello, World!"));
    System.out.println(c("lorem ipsum dolor sit amet."));
    System.out.println(c("We praise the Goat God!"));
    System.out.println(c("I have a pen"));
    System.out.println(c("0123456789_"));
    System.out.println(c("0te_st1"));
  }
}

```

**Output:**

```
Bleeet, Bleeet!
Bleeet Bleeet Bleeet Blt Bleet.
Bl Bleeeet Blt Bleet Blt!
B Bleet B Blt
0123456789_
0Bl_Bl1

```

# Answer
> 0 votes
# 05AB1E, 36 bytes

```
lDAsSå.¡€g£vyAySåPigÍ<'e×"Blÿt"yg£}J

```

Try it online! or as a Test suite

**Explanation**

Prepare input:

```
lD                                    # convert input to lower-case and duplicate
  As                                  # push lower-case alphabet and swap input to the top
    Så                                # check each char in input for
                                      # membership in the alphabet
      .¡                              # split into chunks of equal elements
        €g                            # get length of each chunk
          £                           # split input into chunks of those lengths

```

This creates a list such as `['hello', ', ', 'world', '!']` for the input `Hello, World!`

Iterate over list:

```
v                          # for each element in the list
 y                         # push current element
  AySåPi               }   # if all members of current element are letters
        gÍ<'e×             # repeat string "e" len(element)-3 times
              "Blÿt"       # replace "ÿ" with the e's in the string "Blÿt"
                    yg£    # take the first len(element) chars of the string
                        J  # join to string

```

# Answer
> 0 votes
# sed `-E`, 58 bytes

Port of Martin Ender's Retina answer.

```
s/[a-z]/e/gi
s/(^|[^e])e/\1B/g
s/Be/Bl/g
s/e([^e]|$)/t\1/g

```

Attempt This Online!

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


# Question
Title: Looking back at all the things I said ...
The look-say sequence is a sequence of lists of numbers where each element is the previous element with run length encoding. Run length encoding is the process of grouping together like elements and then giving the element and the size of the group for each group. So for example:

```
1 1 1 2 2 1

```

To run length encode this we group like elements together

```
1 1 1 | 2 2 | 1

```

And then replace each group with its size and the element:

```
3 1 | 2 2 | 1 1

```

Then we concatenate these back together:

```
3 1 2 2 1 1

```

The look-say sequence starting from just `1` goes:

```
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
3 1 1 3 1 2 1 1 1 3 1 2 2 1
1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1
...

```

But we can start with different values. For example we could start with `2`

```
2
1 2
1 1 1 2
3 1 1 2
1 3 2 1 1 2
1 1 1 3 1 2 2 1 1 2
3 1 1 3 1 1 2 2 2 1 1 2
1 3 2 1 1 3 2 1 3 2 2 1 1 2
1 1 1 3 1 2 2 1 1 3 1 2 1 1 1 3 2 2 2 1 1 2

```

Or we could even start it with `3 3 3`:

```
3 3 3
3 3
2 3
1 2 1 3
1 1 1 2 1 1 1 3
3 1 1 2 3 1 1 3
1 3 2 1 1 2 1 3 2 1 1 3
1 1 1 3 1 2 2 1 1 2 1 1 1 3 1 2 2 1 1 3

```

In this task you are going to be given a sequence and your job will be to trace it back as far as you can to get a starting point. That is you are going to undo operations until you get a list of numbers that could not have been produced by run length encoding another list.

As some examples:

* `3 3 3` is not a possible run length encoding since it has an odd number of terms.
* `1 2 2 2` is not a possible run length encoding since expanding it out gives `2 2 2` which would be encoded as `3 2` instead.

As input you will receive a list of positive integers less than 4. You should output all the terms of the look-say sequence up to and including the input. Your output may be in forwards or backwards order.

There is one case where the input can be traced back indefinitely `2 2`. What your program does on this input is undefined behavior.

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

## Test cases

```
1:
1

1 1 1 2 1 1 1 3:
3 3 3
3 3
2 3
1 2 1 3
1 1 1 2 1 1 1 3

1 2 2 1 1 3 1 1 1 2:
1 2 2 2
1 1 3 2
2 1 1 3 1 2
1 2 2 1 1 3 1 1 1 2

1 2 1 3 1 2 1 1:
3 3 3 1 1 1
3 3 3 1
3 3 1 1
2 3 2 1
1 2 1 3 1 2 1 1

```

# Answer
> 7 votes
# Pyth, ~~19~~ 16 bytes

-3 bytes thanks to Mukundan314

```
W.A.+%2t
Q=r9cQ2

```

Try it online!

Prints in reverse order.

### Explanation

```
W                   while:
 .A                    zero is not in
   .+                  the deltas of
     %2tQ              every second element of implicitly printed Q
          =r9cQ2    set Q to the length decoding of itself

```

# Answer
> 6 votes
# Excel (ms365), 374 bytes

Formula in `A3`:

```
=LET(x,CONCAT(1:1),y,TOCOL(SCAN(x,SEQUENCE(1048575),LAMBDA(a,b,LET(c,SEQUENCE(LEN(a)/2,,,2),IF(ISODD(LEN(a)),NA(),CONCAT(REPT(MID(a,c+1,1),MID(a,c,1))))))),3),z,MAP(y,LAMBDA(d,LET(e,SEQUENCE(LEN(d)),f,MID(d,e,1),g,TEXTSPLIT(CONCAT(f&IF(f<>MID(d,e+1,1),"|","")),"|",,1),CONCAT(LEN(g)&LEFT(g))))),MID(FILTER(VSTACK(x,y),VSTACK(1,z=VSTACK(x,DROP(y,-1)))),SEQUENCE(1,LEN(x)),1))

```

All one has to do is change the input in 1st row.

* 'x-varibale' - `CONCAT(1:1)` \- Concatenate all values from row 1 into a string;
* 'y-variable' - `TOCOL(SCAN(x,SEQUENCE(1048575),LAMBDA(a,b,LET(c,SEQUENCE(LEN(a)/2,,,2),IF(ISODD(LEN(a)),NA(),CONCAT(REPT(MID(a,c+1,1),MID(a,c,1))))))),3)` \- Will go over 1048575 possibilities (max rows in ms365 if one include the input at the end) and will get each number from every even position and repeat it n-times where n == its neighboring digit on the left;
* 'z-variable' - `MAP(y,LAMBDA(d,LET(e,SEQUENCE(LEN(d)),f,MID(d,e,1),g,TEXTSPLIT(CONCAT(f&IF(f<>MID(d,e+1,1),"|","")),"|",,1),CONCAT(LEN(g)&LEFT(g)))))` \- Loop over elements from y and reverse it's value into it's logical predecessor;
* `MID(FILTER(VSTACK(x,y),VSTACK(1,z=VSTACK(x,DROP(y,-1)))),SEQUENCE(1,LEN(x)),1)` \- Finally we can check each value against the elements in y and filter what is not a possible run length encoding string. All strings are then cut into seperate integers again.

No doubt other Excel-fanatics can beat this, but my brain is fried! I'm not even sure an answer like this length belongs on CG...

# Answer
> 3 votes
# Pip `-p`, 33 bytes

```
T$|_=BMPDQUWg|%#gg:_@1RL@_MF<>Pgg

```

Takes the initial sequence as separate command-line arguments; prints the sequences from there on back as far as possible to stdout as lists. Try It Online!

### Explanation

The basic structure of the program is

```
T <cond> <body> g

```

that is, loop until `<cond>` becomes true, executing `<body>` each time, and at the end of the loop, output the final value of `g`. (The original value of `g` is a list of the command-line arguments.)

The condition is:

```
$|_=BMPDQUWg|%#g
         UWg      Unweave g into two lists, each containing every other value
       DQ         Get the latter of the two (the values at odd indices)
     MP           Map this function to each adjacent pair of values in that list:
  _=B               The first equals the second
$|                Fold on logical OR: true if any of the equality checks are true
            |     OR:
              #g  The length of g
             %    Is odd

```

The loop body is:

```
g:_@1RL@_MF<>Pg
             Pg  Print the current value of g
           <>    Group into chunks of length 2
         MF      Map this function to each chunk and flatten the resulting list:
       @_          The first number in the chunk
     RL            Create a list containing that many copies of
  _@1              The second number in the chunk
g:               Assign the resulting list back to g

```

# Answer
> 3 votes
# MATL, ~~18~~ 17 bytes

*This uses CursorCoercer's idea of testing if increments are zero.*

The output is in backwards order.

```
`t0h2L&)Y"6Mdyh]x

```

Verify test cases: , , , .

### Explanation

```
`         % Do... while
  t       %   Duplicate current list of numbers (*). This takes input implicitly in
          %   the first iteration
  0h      %   Append a 0
  2L&)    %   Push the subarray of entries at (1-based) even positions (**), then
          %   the subarray of entries at odd positions (***)
  Y"      %   Run-length decoding using those two subarrays as inputs, cyclically
          %   reusing the shorter of the two if needed. The result will contain
          %   zeros if and only if (*) had odd length
  6M      %   Push (**) again
  d       %   Consecutive differences
  y       %   Duplicate from below: pushes again the result of run-length decoding
  h       %   Concatenate horizontally
]         % End. A new iteration is run of the top of the stack contains no zeros
x         % Delete. This removes the last array, which is not valid. Implicit display

```

# Answer
> 3 votes
# JavaScript (ES10), 91 bytes

Inspired by CursorCoercer's answer.

```
f=a=>[...a.every((v,i)=>a[i%2-~i]^i%2*v)?f(a.flatMap((v,i)=>Array(i&1&&p).fill(p=v))):[],a]

```

Try it online!

### Commented

Testing if `a[]` is still valid:

```
a.every((v, i) =>   // for each value v at position i in a[]:
  a[i % 2 - ~i]     //   get a[i + 1] if i is even, or a[i + 2] if i is odd
  ^                 //   and make sure it's different from
  i % 2 * v         //   0 (or undefined) if i is even, or v if i is odd
)                   // end of every()

```

Run-length decoding of `a[]`:

```
a.flatMap((v, i) => // for each value v at position i in a[]:
  Array(i & 1 && p) //   build an array of p entries if i is odd,
                    //   or an empty array if i is even
  .fill(p = v)      //   fill it with v and copy v to p
)                   // end of flatMap()

```

---

# JavaScript (ES6), 91 bytes

A version without `.flatMap()`.

```
f=a=>[...a.every((v,i)=>a[j=i%2,b.push(...Array(j&&p).fill(p=v)),j-~i]^j*v,b=[])?f(b):[],a]

```

Try it online!

# Answer
> 3 votes
# , ~~70~~ 69 bytes

*Edit: -1 byte thanks to pajonk*

```
f=function(v)if(all(w<-c(print(v),0)[!1:0],diff(w)))f(rep(w,v[!0:1]))

```

Try it online!

```
f=function(v,                       # f is recursive function with arg vector v;
                 print(v)           #   first print v
             w=c(          )[!1:0]) #   and set w to every second element of v,
                         ,0         #   followed by a zero if length is odd.
if(              )                  # now, check if v is valid:
   all(w,       )                   #   there shouldn't be a final zero
         diff(w)                    #   and every second element should be different to its neighbour
                  f(              ) # if so, recurse
                    rep(w,v[!0:1])  #   with even numbered elemnts of v
                                    #   repeated odd numbered elements of v times

```

# Answer
> 2 votes
# Japt, 28 bytes

```
OpU;Êv ©Uó Ìän e ©ßUò crÈo{Y

```

Try it

I imagine there's room for improvement. Outputs in "reverse" order.

Explanation:

```
OpU;Êv ©Uó Ìän e ©ßUò crÈo{Y
OpU;                         # Print the input followed by a newline
    Ê                        # The length of the input
     v                       # Is divisible by 2
       ©                     # Break if false
        Uó                   # Separate the input into "sizes" and "elements"
           Ì                 # Take just the array of elements
            än               # Calculate the consecutive differences
               e             # Check that they are all non-zero
                 ©           # Break if false
                  ß          # Otherwise repeat the program with new input:
                   Uò        #  Split the current input into size,element pairs
                      cr     #  Run the following on each pair, then flatten:
                        Èo   #   An array with length equal to the first number
                          {Y #   Where each element is the second number

```

I've made an alternative which builds an array instead of printing in each loop, but it's currently longer.

# Answer
> 2 votes
# 05AB1E, ~~17~~ 15 bytes

```
[=ιÂ`ÅΓ©Åγ‚RÊ#®

```

Outputs in 'reversed' order compared to the challenge description.

Try it online or verify all test cases.

**Explanation:**

I basically run-length decode and then encode it again, and see if it's unchanged.

```
[         # Start an infinite loop:
 =        #  Print the current list with trailing newline (without popping)
          #  (which will be the implicit input-list in the first iteration)
  ι       #  Uninterleave the copy into 2 parts: [lengths,values]
   Â      #  Bifurcate (short for Duplicate & Reverse copy) this pair of lists
    `     #  Pop and push the reversed pair of lists to the stack
     ÅΓ   #  Pop both the values & length lists, and run-length decode them
       ©  #  Store this list in variable `®` (without popping)
   Åγ     #  Run-length encode it again, pushing the list of values and lengths
          #  separated to the stack
     ‚R   #  Pair them together in reversed order: [lengths,values]
   Ê      #  If the two pairs of lists are NOT the same:
    #     #   Stop the infinite loop
 ®        #  (else) Push the list of variable `®` for the next iteration

```

# Answer
> 2 votes
# Pyth, 13 bytes

```
Wq
Qsr8=r9cQ2

```

Try it online!

### Explanation

```
Q is initialized to input

Wq\nQsr8=r9cQ2
W              # while
  \nQ          #   print(Q)
 q             #     ==
     sr8=r9cQ2 #   run_length_encode(Q = run_length_decode(Q)):
               #  pass

```

# Answer
> 1 votes
# Python, ~~126~~ ~~124~~ ~~120~~ ~~113~~ 110 bytes

```
i=lambda t,x,a,b,*c:b and i(t&(b!=c[1]),x+(b,)*a,*c)or(x,a*t)
j=lambda l,t=1:t*[0]and j(*i(1,(),*l,1,0,0))+[l]

```

Attempt This Online!

The recursive function `i` simultaneously undoes the look-and-say sequence and also determines whether it's a valid sequence -- the last element of the return value is `1` if the sequence is valid and `0` if it's not.

This is then used in the main function `j` to undo the calculation until hitting a stopping point.

# Answer
> 1 votes
# Charcoal, 42 bytes

```
Ｗ∧⊞Ｏυθ¬∨﹪Ｌθ²⊙✂θ³Ｌθ²⁼κ§θ⊕⊗λ≔ΣＥ⪪θ²⁺⊟κＥ⊟κ⁰θＩυ

```

Attempt This Online! Link is to verbose version of code. Outputs the lists in reverse order; each element is printed on its own line and lists are double-spaced from each other. Explanation:

```
Ｗ∧⊞Ｏυθ¬∨

```

Push the current list to the predefined empty list, and while neither...

```
﹪Ｌθ²

```

... the length of the list is odd, nor...

```
⊙✂θ³Ｌθ²⁼κ§θ⊕⊗λ

```

... any of the third, fifth, seventh etc. entries equals the entry two previous, then...

```
≔ΣＥ⪪θ²⁺⊟κＥ⊟κ⁰θ

```

... run-length decode the list.

```
Ｉυ

```

Output all of the collected lists.

# Answer
> 1 votes
# Haskell, 86 bytes

```
r!(a:b:t)|r==b=[0]|k<-b<$[1..a]=k++b!t
r![]=[]
r!x=[0]
g l|0`elem`0!l=[l]|1>0=l:g(0!l)

```

Try it online!

r!list compares *r* with element to replicate, if they are equal inserts a 0 in the resulting list, same does if it matches an odd list.

Function *g* repeatedly apply *0!* and stops if there is a *0* in the result.

# Answer
> 1 votes
# Ruby, 73 bytes

-15 bytes thanks to AZTECCO

```
F=->a,y=0{a.all?&&(p a)&&F[a.each_slice(2).flat_map{y!=_2&&[y=_2]*_1},y]}

```

Attempt This Online!

# Answer
> 1 votes
# Jelly, 14 bytes

```
Ṅṭ2/Ḋm2IẠƲ¡Œṙß

```

A full program that accepts a list of integers from \\$\[1,4\]\\$ and prints the results in Jelly's list format separated by newlines.

**Try it online!**

### How?

Inspired by CursorCoercer's Pyth answer.

`Œṙ`, run-length decode, will error if given a list of integers or a list containing a singleton list. The code ensures that if the current list identifies the same value to be repeated twice in a row then the former will be true and, otherwise, if the current list is of odd length when the latter will be true.

```
Ṅṭ2/Ḋm2IẠƲ¡Œṙß - Main Link: list of integers, S
Ṅ              - print S
          ¡    - repeat...
         Ʋ     - ...number of times: last four links as a monad:
    Ḋ          -                       dequeue
     m2        -                       modulo-two slice
       I       -                       deltas
        Ạ      -                       all non-zero?
  2/           - ...action: pairwise reduce by:
 ṭ             -              tack
           Œṙ  - run-length decode
             ß - call this link again with that as S

```

# Answer
> 1 votes
# Raku, 60 bytes

```
{$_,*.flatmap(*Rxx*)...{$_%2|{any $_ Z==.skip}(.[1,3...*])}}

```

Try it online!

This is a lazily generated sequence of the form `first-element, generator ... termination-condition`.

* The first element is `$_`, the list argument to the function.
* `*.flatmap(* Rxx *)` takes the previous element and `flatmap`s over it two elements at a time using the anonymous function `* Rxx *`. `Rxx` is the `R`eversed version of the replication operator `xx`; it produces a number of copies of its right-hand side given by its left-hand side.
* The termination condition is an anonymous function that returns true if `$_ % 2`--that is, if the number of elements in the last list is odd--or if `.[1, 3 ... *]`, the odd-indexed elements of the last list, satisfies the condition `any $_ Z== .skip`--that is, if any two adjacent elements are equal.

# Answer
> 1 votes
# Rust, 146 bytes

```
|a|while dbg!(&a).len()%2<1{let(c,mut r,mut p)=(a.chunks_exact(2),vec![],9);for
t in c{if p==t[1]{return}p=t[1];r.extend([p].repeat(t[0]));}*a=r;}

```

Playground

This is a `fn(&mut Vec<usize>)`.

# Answer
> 1 votes
# Python, 93 bytes

```
f=lambda a:(a,*(eval("0"+(l:=len(b:=a[1::2]))*"!=%d"%b)*a[~l:l]and f(eval(l*"+%d*(%d,)"%a))))

```

Attempt This Online!

Returns the history newest to oldest.

# Python, 80 bytes

```
def f(a):print(a);f(eval(eval((l:=len(b:=a[1::2]))*".0!=%d"%b)*l*"+%d*(%d,)"%a))

```

Attempt This Online!

Prints the history line-by-line newest to oldest. Exits with an error.

#### How?

Nothing clever here. Using `eval` because control structures in general and in particular concatenation of a list of strings or pairwise iteration over a list or chained comparisons are all rather verbose when done "the proper way" in Python.

The second, semi-legal version does away with a few stop conditions (like odd number of terms) because the function crashes at the right time anyway when any of these conditions are met.

---
Tags: code-golf, sequence
---


title: Check Lyndon word

text:
# Question
Title: Check Lyndon word
A Lyndon word is a string that is strictly lexicographically smaller than any of its cyclic rotations. Given a binary string, determine if it's a Lyndon word in as few bytes as possible.

For example, `001011` is a Lyndon word. Its rotations, listed below, are obtained by repeatedly moving the first symbol to the end.

```
001011
010110
101100
011001
110010
100101

```

Of these, the original string comes lexicographically first, or equivalently, represents the smallest binary number.

However, `001001` is not a Lyndon word because one of its rotations is the same as itself, which ties it for lexicographically earliest.

A related problem.

**Input:** A non-empty binary string or list of digits `0` and `1`. You may *not* use numbers, like `5` to represent `101`.

**Output:** A consistent Truthy or Falsey value that says whether the string is a Lyndon word.

Built-ins specifically for Lyndon words are not allowed.

**Test cases:**

The Lyndon words with length up to 6 are:

```
0
1
01
001
011
0001
0011
0111
00001
00011
00101
00111
01011
01111
000001
000011
000101
000111
001011
001101
001111
010111
011111

```

The non-Lyndon words of length up to 4 are:

```
00
10
11
000
010
100
101
110
111
0000
0010
0100
0101
0110
1000
1001
1010
1011
1100
1101
1110
1111

```

**Leaderboard:**

```
    var QUESTION_ID=62587,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/63075/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
    body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 6 votes
# Python 2, 42

It seems to be good enough to compare with suffixes instead of bothering with a rotation.

```
f=lambda s,i=1:i/len(s)or s<s[i:]*f(s,i+1)

```

The setup of the recursion does not seem very nice; maybe it could be done better.

This 44-byte version makes it more obvious what's going on:

```
lambda s:all(s<=s[i:]for i in range(len(s)))

```

# Answer
> 4 votes
## Haskell, ~~43~~ 38 bytes

```
f x=all(x<=)$init$scanl(const.tail)x x

```

`scanl(const.tail)x x` builds a list of all suffixes of `x`, including the empty string `""` at the end, which is stripped off with `init`.

Edit: @feersum spotted a bug in my first version and came up with the idea that comparing to suffixes is enough.

# Answer
> 4 votes
# Pyth, 9 bytes

```
!f>z>zTUz

```

Demonstration

Uses Vihan et. al.'s suffixes approach.

# Answer
> 3 votes
# J, 11 char

Outputs `1` on Lyndon words and `0` otherwise.

```
0=0({/:)<\.

```

`<\.` takes suffixes and then `/:` tells us how to sort them lexicographically. `{` takes the entry at the `0`-th index and `0=` checks if it's zero: if it is, we have a Lyndon word, because the biggest suffix wouldn't change place in a sort; if it's nonzero, it is not a Lyndon word, because some suffix is lexicographically earlier.

```
   0=0({/:)<\. '001011'
1
   0=0({/:)<\. '001001'
0

```

# Answer
> 3 votes
# ShapeScript, ~~57~~ 47 bytes

```
0?1'@"2"@+"20"$""~"21"$""~@2?2?>1<*'3?_1-*!@#@#

```

I created ShapeScript for this competition. The interpreter on GitHub has a slightly modified syntax.

Try it online!

# Answer
> 2 votes
# CJam, ~~15~~ 14 bytes

```
r_,,\fm<(f>1-!

```

Try this fiddle in the CJam interpreter or verify all test cases at once.

### How it works

```
r              e# Read a token from STDIN.
 _,            e# Push the length of a copy.
   ,           e# Turn length L into [0 ... L-1].
    \fm<       e# Rotate the token 0, ..., and L-1 units to the left.
        (      e# Shift out the first rotation, i.e., the original token.
         f>    e# Compare all other rotations with this one.
           1-  e# Remove 1 from the resulting array of Booleans.
             ! e# Apply logical NOT to turn an empty array into 1, and a
               e# non-empty one into 0.

```

# Answer
> 2 votes
# TeaScript, 10 bytes

```
xe»x«xS(i©

```

Very golf, much short. Try it online

### Explanation && Ungolfed

```
xe(#x<=xS(i))

xe(#      // Loop through x
          // Check if all iterations return true
    x <=  // Input is less than or equal to...
    xS(i) // Input chopped at current index
)

```

# Answer
> 2 votes
## Haskell, 29

```
f s=all(s<=)$init$scanr(:)[]s

```

Checks whether `s` is at most each of its non-empty suffixes, like nimi's answer.

The expression `scanr(:)[]` generates the list of suffixes by listing.

```
>> scanr(:)[] "abcd"
["abcd","bcd","cd","d",""]

```

The `init` then gets rid of the empty string at the end. Finally, `all(s<=)` checks whether every suffix `x` satisfies `s<=x`. Since the first suffix is `s` itself, a `<=` is needed.

# Answer
> 2 votes
# Ruby, 37 bytes

```
->s{(1...s.size).all?{|i|s[i..-1]>s}}

```

Testing:

```
lyndon_words = %w(0 1 01 001 011 0001 0011 0111 00001 00011 00101 00111
                  01011 01111 000001 000011 000101 000111 001011 001101
                  001111 010111 011111)

not_lyndon_words = %w(00 10 11 000 010 100 101 110 111 0000 0010 0100 0101
                      0110 1000 1001 1010 1011 1100 1101 1110 1111)

f=->s{(1...s.size).all?{|i|s[i..-1]>s}}

p lyndon_words.all? &f      # => true
p not_lyndon_words.any? &f  # => false

```

# Answer
> 1 votes
## Burlesque, 15 bytes

```
JiRJU_j<]x/==&&

```

Mainly 8 of those 7 bytes are to check if it doesn't tie. Otherwise you can go with simply `JiR<]==`.

**Explanation:**

```
J       -- duplicate word
iR      -- all rotations
J       -- duplicate list of all rotations
U_      -- check if list contains no duplicates
j       -- swap
<]      -- find minimum of the list
x/      -- rotate top
==      -- compare minimum with the original word
&&      -- and results of min == orig and list unique

```

# Answer
> 1 votes
# Vyxal, 5 bytes

```
ẏvǔg=

```

Try it Online!

```
 vǔ   # Rotate by each of...
ẏ     # 0 to len(x)
   g  # Does the (lexicographic) minimum
    = # Equal the input?

```

# Answer
> 0 votes
# Pyth - 12 bytes

Hope to golf a little bit.

```
.A<Lzt.<Lzlz

```

Try online.

# Answer
> 0 votes
# Javascript (ES6), 129 bytes

```
a=Array;s=prompt();console.log(a.from(a(s.length),(x,i)=>i).map(n=>(s.substring(n)+s.substring(0,n--))).sort().pop().contains(s))

```

# Answer
> 0 votes
# Javascript, ~~91~~ 87 bytes

```
f=x=>(y=(x+x).slice(1,-1),x[0]==x||!(y.indexOf(x)+1)&&!x.indexOf('0')&&x.slice(-1)==1);

```

I'm basically concatenating the word with itself and check if it's still there. To check if it is the smallest number possible, I just check that it start with a 0 and end with a 1.

### Tests

```
[
['0',1],
['1',1],
['01',1],
['001',1],
['011',1],
['0001',1],
['0011',1],
['0111',1],
['00001',1],
['00011',1],
['00101',1],
['00111',1],
['01011',1],
['01111',1],
['000001',1],
['000011',1],
['000101',1],
['000111',1],
['001011',1],
['001101',1],
['001111',1],
['010111',1],
['011111',1],
['00',0],
['10',0],
['11',0],
['000',0],
['010',0],
['100',0],
['101',0],
['110',0],
['111',0],
['0000',0],
['0010',0],
['0100',0],
['0101',0],
['0110',0],
['1000',0],
['1001',0],
['1010',0],
['1011',0],
['1100',0],
['1101',0],
['1110',0],
['1111',0]
].forEach(t =>{
  r=f(t[0])
  x=t[1]
  console.log('Test '+(r==x?'OK':'Fail (Expected: ' + x +')')
  +'\nInput: '+t[0]+'\nResult: ' +r+'\n')
})

```

# Answer
> 0 votes
# Mathematica, 86 bytes

```
(s=Table[#~StringRotateLeft~i,{i,StringLength@#}];Last@s==First@Sort@s&&s~Count~#==1)&

```

**input**

> \["1111"\]

# Answer
> 0 votes
# PowerShell Core, 85 bytes

```
param($k)($w=0..($l=$k.Length-1)|%{-join$k[-$_..($l-$_)]}|sort)[0]-eq$k-and$w[1]-ne$k

```

Try it online!

1. Generates all the rotations of the input
2. Sorts them
3. Checks that the first one equals the input and the second one does not

# Answer
> 0 votes
# 05AB1E, 7 (or 8?) bytes

```
ā._{QJR

```

Outputs a 05AB1E truthy/falsey result, where truthy is a `1` padded with leading 0s up to the input-length, and falsey anything else. But since the challenge description mentions 'consistent' truthy/falsey value, a trailing `Θ` (05AB1E-truthify builtin: `==1`) can be added for consistent `1`/`0` outputs.

Try it online or verify some more test cases.

**Explanation:**

```
ā        # Push a list in the range [1, (implicit) input-length] (without popping)
 ._      # Rotate the input that many times (vectorized) towards the left
   {     # Sort this list of rotations
    Q    # Check for each rotation whether it's equal to the (implicit) input
     J   # Join the checks together
      R  # Reverse this string
         # (after which the result is output implicitly)

```

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


# Question
Title: Find the frequency of triplets in a phrase
For context, this problem is based on a old chat-bot project I did.

# Problem:

Given a string of words containing any of the characters:

```
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"

```

Find the frequency of each triplet of words. All non-alphanumeric characters should be ignored, and input/output will be case-insensitive.

For this challenge, the "triplets" of a phrase are each consecutive chunk of 3 words along the string.

For example, in the string

```
"Oh hi there guy. What's up? Oh hi there."

```

The "triplets" of the string are

```
[["oh", "hi", "there"], ["hi", "there", "guy"], ["there", "guy", "whats"], ["guy", "whats", "up"],
 ["whats", "up", "oh"], ["up", "oh", "hi"], ["oh", "hi", "there"]]

```

The frequency of each triplet is 1, except for `["oh", "hi", "there"]`, which appears twice.

# Input

Input will be a string of space-delimited "words" that may contain any of the characters mentioned above. Although punctuation is to be ignored, it must be handled.

You can assume the input will always contain at least 3 words, and that there won't be consecutive whitespace.

# Output

Output can be anything that shows the frequency of each triplet.

For the string "Oh hi there guy.", possible outputs could be:

```
{"oh hi there":1, "hi there guy":1}

["oh hi there", 1, "hi there guy", 1]

"oh hi there|1 hi there guy|1"
            ^ Or any other delimiter

```

# Test Cases (Output order doesn't matter):

```
"Oh hi there guy. What's up? Oh hi there."
{["oh" "hi" "there"] 2,
 ["hi" "there" "guy"] 1,
 ["there" "guy" "whats"] 1,
 ["guy" "whats" "up"] 1,
 ["whats" "up" "oh"] 1,
 ["up" "oh" "hi"] 1}

"aa aa aa aa"
{["aa" "aa" "aa"] 2}

"aa bb a bb a bb a cc a bb a"
{["aa" "bb" "a"] 1,
 ["bb" "a" "bb"] 2,
 ["a" "bb" "a"] 3,
 ["bb" "a" "cc"] 1,
 ["a" "cc" "a"] 1,
 ["cc" "a" "bb"] 1}

"99 bottles of beer"
{["99" "bottles" "of"] 1,
 ["bottles" "of" "beer"] 1}

"There are two main types of chatbots, one functions based on a set of rules, and the other more advanced version uses artificial intelligence. The chatbots based on rules, tend to be limited in functionality, and are as smart as they are programmed to be. On the other end, a chatbot that uses artificial intelligence, understands language, not just commands, and continuously gets smarter as it learns from conversations it has with people."
{["main" "types" "of"] 1,
 ["rules" "and" "the"] 1,
 ["of" "chatbots" "one"] 1,
 ["to" "be" "limited"] 1,
 ["artificial" "intelligence" "understands"] 1,
 ["it" "has" "with"] 1,
 ["chatbots" "based" "on"] 1,
 ["smarter" "as" "it"] 1,
 ["the" "chatbots" "based"] 1,
 ["other" "more" "advanced"] 1,
 ["commands" "and" "continuously"] 1,
 ["chatbots" "one" "functions"] 1,
 ["tend" "to" "be"] 1,
 ["a" "chatbot" "that"] 1,
 ["continuously" "gets" "smarter"] 1,
 ["advanced" "version" "uses"] 1,
 ["functionality" "and" "are"] 1,
 ["are" "two" "main"] 1,
 ["based" "on" "rules"] 1,
 ["on" "a" "set"] 1,
 ["there" "are" "two"] 1,
 ["the" "other" "more"] 1,
 ["just" "commands" "and"] 1,
 ["the" "other" "end"] 1,
 ["that" "uses" "artificial"] 1,
 ["based" "on" "a"] 1,
 ["limited" "in" "functionality"] 1,
 ["smart" "as" "they"] 1,
 ["are" "as" "smart"] 1,
 ["from" "conversations" "it"] 1,
 ["other" "end" "a"] 1,
 ["intelligence" "the" "chatbots"] 1,
 ["functions" "based" "on"] 1,
 ["in" "functionality" "and"] 1,
 ["intelligence" "understands" "language"] 1,
 ["chatbot" "that" "uses"] 1,
 ["more" "advanced" "version"] 1,
 ["gets" "smarter" "as"] 1,
 ["rules" "tend" "to"] 1,
 ["on" "rules" "tend"] 1,
 ["as" "it" "learns"] 1,
 ["are" "programmed" "to"] 1,
 ["and" "the" "other"] 1,
 ["understands" "language" "not"] 1,
 ["and" "are" "as"] 1,
 ["of" "rules" "and"] 1,
 ["has" "with" "people"] 1,
 ["end" "a" "chatbot"] 1,
 ["set" "of" "rules"] 1,
 ["and" "continuously" "gets"] 1,
 ["as" "they" "are"] 1,
 ["they" "are" "programmed"] 1,
 ["as" "smart" "as"] 1,
 ["two" "main" "types"] 1,
 ["a" "set" "of"] 1,
 ["uses" "artificial" "intelligence"] 2, # <----- 2 Here
 ["it" "learns" "from"] 1,
 ["be" "limited" "in"] 1,
 ["programmed" "to" "be"] 1,
 ["types" "of" "chatbots"] 1,
 ["conversations" "it" "has"] 1,
 ["one" "functions" "based"] 1,
 ["be" "on" "the"] 1,
 ["not" "just" "commands"] 1,
 ["version" "uses" "artificial"] 1,
 ["learns" "from" "conversations"] 1,
 ["artificial" "intelligence" "the"] 1,
 ["to" "be" "on"] 1,
 ["on" "the" "other"] 1,
 ["language" "not" "just"] 1}

```

Your submission can be a function or full program, and can take input via stdin, or as an argument. It may output by returning, or printing to the stdout.

This is code golf, so the shortest number of bytes wins.

# Answer
> 5 votes
# Jelly, ~~18~~ 13 bytes

```
ŒlḲf€ØBṡ3ṢŒr'

```

A monadic link (function) that returns a list, each entry contains a list of 3 lists of characters (the words) and a count.

**Try it online!** \- the footer formats the results (as a full program everything just gets smushed together by the implicit print).

### How?

```
ŒlḲf€ØBṡ3ṢŒr' - Main link: s
Œl            - convert s to lowercase
  Ḳ           - split on spaces
     ØB       - base digit yield "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
   f€         - filter keep for €ach
       ṡ3     - all overlapping slices of length 3
         Ṣ    - sort
            ' - call the previous monadic link without vectorising
          Œr  -     run length encode

```

# Answer
> 5 votes
# Perl 6,  ~~67~~  57 bytes

```
*.words.map({[~] .lc.comb(/\w/)}).rotor(3=>-2)».join(' ').Bag.perl

```

Try it

```
*.words.rotor(3=>-2).map({lc S:g/<-:L-:N-:Z>//}).Bag.perl

```

Try it

## Expanded:

```
*\                # WhateverCode lambda (this is the parameter)
.words            # get a list of words
.rotor( 3 => -2 ) # grab 3, back up 2, repeat

.map({            # take those list of 3 elements

  lc              # lower case the following

  S               # remove
  :global         # globally
  /
    <- :L         # not a letter
     - :N         # not a number
     - :Z         # not a space  (inserted when the current list is stringified)
    >
  //

})
.Bag              # turn it into a Bag
.perl             # return the structure as an `EVAL`able Str

```

returns something like

```
("bb a cc"=>1,"aa bb a"=>1,"a cc a"=>1,"a bb a"=>3,"bb a bb"=>2,"cc a bb"=>1).Bag

```

# Answer
> 4 votes
# Retina, 50 bytes

```
T`lLd p`lld _
M!&`(\b\w+ ??){3}
O`
$
¶
D`
¶+
:$.&¶

```

Try it online!

### Explanation

```
T`lLd p`lld _

```

Replace all uppercase letters with lowercase ones, keep other letters, digits and spaces unchanged and delete other characters.

```
M!&`(\b\w+ ??){3}

```

Find all possible matches of three words in a row.

```
O`

```

Sort the matches, so equal triplets end next to each other.

```
$
¶

```

Add a newline at the end.

```
D`

```

Remove duplicate lines (this will keep the newlines at the end of them).

```
¶+
:$.&¶

```

Sequences of newlines are now the counts we need, replace them with a delimiter (`:`) followed by the count and a newline.

# Answer
> 3 votes
# Ruby, 60 bytes

-1 byte thanks to Kevin Cruijssen

```
->s{s.upcase.gsub(/[^A-Z0-9 ]/,'').split.each_cons(3).tally}

```

Attempt This Online!

# Answer
> 2 votes
# Mathematica, 75 bytes

```
Tally@Partition[ToLowerCase@#~StringSplit~RegularExpression@"[_\\W]+",3,1]&

```

Pure function taking a string as input and returning a list of ordered triples of strings together with their number of appearances. For example, on the input `"aa bb a bb a bb a cc a bb a"` the output is `{{{"aa", "bb", "a"}, 1}, {{"bb", "a", "bb"}, 2}, {{"a", "bb", "a"}, 3}, {{"bb", "a", "cc"}, 1}, {{"a", "cc", "a"}, 1}, {{"cc", "a", "bb"}, 1}}`. The expression `RegularExpression@"[_\\W]+"` recognizes all runs of one or more non-word characters (that's what `\\W` does, except it calls `_` a word character whereas we don't want to). `ToLowerCase@#~StringSplit~` then splits the input string at all of those runs, after converting all letters to lowercase. `Partition[...,3,1]` partitions the resulting list into all triples of consecutive words, and `Tally` does exactly what we want to that list of triples.

# Answer
> 2 votes
# JavaScript (ES6), ~~200~~ ~~198~~ 187 bytes

*(-2 bytes thanks to Luke)*

*(-11 bytes thanks to edc65)*

```
H=(h,k=[],i=0)=>i+2<(z=h.toLowerCase().replace(/[^\w ]|_/g,'').split` `).length?H(h,k.concat(z.slice(i,i+3)+''),-~i):new Set(k.map(a=>a+':'+k.filter(b=>b==a).length)).forEach(m=>alert(m))

```

A recursive solution. Takes input as a single string and outputs dialog boxes containing each triplet's count in the format `<Triplet>:<Count>`. As always, golfing tips are greatly appreciated.

## Test Snippet

```
H=(h,k=[],i=0)=>i+2<(z=h.toLowerCase().replace(/[^\w ]|_/g,'').split` `).length?H(h,k.concat(z.slice(i,i+3)+''),-~i):new Set(k.map(a=>a+':'+k.filter(b=>b==a).length)).forEach(m=>alert(m))
```

```
<input type="text" id="i" value="Oh hi there guy._ What's up? Oh hi there."></input>
<input type="button" value="Submit" onclick="H(document.getElementById('i').value)"></input>
```

# Answer
> 2 votes
# Python 2, ~~164~~ 159 bytes

```
s=filter(lambda k:k.isalnum()or k==' ',input()).lower().split()
k=[tuple(s[i:i+3])for i in range(len(s)-3)]
l={}
for i in k:l[i]=l[i]+1if i in l else 1
print l

```

Not a really great solution, I know. Pretty straightforward.

Thanks to @ovs for saving 5 bytes overall.

# Answer
> 2 votes
# Java 8, ~~376~~ 372 bytes

```
import java.util.*;public interface T{static void main(String[]k)throws Exception{String s="";int c;while((c=System.in.read())>10)if(c==32|(""+(char)c).matches("[A-Za-z]"))s+=(char)c;k=s.toLowerCase().split(" ");Map<String,Integer>o=new HashMap<>();for(int i=0;i<k.length-2;i++){s=k[i]+" "+k[i+1]+" "+k[i+2];o.put(s,(o.containsKey(s)?o.get(s):0)+1);}System.out.print(o);}}

```

Ungolfed:

```
import java.util.HashMap;
import java.util.Map;

public interface T {
    static void main(String[] k) throws Exception {
        String s = "";
        int c;
        while ((c = System.in.read()) > 10)
            if (c == 32 | ("" + (char) c).matches("[A-Za-z]"))
                s += (char) c;
        k = s.toLowerCase().split(" ");
        Map<String, Integer> o = new HashMap<>();
        for (int i = 0; i < k.length - 2; i++) {
            s = k[i] + " " + k[i + 1] + " " + k[i + 2];
            o.put(s, (o.containsKey(s) ? o.get(s) : 0) + 1);
        }
        System.out.print(o);
    }
}

```

Never use Java for actual golfing.

**EDIT**: Saved 4 bytes by abusing the fact that the main method has a `String[]` as its parameter so I don't have to initialize one \>:-)

# Answer
> 2 votes
# Python 3, ~~151~~ 149 bytes

```
s="".join(c for c in input()if c.isalnum()or c==" ").lower().split()
k=[tuple(s[i:i+3])for i in range(len(s)-2)]
print(*((x,k.count(x))for x in{*k}))

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~23~~ 20 bytes

```
žLðìÃ#Œ3ù©Ùvyðý®y¢‚ˆ

```

Try it online!

**Explanation**

```
žL                    # push a string of alphanumeric characters
  ðì                  # prepend a space
    Ã                 # keep only those characters from input
     #                # split on spaces
      Œ3ù             # get all sublists of length 3
         ©            # save a copy in register
          Ù           # remove duplicates
           v          # for each unique triplet
            yðý       # join the triplet by spaces
               ®y¢    # count the triplets occurrences in the list saved to register
                  ‚   # pair the string with the count
                   ˆ  # push it to global list
                      # output global list at the end of the program

```

# Answer
> 2 votes
# Python, 143 bytes

```
lambda s:Counter(tuple(''.join(filter(str.isalnum,w))for w in s.lower().split())[i:i+3]for i in range(s.count(' ')-1))
from collections import*

```

**Try it online!**

Unnamed function which returns a dictionary (specifically a Counter object) which has keys that are tuples of the triples (in the correct order) and values that are their counts.

# Answer
> 2 votes
# Bash \+ Unix utilities, 117 bytes

```
s=[^\ ]*
p=s/^$s\ //
tr A-Z a-z|tr -cd \ a-z0-9|sed "p;$p;p;$p"|sed "s/\($s $s $s\) /\1\n/g"|grep ' .* '|sort|uniq -c

```

Try it online!

Input on stdin, output on stdout.

Sample run:

Input:

```
Oh hi there guy. What's up? Oh hi there.

```

Output:

```
      1 guy whats up
      1 hi there guy
      2 oh hi there
      1 there guy whats
      1 up oh hi
      1 whats up oh

```

# Answer
> 2 votes
# JavaScript (ES6), 124

```
s=>s.toLowerCase().replace(/\S+/g,x=>t.push(x.replace(/[\W_]/g,''))>2&&(k[t]=-~k[t],t.shift()),t=[],k={})&&JSON.stringify(k)

```

Note that the output *shows* the frequency of each triplet, as requested. If the output could just *contain* the frequency data in a machine usable format, I could save 16 bytes of `JSON.stringify()`

*Less golfed*

```
s => {
   s = s.toLowerCase() // force to lowercase
   t = [] // init current group (or triplet)
   k = {} // init frequency list
   s.replace(/\S+/g, x => ( // execute for each sequence of non space chars
     x = x.replace(/[\W_]/g,''), //remove non alphanumeric chars
     t.push(x) > 2 // add to end of current group
     && (          // if there are 3 elements in group (it's a triplet)
       k[t] = -~k[t], // add to frequency list incrementing count
       t.shift() // remove first element of current group
     )
   )
   return JSON.stringify(k) // return in human readable format
}

```

**Test**

```
let F=
s=>s.toLowerCase().replace(/\S+/g,x=>t.push(x.replace(/[\W_]/g,''))>2&&(k[t]=-~k[t],t.shift()),t=[],k={})&&JSON.stringify(k)

;["Oh hi there guy. What's up? Oh hi there."
,"aa aa aa aa"
,"aa bb a bb a bb a cc a bb a"
,"99 bottles of beer"
,"There are two main types of chatbots, one functions based on a set of rules, and the other more advanced version uses artificial intelligence. The chatbots based on rules, tend to be limited in functionality, and are as smart as they are programmed to be. On the other end, a chatbot that uses artificial intelligence, understands language, not just commands, and continuously gets smarter as it learns from conversations it has with people."]
.forEach(t=>{
  O.textContent += t + '\n'+ F(t).replace(/,"/g,'\n"')+'\n\n'
})
```

```
<pre id=O></pre>
```

# Answer
> 2 votes
# CJam, 25 bytes

```
qel"␡{a:0!":,:^-S/3ew$e`p

```

␡ represents a Delete character (ASCII 127).

Try it online!

**Explanation**

```
q                          Read all input
 el                        Convert it to all lowercase
   "␡{a:0!"                Push this string
           :,              Map each character in the string to the range of chars up to,
                            but excluding it
             :^            Reduce the array of ranges with symmetric set differences
                           The result will be an array containing all disallowed characters
               -           Remove all instances of these characters from the input
                S/         Split the input on spaces
                  3ew      Take overlapping slices of length 3
                     $     Sort them
                      e`   Take the run-length encoding
                        p  Print it

```

# Answer
> 2 votes
# R, 114 bytes

```
x=readline();y=strsplit(tolower(gsub('[[:punct:]]','',x)),' ')[[1]];s=3:length(y);table(paste(y[s-2],y[s-1],y[s]))

```

Reads input, removes punctuation, splits it into words and counts triplets.

# Answer
> 2 votes
# J-uby, 58 bytes

-1 byte thanks to Kevin Cruijssen

```
:upcase|~:gsub&''&/[^A-Z0-9 ]/|:split|~:each_cons&3|:tally

```

Attempt This Online!

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
#žLδÃlü3{Åγø

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him as well.

Try it online or verify all test cases.

**Explanation:**

```
#             # Split the (implicit) input-string by spaces
   δ          # Map over each word:
    Ã         #  Only keep all
 žL           #  alphanumeric characters (a-zA-Z0-9) of the word
     l        # Convert everything to lowercase
      ü3      # Convert it to a list of overlapping triplets
        {     # Sort this list of triplets
         Åγ   # Run-length encode it, resulting in a list of triplets and list of counts
              # pushed separately to the stack
           ø  # Pair the items in the two lists together
              # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Vyxal, 8 bytes

```
⇩⌈krF3lĊ

```

Try it Online!

Outputs a list of `⟨ triplet | count ⟩`

## Explained

```
⇩⌈krF3lĊ
⇩⌈         # Split the lowercase input on spaces
  krF      # remove all non-alphabet/non-number characters and keep only strings with alphabet letters
     3l    # group into windows of 3
        Ċ  # get the count of each triplet.

```

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


title: Pyramid of broken strings

text:
# Question
Title: Pyramid of broken strings
Given a string n, create a pyramid of the string split into pieces relative to the current row.

The first row contains the string unmodified.

The second row contains the string separated into halves by a pipe.

The third row separates it by thirds...

And so on. The length of each substring, where l is the length of string n is equal to

floor(l/n)

Characters left over are put in their own substring. The last row used is the first one where substrings are 2 in length.

**Test Cases:**

Input: Hello, world.

Output:

```
Hello, world.

Hello,| world|.

Hell|o, w|orld|.

Hel|lo,| wo|rld|.

He|ll|o,| w|or|ld|.

```

---

Input: abcdefghij

Output:

```
abcdefghij

abcde|fghij

abc|def|ghi|j

ab|cd|ef|gh|ij

```

---

Input: 01234567890abcdef

Output:

```
01234567890abcdef

01234567|890abcde|f

01234|56789|0abcd|ef

0123|4567|890a|bcde|f

012|345|678|90a|bcd|ef

01|23|45|67|89|0a|bc|de|f

```

---

# Extra rules:

* You can write a full program or a function, whichever uses less code.
* Input will always be at least 4 characters in length.
* You MUST use line breaks if your language supports them. If not possible, replace line breaks with `:`
* Input will always be printable ASCII.
* Minus 100% if your program solves P vs. NP.

---

# Leaderboard:

```
var QUESTION_ID=104297,OVERRIDE_USER=62384;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
## JavaScript (ES6), ~~103~~ ~~101~~ ~~91~~ 84 bytes

*Fixed to respect challenge requirements*

```
f=(s,n=0,p=s.length/++n|0)=>p>1?s.match(eval('/.{1,'+p+'}/g')).join`|`+'\n'+f(s,n):''

```

Lambda `f` that takes input string as first parameter `s` and recursively prints to console the split string. Pretty straightforward: as long as the substring length, `p`, is above 1, print the string split by a '|' every `p` characters, then proceed with appending the following level. This then calls the function again with `p` being `t / n` floored, where `t` is the original string length and `n` being an incremented divider.
> 0 votes

# Answer
# Perl, 46 + 1 = 47 bytes

Run with the `-n` flag

```
say s/.{$=}(?=.)/$&|/gr while($==y///c/++$,)-2

```

Try it online!

### Code breakdown

```
-n                                              #Reads input into the $_ variable
say s/.{$=}(?=.)/$&|/gr while($==y///c/++$,)-2
                                 y///c          #Transliteration.  Implicitly operates on $_, replacing every character with itself and counting replacements
                                                #y///c effectively returns the length of $_
                                      /++$,     #Increments $, (which starts off at 0) and divides the length of $_ by $,
                              $==               #Stores the result of this division into $=
                                                #$= forces its contents to be an integer, so it truncates any decimal
                             (             )-2  #Returns 0 if $= is equal to 2
                        while                   #Evaluates its RHS as the condition.  If truthy, evaluates its LHS.
    s/          /   /gr                         #Substitution.  Implicitly operates on $_.
                                                #Searches for its first argument and replaces it with its second argument, repeating until it's done, and returns the new string.  $_ is not modified.
      .{$=}                                     #Looks for a string of $= characters...
           (?=.)                                #...that is followed by at least one non-newline character, but does not include this character in the match...
                 $&|                            #...and replaces it with itself followed by a pipe character.
say                                             #Output the result of the substitution.

```
> 4 votes

# Answer
## Pyth, 16 bytes

```
Vh/lQ3j\|cQ/lQhN

V                # For N in range(1, \/ )
 h/lQ3           # 1+lenght(input)/3
      j\|        # join with '|'
         cQ      # chop input in
           /lQhN # lenght(input)/(N+1) pieces

```

try here
> 2 votes

# Answer
## C, ~~145~~ ~~131~~ ~~128~~ 125 bytes

```
l,n,i=1,j;f(char*s){l=strlen(s);puts(s);do{n=l/++i;for(j=0;j<l;)j&&(j%n||putchar('|')),putchar(s[j++]);puts("");}while(n>2);}

```

This is a function that takes a string as its argument and prints the output to STDOUT.

```
l,n,i=1,j;       // declare some variables
f(char*s){       // declare the function
l=strlen(s);     // get the length of the string
puts(s);         // output the initial version, with trailing newline
do{n=l/++i;      // n is the number of characters per "section",
                 //  and we'll do-while n>2 to stop at the right time
for(j=0;j<l;)    // loop through the characters of the string
j&&(             // if j != 0,
j%n||            // and j % n == 0,
putchar('|')),   // insert a | before this character
putchar(s[j++]); // print the character
puts("");        // print a newline after the loop
}while(n>2);}

```
> 2 votes

# Answer
# Pyth, 17 bytes

```
jmj\|cQ/lQdSh/lQ3

```

### Explanation

```
     cQ/lQ         Divide into equal pieces (with the last shorter)
  j\|              Join with pipes
 m        d        Map to each row index...
           Sh/lQ3  ... up to the first row with substrings of length 2
j                  Join with newlines

```
> 1 votes

# Answer
# Javascript, 98 Bytes

```
a=>{for(b=1;2<=a.length/b;)eval("console.log(a.match(/.{1,"+(a.length/b|0)+"}/g).join('|'))"),b++}

```

Function `x(a)`. Call using

`console.log(x("ABCDEF"))`
> 1 votes

# Answer
# Ruby `-n`, 60 bytes

```
z= ~/$/
(z/3+1).times{|n|puts $_.scan(/.{1,#{z/(n+1)}}/)*?|}

```

Attempt This Online!
> 0 votes

# Answer
# Python 3, 123 bytes

```
f=lambda s:print(*['|'.join(s[i:i+n]for i in range(0,len(s),n))for n in[len(s)//i for i in range(1,len(s)//2+1)]],sep='\n')

```

At longer strings some parts will be repeated, as the formula for the length of the substring is `floor(l/n)`. For example with a string 13 chars long, the string split into 5's would be the same as the string split into 6's as `floor(13/5)==floor(13/6)`. I'm not sure if the OP expected this or if it was an oversight.
> 0 votes

# Answer
# Vyxal, 13 bytes

```
₌LżḭvẇUṪ\|vj⁋

```

Try it Online!

12 with `j` flag

## Explained

```
₌LżḭvẇUṪ\|vj⁋
₌Lż            # Push len(input) and [1..len(input)]
   ḭ           # Floor divide the length by each number in the range
    vẇ         # And wrap the input into chunks of each length
      UṪ       # Uniquify the list and remove the last item (which will be the input split into chunks of length 1)
        \|vj   # Join each list on "|"
            ⁋  # And join that on newlines

```
> 0 votes

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


title: Tips for golfing in AWK

text:
# Question
Title: Tips for golfing in AWK
What general tips do you have for golfing in AWK? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to AWK. Please post one tip per answer.

# Answer
> 9 votes
These are not in any particular order, and some of them might even apply to other languages too, but not to a lot of them I think.

* You can sometimes use awk's simple string concatenation to assemble numbers

`z=x*10+y` and `a=b*10`

become

`z=x y` and `a=b 0`
* You can use the ~ operator (match pattern on the right side) to compare numbers or strings if you know that the two parts meet certain conditions

for instance if you know that `a` will always be smaller than or equal to `b`, you can replace

`a==b`

with

`a~b`

or if you want to check for an empty string `s` (which means that s isn't allowed to be `"0"` either), and you haven's changed the variable `X` before, so that it is still undefined, you could use

`X~s`

instead of

`s==""`

if you want to check if i is an integer you can use

`i!~/\./` (`i` doesn't contain a dot)

instead of

`i==int(i)`
* You can swap two numbers in a single command

`t=a;a=b;b=t`

becomes

`a+=b-(b=a)`

saving one character
* If you don't need them as input anymore, you can use the input variables $1, $2, $3, ... as an array. So instead of writing a\[n\] you can just write $n. Sometimes even while reading the input from these you can use the already handled ones as a stack for something.
* You can make good use of the built-in separators FS (space, if not changed by you) and RS (newline) when concatenating strings

`a=$1" "$2`

becomes

`a=$1FS$2`

or even better

`a=$1"\n"$2`

becomes

`a=$1RS$2`
* If there is no input and you use the BEGIN block, you can try to use the END block instead. Depending on the judge it works. If you test it, you have to press `Ctrl-D` (end of input) to access the `END` block.
* If you want to skip the first line, you can use

`C++`

instead of

`NR>1`

if you won't be using `C` anywhere in your program.

# Answer
> 4 votes
## Techniques

* Thanks to Peter Taylor for pointing out the language-generic version of this question for which I did not bother to search. I'll try to limit this answer to things that are not available in other C-like languages.
* The frequently accessed builtin variables are 2 characters long. Find the break-even point for assigning to a temp variable. `a=$1;` is five characters, so it breaks even after five uses of `$1`;
* Remember that the default action for a matching pattern is `print $0`, so if you get what you want printed into `$0`, just use

```
1

```
* Getting creative with operator ordering can save you some parentheses or extra statements

```
for(i=1;i<=NF;i++)print$i;

```

vs

```
for(;i<NF;)print$++i;

```

## Examples

* A solution to Do We Sink or Swim? in 70 characters:

```
n{for(;NF;NF--)s+=$NF;n--}NR==1{n=$1;p=$3}END{print p<s?"Swim":"Sink"}

```
* A solution to The Floating Horde in 44 characters:

```
{for(i=NF;i>1;){n=int($i/2);$i%=2;$--i+=n}}1

```

## Summary

awk will probably never outgolf APL, Golfscript, J, or K, but you can quite consistently beat other high level languages.

# Answer
> 3 votes
To read and process a number on each line:

```
{
    n=$1;
    print(n*n);
    // OR printf("%d\n",n*n);
}

```

Compressed form (Length = 14):

```
{print($1*$1)}       // thanks due to @manatwork

```

Shorter Code (Length = 7)

```
1,$0^=2              // thanks due to @llhuii

```

When compiled and run in `gawk` with inputs:

```
1
2
3

```

Output:

```
1
4
9

```

# Answer
> 1 votes
# Truthy and falsey values

Boolean evaluation is somehow flexible in AWK, and this is awesome. Remember: AWK's basis is `pattern{action}`; when `pattern` is true, it executes `action`.

Besides doing their business, some built-in functions return values, e.g., `split()`, `gsub()`. They are also useful as a `pattern` when manipulating the input.

## Examples of truthy and falsey variables

I tried to come up with valuable examples of how to exploit truthy/falsey variables. This is non-exhaustive. Anyone is encouraged to share more examples, and I would add them to this list.

Try it online!

```
"strings are truthy"{print 1}  # truthy; strings are always truthy, except for the null string

-0xF3e10{print 2} # truthy; numbers different from zero are truthy

0{print 3}  # falsey; zeroes are false: 0, -0, +0, 0x0, 0000... expect for "0", which is a string
0 b{print 4}  # truthy; now the number 0 is concatenated to a null string (a variable still not assigned), thus converting it to "0"
""{print 5} # falsey; null string
b{print 6}  # falsey; b is null (a variable not assigned)

a=@/x/{print 7} # truthy; defining a strongly typed regex constant. Different from a /x/ pattern
/x/{print 8}  # falsey; /x/ does not match the input

c["test"]{print 9}   # falsey; undefined item of array, null
c["test"]++{print 10} # falsey; variable is evaluated before increment
c["test"]{print 11}   # truthy; now, c["test"] equals 1
c["test2"]{print 12}  # falsey; although the c array now exists, the "test2" element does not

```

Result:

```
1
2
4
7
11

```

# Answer
> 1 votes
one of the great things about `awk`'s sigils `$` is that string concat can be even more condensed than having to use the built-ins as buffer zones - say, u wanna prepend a zero to the full row:

> ```
>  _=0
> $_=_$_
>
> ```

```
jot -c 8 75  | gawk '$_=+_$_'

0K
0L
0M
0N
0O
0P
0Q
0R

```

and you wanna make patterns out of it ?

```
jot -c 8 75  | gawk '$_=_++$_'  # integers

0K
L 1
M  2
N   3
O    4
P     5
Q      6
R       7

jot -c 8 75  | gawk '$_=_++$++_' # even numbers

K 0
L   2
M     4
N       6
O         8
P           10
Q             12
R               14

jot -c 8 75  | gawk '$_=++_$++_'  # odd numbers

K 1
L   3
M     5
N       7
O         9
P           11
Q             13
R               15

```

And honestly, what language can repeat stings THIS easily :

```
jot 20 | mawk 'NF=OFS=$_'

1
22
333
4444
55555
666666
7777777
88888888
999999999
10101010101010101010
1111111111111111111111
121212121212121212121212
13131313131313131313131313
1414141414141414141414141414
151515151515151515151515151515
16161616161616161616161616161616
1717171717171717171717171717171717
181818181818181818181818181818181818
19191919191919191919191919191919191919
2020202020202020202020202020202020202020

```

or can decode arbitrary precision hex with this few keystrokes :

```
echo 0xEDCFAB12EDCFAB127659438976594389EDCFAB |

```

> ```
> gawk -nM '$_=+$_'
>
> ```

```
5303367068685265828195859270035065456131166123

```

---
Tags: code-golf, tips
---