title: Pseudofactorial

text:
# Question
Title: Pseudofactorial
There is a rather curious number which shows up sometimes in math problems or riddles. The pseudofactorial(N) is the least (i.e. lowest) common multiple of the numbers 1 through N; in other words, it's the lowest number which has all numbers from 1 through N as factors.

For instance pseudofactorial(7) = 3 * 4 * 5 * 7, which is the same as 7! except that 2 and 6 have been removed because they are contained in other terms.

Write a program to calculate pseudofactorial(N) and as always, shortest code wins.

Here is a short list for your use. More test cases can be found in the OEIS under A003418.

Factorial:

1. 1
2. 2
3. 6
4. 24
5. 120
6. 720
7. 5040

Pseudofactorial:

1. 1
2. 2
3. 6
4. 12
5. 60
6. 60
7. 420

# Answer
# Dyalog APL, 3 bytes

```
∧/⍳

```

APL beats Jelly

1 though argument

`∧/` LCM across
> 21 votes

# Answer
# Jelly, 4 bytes

```
Ræl/

```

Try it online! or verify all test cases.

### How it works

```
Ræl/  Main link. Input: n

R     Range; yield [1, ..., n].
   /  Reduce the range...
 æl     by LCM.

```
> 11 votes

# Answer
## Haskell, 20 bytes

```
f x=foldr1 lcm[1..x]

```

Usage example: `map f [1..7]` -\> `[1,2,6,12,60,60,420]`.

The `lcm` trick in Haskell.
> 7 votes

# Answer
# C (x86-64 `gcc -O1`), 52 bytes

```
d(n,k,b,t){for(b=k=1;b;++k)for(t=n,b=0;t;b+=k%t--);}

```

Checks numbers from 1 upwards. For each number, divides it by all numbers from n down to 1, and sums the remainders. Stops when the sum is 0.

Usage:

```
main()
{
    printf("%d\n", d(7)); // outputs 420
}

```

It's not obvious how it returns a value (there is no `return` statement).

The calling convention for x86 says that the function must return its value in the `eax` register. Conveniently, the division instruction `idiv` expects its input in `eax`, and outputs the result in `eax` (quotient) and `edx` (remainder). The last iteration divides `k` by `1`, so `eax` will contain the right value when the function exits.

This only works with gcc and `-O1` optimization option (otherwise, it outputs different results — usually `0` or random-looking numbers, but sometimes `421`, while the correct answer is `420`).

Try it with Compiler Explorer
> 7 votes

# Answer
## Python, 46 bytes

```
g=lambda n,c=0:n<1or(c%n<1)*c or g(n,c+g(n-1))

```

Looking for the multiple `c` of `g(n-1)` directly. I had though before that this method would wrongly find 0 as a multiple of anything, but the `or` short-circuiting or `(c%n<1)*c` will skip `c==0` as well because 0 is Falsey.

---

**50 bytes:**

```
g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1)

```

Like Dennis's solution, but as a recursive function. Having computed `g(n-1)`, looks for the smallest multiple `i*n` of `n` that's also a multiple of `g(n-1)`. Really slow.

Thanks to Dennis for 4 bytes by looking at multiples of `n` instead of `g(n-1)`.
> 7 votes

# Answer
# Python + SymPy, 45 bytes

```
import sympy
lambda n:sympy.lcm(range(1,n+1))

```

Fairly self-explanatory.

---

# Python 2, ~~57~~ 54 bytes

```
i=r=input();exec't=r\nwhile r%i:r+=t\ni-=1;'*r;print r

```

Test it on Ideone.

### How it works

The input is stored in variables **i** and **r**.

`exec` executes the following code **r** times.

```
t=r
while r%i:r+=t
i-=1

```

While **i** varies from **r** to **1**, we add the initial value of **r** (stored in **t**) as many times as necessary to **r** itself to create a multiple of **i**. The result is, obviously, a multiple of **t**.

The final value of **r** is thus a multiple of all integers in the range **\[1, ..., n\]**, where **n** is the input.
> 6 votes

# Answer
# MATL, 4 bytes

```
:&Zm

```

**Try it online!**

### Explanation

```
:      % Take input N implicitly. Generate range [1 2 ... N]
&Zm    % LCM of the numbers in that array. Display implicitly

```
> 5 votes

# Answer
# J, 9 bytes

```
[:*./1+i.

```

Straight-forward approach. Creates the range of numbers `[0, ..., n-1]`, then adds one to each, and reduce it using the LCM.

## Usage

```
   f =: [:*./1+i.
   f 7
420

```
> 5 votes

# Answer
# Mathematica, 13 bytes

```
LCM@@Range@#&

```
> 5 votes

# Answer
# Julia, 11 bytes

```
!n=lcm(1:n)

```

Try it online!
> 4 votes

# Answer
# Pyth - 8 bytes

Checks all numbers till it finds one that is divisible by `[1..N]`.

```
f!s%LTSQ

```

Test Suite.
> 3 votes

# Answer
# Octave, 27 bytes

```
@(x)lcm(1,num2cell(1:x){:})

```

Creates an anonymous function that can be invoked as `ans(N)`.

**Online Demo**

**Explanation**

This solution creates a list of all numbers between `1` and `x` (`1:x`), converts them to a cell array with `num2cell`. Then the `{:}` indexing creates a comma-separated-list which is passed to `lcm` as multiple input arguments to compute the least common multiple. A 1 is always passed as the first argument to `lcm` because `lcm` always needs at least two input arguments.
> 3 votes

# Answer
# MATLAB, 49 bytes

```
@(x)find(~any(bsxfun(@rem,1:prod(1:x),(1:x)')),1)

```
> 3 votes

# Answer
# Perl 6, 13 bytes

```
{[lcm] 1..$_}

```

Anonymous code block that creates a Range from 1 to the input (inclusive), and then reduces that with `&infix:<lcm>`.

### Example:

```
#! /usr/bin/env perl6
use v6.c;

my &postfix:<p!> = {[lcm] 1..$_}

say 1p!; # 1
say 2p!; # 2
say 3p!; # 6
say 4p!; # 12
say 5p!; # 60
say 6p!; # 60
say 7p!; # 420

say 10000p!; # 5793339670287642968692270879...
# the result from this is 4349 digits long

```
> 3 votes

# Answer
# Arturo, 13 bytes

```
$=>[lcm@..1&]

```

Try it
> 3 votes

# Answer
# Regex  (ECMAScript+`(?*)x*+`RME / PCRE2 v10.35+), ~~60~~ ~~59~~ 54 bytes

```
^((?*(?=(xx+?)\2*$|)((?=x\2)(?=(x+)(\4+$))\5)*+x+)x)*$

```

Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)

Attempt This Online! \- PCRE2 v10.40+
Try it on replit.com \- ECMAScript+`(?*)`+`x*+` (RegexMathEngine `-xml,pq`)

The  output method takes advantage of an aspect of regex that's normally hidden: the backtracking paths that aren't taken. In normal use, all traces of the avenues of potential alternative matches are erased when a final match is found. But in , they're all taken and counted, allowing a number to be outputted that's larger than the input. For scalar unary input, this provides a strict superset of the power of returning a number via the matched substring or a capture group (either of which can only return values less than or equal to the input), except that there can be no extra state of returning "no match" (in , that just returns \\$0\\$).

The limitation of having to work within the space of the input is still present.  can do combinations of multiplication and addition to yield numbers larger than the input, but it can't do subsequent tests on those results (it can only do tests on intermediate results calculated using capture groups and tail). So for example in this problem, the regex can't just directly search for the smallest number that is divisible by all numbers in the range \\$\[1,n\]\\$, because that number is not only larger than the input, it's too large even to be able to emulate using number base arithmetic (and even if that were possible, it would not golf well). So, this regex uses an algorithm different from all of the other answers:

It takes the base prime \\$p\\$ of every prime power \\$p^k\le n\\$, and calculates the product of that list of numbers. And because each \\$p\\$ will occur \\$k\\$ times in that list, this product is the same as the product of the prime powers themselves would be, if only the largest from each base prime were included.

The prime power portion is based on ~~my prime powers answer~~ Neil's prime powers answer (which is in turn based on my earliest CGCC answer). In the prime powers challenge, my regex is shorter, but for the purposes of this challenge, his regex (after some extra golfing) allows capturing the smallest prime factor, thus golfing down the overall regex by ~~1~~ 6 bytes.

```
^                       # tail = N = input number
(                       # Loop the following:
    (?*                 # Non-atomic lookahead:
                            # M = tail, which cycles from N down to 1
        (?=(xx+?)\2*$|)     # \2 = smallest prime factor of M if M ≥ 2;
                            # otherwise, leave \2 unchanged in PCRE, or
                            # unset in ECMAScript
        (
            (?=x\2)         # Keep iterating until tail ≤ \2, and because of
                            # what \2 is, this means at the end of the loop,
                            # either tail == \2 (if M is a prime power) or
                            # tail == 1 (if M is not a prime power)
            (?=(x+)(\4+$))  # \4 = {largest proper divisor of tail}
                            #    = tail / {smallest prime factor of tail};
                            # \5 = tail - \4
            \5              # tail = tail - (tail - \4) = \4
        )*+                 # Iterate the above as many times as possible,
                            # minimum zero, and lock in the result using a
                            # possessive quantifier.
        x+                  # Multiply number of possible matches by tail
    )
    x                   # tail -= 1
)*                      # Loop the above a minimum of 0 times
$                       # Assert that at the end of the above loop, tail == 0

```

This even returns a correct value for \\$n=0\\$, while the earlier 60 byte version did not (and needed to be extended to 63 bytes to do so).

A list of other answers that return \\$f(0)=1\\$ correctly, complete at the time of this edit: AWK, Dyalog APL, , Japt, Julia v0.7+ (but it was v0.6 at the time of posting, and didn't support it then), MATLAB, MATL, Maxima (with functs), Minkolang (1st answer), Nibbles, PHP, Pari/GP, Perl 5, Perl 6, Pyth, Python (with SymPy), Python (with math), Python, QBIC, Rexx, Vyxal. (Not tested: 8th, Axiom, Hoon)
> 3 votes

# Answer
# Brachylog, 5 bytes

```
fa~⟦₁

```

Try it online!

Reversed I/O.

```
 a       An affix of
f        the list of the output's factors
  ~⟦₁    is [1 .. n].

```

Essentially a specialization of my basic LCM solution `f⊇p~d`: ranges are duplicate-free, so they don't need to be deduplicated; ranges are ascending, so they don't need to be permuted; ranges are necessarily contiguous prefixes of the list of factors, so  can be replaced by the evidently much more performant `a`.
> 3 votes

# Answer
# Nibbles, 5.5 bytes

```
/|,~~+.,@%@

```

Attempt This Online!

```
/|,~~+.,@%@
/|,~        Find the first positive integer k such that
     +      the sum
      .,@   for i from 1 to n
         %@ of k mod i
    ~       is zero

```
> 3 votes

# Answer
# JavaScript (ES6), ~~92~~ ~~88~~ ~~80~~ ~~74~~ 69 bytes:

Thanks @ConorOBrien and @Neil

```
y=>(g=(a,b)=>b?g(b,a%b):a,[...Array(y)].map((_,i)=>y=y*++i/g(y,i)),y)

```
> 2 votes

# Answer
# Desmos, 16 bytes

```
f(n)=[1...n].lcm

```

Super straightforward

Try It On Desmos!
> 2 votes

# Answer
# Nim, 52 bytes

```
import math,sequtils
func p[I](n:I):I=lcm toSeq 1..n

```

Attempt This Online!
> 2 votes

# Answer
## 05AB1E, 20 bytes

```
Lpvyi¹LÒN>¢àN>*ˆ}}¯P

```

**Explanation**

```
Lpv                    # for each item in isprime(range(1,N)): N=7 -> [0,1,1,0,1,0,1]
   yi                  # if prime
     ¹LÒN>¢            # count occurrences of the prime
                         in the prime-factorization of range(1,N):
                         p=2 -> [0,1,0,2,0,1,0]
           àN>*ˆ       # add max occurrence of that prime multiplied by the prime
                         to global array: N=7 -> [4,3,5,7]
                }}     # end if/loop
                  ¯P   # get product of global array

```

Try it online
> 1 votes

# Answer
## Minkolang 0.15, 12 bytes

I have *two* 12-byte solutions, and have included them both.

```
1n[i1+4$M]N.

```

Try it here!

## Explanation

```
1               Push 1
 n              Take number from input
  [             For loop that repeats n times
   i1+          Push loop counter + 1
      4$M       Pop b, a and push lcm(a,b)
         ]      Close for loop
          N.    Output as number and stop.

```

About as straightforward as it gets.

---

```
11nLd[4$M]N.

```

Try it here!

## Explanation

```
11              Push two 1s
  n             Take number from input
   L            Pop b, a and push range from a to b, inclusive
    d           Duplicate top of stack (n)
     [4$M]      Pop b, a and push lcm(a,b), n times
          N.    Output as number and stop.

```

A third solution can be derived from this: remove a `1` and add a `d` after the current `d`. In both cases, the extra number is needed because the for loop runs one too many times, and making it run one less time takes two bytes (`1-` just before the `[`).
> 1 votes

# Answer
## Pyke, 3 bytes

```
S.L

```

Try it here!

```
S   - range(1, input+1)
 .L - lowest_common_multiple(^)

```
> 1 votes

# Answer
# Ruby, 25 bytes

```
g=->n{(1..n).reduce :lcm}

```

# Ruby, 25 bytes

```
g=->n{n<1?1:a[n-1].lcm n}

```
> 1 votes

# Answer
# GameMaker Language, 60 bytes

```
for(b=k=1;b;++k){b=0for(t=argument0;t;b+=k mod t--)}return k

```

Based on the logic of anatolyg's answer.
> 1 votes

# Answer
## QBIC, ~~35~~ 32 bytes

This brought me here.

```
:{p=0[a|~q%b|p=1]]~p=0|_Xq\q=q+1

```

Explanation:

```
:        Get cmd line param as number 'a'
{        Start an infinite DO loop
p=0      Sets a flag that shows if divisions failed
[a|      FOR (b=1; b<=a; b++)
~q%b     IF 'q' (which starts at 1 in QBIC) is not cleanly divisible by 'b'
|p=1     THEN Set the flag
]]   Close the FOR loop and the IF, leave the DO open
~p=0     IF 'q' didn't get flagged
|_Xq     THEN quit, printing 'q'
\q=q+1   ELSE raise 'q', redo
         [DO Loop implicitly closed by QBIC]

```

Here's a version that stops testing `q` when `b` doesn't cleanly divide it. Also, the order of testing `b`'s against `q` is reversed in the assumption that higher `b`'s will be harder to divide by (take `2`, `3`, `4` for instance: if `%2=0`, `%4` could be `!0`. Vice versa not so much...).

```
:{p=0[a,2,-1|~q%b|p=1┘b=2]]~p=0|_Xq\q=q+1

```
> 1 votes

# Answer
# PHP, ~~61~~ ~~52~~ 48 bytes

saved 9 bytes thanks to @user59178, 4 bytes by merging the loops.

Recursion in PHP is bulky due to the `function` key word; so I use iteration.
And with a "small"few tricks, I now even beat Arnauld´s JS.

```
while(++$k%++$i?$i>$argv[1]?0:$i=1:$k--);echo$k;

```

takes input from command line argument. Run with `-r`.

**breakdown**

```
while(++$k%++$i?    # loop $i up; if it does not divide $k
    $i>$argv[1]?0       # break if $i (smallest non-divisor of $k) is larger than input
    :$i=1               # while not, reset $i and continue loop with incremented $k
    :$k--);         # undo increment while $i divides $k
echo$k;         # print $k

```

**ungolfed**

That´s actually two loops in one:

```
while($i<=$argv[1]) # loop while $i (smallest non-divisor of $k) is not larger than input
    for($k++,       # loop $k up from 1
        $i=0;$k%++$i<1;);   # loop $i up from 1 while it divides $k
echo$k;             # print $k

```

*Note: copied from my answer on the duplicate*
> 1 votes

# Answer
# Pari/GP, 14 bytes

```
n->lcm([1..n])

```

Try it online!
> 1 votes

# Answer
# Japt, 10 bytes

No LCM built-in.

```
@õ e!vX}a1

```

Try it
> 1 votes

# Answer
# J-uby, 10 bytes

```
:+|:/&:lcm

```

Attempt This Online!

## Explanation

```
:+ | :/ & :lcm

:+ |            # Get range 1..n, then
     :/ & :lcm  # reduce with LCM

```
> 1 votes

# Answer
# Factor, 26 bytes

```
[ [1,b] 1 [ lcm ] reduce ]

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 3 bytes

```
L.¿

```

Pretty similar as most golfing languages.

Try it online or verify all test cases.

**Explanation:**

```
L    # Push a list in the range [1, (implicit) input]
 .¿  # Pop and push the LCM (Least Common Multiple) of this list
     # (which is output implicitly as result)

```
> 1 votes

# Answer
# Pyt, 9 bytes

```
Đ`Đ↔Ĺ↔⁻ł+

```

Try it online!

```
Đ            implicit input; Đuplicate
 `     ł     do... while top of stack is truthy
  Đ          Đuplicate top of stack
   ↔         flip stack
    Ĺ        get ĹCM of top two on stack
     ↔       flip stack
      ⁻      decrement
        +    add (removes pesky 0); implicit print

```
> 1 votes

# Answer
# Thunno, \\$ 5 \log\_{256}(96) \approx \\$ 4.12 bytes

```
R1+Al

```

Attempt This Online!

#### Explanation

```
R      # range(0, input)
 1+    # plus one
   Al  # LCM of list

```
> 1 votes

# Answer
# Python, 44 bytes

```
lambda n:math.lcm(*range(1,n+1))
import math

```

Attempt This Online!

Requires Python 3.9+
> 1 votes

# Answer
# Vyxal, 3 bytes

```
ɾ∆Ŀ

```

Run it!

Explanation:

```
ɾ   # numbers from 1 to input
 ∆Ŀ # least common multiple

```
> 1 votes

# Answer
# Thunno 2, 2 bytes

Try it online!

#### Explanation

```
    # Implicit input
R   # Range [1..input]
 ŀ  # Reduced by LCM
    # Implicit output

```
> 1 votes

# Answer
## Hoon, 67 bytes

```
|*
*
(roll (gulf 1 +<) |=({a/@ b/_1} (div (mul a b) d:(egcd a b))))

```

Create the list `[1..n]`, fold over the list with lcm. Unfortunately, the Hoon stdlib doesn't have a pre-built one I can use :/
> 0 votes

# Answer
# , 7 chars / 9 bytes

```
Мū…⩤⁽1ï

```

`Try it here (ES6 only).`

Just a LCM of inclusive range from 1 to input.
> 0 votes

# Answer
## AWK, 42 bytes

```
{for(x=n=1;n<=$1;)if(x%n++){x++;n=1}$0=x}1

```

Command line usage:

```
awk '{for(x=n=2;n<=$1;)if(x%n++){x++;n=2}$0=x}1' <<< NUM

```

I didn't see an `AWK` solution and a duplicate of the question just got posted yesterday, so I thought I'd throw this together. It's rather slow solving for `19` or larger on my box, but it works.
> 0 votes

# Answer
# Axiom, 35 bytes

```
f(x)==reduce(lcm,[i for i in 1..x])

```

test code and results

```
(25) -> [[i,f(i)] for i in [1,6,19,22,30]]
   (25)  [[1,1],[6,60],[19,232792560],[22,232792560],[30,2329089562800]]
                                                  Type: List List Integer

```

i just make the solution of Find the smallest positive integer which has all integers from 1 to n as factors becouse you say it is douplicate i post it here
> 0 votes

# Answer
# 8th, 23 bytes

**Code**

```
1 ' lcm rot 2 swap loop

```

This code leaves resulting pseudofactorial on TOS

**Usage and example**

```
ok> 7 1 ' lcm rot 2 swap loop .
420

```

Or more clearly

```
ok> : pseudofact 1 ' n:lcm rot 2 swap loop ;

ok> 7 pseudofact .
420

```
> 0 votes

# Answer
# Husk, 3 bytes

```
F⌉ḣ

```

Try it online!

same as APL.
> 0 votes

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


title: Write a haiku-w detector

text:
# Question
Title: Write a haiku-w detector
A haiku is a poem with three lines, with a 5/7/5 *syllable* count, respectively.

A **haiku-w** is poem with three lines, with a 5/7/5 **word** count, respectively.

## Challenge

Write a program that will return **true** if the input is a haiku-w, and **false** if not.

A valid haiku-w input must consist of 3 lines, separated by a newline.

* Line 1 must consist of 5 words, each word separated by a space.
* Line 2 must consist of 7 words, each word separated by a space.
* Line 3 must consist of 5 words, each word separated by a space.

## Examples

```
The man in the suit
is the same man from the store.
He is a cool guy.

```

**Result:** True

```
Whitecaps on the bay:
A broken signboard banging
In the April wind.

```

**Result:** False

---

## Rules

* This is , so the shortest answer in bytes wins.
* Standard code-golf loopholes apply. Cheating is prohibited.
* Other boolean return values, such as `1` and `0`, are acceptable.
* A length-3 list of strings as an input is also acceptable.
* Valid haiku-w inputs should not have leading or trailing spaces, or multiple spaces separating words.

# Answer
# JavaScript (ES6), ~~73~~ ~~72~~ ~~64~~ ~~63~~ ~~54~~ ~~42~~ 39 bytes

*Thanks to Neil for saving 13 bytes*

```
a=>a.map(b=>b.split` `.length)=='5,7,5'

```

## Explanation

This is a fat-arrow function that takes an array of strings as argument. It replaces each line by its word count. If it is a haiku-w, `a` now contains an array of a five, a seven and a five again. Since JavaScript doesn't allow us to compare 2 arrays at the same time, the array is converted to a string first, and then compared. This results in a boolean that is returned.
> 25 votes

# Answer
# AWK (GNU Awk), ~~24~~, ~~30~~, ~~28~~, 20 bytes

**Golfed**

```
517253==$0=q=q NF NR

```

Will output "517253" for *True*, and empty string for *False*.

> In awk, any nonzero numeric value or any nonempty string value is true. Any other value (zero or the null string, "") is false

The GNU Awk User's Guide

**How It Works**

Each awk statement (rule) consists of a pattern (or expression) with an associated action:

```
pattern {action}

```

Awk will read the input line by line (record by record) and evaluate pattern expression to see if a corresponding action is to be invoked.

The code above is a standalone Awk expression (pattern) w/o the action block, which is implied to be `{print $0}` in that case.

It should be read right-to-left:

`q=q NF NR`

Append a **N**umber of **F**ields (words) and **N**umber of **R**ecords (i.e. the current line number), to the variable *q*.

This way, when processing a proper Haiku-w, *q* will be set to:

* *51* \- on line #1 (5 words)
* *5172* \- on line #2 (5 words + 7 words)
* *517253* \- on line #3 (5 words + 7 words + 5 words)

`$0=q`

Assign the newly computed value of *q* to *$0* (which holds the whole current line/record by default).

`517253==$0`

Compare it with a "signature" for a proper Haiku-w (517253), if there is a match, the whole expression evaluates to "true" and a corresponding action (implicit `print $0`) is run, sending "517253" to stdout (True), otherwise output will be empty (False).

Note that this will properly recognize a Haiku-w, even if it is followed by an arbitrary number of garbage lines, but I believe that is ok, as:

> A length-3 list of strings as an input is also acceptable.

(i.e. we can assume the input to be 3 lines long)

**Test**

```
>awk '517253==$0=q=q NF NR'<<EOF
The man in the suit
is the same man from the store.
He is a cool guy.
EOF

517253

```

Try It Online !
> 14 votes

# Answer
# Python, 42 bytes

```
lambda l:[s.count(' ')for s in l]==[4,6,4]

```

**Try it online!**

Takes input as a list of lines, with the words separated by single spaces.

As we're guaranteed there'll be no leading or trailing spaces, and only single spaces will seperate each word, we can verify a w-haiku by simply counting the spaces in each line.

We do this in a list comprehension, to create a list of the space-counts. If it is a correct haiku, it should look like `[4, 6, 4]`, so we compare it with this and return the result.
> 10 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
ċ€⁶⁼“¥©¥‘

```

Try it online!

## Explanation

```
ċ€⁶⁼“¥©¥‘  Input: length-3 list of strings
 €         For each string
ċ ⁶          Count the number of spaces
    “¥©¥‘  Convert string to code page indices, makes [4, 6, 4]
   ⁼       Match

```
> 8 votes

# Answer
## Batch, 102 bytes

```
@echo off
call:c&&call:c 2||exit/b
:c
set/an=%1+5
set/ps=
for %%W in (%s%)do set/an-=1
exit/b%n%

```

Exits with non-zero errorlevel as soon as it reads a line with the wrong number of words.
> 7 votes

# Answer
# Mathematica, 21 bytes

```
{4,6,4}==Count@" "/@#&

```

Unnamed function taking a list of lists of characters as input and returning `True` or `False`. Simply counts how many spaces are in each list of characters, which under the rules of the challenge correlate perfectly with the number of words in each line.

Previous submission:

# Mathematica, 31 bytes

```
Length/@StringSplit/@#=={5,7,5}&

```

Unnamed function taking a list of strings as input and returning `True` or `False`.
> 7 votes

# Answer
## Haskell, ~~34~~ 33 bytes

```
f l=[sum[1|' '<-c]|c<-l]==[4,6,4]

```

Try it online!.

Edit: thanks to @xnor for a byte!
> 6 votes

# Answer
# Retina, 12 bytes

```
M%`
^4¶6¶4$

```

(there's a trailing space after the first line)

Try it online!

* `M%`` \- Count the number of spaces in each line.

+ `M` \- Match mode - print the number of matches.
    + `%` \- for each line
    + ``` \- separate configuration and regex pattern
    + \- just a space.
* `^4¶6¶4$` \- There should be 4, 6, and 4 spaces, and exactly three lines.

+ matches newlines. The rest is a simple regular expression.

Prints `1` for valid input, `0` for invalid.
> 6 votes

# Answer
# PowerShell, 43 bytes

```
"$args"-replace'\S'-match'^(    )
\1
\1$'

```

Try it online!

### Explanation

Takes input as a newline separated string.

Removes all non-whitespace, then checks to see that it matches "4 spaces, newline, 6 spaces, newline, 4 spaces newline" exactly, using a regex.

The capture group matches 4 spaces, the backreference `\1` refers to that. Newlines are embedded in the string. Note the second line of the regex contains two spaces after the backreference.
> 5 votes

# Answer
# Python, ~~58~~ 44 bytes

```
lambda h:[len(l.split())for l in h]==[5,7,5]

```

-14 by tbodt
> 4 votes

# Answer
## Pyke, ~~11~~ 9 bytes

```
dL/uq

```

Try it here!

```
dL/       -  map(i.count(" "), input)
        q - ^ == V
   u  -  [4, 6, 4]

```

After the `u` byte there are the following bytes: `0x03 0x04 0x06 0x04`
> 4 votes

# Answer
# Perl, 26 bytes

24 bytes of code + 2 bytes for `-ap` flags.

```
$m.=@F}{$_=$m==575&$.==3

```

Try it online!
> 4 votes

# Answer
# Pyth, 9 bytes

```
qj464T/R;

```

A program that takes input of a list of `"quoted strings"` and prints `True` or `False` as appropriate.

Test suite

**How it works**

```
qj464T/R;   Program. Input: Q
qj464T/R;Q  Implicit variable fill
     T      Are the base-10
 j          digits
  464       of 464
q           equal
      /     to the number
        ;   of spaces
       R    in each string
         Q  in the input?
            Implicitly print

```
> 4 votes

# Answer
# Japt, 11 bytes

*Saved lots of bytes thanks to @ETHproductions*

This takes an array of three strings as input.

```
®¸lÃ¥"5,7,5

```

Run it online!
> 4 votes

# Answer
## C 142 bytes

```
void f(){char *c;l=3;s[3]={0};while(l>0){if(*c==' ')s[l-1]++;if((*c=getchar())=='\n'){l--;}}printf("%d",(s[0]==4 && s[1]==6 && s[2]==4)?1:0);}

```

Ungolfed version:

```
void f()
{
  char *c;
  c = (char *)malloc(sizeof(char));
  int l=3;
  int s[3]= {0};

  while(l>0)
  {
    if(*c==' ')
    s[l-1]++;

    if( (*c=getchar())=='\n')
    {
      l--;
    }
  }
  printf("%d",(s[0]==4 && s[1]==6 && s[2]==4)?1:0);
}

```

Returns 1 for 5/7/5 sequence else 0.

A positive testcase:
> 3 votes

# Answer
# J, 12 bytes

```
4 6 4=#@;:@>

```

The input is a boxed list of strings.

## Explanation

This is a fork with a constant left tine. This checks the result of the right tine, `#@;:@>`, for equality with `4 6 4`. The right time unboxes each (`>`), then (`@`) converts each string to words (`;:`), then (`@`) takes the length of each (`#`).
> 3 votes

# Answer
# C++, 357 bytes

Sort of new to code golf, but this is the best I could do quickly

```
#include <iostream>
using namespace std;
int n(std::string s)
{
    int b = 0;
    for(char c: s)
        if(c == ' ') b++;
    cout << "C = " << b;
    return b;
}
int main()
{
    string a, b, c;
    getline(cin, a);
    getline(cin, b);
    getline(cin, c);
    if(n(a)==4 && n(b)==6 && n(c)==4)
        cout<<'1';
    else cout << '0';
    return 0;
}

```
> 3 votes

# Answer
## R, 48 bytes

```
all(stringr::str_count(scan(,"")," ")==c(4,6,4))

```

Reads a 3-length character vector from stdin and works by counting the number of spaces. To count the number of spaces we use the `str_count` from the `stringr` package which can count occurrences based on a regex pattern.

An alternative approach without using packages could be:

```
all(sapply(scan(,""),function(x)length(el(strsplit(x," "))))==c(5,7,5))

```
> 3 votes

# Answer
# Ruby 1.9.3

Not golfed, but is itself a haiku-w

```
def haiku_w(input)
  lines = input.split("\n")
  lengths = lines.map(&:split).map(&:length)
  lengths.eql?([5,7,5])
end

```

or...

```
lines equals input split (newlines)
lengths equals lines map split map length
lengths equals five seven five?

```

Unfortunately doesn't work with leading whitespace on any lines, but does cope with trailing.
> 3 votes

# Answer
# Python 2, ~~57~~ 64 bytes

**Edit** Corrected with the addition of 7 bytes after feedback from @Dada. Thanks!

```
i,j=input,''
for x in i():j+=`len(x.split())`+' '
i(j=='5 7 5 ')

```

Try it online!

Not the shortest Python answer by a long way but just wanted to use the new trick I learned recently of using `input()` to display the output and save a `print` statement. Takes a list of lines as input. Requires Ctrl C (or any other key-press for that matter) to terminate the program (with an exception) in a terminal but works fine without on TIO.
> 2 votes

# Answer
# MATL, 16 bytes

```
"@Y:Ybn&h][ACA]=

```

The input is a cell array of strings and returns a truthy or falsey array.

**Try it Online**

**Explanation**

```
        % Implicitly grab input
"       % For each element in the cell array
@Y:Yb   % Split it on spaces
n       % Count the number of elements
&h      % Horizontally concatenate everything on the stack
[ACA]   % Create the array [5 7 5]
=       % Perform an element-wise equality
        % Implicitly display the truthy/falsey array

```
> 2 votes

# Answer
# MATLAB / Octave, 38 bytes

```
@(x)cellfun(@(y)sum(y==32),x)==[4 6 4]

```

This solution accepts a cell array of strings as input, counts the number of spaces in each line and then compares the result to the array `[4 6 4]` and yields a truthy (all values are 1) or falsey (any value is zero) array.

Online demo
> 2 votes

# Answer
# Perl 6, 25 bytes

```
{.lines».words~~(5,7,5)}

```
> 2 votes

# Answer
# Java (OpenJDK), 82 bytes

-2 bytes thanks to @corvus\_192!

```
s->s[0].split(" ").length==5&s[2].split(" ").length==5&s[1].split(" ").length==7

```

Try it online!

It looks *so golfable* but without a builtin map function, I can't find a good way. Iterating through the array is a few bytes longer, as is writing a map function using streams.

Lambda expression takes an array of Strings and returns a Boolean.
> 2 votes

# Answer
## Clojure, 44 bytes

```
#(=(for[l %](count(filter #{\ }l)))'(4 6 4))

```

Input is list of strings. Function finds only spaces and counts them. This explanation is a Haiku. :)
> 2 votes

# Answer
# SmileBASIC, ~~96~~ 94 bytes

```
INPUT A$,B$,C$?C(A$,4)*C(B$,6)*C(C$,4)DEF C(S,E)WHILE""<S
INC N,POP(S)<"!
WEND
RETURN N==E
END

```
> 2 votes

# Answer
# Java 7, 154 bytes

```
class M{public static void main(String[]a){System.out.print(a.length==3&&a[0].split(" ").length==5&a[1].split(" ").length==7&a[2].split(" ").length==5);}}

```

The program requirement and potential of having less or more than three lines, not too mention Java's verbosity itself, causes this 'golfed' code to be pretty big..

**Ungolfed:**

Try it here.

```
class M{
  public static void main(String[] a){
    System.out.print(a.length == 3
        && a[0].split(" ").length == 5
         & a[1].split(" ").length == 7
         & a[2].split(" ").length == 5);
  }
}

```
> 2 votes

# Answer
# SimpleTemplate, 77 bytes

Sadly, the regular expression aproach is the shortest.

```
{@if"@^([^\s]+ ?){5}\s([^\s]+ ?){7}\s([^\s]+ ?){5}+$@"is matchesargv}{@echo1}

```

Requires that the text is given as the first argument, with \*NIX-style newlines. This won't work with Windows-style newlines.

**Ungolfed:**

```
{@if "@^([^\s]+ ?){5}\s([^\s]+ ?){7}\s([^\s]+ ?){5}+$@"is matches argv}
    {@echo 1}
{@/}

```

---

**Non-regex based, 114 byes**

```
{@setR 1}{@eachargv asL keyK}{@php$DATA[L]=count(explode(' ',$DATA[L]))!=5+2*($DATA[K]&1)}{@set*R R,L}{@/}{@echoR}

```

This requires that each line is given as an argument to the function.

**Ungolfed:**

```
{@set result 1}
{@each argv as line key k}
    {@php $DATA['line'] = count(explode(' ', $DATA['line'])) != 5+2*( $DATA['k'] & 1 )}
    {@set* result result, line}
{@/}
{@echo result}

```
> 2 votes

# Answer
# Stacked, 22 bytes

```
[' 'eq sum]map(4 6 4)=

```

Takes input from the top of the stack as a list of character strings, as such:

```
($'The man in the suit' $'is the same man from the store.' $'He is a cool guy.')

```

## Explanation

```
[' 'eq sum]map(4 6 4)=
[         ]map          map the following function over each item
 ' 'eq                  vectorized equality with ' '
       sum              summed
              (4 6 4)=  is equal to (4 6 4)

```
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
€#€g575SQ

```

Try it online!

**Explanation**

```
€#         # split each line on spaces
  €g       # get length of each line
    575    # push the number 575
       S   # split into list of digits
        Q  # compare for equality

```
> 2 votes

# Answer
## R, 100 bytes

```
f<-function(a){all(sapply(a,function(x){length(grep(" ",as.list(strsplit(x,"")[[1]])))})==c(4,6,4))}

```

Takes as an argument a length-3 list of strings. Probably won't be golfed further since further golfing turns it into @Billywob's answer.
> 1 votes

# Answer
# SpecBAS - 135 bytes

```
1 INPUT a$: DIM b$(SPLIT a$,NOT ","): l$=""
2 FOR EACH c$ IN b$()
3 DIM d$(SPLIT c$,NOT " ")
4 l$=l$+STR$ ARSIZE d$()
5 NEXT c$
6  ?l$="575"

```

Input is a comma separated string, each part being put in an array. Then each of those elements are split up on spaces and the length of that array is appended to a string.

Prints 1 (true) or 0 (false) if it matches the 5-7-5 format.
> 1 votes

# Answer
# C#, ~~136~~ 124 bytes

*Saved 12 bytes thanks to **VisualMelon***

```
class P{static void Main(string[]s){var v="";foreach(var c in s)v+=c.Split(' ').Length;System.Console.WriteLine(v=="575");}}

```

Arguments require each sentence to be wrapped in double quotes and then separated by a space, like this:

```
"One two three four five" "One two three four five six seven" "One two three four five"

```

## Ungolfed

```
    class P
{
    static void Main(string[]s)
    {
        var v=""; //Short way to make a string
        foreach(var c in s) //loop through all sentences
            v += c.Split(' ').Length; //split on space and append the array size as string
        );
        System.Console.WriteLine(v == "575"); //print the result!
    }
}

```

Please note this is my first attempt on golfing ever, let me know if anything is against the rules. Also feel free to point out things that makes this golf even shorter!
> 1 votes

# Answer
# Ruby, 39 bytes

```
puts ARGV.map{|l|l.split.size}==[5,7,5]

```

Try it online!

Accepts lines of input as command-line arguments, finds the word counts, and check they are 5/7/5
> 1 votes

# Answer
## C# 6 - 80 bytes (98 with using)

```
bool a(string[]s)=>s.Select(x=>x.Split(' ').Length).SequenceEqual(new[]{5,7,5});

```

This, as usual, assumes a method is enough, and doesn't include a complete program.

It also doesn't include `using System.Linq;`, as it is present as default in the standard C# class template from VS 2008 onwards. Add 18 bytes if you want to include it in the count.

The method accepts the input as an aray of strings (one per line), then splits every string using spaces as separators, keeping the length of every array generated this way. Finally, it checks if those lengths are equal to {5,7,5}.
> 1 votes

# Answer
# PHP - ~~78~~ 75 bytes

*Saved one byte thanks to **Kevin Cruijssen***

Here's my first ever submission on PPCG :

```
<?=preg_match('#^(\S+ ){4}\S+\r\n(\S+ ){6}\S+\r\n(\S+ ){4}\S+$#',$argv[1]);

```

**Regex breakdown :**

```
#                   Regex delimiter
^                   Starts with
(\S+ ){4}           [Any non-space character present n times, followed by a space] x 4
\S+                 Any non-space character present n times
\r\n                Carriage return
(\S+ ){6}           [Any non-space character present n times, followed by a space] x 6
\S+                 Any non-space character present n times
\r\n                Carriage return
(\S+ ){4}           [Any non-space character present n times, followed by a space] x 4
\S+                 Any non-space character present n times
$                   Ends with
#                   Regex delimiter

```

Try it online !
> 1 votes

# Answer
# PHP, 46 bytes

```
<?=array_map(str_word_count,$argv)==[0,5,7,5];

```

Run like this:

```
echo '<?=array_map(str_word_count,$argv)==[0,5,7,5];' | php -- "The man in the suit" "is the same man from the store." "He is a cool guy." 2>/dev/null
> 1

```

# Explanation

```
<?=                        # Print result of the expression.
  array_map(               # Apply function to each input line.
    str_word_count,        # Count words
    $argv
  )==[0,5,7,5];            # Check if result is 5,7,5 (need 0 because
                           # first arg is always `-`).

```
> 1 votes

# Answer
# Haskell, 29 bytes

```
([5,7,5]==).(length.words<$>)

```

Ungolfed

```
wordCount line = length (words line)
isHaikuW lines = map wordCount lines == [5, 7, 5]

```
> 1 votes

# Answer
# Regex, 44 Bytes

I'm new to codegolfing, but have attempted one with a regex.

```
/^(\S+ ){4}\S+\n(\S+ ){6}\S+\n(\S+ ){4}\S+$/

```

will match exactly 5, 7, 5 words and not match anything else. ie.

```
Golfing with regex is fun
obscurity prevails; intention is hidden from view
and sanity is forever lost

```

First block `(\S+ ){4})` matches four words (at least one nonspace character) with a trailing space. `\S+\n` matches a word and a newline.

Second block `(\S+ ){6}\S+\n` is similar but for 6 words, trailing space, word and newline. Third block is identical to first `(\S+ ){4}\S+\n)`

`^(...)$` ensures that the match is found at the beginning and end, so it won't match a haiku inside a string.

Suggested improvements welcome as it's my first time golfing (and I'm rusty at regex).
> 1 votes

# Answer
# CJam, 15 bytes

```
5 7 5]qN/Sf/:,=

```

Try it online!

**Explanation**

```
5 7 5]           The array [5, 7, 5]
      q          Read all input
       N/        Split on newlines
         Sf/     Split each line on spaces
            :,   Get the length of each line (in words)
              =  Check if the two arrays are equal

```
> 0 votes

# Answer
# Scala, 34 bytes

```
_.map(_ split " "size)==Seq(5,7,5)

```

Usage:

```
val f:(Seq[String]=>Boolean)=_.map(_ split " "size)==Seq(5,7,5)
println(f(Seq("The man in the suit", "is the same man from the store.", "He is a cool guy.")))

```

Ungolfed:

```
array=>array.map(line=>line.split(" ").size)==Seq(5,7,5)

```

Explanation:

```
 _.map(               //map each line in the argument
     _ split " "size  //  to the number of parts when the line is splitted at spaces
 ) == Seq(5,7,5)      //compare that to a sequence of 5, 7, and 5

```
> 0 votes

# Answer
# C, ~~114~~ ~~113~~ 108 bytes

```
n,i,r,c;f(){n=i=r=1;while(n<4){c=getchar();c-32?c-10?1:++n%2?i-7?(r=0):(i=1):i-5?(r=0):(i=1):++i;}return r;}

```
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
εð¢}ƵĆ7вQ

```

Try it online!

```
εð¢}ƵĆ7вQ  # full program
        Q  # is...
  ¢        # the list of the number of..
 ð         # spaces...
  ¢        # in...
           # (implicit) current element in...
ε          # for each element in...
           # implicit input...
        Q  # equal to...
       в   # the list of the base...
      7    # literal...
       в   # digits of...
    ƵĆ     # 242...
        Q  # ?
   }       # end map
           # implicit output

```
> 0 votes

# Answer
# Thunno 2, 7 bytes

```
Oḷ575d⁼

```

Try it online!

#### Explanation

```
Oḷ575d⁼  # Implicit input
O        # Split each line on spaces
 ḷ       # Get the length of each inner list
      ⁼  # And check if it's exactly equal to
  575d   # The list [5,7,5]
         # Implicit output

```
> 0 votes

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


title: Decode the string

text:
# Question
Title: Decode the string
This is my first challenge on ppcg!

### Input

A string consisting of two different ascii characters. For example

```
ABAABBAAAAAABBAAABAABBAABA

```

### Challenge

The task is to decode this string following these rules:

1. Skip the first two characters
2. Split the rest of the string into groups of 8 characters
3. In each group, replace each character with `0` if that character is the same as the first character of the original string, and with `1` otherwise
4. Now each group represents a byte. Convert each group to character from byte char code
5. Concatenate all characters

### Example

Let's decode the above string.

```
 AB  AABBAAAA  AABBAAAB  AABBAABA
 ^^     ^         ^         ^
 |      |         |         |
 |      \---------|---------/
 |                |
Skip      Convert to binary

```

Notice that `A` is the first character in the original string and `B` is the second. Therefore, replace each `A` with `0` and each `B` with `1`. Now we obtain:

```
00110000  00110001  00110010

```

which is `[0x30, 0x31, 0x32]` in binary. These values represent characters `["0", "1", "2"]` respectively, so the final output should be `012`.

### Scoring

This is, of course, , which means make your code as short as possible. Score is measured in bytes.

### Constraints and IO format

Standard rules apply. Here are some additional rules:

* You can assume valid input
    + Input string consists of exactly two different characters
    + The first two characters are different
    + The minimal length of the input string is 2 characters
    + The length will always give 2 modulo 8
* You can assume the string will always consist only of printable ASCII characters
    + Both in the input and in the decoded string
* Leading and trailing whitespace are allowed in the output (everything that matches `/\s*/`)

# Answer
> 14 votes
# brainfuck, ~~76 71~~ 65 bytes

-6 bytes thanks to Nitrodon!

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

```

Try it online!

Feels weird beating Python...

# Answer
> 9 votes
# Stax, ~~15~~ 11 bytes

```
ó║¥U⌂½íèäöñ

```

Run and debug it at staxlang.xyz!

~~Quick 'n' dirty approach. Working on improving it.~~ Improved it!

### Unpacked (13 bytes) and explanation

```
2:/8/{{[Im:bm
2:/              Split at index 2. Push head, then tail.
   8/            Split into length-8 segments.
     {      m    Map block over each segment:
      {  m         Map block over each character:
       [             Copy first two elements (below) in-place.
        I            Index of character in first two characters.
          :b       Convert from binary.
                 Implicit print as string.

```

# Answer
> 7 votes
# 05AB1E, 10 bytes

```
¦¦Sk8ôJCçJ

```

Try it online!

-3 thanks to emigna.

---

```
Ù             # Unique letters, in order they appear.
 v            # For each...
  yN:         # Push letter and index, replace in input.
     }        # End loop.
      ¦¦      # Remove first x2.
        8ô    # Split into eighths.
          C   # Convert to integer.
           ç  # Convert to char.
            J # Join together entire result.

```

# Answer
> 6 votes
## bash, ~~59~~ ~~58~~ 52 bytes

```
tr -t "$1" 01 <<<$1|cut -c3-|fold -8|sed 'i2i
aP'|dc

```

Try it online!

Thanks to Cows quack for saving 6 bytes.

This challenge works remarkably well with a series of coreutils (and `dc` to do the conversion and output at the end). First, we use

```
tr -t "$1" 01 <<<$1

```

to transliterate the two characters in the input to zeroes and ones. The `-t` flag truncates the first argument to the length of the second, so this reduces to transliterating the first two characters in the input to `0` and `1`, which is what we want. Then,

```
cut -c3-

```

removes the first two characters, and

```
fold -8

```

outputs 8 of the characters per line. Finally, the `sed` command turns each line into a `dc` snippet that reads the number as binary and outputs that byte.

# Answer
> 6 votes
# JavaScript (Node.js), 67 bytes

```
s=>s.replace(/./g,x=(c,i)=>(x=x*2|c==s[1],Buffer(i<3|i&7^1?0:[x])))

```

Try it online!

### How?

We use two different syntaxes of the `Buffer` constructor:

* **`Buffer([n])`** generates a buffer containing the sole byte **n** and is coerced to the corresponding ASCII character. Only the 8 least significant bits of **n** are considered.
* **`Buffer(n)`** generates a buffer of **n** bytes. Therefore, `Buffer(0)` generates an empty buffer, which is coerced to an empty string.

*Note: They both are deprecated in recent Node versions. `Buffer.from([n])` and `Buffer.alloc(n)` should be used instead.*

### Commented

```
s =>                   // given the input string s
  s.replace(/./g, x =  // initialize x to a non-numeric value (will be coerced to 0)
    (c, i) => (        // for each character c at position i in s:
      x = x * 2 |      //   shift x to the left
          c == s[1],   //   and append the new bit, based on the comparison of c with s[1]
      Buffer(          //   invoke the constructor of Buffer (see above):
        i < 3 |        //     if i is less than 3
        i & 7 ^ 1 ?    //     or i is not congruent to 1 modulo 8:
          0            //       replace c with an empty string
        :              //     else:
          [x]          //       replace c with the ASCII char. whose code is the LSB of x
      )                //   end of Buffer constructor
  ))                   // end of replace(); return the new string

```

# Answer
> 6 votes
# Z80 machine code on an Amstrad CPC, ~~32 31~~ 30 bytes

```
000001  0000  (9000)        ORG &9000
000002  9000  EB            EX DE, HL
000003  9001  46            LD B, (HL)
000004  9002  23            INC HL
000005  9003  5E            LD E, (HL)
000006  9004  23            INC HL
000007  9005  56            LD D, (HL)
000009  9006  1A            LD A, (DE)
000010  9007  05            DEC B
000011  9008  13            INC DE
000012  9009  4F            LD C, A
000014  900A                Light
000015  900A  26 01         LD H, &01
000016  900C                Last
000017  900C  13            INC DE
000018  900D  05            DEC B
000019  900E  C8            RET Z
000021  900F                Loop
000022  900F  1A            LD A, (DE)
000023  9010  B9            CP C
000024  9011  28 01         JR Z, Lable
000025  9013  37            SCF
000026  9014                Lable
000027  9014  ED 6A         ADC HL, HL
000028  9016  30 F4         JR NC, Last
000029  9018  7D            LD A, L
000030  9019  CD 5A BB      CALL &BB5A
000032  901C  18 EC         JR Light

```

The code takes the instruction *replace each character with `0` if that character is the same as the first character of the original string, and with `1` otherwise* literally and doesn't ever bother to check that a character matches the second character in the input string. It just checks for same-as-first-character and different-from-first-character.

I ran out of registers (the Z80 only has 7 easily usable 8-bit registers, the rest need longer instructions) so I put `&01` in `H`, along with using `L` to build up the ASCII character (I just realised it's unnecessary to initialise `L`, saving one byte). When `H` overflows into the Carry flag, the character in `L` is ready to be output. Luckily, there is a 16-bit `ADC` (**Ad**d with **C**arry) that does the job of a left-shift instruction.

`(DE)` can only be read into `A` although `(HL)` can be read into any 8-bit register, so it was a compromise which one to use. I couldn't compare `(DE)` with `C` directly, so I had to load one into `A` first. The labels are just random words that start with `L` (a requirement of the assembler).

* `A` the Accumulator - the only register that can do comparisons
* `B` the counter register ~~for the instruction `DJNZ`: **D**ecrement (`B`) and **J**ump if **N**on **Z**ero~~. By rearranging the code, I was able to do the job of `DJNZ` with one fewer byte
* `C` the first character in the input string
* `D`, `E` as `DE` the address of the current input character
* `H` the carry trigger (every 8th loop)
* `L` the output character being built up

# Answer
> 5 votes
# J, ~~17~~ 13 Bytes

```
u:_8#.\2}.1{=

```

-4 thanks to FrownyFrog

Old version:

```
u:_8#.\2&({.i.}.)

```

### Explanation:

```
u:_8#.\2}.1{=
            =  | Self classify, for each unique element x of y, compute x = y, element-wise
          1{   | Second row
       2}.     | Drop 2
  _8#.\        | Convert non-intersecting subarrays of length 8 from binary
u:             | Convert to characters

```

Examples:

```
   = 'ABAABBAAAAAABBAAABAABBAABA'
1 0 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 0 1 1 0 0 1 1 0 1
0 1 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0

   2}.1{= 'ABAABBAAAAAABBAAABAABBAABA'
0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0

   _8#.\2}.1{= 'ABAABBAAAAAABBAAABAABBAABA'
48 49 50

   u:_8#.\2}.1{= 'ABAABBAAAAAABBAAABAABBAABA'
012

```

# Answer
> 5 votes
# , 71 bytes

```
function(s)intToUtf8(2^(7:0)%*%matrix((y=utf8ToInt(s))[-1:-2]==y[2],8))

```

Try it online!

Surprisingly golfy!

First, converts the string to ascii code-points with `utf8ToInt`, saving it as `y`. Removing the first two characters with negative indexing is shorter than using `tail`.

The array `y[-1:-2]==y[2]` is equivalent to the bits when `%*%` (matrix multiplication) is applied, but first we reshape that array into a `matrix` with `nrow=8`, converting from a linear array to byte groupings. Fortuitously, we can then convert to the ascii code points using matrix multiplication with the appropriate powers of 2, `2^(7:0)`, and then we convert the code points back to a string with `intToUtf8`.

# Answer
> 5 votes
# Python 2, 77 bytes

```
lambda s:[chr(int(`map(s.find,s)`[i:i+24:3],2))for i in range(7,3*len(s),24)]

```

Try it online!

# Answer
> 4 votes
# Pyth, ~~20~~ 9 bytes

```
CittxLQQ2

```

Saved 11 bytes thanks to FryAmTheEggman.

Try it here

### Explanation

```
CittxLQQ2
    xLQQ    Find the index of each character in the string.
  tt        Exclude the first 2.
 i      2   Convert from binary.
C           Get the characters.

```

# Answer
> 4 votes
# Python 3, 77 bytes

```
a,b,*r=input();x=i=0
for c in r:i*=2;i|=a!=c;x+=1;x%8or print(end=chr(i&255))

```

Try it online!

# Answer
> 4 votes
# PHP, ~~73~~ 71 bytes

```
while($s=substr($argn,-6+$i+=8,8))echo~chr(bindec(strtr($s,$argn,10)));

```

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

golfings:

* start index at `-6` and pre-increment by `8`
* exploit that `strtr` ignores excessive chars in the longer parameter (no `substr` needed)
* translating to `10` and then inverting needs no quotes -\> -1 byte
* invert character instead of ascii code --\> `~` serves as word boundary -\> -1 byte.

# Answer
> 3 votes
# Japt, 11 bytes

```
¤£bXÃò8 ®Íd

```

Try it

---

## Explanation

```
¤               :Slice from the 3rd character
 £  Ã           :Map over each X
  bX            :  Get the first 0-based index of X in the input
     ò8         :Split to an array of strings of length 8
        ®       :Map
         Í      :  Convert from base-2 string to base-10 integer
          d     :  Get the character at that codepoint

```

# Answer
> 3 votes
# Java 8, ~~143~~ ~~142~~ 141 bytes

```
s->{char i=47;for(;++i<50;)s=s.replace(s.charAt(i%2),i);for(i=2;i<s.length();)System.out.print((char)Long.parseLong(s.substring(i,i+=8),2));}

```

-1 byte thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
s->{                            // Method with String parameter and no return-type
  char i=47;                    //  Index character, starting at 47
  for(;++i<50;)                 //  Loop 2 times
    s.replace(s.charAt(i%2),i)  //   Replace first characters to 0, second characters to 1
  for(i=2;i<s.length();)        //  Loop `i` from 2 upwards over the String-length
    System.out.print(           //   Print:
     (char)                     //    As character:
      Long.parseLong(           //     Convert Binary-String to number
       s.substring(i,i+=8)      //      The substring in range [i,i+8),
      ,2));}

```

# Answer
> 3 votes
# Ruby, ~~82~~ 79 bytes

```
->s{s[2..-1].tr(s[0,2],'01').chars.each_slice(8).map{|s|s.join.to_i(2).chr}*''}

```

Try it online!

# Answer
> 3 votes
## PHP + GNU Multiple Precision, 63 61

```
<?=gmp_export(gmp_init(substr(strtr($argn,$argn,"01"),2),2));

```

sadly the GMP extention is not default activated (but shipped).

Run like this:

```
echo "ABABABAAAAABABAAAAAABAABBAABAAAABBABAAABBB" | php -F a.php

```

# Answer
> 2 votes
# Python 3, ~~99~~ 86 bytes

```
lambda s:[chr(int(str(list(map(s.find,s[i:i+8])))[1::3],2))for i in range(2,len(s),8)]

```

Try it online!

Thanks to ASCII-only for basically the whole thing really

# Answer
> 2 votes
# Red, 110 bytes

```
func[s][t: 0 i: 128 foreach c next next s[if c = s/2[t: t + i]i: i / 2 if i = 0[prin to-char t t: 0 i: 128]]]

```

Try it online!

## Explanation:

A simple straightforward solution, no builtins.

```
f: func [s] [                      ; s is the argument (string)
    t: 0                           ; total - initially 0
    i: 128                         ; powers of 2, initially 0
    b: s/2                         ; b is the second charachter
    foreach c next next s [        ; for each char in the input string after the 2nd one
        if c = b [t: t + i]        ; if it's equal to b than add the power of 2 to t
        i: i / 2                   ; previous power of 2
        if i = 0 [                 ; if it's 0
            prin to-char t         ; convert t to character and print it
            t: 0                   ; set t to 0
            i: 128                 ; i to 128
        ]
    ]
]

```

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

Index origin 0. Prompts for input of string

```
⎕av[2⊥¨(+\0=8|⍳⍴b)⊂b←2↓s≠↑s←⎕]

```

Explanation:

```
s≠↑s←⎕ prompts for string and creates binary vector not equal to first character

b←2↓s drops first two elements of binary

(+\0=8|⍳⍴b)⊂ splits binary into groups of 8

2⊥¨ converts each group to decimal

⎕av[...] displays decoded characters

```

# Answer
> 2 votes
# Ruby, ~~61~~ 42 bytes

-19 bytes thanks to benj2240

```
->s{[s[2..-1].tr(s[0,2],"01")].pack("B*")}

```

Try it online!

# Answer
> 2 votes
# Google Sheets, 123 bytes

```
=ArrayFormula(Join("",IfError(Char(Bin2Dec(Substitute(Substitute(Mid(A1,3+8*(Row(A:A)-1),8),Left(A1),0),Mid(A1,2,1),1))),""

```

Input is in cell `A1`. Google will automatically add `)))` to the end of the formula.

Explanation:

* `Mid(A1,3+8*(Row(A:A)-1),8)` grabs chunks of characters 8 at a time, starting with the third.
* `Substitute(Mid(~),Left(A1),0)` replaces each instance of the first character with 0.
* `Substitute(Substitute(~),Mid(A1,2,1),1)` replaces the second character with 1.
* `Char(Bin2Dec(Substitute(~)))` converts the chunk to decimal and then to ASCII.
* `IfError(Char(~,""))` corrects all the errors that result from the fact that `Row(A:A)` returns *far* more values than we so `Bin2Dec` gives us a lot of zero values and `Char` errors out on zero.
* `ArrayFormula(Join("",IfError(~)))` joins together all the `Char` results and `ArrayFormula` is what makes the `Row(A:A)` return an array of values instead of just the first value.

# Answer
> 2 votes
# Python 2, 88 bytes

```
i=input()
f=''.join('10'[x==i[0]]for x in i[2:])
while f:print chr(int(f[:8],2));f=f[8:]

```

Try it online!

Not the shortest - just an alternative way.

Following version prints the output on one line for 98 bytes although the rules state that trailing whitespace is allowed.:

```
i=input();f=''.join('10'[x==i[0]]for x in i[2:]);o=""
while f:o+=chr(int(f[:8],2));f=f[8:]
print o

```

Try it online!

# Answer
> 2 votes
# Haskell, 75 bytes

```
f[_,_]=""
f(z:o:s)=toEnum(sum[2^b|(b,c)<-zip[7,6..0]s,c==o]):f(z:o:drop 8s)

```

Try it online!

# Answer
> 2 votes
# Perl 5 `-lp`, 34 bytes

```
#!/usr/bin/perl -lp
s%.%1-/^$&/%eg;$_=pack'B*',s/..//r

```

Try it online!

# Answer
> 2 votes
## REXX, 41 bytes

```
arg a+2 b
say x2c(b2x(translate(b,01,a)))

```

Try it online!

# Answer
> 1 votes
# Haskell, 124 105 93 bytes

```
f(x:_:y)=fromEnum.(/=x)<$>y
g[]=[]
g s=(toEnum.sum.zipWith((*).(2^))[7,6..0])s:g(drop 8s)
g.f

```

Try it online!

`f` converts the string to a list of bits by comparing each character to the first one, turning the `Bool`s into zeros and ones with `fromEnum`. `g` divides this list into groups of 8, converts them to decimal, and takes the value of the resulting number as an `Enum`, which `Char` is an instance of.

### Changes:

* -19 bytes thanks to @Laikoni (removing import, embedding `map` into function)
* -12 bytes inspired by @Lynn's answer (getting rid of `take` by zipping with shorter list)

# Answer
> 1 votes
# C# (Visual C# Compiler), 158 bytes

```
using System.Linq;a=>new string(a.Skip(2).Where((c,i)=>(i-2)%8==0).Select((c,i)=>(char)a.Skip(8*i+2).Take(8).Select((d,j)=>d!=a[0]?1<<7-j:0).Sum()).ToArray())

```

Try it online!

# Answer
> 1 votes
# Perl 5 `-p`, 40 bytes

```
s/(.)(.)//;$_=pack'B*',eval"y/$1$2/01/r"

```

Try it online!

# Answer
> 1 votes
# Scala, 95 bytes

```
s.substring(2).replace(s(0),'0').replace(s(1),'1').grouped(8).map(Integer.parseInt(_,2).toChar)

```

Try it online!

# Answer
> 1 votes
# K4, ~~22~~ 21 bytes

**Solution:**

```
"c"$2/:'0N 8#?/0 2_x:

```

**Example:**

```
q)k)"c"$2/:'0N 8#?/0 2_x:"ABAABBAAAAAABBAAABAABBAABA"
"012"

```

**Explanation:**

Evaluated right-to-left:

```
"c"$2/:'0N 8#?/0 2_x: / the solution
                  x:  / save input as x
               0 2_   / cut x at 0 and 2nd index
             ?/       / lookup (?) over (/)
        0N 8#         / reshape into 8-long rows
    2/:'              / decode (/:) each (') from base 2
"c"$                  / cast to character

```

**Notes:**

* -1 byte thanks to ngn!

# Answer
> 1 votes
# Forth (gforth), 83 bytes

```
: f over c@ 0 rot 2 do 2* over i 4 pick + c@ <> - i 8 mod 1 = if emit 0 then loop ;

```

Try it online!

Input is a standard Forth string (address and length) output is printed to stdout

## Explanation

```
over c@          \ get the value of the first character in the string
0 rot            \ add a starting "byte" value of 0 and put the length on top of the stack
2 do             \ start a loop from 2 to length-1
   2*            \ multiply the current byte value by 2 (shift "bits" left one)
   over          \ copy the reference char to the top of the stack
   i 4 pick +    \ add the index and the starting address to get address of the current char
   c@ <>         \ get the char at the address and check if not equal to the reference char
   -             \ subtract the value from our bit count, -1 is default "true" value in forth
   i 8 mod 1 =   \ check if we are at the last bit in a byte
   if            \ if we are
      emit 0     \ print the character and start our new byte at 0
   then          \ and end the if statement
loop             \ end the loop

```

# Answer
> 1 votes
# C++, 181 Bytes (VS 2017)

```
#include<iostream>
int main(int,char**a){int c=7;uint8_t b=0;for(int i=2;a[1][i]!='\0';++i,--c){if(a[1][i]!=a[1][0]){b|=(1<<c);}if(c==0){std::cout<<static_cast<char>(b);c=8;b=0;}}}

```

# Formatted, with better variable names and comments:

```
#include <iostream>

int main(int argc, char* argv[])
{
  int counter = 7;
  uint8_t byte = 0;

  // Loop until input string is fully read
  for (int i = 2; argv[1][i] != '\0'; ++i, --counter)
  {
    if (argv[1][i] != argv[1][0])
    {
      byte |= (1 << counter); // Shift 2^counter into the current byte
    }

    if (counter == 0)
    {
      std::cout << static_cast<char>(byte); //
      counter = 8;
      byte = 0;
    }
  }
}

```

# Answer
> 0 votes
# Charcoal, 17 bytes

```
Ｆ⪪Ｅ✂θ²Ｌθ¹⌕θι⁸℅↨ι²

```

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

```
   ✂θ²Ｌθ¹           Slice first two characters from input
  Ｅ      ⌕θι        Replace each character with its index in the input
 ⪪          ⁸       Split into groups of 8
Ｆ                   Loop over each group
              ↨ι²   Convert from binary
             ℅      Convert from code to character
                    Implicitly print

```

# Answer
> 0 votes
# Jelly, 8 bytes

```
ṫ3nḢs8ḄỌ

```

Try it online!

```
ṫ3nḢs8ḄỌ
ṫ3        All but first two characters...
  n       does not equal...
   Ḣ      the first character.
    s8    Split into groups of 8.
      Ḅ   Convert from binary (vectorizes).
       Ọ  chr() (vectorizes).

```

# Answer
> 0 votes
# Jelly, 7 bytes

```
ḢnḊs8ḄỌ

```

Try it online!

Who needs  (tail)?

~~Coincidentally~~ Because there is only one way to do it, the 4 last bytes are identical to dylnan's answer.

---

Actually there is another way, providing there are no leading NUL bytes in the output:

# Jelly, 7 bytes

```
ḢnḊḄb⁹Ọ

```

Try it online!

# Answer
> 0 votes
# C (gcc), 94 86 bytes (107 for leading whitespace)

Thanks to Jonathan Frech for saving 8 bytes!

```
f(s,v,i,j)char*s,*v;{for(v=++s,i=j=0;*++s;j&7||(putchar(i),i=0))i|=!(*s-*v)<<(--j&7);}

```

Try it online!

---

Original solution:

```
f(s,v,i,j)char*s,*v;{for(v=++s,i=j=0;*++s;){i|=!(*s-*v)<<(--j&7);if(!(j&7)){putchar(i);i=0;}}}

```

Try it online!

This assumes that `main()`'s stripping of whitespace is allowable. Otherwise, I got it to 107 bytes:

```
f(s,v,i,j)char*s,*v;{while(*s++<33);for(v=s,i=j=0;*++s;){i|=!(*s-*v)<<(--j&7);if(!(j&7)){putchar(i);i=0;}}}

```

Try it online!

# Answer
> 0 votes
# Perl 6, 82 bytes 79 bytes

```
{.[2..*].map({+($^s ne.[0])}).rotor(8)».join».parse-base(2)».chr with .comb}

```

Shortened with help from Phil H (but his solution is still shorter, so go look at his one)

Try it online!

# Answer
> 0 votes
# Perl 6, 59 bytes

```
{/(..)(.**8)*/;$1>>.trans(~$0=>"01")>>.parse-base(2)>>.chr}

```

Try it online!

Matches the pattern first, then uses a transliteration to 01 and parses the number.

# Answer
> 0 votes
# C (tcc), 134 bytes

```
f(char*x){
    int a=*x,i,l=strlen(x);
    for(i=2;i<l;)
        x[i] = x[i++] - a ? 49 : 48;
    for(i=10;i<=l;i+=8)
        a=x[i],
        x[i]=0,
        putchar(strtol(x+i-8,0,2)),
        x[i]=a;
}

```

Try it online!

I am still trying to think of a better way than that ugly swap :P

# Answer
> 0 votes
# Rust, 166 bytes

```
fn x(x:&str){for i in(2..x.len()-2).step_by(8){print!("{}",u8::from_str_radix(&x[i..i+8].chars().map(|c|(c as u8-17)as char).collect::<String>(),2).unwrap()as char)}}

```

Playground

Playground link because it requires nightly and tio seems to use stable.

# Answer
> 0 votes
# Coconut, 71 bytes

```
s->k(chr..int$(?,2)..k$(str..s.index),groupsof(8,s[2:]))
k=''.join..map

```

Try it online!

# Answer
> 0 votes
# GolfScript, 24 bytes

```
1>(:x;8/{{x=}%2base}%''+

```

Try it online!

Explanation:

```
1>(:x;8/{{x=}%2base}%''+ Full program, implicit input.
                         Stack: "ABAABBAAAAAABBAAABAABBAABA"
1>                       Pop the first character (str[1:])
                         Stack: "BAABBAAAAAABBAAABAABBAABA"
  (:x;                   Pop the next character and assign it to x
                         Stack: "AABBAAAAAABBAAABAABBAABA"; x = 66
      8/                 Split into groups of 8
                         Stack: ["AABBAAAA" "AABBAAAB" "AABBAABA"]; x = 66
        {          }%    Map
                           Stack (first run): "AABBAAAA"; x = 66
         {  }%             Map again
                             Stack (first run): 65; x = 66
          x=                 Compare to x
                             Stack: 0; x = 66
                           Stack: [0 0 1 1 0 0 0 0]; x = 66
                           Well, actually, it is a string of 0 and 1 bytes.
              2base        Convert binary string to number
                           Stack: 48; x = 66
                         Stack: [48 49 50]; x = 66
                     ''+ Convert to string
                         Stack: "012"; x = 66
                         Implicit output

```

# Answer
> 0 votes
# bash \+ bc \+ xxd, 87 bytes

```
a="${1:2:${#1}}"
b="${a//${1::1}/0}"
bc<<<"obase=16;ibase=2;${b//${1:1:1}/1}"|xxd -r -p

```

Usage:

```
bash foo.bash 'ABAABBAAAAAABBAAABAABBAABA'

```

# Answer
> 0 votes
# Thunno 2 `B`, 9 bytes

```
Ḣsḣ8ẇQ2ȷḋ

```

Try it online!

#### Explanations

```
Ḣsḣ8ẇQ2ȷḋ  # Implicit input, converted to charcodes
Ḣ          # Extract the first character from the input
 sḣ        # And remove the next character from the rest
   8ẇ      # Split it into groups of eight
     Q     # For each: is it not equal to the first character
       ȷ   # For each inner list in this nested list:
      2 ḋ  # Convert it back from binary to decimal
           # Implicit output, converted to characters

```

Old:

```
2ɱ$2ỵ8ẇsȷbC  # Implicit input
2ɱ           # Take the first two characters
  $2ỵ        # And then push the rest of the string
     8ẇ      # Split it into groups of eight
       sȷb   # Convert each from base-(first two characters)
          C  # Convert to characters
             # Implicit output

```

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


title: Equal numbers in sub-array

text:
# Question
Title: Equal numbers in sub-array
Given an array of numbers with `length >=3` and `length % 3 == 0`

`[1, 2, 3, 4, ...]`

You will split it in sub-arrays of length 3

`[[1, 2, 3], [4, 5, ...], [...`

And return an array with

* \[0\] =\> The amount of cases in the sub-array where **all numbers are equal**
* \[1\] =\> In case all numbers in sub-array are not equal, the amount of cases in the sub-array where **only 2 numbers are equal**

**Example and test cases:**

* Input: `[2, 4, 2, 5, 5, 5, 4, 2, 1, 3, 3, 1]` output `[1, 2]`

This is because

```
[[2, 4, 2], [5, 5, 5], [4, 2, 1], [3, 3, 1]]
  ^     ^    ^  ^  ^               ^  ^
   equal    all equal              equal

```

so 2 `equal` and 1 `all equal`

* `[3,5,6,5,5,7,6,6,8,7,7,7,3,4,2,4,4,3] => [1, 3]`
* `[3,3,3,4,4,4,5,5,5,6,6,6,5,4,3] => [4, 0]`
* `[3,4,5,6,7,8,9,8,7,6,5,4,3,2,1] => [0, 0]`

---

This is , so the shortest answer in bytes win.

---

PD: Apologies for my English.

# Answer
# Octave, ~~60~~ ~~52~~ 50 bytes

```
@(x)sum(sum(~diff(sort(reshape(x,3,[]))))'==[2 1])

```

Try it online!

Saved 8 bytes thanks to Luis!

### Explanation:

Reshapes the input into a matrix with 3 rows, and the appropriate amount of columns. It then sorts each of the columns, and calculates the difference between the elements on different rows. This gives a matrix with two rows, where identical numbers will have a zero, and different numbers will have a positive number. This is negated, so that all equal elements are `1`, and all unequal are `0`. We then sum each of those columns, giving us one of the three alternatives: `0 = All elements are unequal`, `1 = Two elements are equal` and `2 = All elements are equal`. We then check how many are `>1`, and how many are exactly `==1`.
> 6 votes

# Answer
# Jelly,  ~~9~~  8 bytes

-1 thanks to Dennis (use a new alias for `L€`, )

```
Q3ÐƤẈċⱮ2

```

**Try it online!**
> 4 votes

# Answer
# 05AB1E, 10 bytes

```
3ôεÙg}12S¢

```

Try it online!

**Explanation**

```
3ô          # split input into groups of 3
  ε  }      # for each triple
   Ù        # remove duplicates
    g       # and get the length
      12S¢  # count the number of 1s and 2s in the result

```
> 4 votes

# Answer
# JavaScript (ES6), 70 bytes

```
f=([a,b,c,...d],t=p=0)=>1/a?f(d,t+!(a-b&&a-c?b-c||++p:b-c&&++p)):[t,p]

```

Try it online!

### How?

We recursively extract each triplet **\[a,b,c\]** from the input array and update two counters **t** (three-of-a-kind) and **p** (pair), using the following formula:

```
t =
t + !(a - b && a - c ? b - c || ++p : b - c && ++p)

```

There are 5 possible cases which are detailed below, from 'all equal' to 'all distinct'.

```
a b c | a-b && a-c | b-c | b-c || ++p | b-c && ++p | t +=
------+------------+-----+------------+------------+------------
4 4 4 | false      | 0   | n/a        | 0          | !0    --> 1
4 4 5 | false      | ≠0  | n/a        | ++p        | !++p  --> 0
4 5 4 | false      | ≠0  | n/a        | ++p        | !++p  --> 0
5 4 4 | true       | 0   | ++p        | n/a        | !++p  --> 0
4 5 6 | true       | ≠0  | ≠0         | n/a        | !(≠0) --> 0

```
> 4 votes

# Answer
# Pyth, ~~13~~ ~~14~~ ~~12~~ 11 bytes

```
/Lml{kcQ3S2

```

Try it here

### Explanation

```
/Lml{kcQ3S2
      cQ3        Split the input into groups of 3.
  ml{k           Deduplicate and get the length of each.
/L               Count the number...
         S2      ... of 1s and 2s.

```
> 3 votes

# Answer
# oK, ~~17~~ 16 bytes

```
+/(1 2=#=:)'0N3#

```

Try it online!

```
            0N3# /reshape into groups of 3 (see ngn's comment)
  (       )'     /for each group:
        =:       /    make a map from number -> indices
       #         /    count number of keys/values
   1 2=          /    check if the count is equal to 1 or 2
+/               /sum together the columns

```

For , the 17 byte version is: `+/(1 2=#=:)'0N 3#`.
> 3 votes

# Answer
# , 70 bytes

```
function(v,x=lengths(by(v,seq(0,a=v)%/%3,table)))c(sum(x<2),sum(x==2))

```

Try it online!

***Previous versions :***

# , 82 bytes

```
function(v,a=!1:2){for(i in lengths(by(v,seq(0,a=v)%/%3,table)))a[i]=a[i]+1;a[-3]}

```

Try it online!

---

# , 93 bytes

```
function(v,a=table(lengths(by(v,0:(length(v)-1)%/%3,unique)))[c('1','2')])`[<-`(a,is.na(a),0)

```

Try it online!
> 3 votes

# Answer
# Java (JDK 10), 116 bytes

```
l->{int r[]={0,0,0},i=0,a,b,c;for(;i<l.length;b=l[i++],c=l[i++],r[a==b?b==c?0:1:b==c|a==c?1:2]++)a=l[i++];return r;}

```

Try it online!

Note: returns a 3-elements array with `[0]` and `[1]` returning th appropriate values, and `[2]` returning a dummy value (the number of 3-lists without any elements in common) . This is totally valid according to the current rules.
> 3 votes

# Answer
# PowerShell, 106 bytes

```
param($a)for(;$a){$x,$y,$z,$a=$a;if($x-eq$y-and$y-eq$z){$i++}else{$j+=$x-eq$y-or$y-eq$z-or$z-eq$x}}+$i,+$j

```

Try it online!

Exactly what it says on the tin. Loops over input `$a`. Each iteration, peels off `$x,$y,$z` as the next three elements. Tests `if` they're all equal and if so, increments `$i`. `Else`, increments `$j` if at least one pair is equal. Once the loop is complete, output `$i` and `$j` as integers.

*So ... many ... dollars ...*
> 2 votes

# Answer
# Japt, ~~14~~ 13 bytes

```
2õ@ò3 x_â Ê¶X

```

Try it

---

## Explanation

```
2õ                :Range [1,2]
  @               :Pass each X through a function
   ò3             :  Split input to arrays of length 3
       _          :  Pass each through a function
        â         :    Remove duplicates
          Ê       :    Get length
           ¶X     :    Test for equality with X
      x           :  Reduce by addition

```
> 2 votes

# Answer
# Python 2, ~~77~~ ~~72~~ 65 bytes

```
lambda a:map([len(set(t))for t in zip(*[iter(a)]*3)].count,(1,2))

```

Try it online!

7 bytes saved via a clever trick from xnor
> 2 votes

# Answer
# Retina 0.8.2, 68 bytes

```
(.+)¶(.+)¶(.+)
;$1;$2;$3;$1;
%M`(;\d+)(?=\1;)
s`((1)|(3)|.)+
$#3 $#2

```

Try it online! Link includes test cases with header to convert to desired format of one value per line. Explanation:

```
(.+)¶(.+)¶(.+)
;$1;$2;$3;$1;

```

Collect three values onto each line with separators and duplicate the first one at the end.

```
%M`(;\d+)(?=\1;)

```

Count the number of pairs of duplicates.

```
s`((1)|(3)|.)+
$#3 $#2

```

Count the number of `3`s and `1`s.
> 2 votes

# Answer
# Stax, 8 bytes

```
íUÖ←#"ë╕

```

Run and debug it
> 2 votes

# Answer
# , 16 15 bytes

-1 byte thanks to cole!

```
1#.1 2=/_3#@=\]

```

Try it online!

Pretty much the same approach as the majority of solutions.

## Explanation:

```
        _3    \]  - split the input into sublists of lenght 3
          #@~.    - for each triplet remove duplicates and take the length
   1 2=/          - compare with 1 and 2
1#.               - add up

```
> 2 votes

# Answer
# Common Lisp, 113 bytes

```
(lambda(l &aux(a 0)(b 0))(loop for(x y z)on l by #'cdddr do(if(= x y z)(incf a)(if(/= x y z)()(incf b))))`(,a,b))

```

Try it online!

Used the fact that in Common Lisp `(= x y z)` gives true if all the three elements are equal, and `(/= x y z)` gives true if no pair of numbers is equal.
> 2 votes

# Answer
# Retina, 23 bytes

```
S2,3,`
%Cq`\S+
*\C`1
2

```

Try it online!

### Explanation

```
S2,3,`

```

Split the input at every 3rd space starting at the (0-based) 2nd, i.e. split the input into groups of three.

```
%Cq`\S+

```

On each line (`%`) count the number (`C`) of unique (`q`) values (`\S+`).

```
*\C`1

```

Count the number of `1`s and print them with a trailing linefeed (`\`), but do so in a dry-run (`*`) so that we don't lose the previous result.

```
2

```

Count the number of `2`s (and print them automatically).
> 2 votes

# Answer
# Wolfram Language (Mathematica), 49 bytes

Saved two bytes thanks to Martin Ender.

```
{#~Count~{_},#~Count~{_,_}}&@BlockMap[Union,#,3]&

```

Try it online!
> 2 votes

# Answer
# Haskell, 90 bytes

```
g[]=[]
g(a:b:c:x)=(sum$map fromEnum[a==b,a==c,b==c]):g x
f x=[sum[1|y<-g x,y==n]|n<-[3,1]]

```

Try it online!

Looks a bit awkward...
> 2 votes

# Answer
# Elixir, 92 bytes

```
fn a->import Enum;c=map chunk(a,3),&(length uniq&1);{count(c,&(&1==1)),count(c,&(&1==2))}end

```

First, chunks the list into size length 3 `chunk(a,3)`

Secondly, it converts finds the length of each element, uniqified; `map chunk(a,3),&(length uniq&1)`.

Finally, it returns an array consisting of the number of times the resulting list is equal to one `count(c,&(&1==1))` and the number of times the resulting list is equal to two `count(c,&(&1==2))`.

Try it online!
> 2 votes

# Answer
# Ruby, 59 bytes

```
->a{[1,2].map{|x|a.each_slice(3).count{|y|x==y.uniq.size}}}

```

Try it online!
> 2 votes

# Answer
# Japt, ~~24~~ 19 bytes

```
ò3 ®â l
[Uè¥1 Uè¥2]

```

Try it online!
> 1 votes

# Answer
# Stax, 14 bytes

```
ü┬─*HTÜ╫\Ä╢qm♥

```

Run and debug it
> 1 votes

# Answer
# Prolog (SWI), 80 bytes

```
[A,B,C|T]-X/Y:-T-M/N,(A=B,B=C,X is M+1,Y=N;X=M,(A\=B,B\=C,Y=N;Y is N+1)).
_-0/0.

```

Try it online!
> 1 votes

# Answer
# Factor \+ `pair-rocket`, 58 bytes

```
[ 3 group 1 => 2 [ '[ cardinality _ = ] count ] with map ]

```

Try it online!
> 1 votes

# Answer
# Desmos, 84 bytes

```
l(r)=r.length
b=[l(k[3x-2...3x].unique)forx=[1...l(k)/3]]
f(k)=[l(b[b=1]),l(b[b=2])]

```

Try it on Desmos!
> 1 votes

# Answer
# Arturo, ~~61~~ ~~57~~ 56 bytes

```
$->a[b:[x,y,z]map[1,2]'n->enumerate a b->n=size tally@b]

```

Try it
> 1 votes

# Answer
# Husk, 9 bytes

```
hmLkoLuC3

```

Try it online!
> 1 votes

# Answer
# Vyxal ~~14~~ 13 bytes

```
3ẇƛ∪L;:1O$2Ox

```

Try it online!

#### Explanation:

```
3ẇ             # 3-partition
  ƛ            # Open lambda map
   ∪L          # Length of sublist union
     ;         # Close lambda map
      :        # Duplicate for next operation
       1O      # Count 1
         $     # Swap
          2O   # Count 2
            x  # Print stack as list

```
> 1 votes

# Answer
# Elm, ~~108~~ 106 bytes

```
import List.Extra as E
m=List.map
f x=m(\j->E.count((==)j)<|m(List.length<<E.unique)<|E.groupsOf 3 x)[1,2]

```

Try it on Ellie
> 1 votes

# Answer
# C (GCC), ~~135~~ ~~128~~ 117 bytes

*-7 bytes thanks to @ceilingcat*

*-11 more, again thanks to @ceilingcat*

This is basically @ceilingcat's answer now, since he's improved it by more than 13 percent.

```
#define E(k)v[k-~i]==v[i
a;b;i;f(v,l)int*v;{for(a=b=i=0;i<l;i+=3)E()]&E(1)]?++a:E()]|E(1)]|E(1)+1]&&++b;*v=a;v[1]=b;}

```

Try It Online!

Unfortunately, I'm too lazy to write a new explanation for the most recent answer, but it's quite similar to the previous 128-byte one:

```
#define E(j,k)v[j+i]==v[k-~i]
a;b;i;f(v,l)int*v;{for(a=b=i=0;i<l;i+=3)E(,)&&E(,1)&&++a||(E(,)||E(,1)||E(1,1))&&++b;*v=a;v[1]=b;}

```

Try It Online!

`f` takes a vector (`v`) and its length (`l`) as arguments, and return its values in the first two elements of that vector. Explanation:

```
#define E(j,k)v[j+i]==v[k-~i] // k-~i == k-(-i-1) == k+i+1. an empty first argument equals +i, and an empty second argument equals -~i == i+1
a;b;i;
f(v,l)int*v;
{
    for(a=b=i=0;i<l;i+=3)
        E(,)&&E(,1)&&++a // if element i, i+1 and i+2 are all equal, increment a
        ||(E(,)||E(,1)||E(1,1))&&++b; // otherwise, if any two elements are equal, increment b
    *v=a; // set the first element in v to a
    v[1]=b; // set the second one to b
}

```
> 1 votes

# Answer
# Zsh +coreutils, 67 bytes

```
for i j k;sort<<<"$i
$j
$k"|uniq -c>>a;h()grep -c "^ *$1" a;h 3;h 2

```

Try it online! ~~72b~~ ~~78b~~ ~~83b~~ ~~102b~~ ~~116b~~ ~~128b~~

`for...` passes the args in groups of 3, `uniq` finds the doubles and triples, `grep` counts the results.

### Zsh builtins only, 67 bytes

```
repeat $#/3 a+=(${#@[1,3]:#$1})&&shift 3;h()<<<${(M)#a:#$1};h 0;h 1

```

Try it online!
> 1 votes

# Answer
# Nibbles, 9 bytes

```
.,2,`?.`/3@,`$$@

```

Attempt This Online!

## Explanation

```
.    Map
,2    [1,2]
,     length of
`?     find indices in
.       map
`/ 3     split into chunks of 3
@         input
,        length of
`$        deduplicate
$          the chunk
@       of the number (1 or 2)

```
> 1 votes

# Answer
# Raku, 30 bytes

```
(+«*.rotor(3)».Set).Bag{1,2}

```

Try it online!

* `*.rotor(3)` breaks up the input list into groups of three elements.
* `».Set` converts each of those groups into a `Set`.
* converts each of those sets into its size.
* `.Bag` makes a `Bag` (a set with multiplicity) out of those sizes.
* `{1, 2}` looks up in that `Bag` the number of times sets with sizes of 1 and 2 were present.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 44 bytes

```
0&@@@c@BlockMap[Max@*c,#,3]/@{3,2}&
c=Counts

```

Try it online!

```
            BlockMap[Max@*Counts,#,3]           #equal in each block of 3
     Counts@                         /@{3,2}    count 3 equal, 2 equal
0&@@@                                           coerce Missing[...] to 0

```
> 1 votes

# Answer
# Thunno 2, 10 bytes

```
3ẇıUl;12dc

```

Try it online!

#### Explanation

```
3ẇıUl;12dc  # Implicit input
3ẇ          # Split into threes
  ı  ;      # Map over the list:
   Ul       #  Length of uniquified list
      12dc  # Count 1s and 2s
            # Implicit output

```
> 1 votes

# Answer
# Tcl, 111 bytes

```
proc S {L a\ 0 e\ 0} {lmap {x y z} $L {expr {$x-$y|$y-$z?$x==$y|$y==$z|$x==$z?[incr e]:0:[incr a]}}
list $a $e}

```

Try it online!

---

~~Tcl, 112 bytes
```
proc S {L a\ 0 e\ 0} {lmap {x y z} $L {expr {$x-$y||$y-$z?$x==$y|$y==$z|$x==$z?[incr e]:0:[incr a]}}
list $a $e}

```
Try it online!
~~

---

~~Tcl, 114 bytes
```
proc S {L a\ 0 e\ 0} {lmap {x y z} $L {expr {$x==$y&&$y==$z?[incr a]:$x==$y|$y==$z|$x==$z?[incr e]:0}}
list $a $e}

```
Try it online!
~~
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 108 bytes

```
x=>new[]{1,2}.Select(n=>x.Select((v,i)=>(v,g:i/3)).GroupBy(y=>y.g,y=>y.v).Count(y=>y.Distinct().Count()==n))

```

Try it online!

Less golfed...

```
// x is the input list of ints
x=>x
  // 1 distinct number means 3/3 are the same
  // 2 distinct number means 2/3 are the same
  new[]{1,2}
  // iterate over the outer array to get an index
  .Select(n=>x
    // iterate over the whole list with an index
    // and break into groups of size 3
    .Select((v,i)=>v,g:i/3))
    .GroupBy(y=>y.g,y=>y.v)
     // count the distinct values in each group
     // and get the result based on outer array value
    .Count(y=>y.Distinct().Count()==n))

```
> 0 votes

# Answer
# Tcl, 98 bytes

```
proc A l {set 1 0;set 2 0
foreach a\ b\ c $l {incr [llength [lsort -u "$a $b $c"]]}
return $1\ $2}

```

Try it online!

using `-unique` option of `lsort` command. I named `1` and `2` my variables for convenience, tough it seems pretty unusual to code `set 1 0` :)
> 0 votes

# Answer
# Thunno, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

```
3ApeZULE12dc

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

#### Explanation

```
3ApeZULE12dc  # Implicit input
3Ap           # Split into sublists of length 3
   e   E      # For each sublist:
    ZU        #   Remove duplicates
      L       #   And get the length
        12dc  # Count the number of 1s and 2s in this list
              # Implicit output

```
> 0 votes

# Answer
# Pip `-p`, 14 bytes

```
_N#*UQ*g<>3M12

```

Takes the numbers as command-line arguments. Attempt This Online!

### Explanation

```
_N#*UQ*g<>3M12
       g        ; List of command-line args
        <>3     ; Group into 3-element sublists
    UQ*         ; Uniquify each
  #*            ; Get length of each
_N              ; Lambda expression: how many times does the argument appear in ^
           M12  ; Map that lambda to the arguments 1 and 2

```

This returns a list containing the number of length-1 uniquified sublists and the number of length-2 uniquified sublists.
> 0 votes

# Answer
# Julia, 89 bytes

```
!x=(~=sum;a=length(x);b=[x[i:i+2] for i=1:3:a];c=~allequal.(b);[c,a÷3-c-~allunique.(b)])

```

Attempt This Online!

Julia has `allequal` and `allunique` built in. To find the number of triplets containing exactly 2 matching values (all remaining cases), I subtract these two amounts from the total. Replacing `÷` with `/` saves one byte, but the value becomes a float.
> 0 votes

# Answer
# Nim, 105 bytes

```
import sequtils
proc e[S](s:S):S=[1,2].mapIt s.distribute(s.len div 3).mapIt(it.deduplicate.len).count it

```

Attempt This Online!
> 0 votes

# Answer
# JavaScript, 82 bytes

Without recursion

```
a=>(b=[,0,0],a.map(d=>([x,y,z,...a]=a,x&&++b[new Set([x,y,z]).size])),[b[1],b[2]])

```

Try it:

```
f=a=>(b=[,0,0],a.map(d=>([x,y,z,...a]=a,x&&++b[new Set([x,y,z]).size])),[b[1],b[2]])

console.log(f([3,5,6,5,5,7,6,6,8,7,7,7,3,4,2,4,4,3])); // [1, 3]
console.log(f([3,3,3,4,4,4,5,5,5,6,6,6,5,4,3])); // [4, 0]
console.log(f([3,4,5,6,7,8,9,8,7,6,5,4,3,2,1])); // [0, 0]
```
> 0 votes

# Answer
# PowerShell, 81 bytes

```
for($r=@{};$i-$args.Count;$i++){$r[($args[$i++..++$i]|sort|gu).Count]++}
$r[1..2]

```

Try it online!

## Explanations

Look at the array by taking sub arrays of three successive elements `$args[$i..($i+2)]`

We count the number of items in the sub array after sorting and removing duplicates (`gu`)

Then we increment the count in the result object `$r`

From `$r`, we then show only the entries with a single or two numbers
> 0 votes

# Answer
# Scala, 185 bytes

Golfed version. Try it online!

```
val f:Array[Int]=>Array[Int]=l=> {var r=Array(0,0,0);var i=0;var a,b,c=0;while(i<l.length){b=l(i);c=l(i+1);a=l(i+2);r(if(a==b){if(b==c)0 else 1} else if(b==c||a==c)1 else 2)+=1;i+=3};r}

```

Ungolfed version. Try it online!

```
import java.util.Arrays
import java.util.function.Function

object Main {
  def main(args: Array[String]): Unit = {
    val f: Array[Int] => Array[Int] = l => {
      var r = Array(0, 0, 0)
      var i = 0
      var a, b, c = 0
      while (i < l.length) {
        b = l(i)
        c = l(i + 1)
        a = l(i + 2)
        r(if (a == b) {
          if (b == c) 0 else 1
        } else if (b == c || a == c) 1 else 2) += 1
        i += 3
      }
      r
    }
    val tests = Array(
      Array(2, 4, 2, 5, 5, 5, 4, 2, 1, 3, 3, 1),
      Array(3, 5, 6, 5, 5, 7, 6, 6, 8, 7, 7, 7, 3, 4, 2, 4, 4, 3),
      Array(3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 5, 4, 3),
      Array(3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    )
    for (test <- tests) {
      val result = f.apply(test)
      printf("%s: %s%n", Arrays.toString(test), Arrays.toString(result))
    }
  }
}

```
> 0 votes

# Answer
# Vyxal `s`, 57 bitsv1, 7.125 bytes

```
3ẇƛUL12f=

```

Try it Online!

## Explained

```
3ẇƛUL12f=
3ẇ         # Wrap into chunks of 3
  ƛ        # to each chunk
   UL      #   take the length of the chunk uniquified
     12f=  #   and push whether 1 and 2 is in that length list
# the s flag reduces the list by addition, which is performed element-wise vectorised

```

Created with the help of Luminespire.
> 0 votes

---
Tags: code-golf, array
---