title: Shorten text with Run Length Encoding

text:
# Question
Title: Shorten text with Run Length Encoding
Shorten (or not) text using run length encoding

**Input:**

```
heeeello
woooorld

```

**Output:**

```
1h4e2l1o
1w4o1r1l1d
```
* Read lines from stdin.
* Print to stdout.
* Stderr is of course discarded.
* Assume there are hidden testcases (no embedding of the output)
* Input/Output as ASCII
* Any language is accepted

# Answer
# Perl: ~~46~~ → 36 or 27 characters

~~`perl -pe's|((.)\2*)|@x=split//,$1;@x.$x[0]|eg'`~~

All hail @ardnew for coming up with the idea of using the `tr///c` operator to count the number of characters in the matched string instead of splitting:

```
perl -pe's|((.)\2*)|$1=~y///c.$2|eg'

```

Degolfed:

```
while(defined($_ = <>)) {
  $_ =~ s{((.)\2*)}           # match 1 or more consecutive identical non-newlines
         {
           ($1 =~ y///c )     # count the number of characters in $1
           .                  # and concatenate it
           $2                 # with the first matched character
         }eg;                 # execute substitution, match "global"
  print $_;                   # print the modified line
}

```

Usage:

```
$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg' infile

```

or via STDIN

```
$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg'
heeeello

```

prints

```
1h4e2l1o

```
> 4 votes

# Answer
# Stax, 7 bytes

```
ûèB☼å°╤

```

Run and debug it st staxlang.xyz!

### Unpacked (8 bytes) and explanation:

```
m|RFNppz
m           For each line of input:
 |R           Run-length encode: "heeeello" -> [[104,1],[101,4],[108,2],[111,1]]
   F          For each pair:
    N           Uncons-left: [104,1] -> push [104]; push 1
     ppz        Pop and print. Pop and print. Push "".
              Implicit print (always an empty string) with a newline

```

### 5 bytes, works only on a single line:

```
∩l↨me
|RmEp]    Unpacked
|R        Run-length encode: "heeeello" -> [[104,1],[101,4],[108,2],[111,1]]
  m       Map block over input:
   E        Explode array: [104,1] -> push 104, push 1
    p       Pop and print with no newline
     ]      Make a one-element list: 104 -> [104] (which is "h")
            Implicit print with newline

```

Run and debug it at staxlang.xyz!

Perhaps not legal. This program prints each pair on a line of its own. A bit sketchy.

If that output format is illegal, I give you **6 bytes**:

```
╡δôZ→╬
|RFEp]p    Unpacked
  F        For each item in array, execute block:
      p      Pop and print with no newline
             No implicit print in for-each block, so no extra newlines

```

Run and debug it at staxlang.xyz!

The language's creator recursive points out that uncons-right (`N`) can shorten this to six bytes unpacked, as it handles the `E` and the `]` on its own. Programs this short, however, often get no shorter when packed, and this is am example. Still six bytes: `|RFNpp` Edit: Had to update my main answer; this form is what I used.
> 3 votes

# Answer
# K (oK), 28 bytes

```
{,/($#:'c),'*:'c:(&~=':x)_x}

```

Try it online!

On mobile, explanation to follow...
> 3 votes

# Answer
# Scala, ~~150~~ ~~144~~ 134 bytes

```
io.Source.stdin.getLines.map(s=>println{val(x,y,z)=s.tail./:(("",s.head,1)){case((a,b,c),d)=>if(b==d)(a,b,c+1)else(a+c+b,d,1)};x+z+y})

```

Try it online!

**UPDATE**:

* 6 bytes saved thanks to @Kjetil S.
* 10 bytes saved thanks to @user

Here the pure Lambda de-golfed (97 bytes):

```
  s => {
    val (x,y,z) = s.tail./:(("", s.head, 1)) {
      case ((a, b, c), d) =>
        if (b == d)
          (a, b, c + 1)
        else
          (a + c + b, d, 1)
    }
    x+z+y
  }

```
> 3 votes

# Answer
# Add++, 74 bytes

```
D,g,@:,BGd€q$€bLzBFJ
D,f,@,10C$t€g
]getchar
y:''
Wx,`y,+x,`x,]getchar
$f>y

```

Try it online!

This could be half the size if we could take input from the command line

## How it works

The first line (the function `g`) actually performs RLE. The rest of it just reads the input char by char, passes it to a function `f`, which splits on newlines, then runs `g` on each line.

`g` simply groups equal adjacent characters with `BG`, then gets the lengths (`€bL`) and deduplicates (`€q`). We then `z`ip these together, flatten, `J`oin and print.
> 3 votes

# Answer
## J, 35 31 characters

```
,(](":@#,{.);.1~1,2~:/\])1!:1[1

```

Usage:

```
   ,(](":@#,{.);.1~1,2~:/\])1!:1[1
heeeello
1h4e2l1o
   ,(](":@#,{.);.1~1,2~:/\])1!:1[1
woooorld
1w4o1r1l1d

```
> 2 votes

# Answer
# Python 3, 84 bytes

```
def f(s,c=1):i,*j=s;b=j[:1]==[i];print(end='%s%s'%(c,i)*(b^1));f(j,1+b*c)
f(input())

```

Try it online!

# Explanation

Checks if the first and second characters of the string are equal. If they are, increase the counter by 1. If they are not, print the counter and the first item and reset the counter to 1. In both cases, the function is called recursively with the first character removed.

Raises an error when end of string is reached.

---

Without I/O restrictions, but with minimal byte count:

# Python 3.8 (pre-release), 70 bytes

```
f=lambda s:'%s%s'%(len(s)-len(t:=s.lstrip(p:=s[0])),p)+f(t)if s else''

```

Try it online!

Python 3 equivalent (77 bytes)

# Explanation

Strips all repeating characters off the start of the string. Then it returns a string containing (1.) the difference in lengths between the original string and the stripped string; (2.) the first character of the original string; (3.) the result of the recursive function applied to the stripped string. Recursion ends when an empty string is encountered.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
|εÅγs.ιJ,

```

Try it online.

Or alternatively:

```
|εÅγøí˜J,

```

Try it online.

**Explanation:**

```
|          # Read all lines of input as list
 ε         # For-each over the lines:
  Åγ       #  Run-length encode, pushing the list of characters and lengths separately
    s      #  Swap so the characters at at the top and lengths below it
     .ι    #  Interleave the two lists
       J   #  Join the list of characters and lengths together to a single string
        ,  #  And output it with trailing newline

|εÅγ       # Same as above
    ø      #  Zip/transpose; creating pairs of [character, length]
     í     #  Reverse each pair to [length, character]
      ˜    #  Deep flatten the pairs to a single list
       J,  #  Join them together to a single string, and output it with trailing newline

```
> 2 votes

# Answer
# Ruby, 42 bytes

```
->s{s.gsub(/(.)\1*/){|m|"#{m.size}"+m[0]}}

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 98 bytes

```
Print[""<>StringCases[#,s:x_..:>ToString@StringLength@s<>x]]&/@StringSplit[$ScriptInputString,"
"]

```

Try it online!

A more flexible I/O format reduces this solution to **54 bytes**:

```
""<>StringCases[#,s:x_..:>ToString@StringLength@s<>x]&

```

Try it online!
> 2 votes

# Answer
# CJam, 2 bytes

```
e`

```

`e`` is a built-in for run-length encoding. CJam's implicit output ignores array brackets, and so turns `[[1 'h] [2 'e]]` into `"1h2e"`

Try it online!
> 2 votes

# Answer
# Husk, 10 bytes

```
m(ṁ§:osL←g

```

Try it online!
> 2 votes

# Answer
# Haskell, 78 bytes

```
import Data.List
m@main=getLine>>=putStrLn.(>>=shows.length<*>take 1).group>>m

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
Åγsø˜

```

Try it online!

```
Åγsø˜  # full program
    ˜  # flatten each sublist of...
   ø   # list of all elements of...
Åγ     # chars and corresponding run lengths of chars in...
       # implicit input...
   ø   # with each element from...
  s    # second...
   ø   # sublist paired with corresponding element in...
  s    # first...
   ø   # sublist
       # implicit output

```
> 2 votes

# Answer
# JavaScript (V8), 66 bytes

*-10 thanks to @Original Original Original VI*

```
r=>r.split`
`.map(d=>d.replace(/(.)\1*/g,g=>g.length+g[0])).join`
`

```

My first time using `\1` in a regular expression, which is a super overpowered way to approach this problem (looks like a few answers already use it). The rest of the code is basically just I/O.
> 2 votes

# Answer
# Scala, 116 bytes

```
_ split "\n"map{def d:Seq[_]=>Any={case e+:f=>val(g,h)=f span e.==
""+e+(g.size+1)+d(h)case x=>x}
d(_)}mkString "\n"

```

Try it online!

Is it short? No. Does it use best practices where it wouldn't make the code longer? No. Did I do it for ethical reasons? No. Is it creative? No. Am I proud of it? Yes.
> 2 votes

# Answer
# Brachylog, 11 bytes

```
ḅ⟨{lṫ}ch⟩ᵐc

```

Try it online!

(If output *really* has to be on stdout, add one byte for `w` at the end.)

```
          c    The output is the concatenation of
 ⟨    c ⟩ᵐ     the concatenated pairs of
  {lṫ}         length converted to a string
       h       and first element
ḅ        ᵐ     for every run in the input.

```
> 1 votes

# Answer
# Python 3 iterative, ~~115~~ ~~99~~ 97 bytes

```
while 1:
 a=b='';k=0
 for c in input():e=a!=c;b+=(str(k)+a)*e;k+=1-k*e;a=c
 print(b[1:]+str(k)+a)

```

Try it online!

# Python 3 recursive, ~~136~~ ~~130~~ 129 bytes

```
f=lambda r,c,s,k=1:s and(c==s[0]and f(r,c,s[1:],k+1)or f(r+str(k)+c,s[0],s[1:]))or r[1:]+str(k)+c
while 1:print(f('','',input()))

```

Try it online!

The iterative approach seems quite successful, while the recursive version has a lot of room for improvement.
> 1 votes

# Answer
# Julia 1.1, ~~94~~ ~~84~~ 81 bytes

```
foldl(((n,l),c)->(c==l||print(n,l);((c==l&&n)+1,c)),readline()*'\n',init=("",""))

```

Try it online!
> 1 votes

# Answer
# Retina, 12 bytes

```
(.)\1*
$.0$1

```

Try it online.

**Explanation:**

Get a part of 1 or more of the same character, capturing the character in capture group 1.

```
(.)\1*

```

Replace it with the length of the total match, concatted with the character from capture group 1:

```
$.0$1

```
> 1 votes

# Answer
# Vyxal, `d`, 2 bytes

```
øe

```

Try it Online!

That is,

```
øe  # run length encode the implicit input
    # the d flag deep sums the top of the stack before outputting

```
> 1 votes

# Answer
# Pyth, 6 5 bytes

```
jksr8

```

Relatively self explanatory, just joins together Pyth's run length encode instruction

Edit: -1 byte because while working on something completely different I remembered flattening a 2D list is just summing the elements.

Try it online!
> 1 votes

# Answer
## Zsh, 117

```
while read s;do n=1;for i in {1..$#s};do if [[ $s[i] != $s[i+1] ]];then echo -n $n$s[i];n=0;fi;((n++));done;echo;done

```

Run it like this:

```
zsh script.zsh < infile

```

### De-golfed

```
while read s; do                      # while stdin has more
  n=1                                 # repeat counter
  for i in {1..$#s}; do               # for each character
    if [[ $s[i] != $s[i+1] ]]; then   # same as next one?
      echo -n $n$s[i]                 # print if no
      n=0
    fi
    ((n++))
  done
  echo                                # newline between words
done

```
> 0 votes

# Answer
# Bash: 104 characters

```
while read s;do e=;while [[ $s ]];do c=${s:0:1};n=${s##+($c)};e+=$[${#s}-${#n}]$c;s=$n;done;echo $e;done

```

Sample run:

```
bash-4.2$ while read s;do e=;while [[ $s ]];do c=${s:0:1};n=${s##+($c)};e+=$[${#s}-${#n}]$c;s=$n;done;echo $e;done <<END
heeeello
woooorld
END
1h4e2l1o
1w4o1r1l1d

```
> 0 votes

# Answer
# Burlesque (17B)

```
{=[{J[-jL[Q}\m}WL

{=[{^^[~\/L[Sh}\m}WL

```

Older/Alternative and longer versions:

```
{=[{^^L[Sh\/-]Sh.+}m[\[}WL
{=[{^^L[Sh\/-][-.+}m[\[}WL
{=[{^^L[Sh\/-~.+}m[\[}WL
{=[{^^L[Sh\/-].+}\m}WL
{=[{^^L[Sh\/[~.+}\m}WL
{=[{^^L[Sh\/[~_+}\m}WL
{=[{^^L[Sh\/fc.+}\m}WL
{=[{^^L[Sh\/-~.+}\m}WL
{=[{^^L[Sh\/-]\/}\m}WL

```
> 0 votes

# Answer
## APL (24)

```
,↑{(⍕⍴⍵),⊃⍵}¨B⊂⍨B≠¯1⌽B←⍞

```
> 0 votes

# Answer
# rs, 19 chars

This doesn't really count because I created rs *way* after this was posted...but it was fun anyway!

```
(.)(\1*)/(^^\1\2)\1

```

Try it here!
> 0 votes

# Answer
# Zsh, 44 bytes

44 bytes: try it online. Based on this.

```
echo ${(s::)1}|xargs -n1|uniq -c|tr -d \\n\

```

---

70 bytes: try it online. Based on this.

```
for ((n=1;i++<#w;n++))[[ $w[i] != $w[i+1] ]]&&printf $n$w[i]&&n=0
echo

```
> 0 votes

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


title: Elias omega coding: encoding

text:
# Question
Title: Elias omega coding: encoding
## Background

**Elias omega coding** is a universal code which can encode positive integers of any size into a stream of bits.

Given a positive integer \\$N\\$, the encoding algorithm is as follows:

1. Start with a single zero in the output.
2. If \\$N=1\\$, stop.
3. Prepend the binary digits of \\$N\\$ to the current output.
4. Let \\$N\\$ be the number of digits just prepended, minus one. Go back to step 2.

In Python-like pseudocode:

```
n = input()
s = "0"
while n > 1:
    # bin(n) is assumed to give a plain string of bits, without "0b" prefix
    s = bin(n) + s
    n = len(bin(n)) - 1
output(s)

```

## Illustration

The number 1 gets encoded into a single `0`.

The number 21 gets encoded into `10100101010`, or `10 100 10101 0` in chunks, where each chunk is added to the output stream in the following order: first "0" by default, then the binary of 21, then 4 (the bit length of 21 minus 1), then 2, then stop.

## Task

Given a positive integer \\$N\\$, output its Elias omega code.

You can take the input number \\$N\\$ in any convenient format, including its representation in binary.

The output must be a valid representation of a flat stream of bits, which includes:

* a plain string or array of zeros and ones, or
* a single integer whose binary representation corresponds to the stream of bits.

Outputting the bits in reverse or outputting a nested structure of bits (e.g. `["10", "100", "10101", "0"]` for 21) is not allowed.

Shortest code in bytes wins.

## Test cases

```
N     => Omega(N)
1        0
2        100
3        110
4        101000
5        101010
6        101100
7        101110
8        1110000
12       1111000
16       10100100000
21       10100101010
100      1011011001000
345      1110001010110010
1000     11100111111010000
6789     11110011010100001010
10000    111101100111000100000
1000000  1010010011111101000010010000000

```

This is OEIS A281193.

# Answer
> 7 votes
# Dodos, ~~96~~ ~~91~~ 90 bytes

```
	> > E
	+ >
E
	E - + L B
	> B
B
	B + L H
	+ H
L
	>
	> -
H
	H - -
	+ >
-
	dip
+
	dot
>
	dab

```

Try it online!

I've re-discovered this crazy and wonderful language today, so I've wasted two hours building this :D

### Explanation

Dodos programs are composed by a series of function definitions, each non-indented symbol here is a function name and the indented lines following the symbol are the definition (the first 2 lines are the definition of the main function).

Each function takes a list of number as input and produces new list by concatenating in a list the outputs of the definitions of each line. Each line can be interpreted as function composition, where `F G H` means `F(G(H(input)))`.

Recursion is where the crazy part really start: if while computing a function `F(x)` we try computing `F(y)` for any `y≤x`, then Dodos surrenders and returns the input unchanged. This prevents infinite recursion from happening, and it is the only form of conditional branching in the language. It can take a while to enter the right mindset to write anything in Dodos ^^"

So, starting from the bottom let's see what these functions are doing:

`dab`, `dot`, and `dip` are the only three builtin commands in Dodos, here redefined as `>`, `+`, and `-` to save bytes in the rest of the program. `dab` returns the input list without the first element; `dot` sums all elements of the input list (and returns 0 if the list is empty); `dip` subtracts 1 from each element of the list **and then takes the absolute value of each element**: negative numbers don't exist in Dodos! Any time we try to subtract 1 from 0 we obtain 1 as a result.

I had originally written much more about the rest, but this post is long enough as it is, so I will only provide descriptions of the input/output of each function. Trying to understand how each function works can be a good exercise, but if you want more information leave me a comment and we can discuss more in chat :)

`H` \- Input: a number `n`. Output: `n%2` followed by (0 repeated `n//2` times)

`L` \- Input: a list of 0s and 1s `l`. Output: `[tail(l),tail(l) with each bit flipped]` (hint: `+ L` will compute the length of `l` \- 1)

`B` \- Input: a number `n`. Output: the binary representation of `n`, with a leading `0`

`E` \- Input: a number `n`. Output: the Elias omega coding of `n`, with an extra leading `01` and missing the trailing `0`.

`main` \- Input: a number `n`. Output: the Elias omega coding of `n`.

# Answer
> 6 votes
# Husk, ~~16 13~~ 11 bytes

```
ṁḋ↔Θ↑←¡ȯ←Lḋ

```

Try it online!

Outputs a flat boolean array.

-2 using the idea from Jonathan Allan's answer.

## Explanation

```
ṁḋ↔Θ↑←¡ȯ←Lḋ
      ¡ȯ    create an infinite list using:
         Lḋ length of binary digits
        ←   decremented
    ↑       take the longest prefix with:
     ←       elements that aren't falsy when decremented(1)
   Θ        prepend 0 to that
  ↔         reverse
ṁḋ          convert each to binary and flatten

```

# Answer
> 5 votes
# Jelly,  ~~11~~  10 bytes

Is there a trick to make for shorter code?

```
BL’ƊƬṣ1UBF

```

A monadic Link accepting a positive integer which yields a list of ones and zeros.

**Try it online!**

### How?

```
BL’ƊƬṣ1UBF - Link: n           e.g. n=12
    Ƭ      - collect up starting with n until no change:
   Ɗ       -   last three links as a monad:        (3)     (1)     (0)
B          -     to binary            [1,1,0,0]    [1,1]   [1]     [0]
 L         -     length               4            2       1       1
  ’        -     decrement            3            1       0       0   <- 0=0: stop
             }                     -> [12,3,1,0]
     ṣ1    - split at ones            [[12,3],[0]]
       U   - upend                    [[3,12],[0]]
      B    - to binary                [[[1,1],[1,1,0,0]],[0]]
         F - flatten                  [1,1,1,1,0,0,0]

```

# Answer
> 4 votes
# Vyxal, `d`, ~~15~~ ~~13~~ ~~11~~ ~~10~~ 9 bytes

```
≬bL‹↔1€Rb

```

Try it Online!

## Explained (old)

```
≬bL‹↔1€Rb
≬bL‹         # lambda: len(bin(argument)) - 1
   ↔        # generate_until_no_change(^, input)
     1€      # ^.split(1)
       R     # map(reverse, ^)
        b    # bin(^)
             # `d` flag: deep_sum(^)

```

# Answer
> 4 votes
# , 29 28 bytes

```
1;@}.1#:&.>@|.&|.<:@#@#:^:a:

```

Try it online!

This approach, which I prefer to the strightforward recursion, is thanks to Jonathan Allen's nice idea.

-1 thanks to Bubbler

* `<:@#@#:^:a:` Iteratively convert to binary `#:`, get size `#`, and decrement `<:`, keeping track of results `a:`.
* `1...&|.` Reverse both arguments `&|.` (1 on the left, and the output of the previous step on the right). A golfy way to include the constant 1 (which is unaffected by reversal, and which we'll use in the next step) while reversing step 1's output.
* `|.` Rotate by 1. So now we have the output of step 1 reversed and rotated left by 1. Importantly, the `0` is now in the correct place all the way on the right, though we still have a stray `1` at the beginning...
* `#:&.>@` Convert to binary `#:` under open `&.>`. A golfy way to convert every element to binary and box it.
* `1;@}.` Kill the first element `1...}.` (the stray `1`) and raze `;` (unbox so we have a single list of numbers)

## , 29 bytes (recursive approach)

```
0&g=.((,~g<:@#@])#:)`[@.(1=])

```

Try it online!

-3 thanks to Bubbler's realization we could 1-line it

Straightforward implementation of the recursion formula.

# Answer
> 4 votes
# JavaScript (ES6), 50 bytes

### With `.toString(2)`

```
f=(n,s=0,b=n.toString(2))=>n-1?f(b.length-1,b+s):s

```

Try it online!

### Without `.toString(2)`

```
f=(n,i,q=n*2>>i)=>n>!!i?q?f(n,-~i)+q%2:f(i-2,1):''

```

Try it online!

# Answer
> 4 votes
# Add++, 70 bytes

```
D,f,@,BBBFJ
D,g,@,bL1_
+?
n:x
y:'0'
Wn,`s,$f>x,`x,$g>s,`y,s+,`n,x-1
Oy

```

Try it online!

Add++ isn't too golfy.

`f` is a function that converts its input to a binary string. `g` gets a string and returns it's length minus one.

We then set **x** and **n** equal to the input, and **y** equal to the string `'0'`. Now, we enter a while loop, looping while **n** is non-zero. The loop has the following steps:

* Set **s** equal to `f(**x**)`
* Set **x** equal to `g(**s**)`
* Prepend **s** to **y**
* Set **n** equal to **x - 1**

Finally, output **y**

# Answer
> 3 votes
# Perl 5 `-n`, 58 bytes

```
while($_>1){unshift@a,$_=sprintf"%b",$_;$_=y///c-1}say@a,0

```

Try it online!

# Answer
> 3 votes
# K (ngn/k), ~~25~~ ~~20~~ 18 bytes

-2 bytes thanks to coltim

```
1_,/|0,2\'(#1_2\)\

```

Try it online!

# Answer
> 3 votes
# Rust, ~~129~~ 87 bytes

```
|mut n|{let mut s=0.to_string();while n>1{let b=format!("{:b}",n);n=b.len()-1;s=b+&s}s}

```

Try it online!

My first Rust answer! ~~(and first time appeasing the Rust compiler gods)~~

A straight translation of the algorithm in the main post.

Ungolfed:

```
fn e(mut n: usize) -> String {
    let mut s = "".to_string();
    while n > 1 {
        let mut b = format!("{:b}", n);
        n = b.len() - 1;
        b.push_str(&s);
        s = b;
    }
    s+"0"
}

```
* -42 bytes from @Bubbler through a closure and miscellaneous golfs

# Answer
> 2 votes
# Ruby, 39 bytes

```
f=->n,s=?0{n>1?f[/.$/=~x="%b"%n,x+s]:s}

```

Try it online!

Recursive function that takes \\$N\\$ as an integer. A regex match returns the index of the last bit in the binary representation of \\$N\\$, which is equivalent to one less than the bit length of \\$N\\$.

# Answer
> 2 votes
# Zsh, 50 bytes

```
<<<${${1#?}:+`$0 ${$(([#2]$#1-1))#??} ''`}$1${2-0}

```

Try it online!

Neat recursive solution

```
<<<${${1#?}:+`$0 ${$(([#2]$#1-1))#??} ''`}$1${2-0}
                                          $1         # N
                                            ${2-0}   # $2, unless it is unset; then substitute "0"
   ${${1#?}:+                            }           # If after removing ?any digit from $1 there is something left, then substitute
             `$0                        `            # Backtick subshell, $0 is the current program
                 ${$(([#2]$#1-1))#??}                # Take the #length of $1, subtract one, substitute as 2#binary, remove the "2#"
                                      ''             # Add empty second argument to cause ${2-0} to substitute nothing on recursion
<<<                                                  # Print to stdout

```

# Answer
> 2 votes
# Python 3, ~~57~~ 56 bytes

Saved a byte thanks to ovs!!!

```
f=lambda n:n>1and f(len(f'{n:b}')-1)[:-1]+f'{n:b}0'or'0'

```

Try it online!

Inputs an integer and returns a string.

# Answer
> 2 votes
# Scala, 74 bytes

```
x=>{var n->r=x->"0";while(n>1){val b=n.toBinaryString;r=b+r;n=b.size-1};r}

```

Try it online!

So this is a bit embarrassing: the imperative version is 13 bytes shorter.

# Scala, 87 bytes

```
Seq.unfold(_){n=>val b=n.toBinaryString;Option.when(n>1)(b,b.size-1)}./:("0")(_.++:(_))

```

Try it online!

# Answer
> 2 votes
# C (clang), ~~87~~ 86 bytes

```
l,a;g(n,b)char*b;{l=1;for(*b=48;n>1;n=a)for(a=0;bcopy(b,b+1,++l),*b=48+n%2,n/=2;)a++;}

```

Try it online!

* saved 1 thanks to @ceilingcat suggestion of using Linux bcopy instead of memcpy.
* function tacking a number `n` and a buffer `b`.

# Explanation

* `l` length of result, used to shift the buffer.
* `a` length of current `n`.
* second for loop shifts the buffer by one and push next bit at the beginning.
* first loop resets `n` to length `a` which is already minus 1.
* initially we set `l` to 1 and the first bit to '0'

# Answer
> 2 votes
# Japt, 19 bytes

```
@=¤T=U+T U=ÊÉ}f
Tj0

```

Try it

```
@ ... }f - return first falsey value returned by @
=¤       - convert input(U) to binary
T=U+T    - append to variable T(initially 0)
U=ÊÉ     - returns lenght -1 and assigns to U
Tj0      - discards first bit of T and implicitly print

```

# Answer
> 2 votes
# Japt, 14 bytes

```
É?T=¢+T,ß¢ÊÉ:T
É?             // If input U - 1, aka if U > 1,
   =           // then assign
    ¢          // U to a binary string
     +T        // plus builtin variable T (initially zero),
  T            // to the builtin variable T.
       ,       // Following that,
        ß      // recursively run the application again with a new input of
          Ê    // the length of
         ¢     // the current input to binary string
           É   // minus one.
            :  // If the initial check was falsy instead,
             T // we're finished, return the result which is stored in T.

```

Try it here.

# Answer
> 2 votes
# Factor \+ `math.extras`, 73 bytes

```
[ { f } swap [ [ make-bits append ] keep log2 ] until-zero reverse rest ]

```

Try it online!

Takes an integer and returns an array of `f`s and `t`s to represent 0 and 1 bits respectively (which is the default bit array representation). `until-zero` is two bytes shorter than `dup 0 > loop`. Also, `make-bits` gives the binary representation in LSB-first order (so `4 make-bits` is `{ f f t }`), so a `reverse` is needed at the end.

```
[                              ! A quotation, input: n
  { f } swap                   ! Put the initial s="0" under n
  [ ... ] until-zero           ! Repeat until n becomes zero...
    [ make-bits append ] keep  !   Append bits of n to s, and keep n at the top
    log2                       !   Next term (floor of log 2 = bit length - 1)
  reverse rest                 ! Reverse s and remove the part representing 1
]

```

# Answer
> 1 votes
# Stax, 13 bytes

```
┴P&:ë▄▒ë╙G²╟ì

```

Run and debug it

A generator with a filter.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 54 bytes

```
Rest[#<>0//.a_/;a>1:>Floor@Log2@a<>a~IntegerDigits~2]&

```

Try it online!

Returns a `StringJoin` of digits.

# Answer
> 1 votes
# C (MinGW), 79 bytes

Uses `itoa()` which is woefully lacking from the standard, but present on Windows systems.

The TIO link therefore contains a shoddy version of that function that only supports base 2.

```
d;f(n){int s[9]={0};d++;n>1&&f(strlen(s)-1,itoa(n,s,2));printf(--d?s:"%s0",s);}

```

Try it online!

# Answer
> 1 votes
# Java 8, 77 bytes

```
n->{String r="0",b;for(;n>1;r=b+r,n=b.length()-1)b=n.toString(n,2);return r;}

```

Try it online.

**Explanation:**

```
n->{                    // Method with Integer parameter and String return-type
  String r="0",         //  Result-String, starting at "0"
         b;             //  Temp-String, uninitialized
  for(;n>1              //  Loop as long as `n` is larger than 1:
      ;                 //    After every iteration;
       r=b+r,           //     Prepend `b` to the result-String
       n=b.length()-1)  //     Set `n` to the length of `b` minus 1
    b=n.toString(n,2);  //   Set `b` to `n` converted to a binary-String
  return r;}            //  After the loop, return the result-String `r`

```

# Answer
> 1 votes
# , ~~70~~ ~~64~~ 61 bytes

```
function(N){while(N>1)F=c(N%/%2^((N=log2(N)%/%1):0)%%2,F);+F}

```

Try it online!

To my disappointment, a no-frills iterative implementation of the pseudocode comes-out significantly shorter than my initial recursive approach...

# Answer
> 1 votes
# Retina, 50 bytes

```
^.
$.%'*_¶$&
+`(_+)\1
${1}0
/^../}`0?_
1
^.|¶

$
0

```

Try it online! Takes input in binary, but link includes test suite with decimal to binary conversion for convenience. Explanation:

```
/^../}`

```

While the input is greater than 1, ...

```
^.
$.%'*_¶$&

```

... prepend a decremented unary copy of the length...

```
+`(_+)\1
${1}0
0?_
1

```

... and convert from unary to binary.

```
^.|¶

$
0

```

Remove the last result, join the remaining results together and append a trailing `0`.

# Answer
> 1 votes
# PowerShell, 77 bytes

```
param($n)while($n-1){$s=($l=[Convert]::ToString($n,2))+$s;$n=$l.Length-1}$s+0

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
Î[b©#®ì®g<

```

Try it online or verify all test cases.

**Explanation:**

```
Î         # Push 0 and the input-integer
 [        # Start an infinite loop:
  b       #  Convert the current integer to a binary string
   ©      #  Store this binary string in variable `®` (without popping)
          #  If this binary string is equal to 1:
    #     #   Stop the infinite loop
          #   (after which the string at the top is output implicitly as result)
   ®ì     #  Prepend binary string `®` in front of the current result-string
     ®g<  #  Push the length of `®` minus 1 for the next iteration

```

# Answer
> 0 votes
# Red, ~~119~~ 115 bytes

```
func[n][o: copy"0"until[t: copy[]until[insert t n % 2 n:
to 1 n / 2 1 > n]n:(length? t)- 1 insert o t n < 1]next o]

```

Try it online!

# Answer
> 0 votes
# Perl 5 (`-l060p`), 51 bytes

```
$\=($,=sprintf"%b",$_).$\,$_=-1+length$,while$_>1}{

```

Try it online!

# Answer
> 0 votes
# Charcoal, 16 bytes

```
←0Ｗ⊖θ«←⮌θ≔⍘⊖Ｌθ²θ

```

Try it online! Link is to verbose version of code. Takes input in binary. Explanation:

```
←0

```

Output the trailing `0`.

```
Ｗ⊖θ«

```

Repeat until `N=1`.

```
←⮌θ

```

Prepend `N` to the output.

```
≔⍘⊖Ｌθ²θ

```

Replace `N` with its binary decremented length.

20 bytes for decimal input:

```
Ｎθ←0Ｗ⊖θ«←⮌⍘θ²≔⊖Ｌ⍘θ²θ

```

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

```
Ｎθ

```

Input `N`.

```
←0

```

Output the trailing `0`.

```
Ｗ⊖θ«

```

Repeat until `N=1`.

```
←⮌⍘θ²

```

Prepend `N`'s binary representation to the output.

```
≔⊖Ｌ⍘θ²θ

```

Replace `N` with its decremented binary length.

---
Tags: code-golf, binary, encoding
---


# Question
Title: Decode Polybus Square/Tap Code/Prison Code
The code has a lot of names, but is very simple:

```
  1 2 3 4 5
1 A B C D E
2 F G H I J
3 L M N O P
4 Q R S T U
5 V W X Y Z

```

A letter is coded by its coordinates, with the row first, then the column. Ex:

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

```

Note the letter 'K' is missing, as a letter needs to be removed to make the alphabet fit in the grid. In some versions, the letter 'J' is removed but K is easier to remove because every line stays in order.

More info here on Wikipedia.

Challenge: Make a program that takes in a message encoded in this way, that outputs the decoded message. Input can be in any reasonable format.

```
23 15 31 31 34 52 34 42 31 14
23153131345234423114
etc

```

Are all reasonable input formats. Standard loopholes apply.

## Test Cases

```
23 15 31 31 34 52 34 42 31 14 => HELLOWORLD
24 25 31 32 => IJLM
11 22 33 44 55 => AGNTZ

```

# Answer
> 16 votes
# Python 2,  ~~40~~  39 bytes

-1 thanks to kops! (Multiply before integer division)

```
lambda a:[chr(r*16/3+c+59)for r,c in a]

```

An unnamed function accepting an iterable of pairs which returns a list of characters.

**Try it online!**

# Answer
> 9 votes
# , 22 bytes

```
65(u:@+>&74)@+[:5&#.<:

```

Try it online!

* `[:5&#.<:` Decrement each input value `<:` and interpret every resulting 2-element pair as a base 5 number `5&#.`.
* `65...@+` Add 65 to each (to make it an ascii value), and...
* `u:@+>&74` Add 1 more to each number greater than 74 `+>&74` to adjust for the missing K. Finally, convert the result to a character `u:@`.

# Answer
> 8 votes
# Jelly, 10 bytes

```
ØAḟ”Ks5⁸œị

```

Try it online!

-1 byte thanks to Jonathan Allan!

## How it works

```
ØAḟ”Ks5⁸œị - Main link. Takes a list of pairs P on the left
ØA         - Yield the uppercase alphabet
  ḟ”K      - Filter out "K"
     s5    - Split into a 5x5 matrix, S
       ⁸   - Yield P
        œị - For each pair [A, B] in P,
              get the B'th element of the A'th row of S

```

# Answer
> 8 votes
# Jelly, 10 bytes

```
ḅ5<⁴ạƊ+60Ọ

```

Try it online!

A completely different approach.

## Explanation

```
ḅ5<⁴ạƊ+60Ọ   Main monadic link
             All following operations are automatically vectorized.
ḅ5           Convert from base 5
    ạƊ       Absolute difference with
  <⁴           1 if it's less than 16, else 0
      +60    Add 60
         Ọ   Convert to character

```

# Answer
> 8 votes
# brainfuck, 85 bytes

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

```

Try it online!

## Explanation

```
,  Read a character
[  While not at the end of input
  >++++++++[<------>-]  Subtract 48 to get the actual number
  ,  Read another character
  <[>+++++>>[>]+[<]<<-]  Add 5 times the number to the character and also expand the number into a group of 1s
  >+++++++++++  Add 11 to the character to turn it into a letter
  >>>>  Go to the third item in the group of 1s
  [<<<<+>>>>-]  If it's a 1 then add 1 to the character
  <<<<.  Print the character
  >>>>>>  Skip past the dirty memory cells
  ,  Read a new character
]

```

# Answer
> 6 votes
# brainfuck, 78 bytes

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

```

Try it online!

Takes input for each letter as 2 ascii encoded digits.

**Explanation**

Essentially the formula is `65+[Row ASCII - 49]*5+[Column ASCII -49]+[1 if row >2]` .

The row ASCII value is reduced by 49, but the column ASCII offset is calculated as

```
 65-49 = 16 = 17-2+1 plus an additional 1 if in row 3 onwards.

```

The approach is quite different to the existing brainfuck answer.

```
,[<<             Take an input for row value into cell 0 to get started then move to cell minus 2
-[----->+>-<<]   make cell minus 1 equal 255/5=51 and also subtract this number from input
>>+>,<           add 1 to row value in cell 0 and input column value into cell 1
[>+>]<<[<]       if cell 0 not 0  row input was not 2 so add 1 to column value
>>+              add 1 to row value in cell 0 so now it is 49 minus the input / note ASCII 49 is 1
[>+>]<<[<]       if cell 0 not 0 row input was not 1 so add 1 to column value
>[--->>+<<]      add 51/3=17 to column value
>[->+++++<]      add 5 times row value to column value
>--.             subtract 2 from column value and output letter
>>>,]            skip 3 dirty cells and take next row input

```

# Answer
> 5 votes
# Haskell, ~~39~~ 37 bytes

```
map(\(r,c)->[';'..]!!(r*5+c+r`div`3))

```

Try it online!

* saved 2 thanks to @cole

# Answer
> 4 votes
# Scala, ~~37~~ 36 bytes

Saved 1 byte thanks to @xigoi, who suggested applying @kops's suggestion to Jonathan Allan's answer.

```
_.map{case(r,c)=>r*16/3+c+59 toChar}

```

Try it online!

Now simply a port of Jonathan Allan's Python answer, which you should upvote!

Outputs a list of characters.

# Answer
> 4 votes
# 05AB1E, ~~13~~ 12 bytes

```
<ε5β}Au'Kмsè

```

Try it online!

-1 byte thanks to Makonede. Outputs as a list of characters

## How it works

```
<ε5β}Au'Kмsè - Program. Takes an input of a list of pairs P
<            - Decrement to use 0-indexing
 ε  }        - Over each pair [A, B]:
  5β         -   Convert from base 5, yielding 5A+B
     Au      - Push the uppercase alphabet
       'K    - Push "K"
         м   - Remove "K" from the alphabet
          sè - Index into this modified alphabet

```

# Answer
> 4 votes
# JavaScript (Node.js), 42 bytes

```
a=>Buffer(a.map(([y,x])=>+x+y*16/3+59))+''

```

Try it online!

Takes an array of strings.

# Answer
> 4 votes
# convey, 568 bytes

```
{:v
 1v
v#<   0
v^<<<<(<
v9     ^9
v+2v'A'^+2
"=>!}  ^*5v'Z'
v9     "=>!}
v+3v'B'^9
"=>!}  ^*6v'Y'
v9     "=>!}
v+4v'C'^9
"=>!}  ^*6
v9     ^-1v'X'
v+5v'D'"=>!}
"=>!}  ^9
v9     ^+4
v+6v'E'^*4v'W'
"=>!}  "=>!}
v7     ^9
v*3v'F'^+8
"=>!}  ^*3v'V'
v9     "=>!}
v+2    ^9
v*2v'G'^*5v'U'
"=>!}  "=>!}
v9     ^9
v+9    ^+2
v+5v'H'^*4v'T'
"=>!}  "=>!}
v6     ^9
v*4v'I'^*4
"=>!}  ^+7v'S'
v5     "=>!}
v*5v'J'^7
"=>!}  ^*6v'R'
v9     "=>!}
v*3    ^9
v+4v'L'^*4
"=>!}  ^+5v'Q'
v8     "=>!}
v*4v'M'^5
"=>!}  ^*7v'P'
v9     "=>!}
v+2    ^9
v*3v'N'^+8
"=>!}  ^*2v'O'
>>>>>>>"=>!}

```

And here's a picture of the factory (the gif thing kept crashing):

The basic idea is that there is a massive loop which lets one value through at a time. It goes through every letter. Note: Some things which appear to be golfable aren't due to interpreter glitches.

Try it online!

I can't believe Brainfuck is beating this :( - Convey has terrible string handling, so this is the only answer where it implicitly checks every single letter...

# Answer
> 3 votes
# Charcoal, 14 bytes

```
⭆⪪⭆Ｓ⊖ι²§⁻αK⍘ι⁵

```

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

```
   Ｓ            Input string
  ⭆             Map over characters and join
     ι          Current character
    ⊖           Decremented
 ⪪    ²         Split into pairs of digits
⭆               Map over pairs and join
            ι   Current pair
           ⍘ ⁵  Convert from base 5
       §        Index into
         α      Predefined variable uppercase alphabet
        ⁻       Minus
          K     Literal string `K`
                Implicitly print

```

# Answer
> 3 votes
# Jelly (fork), 10 bytes

```
’ḅ5ịØȦḟ”K¤

```

Try it online! (or rather, don't)

## How it works

```
’ḅ5ịØȦḟ”K¤ - Main link. Takes a list of pairs P on the left
’          - Decrement each integer to use 0-indexing
 ḅ5        - For each pair [A, B], yield 5A+B (convert from base 5)
         ¤ - Group the previous links into a nilad:
    ØȦ     -   Shifted alphabet; Yield "BCDE...XYZA"
      ḟ”K  -   Filter out "K"
   ị       - Index into this modified alphabet

```

# Answer
> 3 votes
# Stax, 10 bytes

```
▄πKñ╜╓♥F⌂F

```

Run and debug it

takes inputs as `[column, row]`. Based on Jonathan Allan's answer.

# Answer
> 3 votes
# K (ngn/k), 20 bytes

```
`c${x+74<x}65+5/'-1+

```

Try it online!

Uses @Jonah's method - don't forget to upvote him!

# Answer
> 3 votes
# Excel, 42 bytes

```
=CONCAT(REPT(CHAR(A:A*16/3+B:B+59),A:A>0))

```

Another port of Johnathan Allan's Python Answer

Input is 2 columns of cells.

# Answer
> 3 votes
# Befunge-93, 31 bytes

```
~:1+!#@_"0"-:2`\5*+~"0"-+";"+,~

```

Try it online!

### Explanation

```
~             Get a char
:1+!#@_       If at the end of the string, stop the execution (see if the char is -1)
"0"-          Get the row number
:2`\          If greater than 2, push a 1, otherwise a zero, swap the top two in the stack
5*+           Multiply by 5 and sum the 0/1
~"0"-+        Get the col number and sum everything
";"+,         Sum 59 to get the ASCII value of the char
~             Remove the space

```

# Answer
> 2 votes
# , 37 bytes

```
function(a)intToUtf8(a$x*16/3+a$y+59)

```

Try it online!

Port of Jonathan Allan's Python answer.

Takes input as a data frame with first digit in first column and second digit in second column.

# Answer
> 2 votes
# Ruby, 34 bytes (31 bytes with Ruby 2.7)

```
->x{x.map{|i,j|(i*16/3+j+59).chr}}

```

A direct port of Johnathan Allan's Python answer.

This lambda accepts an array of pairs and returns an array of characters.

Try it online!

`->x{x.map{(_1*16/3+_2+59).chr}}` is written in 31 bytes and also works fine, but it requires Ruby 2.7 (not yet supported by TIO).

# Answer
> 2 votes
# PowerShell 5+, 47 bytes

Tribute to Metal gear 2: Solid Snake

```
-join($args|%{(';'..'_'-ne'K')[5*$_[0]+$_[1]]})

```

Try it online!

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

```
s/(.)(.)/(A..J,L..Z)[5*$1-6+$2]/ge

```

Try it online!

# Answer
> 2 votes
# C (gcc), 75 bytes

```
main(int a,char**b){for(b++;**b;++*b)putchar(16+(a=**b-49)*5+(a>1)+*++*b);}

```

Try it online!

In the end, this is pretty straightforward and just uses C's willingness to be fluid about treating characters as integers. It runs through the characters in the first commandline argument, then uses a golfed version of this logic to map each one to the desired character.

```
'A' + (char1-'1')*5 + (char1-'1'>1) + (char2-'1')

```

The only trickery here is using the using the storage provided by the arguments to the `main()` call to avoid having to declare local variables. And the operator precedence in C means this jumble of punctuation,

```
+*++*b

```

does a number of things with just a few characters. That fragment, increments the pointer to the "current character" `*b`, then dereferences that location as a single character, implicitly converts it to an integer and adds it to the rest of the expression. The fact that `+*++*`, which looks more like Morse Code than C code, does something useful is pretty much why I decided to post this entry. :)

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~33~~ 15 bytes

Saved 18 bytes thanks to Razetime! (they also pointed out the answer was invalid)

```
⌷∘(5 5⍴⎕A~'K')¨

```

Try it online!

Takes a vector of pairs of numbers.

```
⌷∘(5 5⍴⎕A~'K')¨
               ¨ ⍝ For each pair in the input
⌷                ⍝ Index into:
       ⎕A        ⍝ Capital letters
          ~'K'   ⍝ Without 'K'
   5 5⍴          ⍝ Reshaped into a 5x5 matrix

```

# Answer
> 1 votes
# Retina 0.8.2, 37 bytes

```
T` d`__9\EKPU` |\b\d
+T`dL`__1-7L`.\d

```

Try it online! Link includes test cases. Explanation:

```
T` d`__9\EKPU` |\b\d

```

This does two things; it deletes all the spaces, and it replaces the first of each pair of digits with the characters `9EKPU` respectively, these being the characters in the translation string below that precede the letters from the first column of the code.

```
+T`dL`__1-7L`.\d

```

Repeatedly decrement the remaining digits and increment the preceding letter until the digits become zero, at which point they are deleted. Note that on the first pass the "letter" might actually be a `9`, but this works because on the first pass of this loop all the "letters" will be paired with a digit.

# Answer
> 1 votes
# , 62 bytes

```
function(x)for(i in x)cat(letters[(y=(i-1)%*%c(5,1)+1)+(y>9)])

```

Try it online!

Aaargh! I clicked submit and then saw pajonk's much shorter answer waiting for me! Upvote that one (and Jonathan Allan's one that it's based-on)!

# Answer
> 1 votes
# GolfScript, 22 bytes

```
~]2/{~\16*3/+59+}/]''+

```

Try it online!

Another port of @Jonathan Allen’s answer, and my first time trying out GolfScript. Input is just a series of numbers, separated by spaces, but you can separate number pairs with extra spaces for readability.

# Answer
> 0 votes
# PowerShell, 60 bytes

```
($a|%{[char][int][math]::floor($_[0]*16/3+$_[1]+59)})-join''

```

Try it online!

Thanks to @JonathanAllan

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


title: Visualize long division with ASCII art

text:
# Question
Title: Visualize long division with ASCII art
Write a program that visualizes long division with ASCII art. Input consists of two integers, a numerator and a denominator, using the input format of your choice.

**Examples:**

1234 ÷ 56:

```
     22
   ----
56|1234
   112
   ---
    114
    112
    ---
      2

```

1002012 ÷ 12:

```
     83501
   -------
12|1002012
    96
   ---
     42
     36
     --
      60
      60
      --
        12
        12
        --

```

0 ÷ 35

```
   0
   -
35|0

```

**Rules:**

* Use of the programming language's division operator **is** allowed.
* Use of big integer support is also allowed.
* For consistency:
    + If the quotient is zero, print a single zero at the end of the diving board.
    + If the remainder is zero, do not print it.
    + Do not print leading zeros on any numbers.
* Excess newlines at the end and trailing spaces to the right are allowed.
* Solution with the fewest characters wins.

**Limits:**

* 0 \<= numerator \<= 1072 \- 1
* 1 \<= denominator \<= 9999999

This implies that the output will never be wider than 80 columns.

**Test suite and sample implementation:**

You can use long-division.c (gist) to test your program. It is actually a bash script with a C program inside. Tweak it to invoke your program in the test suite. Look at the C code at the bottom to see the reference implementation. Please let me know if there are any problems with the sample program or test suite.

```
$ ./long-division.c 10 7
   1
  --
7|10
   7
  --
   3
$ ./long-division.c
PASS 1234 ÷ 56
PASS 1002012 ÷ 12
PASS 1 ÷ 1
--- snip ---

Score: 35 / 35
All tests passed!

```

**Edit:** By request, I put the test suite input and expected output into text files (gist). Sample usage (bash):

```
cat input | while read nd; do
    ./program $nd |
        sed 's/\s*$//' | sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba'
done > output

diff -u expected output

```

The weird sed commands filter out trailing newlines and spaces from the program output.

# Answer
# Python 3, ~~284~~ 257 characters

## div.py

```
n,t=input().split()
d=int(t)
l=lambda x:len(str(x))
s=l(n)
def p(x):print(' '*(l(d)+s-l(x)+1)+str(x))
p(int(n)//d)
p('-'*s)
p(t+'|'+n)
s=z=f=0
while t:
 try:
  while z<d:z=z*10+int(n[s]);s+=1
 except:t=0
 if z*f:p(z)
 if t:f=1;t=z//d*d;p(t);p('-'*l(z));z-=t

```

Usage: `python3 div.py`
Input: from keyboard

## test.py

```
import sys
sys.stdin=open('input'); sys.stdout=open('output','w')
for line in open('input'): exec(open('div.py').read())

```

*output* matches *expected*

Versions:
1. 284
2. 257: `s,z,f=0,0,0``s=z=f=0`; `z and f``z*f`; better looping; removed a few newlines.
> 5 votes

# Answer
## Haskell, 320 characters

```
l=length
(®)=replicate
p!v=p&show v
p&s=(p-l s)®' '++s
0§_=[];_§l=l
d[m,n]=l c!(read m`div`e):l c&(l m®'-'):c:drop 1(g 0(map(toInteger.fromEnum)m)$1+l n)where
 e=read n;c=n++'|':m
 g r(d:z)p=i§[o!k,o!(i*e),o&(l(show k)®'-')]++g j z o where k=r*10+d-48;(i,j)=k`divMod`e;o=1+p
 g r[]p=r§[p!r]
main=interact$unlines.d.words

```

Passes all tests. While is this pretty golf'd -- I think there is still yet more to be done here...

---

* Edit: (344 -\> 339) delay `read` calls, which reduces need to call `show`, enough that abbreviating `show` as `s` isn't worth it.
* Edit: (339 -\> 320) rewrote string field formatting functions
> 4 votes

# Answer
## JavaScript (400 394 418)

```
function d(n,d){t=parseInt;p=function(v){return(s+v).substring(v.length)};a=function(v,c){return v.replace(/\d/g,c)};w='\n';q=b=o=c=e='';s=a(d,' ')+' ';f=true;i=-1;z='0';while(++i<n.length){s+=' ';if(t(c+=n[i])>=t(d)){q+=r=Math.floor(t(c)/t(d));o+=(!f?p(c)+w:e)+p(''+r*t(d))+w+p(a(c,'-'))+w;c=t(c)%t(d);f=false}else if(!f){q+=z;}c=(c==0)?e:e+c}return p(!q?z:q)+w+p(a(n,'-'))+w+d+'|'+n+w+o+(q?p(c):e)}

```

NOTE: As tempting as it looks to shave off a few chars by replacing `c=(c==0)?` with `c=!c?`, it is not usable because it causes floating point-related bugs.

http://jsfiddle.net/nLzYW/9/

Sample Execution:

```
document.writeln("<pre>");
document.writeln(d("1234","56"));
document.writeln();
document.writeln(d("1002012","12"));
document.writeln();
document.writeln(d("0","35"));
document.writeln();
document.writeln(d("123000123000123","123"));
document.writeln("</pre>");

```

**Edit 1**: Minor bug fixes, numerous code optimizations.

**Edit 2**: Fix bug with 1/7 generating extra output.
> 3 votes

# Answer
# AWK, 422 bytes

I think it took me over a week to solve this problem.

```
function l(x){return length(x)}{P=9(d=$2);gsub(".",FS,P);N=l(L=n=$1);gsub(".","-",L);O(0,q=int($1/$2));Q=l(q);print P L RS d"|"n}function O(i,x){printf"%"l(d)+N-Q+1+i"d\n",x}m=substr(q,1,1)*d{for(i=1;i<=Q;){O(i,m);print P substr(L,1,N-Q+1);for(_=l(j=n)-l(n-=m*10**(Q-i));_--;)P=P FS;if(!n)exit;match(q,".0*");i+=R=RLENGTH;sub(".{"R"}",E,q);b=q+0?substr(n,1,M=l(m=substr(q,1,1)*d)):n;if(b<m)b=substr(n,1,M+1);O(i-(i>Q),b)}}

```

Try it online!

## Usage

* Input is given from STDIN, as single line.
* Two natural numbers are on same line.
* Output is returned to STDOUT.
* This program does never handle overflow; fails on huge values.
* This program does not handle multiple lines of input correctly; only the first line is handled correctly.

## Formatted

```
function l(x){
  return length(x)}
{
  P=9(d=$2);gsub(".",FS,P);
  N=l(L=n=$1);gsub(".","-",L);
  O(0,q=int($1/$2));
  Q=l(q);
  print P L RS d"|"n}
function O(i,x){
  printf"%"l(d)+N-Q+1+i"d\n",x}
m=substr(q,1,1)*d{
  for(i=1;i<=Q;){
    O(i,m);
    print P substr(L,1,N-Q+1);
    for(_=l(j=n)-l(n-=m*10**(Q-i));_--;)
      P=P FS;
    if(!n)
      exit;
    match(q,".0*");
    i+=R=RLENGTH;
    sub(".{"R"}",E,q);
    b=q+0?substr(n,1,M=l(m=substr(q,1,1)*d)):n;
    if(b<m)
      b=substr(n,1,M+1);
    O(i-(i>Q),b)}}

```
> 3 votes

# Answer
# Javascript: (372)

```
function g(a){for(var c="",e=0;e<a;e++)c=" "+c;return c}function i(a,c){for(var e=a+"/"+c+"\\",j=(""+c).split(""),k="",d=0,b=0;b<j.length;b++){d*=10;d+=parseInt(j[b],10);var f=d>9?b-1:b,h=0;h=Math.floor(d/a);d%=a;f=g(f+a.toString().split("").length);f+=h*a+"\n"+g(b+a.toString().split("").length)+"--\n"+g(b+a.toString().split("").length)+d+"\n";k+=f;e+=h}return e+"\n"+k}

```

Invoke by using i(divider,number). Codegolfed JS: http://jsfiddle.net/puckipedia/EP464/ Ungolfed (dutch) JS: http://jsfiddle.net/puckipedia/M82VM/

Returns the long division (in dutch format as i learned it):

```
5/25\05
 0
 --
 2
 25
  --
  0

```

Testcase:

```
document.write("<pre>"+i(5,25)+"</pre>");
document.write("<pre>"+i(7,65669726752476)+"</pre>");

```
> 2 votes

---
Tags: code-golf, ascii-art, arithmetic, division
---


title: Visualize a Recursive Acronym

text:
# Question
Title: Visualize a Recursive Acronym
# Background

Famously, the acronym `GNU` stands for `GNU's Not Unix`. 1

It's recursive because, after expanding it once, it still contains the acronym `GNU`, and so must be exanded again:

```
(GNU's Not Unix)'s Not Unix

```

And so on, ad infinitum. Visualizing this, we get a kind of Droste effect:

```
┌────────────────────────────────────────────┬───────────┐
│┌──────────────────────────────┬───────────┐│'s Not Unix│
││┌────────────────┬───────────┐│'s Not Unix││           │
│││┌──────────────┐│'s Not Unix││           ││           │
││││GNU's Not Unix││           ││           ││           │
│││└──────────────┘│           ││           ││           │
││└────────────────┴───────────┘│           ││           │
│└──────────────────────────────┴───────────┘│           │
└────────────────────────────────────────────┴───────────┘

```

Recursive acronyms need not recurse on the first word, or only once. For example:

* `YOPY`: `Your Own Personal YOPY`
* `PIPER`: `PIPER Is PIPER Expanded Recursively`

Visualized:

# Challenge

## Input

You will be given two inputs:

1. A string whose space-delimited words form a recursive acronym. That is, if you form a string from the first letter of each word, that string is guaranteed to be either:
    * One of the words of the input string (it may occur more than once).
    * A prefix of one or more of those words (e.g. `GNU` is a prefix of `GNU's`)
    * The casing will match exactly
2. A non-negative integer -- the number of times to recursively expand. Given `0`, you'll return the input unaltered (or "framed" once, in its entirety). Given `1`, you'll expand once. Etc.

## Output

The output is the input string with all instances of the acronym visually expanded, recursively, the specified number of times.

You must use some visual effect to "frame" the nesting -- at minimum, distinct start and end delimiters like parentheses. Ascii boxing of some sort, as in the examples above, is also fine. As would be outputting an actual image that showed the nesting.

I'm flexible as long as the nesting is in fact visualized.

For clarity, parenthesized output would like this:

```
(((GNU's Not Unix)'s Not Unix)'s Not Unix)'s Not Unix

```

You are guaranteed that parentheses will never be part of acronym. Other than alphanumeric characters, the acronym will only contain apostrophes, commas, quotes, question marks and exclamation points, and those will only occur as valid punctuation (e.g., a question mark will not appear at the beginning of a word).

This is code golf, fewest bytes wins, no loopholes.

## Test Cases

This assumes you're using a parentheses visualization.

Format for test cases:

1. Input string (the acronym)
2. Input integer (recursion)
3. Expected Output

---

1. `GNU's Not Unix`
2. `0`
3. `GNU's Not Unix`

---

1. `GNU's Not Unix`
2. `2`
3. `((GNU's Not Unix)'s Not Unix)'s Not Unix`

---

1. `YOPY Own Personal YOPY`
2. `1`
3. `(YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)`

---

1. `YOPY Own Personal YOPY`
2. `2`
3. ```
((YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY)) Own Personal ((YOPY Own Personal YOPY) Own Personal (YOPY Own Personal YOPY))

```

---

1. `YourYOPY Own Personal YOPY`
2. `2`
3. ```
YourYOPY Own Personal (YourYOPY Own Personal (YourYOPY Own Personal YOPY))

```

# Answer
# Stax, 11 bytes

```
û╟;±å↕êg╥σç

```

Run and debug it

Regex is pretty nice.

## Explanation

```
D.\bxjMh+x:{R X → input
D             do the following n times, with the first input on stack
 .\b          push "\b" (word boundary)
    xj        split X on spaces
      M       transpose
       h      take first row to get abbreviation
        +     add that to the boundary
         x:{  push X, embedded in braces
            R replace matches of the created regex with "(X)"

```
> 2 votes

# Answer
# APL (Dyalog Extended), ~~33~~ 32 bytes

-1 byte thanks to Bubbler.

Anonymous infix lambda. Takes count as left argument and string as right argument.

```
{('\b',⊃¨⍵⊆⍨≠⍵)⎕R(1⌽')(',⍵)⍣⍺⊢⍵}

```

Try it online!

`{``}` "dfn"; number is  and text is :

`⊢⍵` on the text:

`⍣⍺` repeat given number of times

`(``)⎕R(``)` PCRE **R**eplace:

`')(',⍵` the text prefixed by `")("`

`1⌽` cyclically rotated one step left (puts `")"` at end)

… with:

`≠⍵` The mask of non-spaces in the text

`⍵⊆⍨` characters runs in the text corresponding to runs of 1s in that

`⊃¨` first character of each

`'\b',` prepend PCRE for word boundary
> 7 votes

# Answer
# JavaScript (ES9),  ~~88 85~~  82 bytes

Takes input as `(string)(n)`.

```
s=>g=n=>n?s.replace(eval(`/\\b${s.match(/(?<=^| )./g).join``}/g`),`(${g(n-1)})`):s

```

Try it online!

### Commented

```
s =>                       // s = string
  g = n =>                 // g is a recursive function taking the counter n
    n ?                    // if n is not equal to 0:
      s.replace(           //   replace in s:
        eval(              //     each word matching:
          `/\\b${          //       a word boundary followed by
            s.match(       //       the acronym which consists of
              /(?<=^| )./g //         the letters that are preceded by
                           //         either a space or nothing at all
            ).join``       //       joined together
          }/g`             //
        ),                 //     with:
        `(${               //     the result of
          g(n - 1)         //       a recursive call
        })`                //     surrounded with parentheses
      )                    //   end of replace()
    :                      // else:
      s                    //   end of recursion: just return s

```
> 7 votes

# Answer
# 05AB1E, ~~27~~ ~~25~~ 22 bytes

```
ðìÐ#€нJðìs" (ÿ )"Iи.:¦

```

Try it online!

To make sure we only match the acronym at the beginning of a word, we match an extra leading space. This results in extra spaces in the output, which is allowed.

```
ðì                      # prepend a space to the input
  Ð                     # triplicate
   #€нJ                 # acronymize (split on spaces, head of each, join)
       ðì               # prepend a space to the acronym
         s              # swap
          " (ÿ )"       # surround with parentheses
                 Iи     # repeat the following second-input times:
                   .:   #  replace the acronym with the parenthesized string
                     ¦  # remove the leading space

```
> 5 votes

# Answer
# Husk, 20 bytes

```
!→⁰Ṡ¡§¤σΘom←w`J"()"Θ

```

Try it online! Takes the number followed by the string. Outputs with parentheses, prefixing each expansion with a space.

### Explanation

```
!→⁰Ṡ¡§¤σΘom←w`J"()"Θ  (Let X and Y denote the arguments.)
                   Θ  Take Y prefixed with a space; denote this Y'.
!→⁰                   Take element X + 1 of
   Ṡ¡                  the infinite list created by iterating this function on Y':
       σ                Take the argument and substitute
          m←              the string containing the first character of
   Ṡ §      w              each space-separated word of Y',
      ¤ Θ                prefixed with a space, with
   Ṡ §       `J           the characters of Y' placed between
               "()"        '(' and ')',
      ¤ Θ                prefixed with a space.

```
> 4 votes

# Answer
# Perl 6, 48 bytes

```
{($^s,{S:g/$([~] $s~~m:g/<<./)/($s)/}...*)[$^x]}

```

Try it online!

### Explanation

```
{                                              }  # Anonymous block
 (   ,                               ...*)  # Construct infinite sequence
  $^s                                       # starting with input string.
      {                             }  # Compute next item by
       S:g/                   /    /   # globally replacing
           $(                )         # interpolated
                 $s~~m:g/<<./          # first letters of each word
             [~]                       # joined (the acronym)
                               ($s)    # with input string in parens
                                          [$^x]  # Take nth item

```
> 3 votes

# Answer
# Perl 5 `-apl`, ~~49~~ 43 bytes

```
/./,$p.=$&for@F;for$a(1..<>){s/\b$p/(@F)/g}

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~104~~ 96 bytes

-7 bytes thanks to @DeathIncarnate, and another -1 byte thanks to @wastl

```
import re
f=lambda s,n:n and re.sub('\\b'+''.join(c[0]for c in s.split()),f'({s})',f(s,n-1))or s

```

Try it online!

Explanation:

```
re.sub(
  '\\b'+''.join(c[0]for c in s.split()), # match all acronyms that starts on a word boundary
  '('+s+')',                             # replace with the original string in parenthesis
  f(s,n-1)                               # on the result of the (n-1)th recursion
)

```

This is the acronym expanded n times.

```
return n and recursive_case or base_case

```

This returns `base_case` if n is 0, and `recursive_case` otherwise. This works because in Python, `0` is Falsy and non-empty string is Truthy.

* If n is 0, `n and recursive_case` short circuits to `False`, then `False or base_case` is evaluated which returns `base_case`.
* If n is not 0, `n and recursive_case` evaluates to `recursive_case` which is Truthy, so `recursive_case or base_case` is short-circuited to `recursive_case`.
> 2 votes

# Answer
# Retina, 48 bytes

```
~(`$
 ¶($%`)
(.).*? (?=.*¶)
$1
^(.+)¶
1A`¶$1+`\b

```

Try it online! Takes the expansion count and acronym string on separate lines. Explanation:

```
~(`

```

After performing the script, interpret the result as a new script to be evaluated on the original input.

```
$
 ¶($%`)

```

Append a space to the string, and append a copy of the string wrapped in `()`s on a new line.

```
(.).*? (?=.*¶)
$1

```

Turn the string into the acronym.

```
^(.+)¶
1A`¶$1+`\b

```

Replace the count with a Retina repeat instruction, and also prefix an instruction to delete the count from the original input.

For example, the result of evaluating the inner script on the input `2` `GNU's Not Unix` is

```
1A`
2+`\bGNU
(GNU's Not Unix)

```

This deletes the count from the original input, and then performs the acronym expansion twice.
> 1 votes

# Answer
# sed 4.2.2, 180 bytes

```
h
s/(.)[^ ]* */\1/g
G
s/$/\n/
G
h
N
s/.*\n//
tx
:l
s/^(.*)\n(.*)\b\1(.*)\n(.*)\n(.*)/\1\n\2\n(\5)\3\4\n\5/
tl
s/\n(.*)\n(.*)\n/\n\1\2\n\n/
x
tx
:x
s/.//
x
tl
s/.*\n(.*)\n.*\n.*/\1/

```

Try it online!

Well, finding one part of input in another part of input is not that simple in `sed`. Input is on two lines: first line is the acronym string; second line is number of expansions in unary.
> 1 votes

# Answer
# Python 2, 93 bytes

```
f=lambda s,n:n and re.sub('\\b'+''.join(zip(*s.split())[0]),'('+s+')',f(s,n-1))or s
import re

```

Try it online!

Similar to a few other answers.

If simple substitutions were allowed, I could do...

# Python 2, 78 bytes

```
f=lambda s,n:n and f(s,n-1).replace(''.join(zip(*s.split())[0]),'('+s+')')or s

```

Try it online!

Except I didn't see the `YourYOPY` example when I put this together...
> 1 votes

# Answer
# PowerShell, 106 bytes

```
function f($a,$n){$s="\b"+(($a.split(" ")|%{$_[0]})-join'')+"\b"
$o=$a;1..$n|%{$a=$a-replace$s,"($o)"};$a}

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~84~~ 71 bytes

Inspired by Wasif

```
param($n,$a)$o=$a
1..$n*!!$n|%{$a=$a-creplace'\b[A-Z]{2,}\b',"($o)"}
$a

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~123~~ ~~106~~ 118 bytes

Rolled back to my initial post.
Chas Brown kindly pointed out I was going down a rabbit hole.
Added 17 bytes to fix word boundary bug.

```
import re
def f(a,n):
 o=a
 for i in[1]*n:a=re.sub(r'\b'+''.join([i[0]for i in o.split()])+r'\b',f"({o})",a)
 return a

```

Try it online!
> 0 votes

---
Tags: code-golf, string, balanced-string, recursion, text-processing
---


title: Counting triangles

text:
# Question
Title: Counting triangles
You are required to find how many triangles are unique out of given triangles. For each triangle you are given three integers a,b,c , the sides of a triangle.

A triangle is said to be unique if there is no other triangle with same set of sides.

Note : It is always possible to form triangle with given sides.

**INPUT:**

First line contains n, the number of triangles. Each of next n lines contain three integers a,b,c (sides of a triangle).

**Output:**

print single integer, the number of unique triangles.

**Constraints:**

```
1 <= n <= 10^5
1 <= a,b,c <= 10^15

```

**Sample Input**

```
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3

```

**Sample Ouput**

```
1

```

**Explanation**

```
only triangle with sides 8, 2, 9 is unique

```

# Answer
> 8 votes
### GolfScript, 22 characters

```
n%{~]$}%:^{]^\/,3<},,(

```

Includes the first line into the list of triangles but subtracts one from the result later. Run online.

*Commented code*

```
n%            # Split input into lines
{             # For each line
  ~]          # Evaluate the content and put into array
  $           # Sort the array (aka sides)
}%
:^            # Assign to variable ^
{             # Filter list of triangles
  ]           # Make array from triangle
  ^\/         # Count number of occurences in ^ by splitting
  ,3<         # and testing if number of parts is less than 3 (i.e.
              # triangle occurse only once
},
,(            # Count distinct lines and subtract 1 (for first line)

```

# Answer
> 3 votes
# k \[22 chars\]

```
{+/1=#:'={x@<x}'x:1_x}

```

### Example

```
input:(5;7 6 5;5 7 6; 8 2 9;2 3 4;2 4 3)
input
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3

```

Output

```
{+/1=#:'={x@<x}'x:1_x}[input]
1

```

### Example

```
input:(3;1 2 3;4 5 6;7 8 9)
input
3
1 2 3
4 5 6
7 8 9

```

Output

```
{+/1=#:'={x@<x}'x:1_x}[input]
3

```

# Answer
> 3 votes
# APL, 18 chars/bytes\*

```
{+/1=+/∘.(≡⍦)⍨1↓⍵}

```

Dialect is Nars2000. Following the lead in the K answer, this code is a *function* that accepts a list of vectors, first the number of lines (which is ignored) and then the triangles. Let me know if this is not ok.

**Exploded view**

```
{             1↓⍵}   drop the first element of the list (the number of lines)
       ∘.(  )⍨       for each possible pair of vectors (triangles) from the list,
          ≡⍦         compare them as multisets: check whether they are the same triangle
     +/              sum each row: for each triangle, count how many others are the same
   1=                find out which ones are unique
 +/                  and count them

```

**Example**

```
      {+/1=+/∘.(≡⍦)⍨1↓⍵} 5(7 6 5)(5 7 6)(8 2 9)(2 3 4)(2 4 3)
1
      {+/1=+/∘.(≡⍦)⍨1↓⍵} 6(7 6 5)(5 7 6)(8 2 9)(2 3 4)(2 4 3)(2 4 6)
2

```

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.

# Answer
> 2 votes
## GolfScript (24 chars)

```
~](;3/{$}%:^1/{^\/,2=},,

```

Online demo

This relies on the triangle sides being GolfScript literals of the same type (and hence sortable): it would work equally well with strings.

# Answer
> 2 votes
## Bash and coreutils (~~87~~,~~98~~,~~95~~,93)

Assumes input file is called "f",

```
sed 1d f|while read n;do echo `echo $n |tr ' ' '\n'|sort|tr '\n' ' '`;done|sort|uniq -u|wc -l

```

Reads line by line, sorts each line separately, then sorts all the lines. Finally the unique lines are filtered and counted. Also works for strings.

EDIT: As Yimin Rong pointed out, the first line containing the number of triangles is now handled (by removing it :) ).

# Answer
> 2 votes
## C#: 250c

*(compiled to exe; assumes "line" means from stdin, so ran as `type trianglesfile | counttri.exe`)*

```
using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());var a=new string[n];while(--n>=0)a[n]=string.Join(":",Console.ReadLine().Split(' ').OrderBy(x=>x));Console.Write(a.GroupBy(s=>s).Count(g=>g.Count()==1));}}

```

Ungolfed:

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());            // reads line from stdin; converts to int without validation
        var a = new string[n];

        while (--n >= 0)
            a[n] = string.Join(":",                       // re-stringfy the following:
                               Console.ReadLine()         //  - read the next line
                                      .Split(' ')         //  - splits by space to form an array of sides
                                      .OrderBy(x => x)    //  - sorts by default comparison
                   );

        Console.Write(
            a.GroupBy(s => s)                             // group on the sorted, stringified value
             .Count(g => g.Count() == 1)                  // count the number of groups which have 1 member
        );
    }
}

```

---

## C#: 116c

*(via LINQPad, in "C# Statements" mode; assumes "line" means any single line from an arbitrary string `s`, definition not counted)*

```
string s = @"5
1 2 3
2 1 3
4 5 6
3 1 2
8 7 6";            // <- input not included in overall count

Regex.Split(s,"\r\n").Skip(1).GroupBy(x=>string.Join(":",x.Split(' ').OrderBy(y=>y))).Count(g=>g.Count()==1).Dump();

```

Ungolfed:

```
string s = @"5
1 2 3
2 1 3
4 5 6
3 1 2
8 7 6";                                              // literal string definition, not counted

Regex.Split(s, "\r\n")                               // split on regex
     .Skip(1)                                        // who cares about the number of following lines?
     .GroupBy(x => string.Join(":",                  // re-stringify the following:
                               x.Split(' ')          //  - split by space into sides array
                                .OrderBy(y => y)))   //  - sort sides array
     .Count(g => g.Count() == 1)                     // count the number of groups that have 1 member
     .Dump();                                        // Output into LINQPad results pane

```

# Answer
> 2 votes
## **Perl, ~~53~~ ~~50~~ 45**

```
perl -nE '$h{"@{[sort split]}"}++}{say-1+grep{!log}values%h'

```

Input either STDIN or append filename to the line above. "**50**" -- counting inside `' '` and `n`.

Another edit:

```
perl -nE '$h{1,sort split}++}{say-1+grep{!log}values%h'

```

i.e. **45**. As I understand, the trick here is to force list context when evaluating hash index. Then Perl joins this list with `$;` (cf. with `$"` in my previous take). Without `1,`, `sort` evaluates in scalar context = undefined behaviour.

# Answer
> 2 votes
## D - ~~201~~, ~~172~~, ~~171~~, 170 chars

Reads from STDIN only and relies on D 2.x for UFCS (Uniform Function Call Syntax) and assumes the `-property` compiler flag isn't set.

```
import std.stdio,std.algorithm,std.conv;void main(){int n=[stdin.readln[0]].to!int;char[][]a;while(n-->0)a~=stdin.readln.dup.sort;a.group.filter!(x=>x[1]<2).count.write;}

```

Normal indented version:

```
import std.stdio, std.algorithm, std.conv;

void main()
{
    int n = [ stdin.readln[0] ].to!int;
    char[][] a;

    while( n --> 0 )
        a ~= stdin.readln.dup.sort;

    a.group.filter!( x => x[1] < 2 ).count.write;
}

```

Input:

```
F:\Code\Other>rdmd tri.d
5
7 6 5
5 7 6
8 2 9
2 3 4
2 4 3

```

Output:

```
1

```

# Answer
> 1 votes
# bash — 98 ~~113~~ characters

I'm sure this isn't the smallest `bash` solution (assumes `i` is the input file):

```
rm -f w;sed 1d i|while read L;do echo $L|xargs -n 1|sort|xargs -n 3 >>w;done;sort <w|uniq -u|wc -l

```

Explanation:

`rm -f w;` // delete working file

`sed 1d i|while read L;` // read each line, skipping the first one

`do echo $L|xargs -n 1|sort|xargs -n 3 >>w;` // normalize each line by sorting the elements

`done;` // end of while loop

`sort <w|uniq -u|wc -l` // sort all the lines, pull out unique ones and count

# Answer
> 1 votes
# Haskell (116, 99 w/o import)

```
import Data.List
main=getContents>>=(\x->print((length.(filter((<2).length)).group.(map(sort.words)).tail.lines)x))

```

If the file `input` contains the example input, run with:

```
$ cat input | runghc solution.hs
1

```

# Answer
> 1 votes
# Ruby, 55 characters

```
a=$<.map{|s|s.split.sort}
p a.count{|b|1==a.count(b)}-1

```

The code is pretty straightforward for golfing standards:

* first `a=$<.map{|s|s.split.sort}` reads all lineas from stdin, splits them into arrays, sorts them and stores them in the array `a`,
* then `a.count{|b|1==a.count(b)}` counts how many of those arrays appear only once in `a`,
* and the final `-1` is just not to count the first line read from stdin :)

# Answer
> 1 votes
```
#include<iostream>
#include<stdio.h>

void unique_check();

typedef struct triangle
{
    int s1, s2, s3;

}t;

t *tp[10];

int no;
void main()
{
    int  i,ch=0;

    do
    {
        int ch;
        printf("Enter the no triangles\n");
        scanf_s("%d", &no);

        for (i = 0; i < no; i++)
        {
            tp[i] = (t *)malloc(sizeof(t));
            printf("Enter the sides of %d triangle ", i);
            scanf_s("%d", &tp[i]->s1);
            scanf_s("%d", &tp[i]->s2);
            scanf_s("%d" ,&tp[i]->s3);
        }

        unique_check();

        printf("Enter the choice\n1 Perform more \n2 End\n");
        scanf_s("%d", &ch);
        system("cls");

    } while (ch!=2);

}

void unique_check()
{
    int i, j, f = 0, count = 0,tri=0;

    for (i = 0; i < no; i++)
    {
        for (j = 0; j < no; j++)
        {
            if (i == j)
                continue;
            else
            {
                if (((tp[i]->s1 == tp[j]->s1) || (tp[i]->s1 == tp[j]->s2) || (tp[i]->s1 == tp[j]->s3)) &&
                    ((tp[i]->s2 == tp[j]->s1) || (tp[i]->s2 == tp[j]->s2) || (tp[i]->s2 == tp[j]->s3)) &&
                    ((tp[i]->s3 == tp[j]->s1) || (tp[i]->s3 == tp[j]->s2) || (tp[i]->s3 == tp[j]->s3)))
                {
                    f = 0;
                    break;
                }

                else
                    f = 1;
            }

        }

        if (f == 1)
            tri++, f = 0;

    }

    printf("No of unique triangle\n%d\n",tri);

}

```

# Answer
> 1 votes
# Husk, ~~12~~ 8 bytes

```
#εkOmwt¶

```

Try it online!

-4 bytes from Leo.

# Answer
> 0 votes
# Pyth, 17 bytes

This is not a serious participation, because Pyth is much younger than this question. Found the question while researching for another question and had to try it.

```
JmScd)t.zlfq/JT1J

```

Try it online: Pyth Compiler/Executor.

Wasted quite a few bytes on parsing the awkward input format.

```
       .z           read all of input
      t             discard the first line
 m                  map each line d to:
   cd)                 split d by spaces
  S                    and sort
J                   store the result in J
          f     J   filter J for trianges T, which satisfy the condition:
            /JT        count T in J
           q   1        == 1
         l          length / number of remaining triangles, print

```

Another 17 byte solution, which uses the `.r` command (run length encoding).

```
lfqeT1.rSmScd)t.z

```

---
Tags: code-golf
---


title: Is it really time?

text:
# Question
Title: Is it really time?
A time in the format hhMMss is represented by six numbers in the range 0..9 (e.g.`100203` for 3 seconds after 2 minutes after 10am (10:02.03), or `155603` for three seconds after 56 minutes after 3pm (15:56.03).

Treating these times as integers, these numbers are therefore in the range `000000` to `235959`; but not all numbers in that range are valid times.

Normally, though, integers aren't represented with leading 0s, right?

So, this challenge is to take a numeric input (without leading 0s), and say whether it represents a proper time or not when the leading 0s are put back.

### Input

Any integer, as a string or an integer type, in the range `0..235959` inclusive. all numbers as strings will be input with no leading 0s (e.g. `2400`, not `002400`). The time `000000` maps to `0`; or exceptionally as. Inputs outside of this range should return Falsy, but there is no requirement that they are supported.

### Output

Truthy/Falsy value - by which I mean there must be a consistent distinction in the output between True and False - e.g. True could be output as `1` and False could be any other output (or even a variable output) - as long as it can be documented how to tell what is True and what is not.

### More Challenge Details

Given the input integer, figure out if the number represents a time (Truthy) or not (Falsy).

A number represents a time if a time (hhMMss) with leading 0s removed is the same as the number.

e.g. 00:00.24 is represented by 24
e.g. 00:06.51 is represented by 651
e.g. 00:16.06 is represented by 1606
e.g. 05:24.00 is represented by 52400
e.g. 17:25.33 is represented by 172533

There are therefore some numbers that can't represent times:

e.g. 7520 - this can't represent hhMMss because 00:75:20 isn't a time

As a general rule, the valid numbers fall into the pattern:

`trimLeadingZeros([00..23][00..59][00..59]);`

*The following numbers are the entire set of inputs and the required answers for this challenge*

**Seconds only (e.g. 00:00.ss, with punctuation and leading 0s removed, -\> ss)**
`0 to 59` \- Truthy
`60 to 99` \- Falsy

**Minutes and seconds (e.g. 00:MM.ss, with punctuation and leading zeros removed, -\> MMss)**
`100 to 159` \- Truthy
`160 to 199` \- Falsy
etc, up to:
`2300 to 2359` \- Truthy
`2360 to 2399` \- Falsy
`2400 to 2459` \- Truthy
`2460 to 2499` \- Falsy
etc, up to:
`5900 to 5959` \- Truthy
`5960 to 9999` \- Falsy

**Hours 0..9, minutes and seconds (e.g. 0h:MM.ss with punctuation and leading zeros removed -\> hMMss)**

`10000 to 10059` \- Truthy
`10060 to 10099` \- Falsy
etc, up to:
`15800 to 15859` \- Truthy
`15860 to 15899` \- Falsy
`15900 to 15959` \- Truthy
`15960 to 19999` \- Falsy

`20000 to 20059` \- Truthy
`20060 to 20099` \- Falsy
`20100 to 20159` \- Truthy
`20160 to 20199` \- Falsy
etc, up to:
`25800 to 25859` \- Truthy
`25860 to 25899` \- Falsy
`25900 to 25959` \- Truthy
`25960 to 25999` \- Falsy
etc, up to:
`95800 to 95859` \- Truthy
`95860 to 95899` \- Falsy
`95900 to 95959` \- Truthy
`95960 to 99999` \- Falsy

**Hours 10..23, minutes and seconds (e.g. hh:MM.ss with punctuation and leading zeros removed -\> hhMMss)**

`100000 to 100059` \- Truthy
`100060 to 100099` \- Falsy
`100100 to 100159` \- Truthy
`100160 to 100199` \- Falsy
etc, up to:
`105800 to 105859` \- Truthy
`105860 to 105899` \- Falsy
`105900 to 105959` \- Truthy
`105960 to 109999` \- Falsy

This pattern is then repeated up to:

`235900 to 235959` \- Truthy
(`236000 onwards` \- Falsy, if supported by program)

Leading 0s must be truncated in the input, if strings are used.

Code golf, so least bytes wins - usual rules apply.

# Answer
> 3 votes
# , 6 bytes

Source compression ftw!

```
♀♥@p▒ö

```

Uncompressed:

```
2,a60<A

```

## Explanation

```
2,      % Split number into chunks of length 2
        % The splitting is right-to-left *instead* of left-to-right.
      A % Is all items in the list ...
  a60<  % ... less than 60?

```

# Answer
> 15 votes
# Python, ~~45~~ ~~43~~ ~~38~~ 27 bytes

For inputs up until 239999:

```
lambda n:n/100%100<60>n%100

```

You can try it online! Thanks @Jitse and @Scurpulose for saving me several bytes ;)

For inputs above 239999 go with 36 bytes:

```
lambda n:n/100%100<60>n%100<60>n/4e3

```

# Answer
> 8 votes
# Perl 6, ~~33~~ 25 bytes

*-7 bytes thanks to Kevin Cruijssen*

```
60>*.polymod(100,100).max

```

Try it online!

# Answer
> 6 votes
# APL (Dyalog Extended), ~~1~~9 bytesSBCS

-10 bytes thanks to Kevin Cruijssen.

Anonymous tacit prefix function. Takes argument as integer.

```
⍱59<100∘⊤

```

Try it online!

`100∘⊤` convert **T**o base-100

`59<` are they, each, greater than 59?

are none of them true?

# Answer
> 5 votes
# 05AB1E, ~~14~~ ~~13~~ 12 bytes, supports inputs \> 235959

```
твR₅0šR12*‹P

```

Try it online!

```
тв             # convert input to base 100
  R            # reverse
   ₅           # 255
    0š         # convert to list and prepend 0: [0, 2, 5, 5]
      R        # reverse: [5, 5, 2, 0]
       12*     # times 12: [60, 60, 24, 0]
          ‹    # a < b (vectorizes
           P   # product

```

# Answer
> 5 votes
# Python, 35 bytes

```
f=lambda n:n<1or(n%100<60)*f(n/100)

```

A recursive function which returns `1` or `True` (which are truthy) if valid or `0` (which is falsey) if not.

**Try it online!** *

### How?

`True` and `False` are equivalent to `1` and `0` respectively in Python.

The function (`f=lambda n:...`) checks that the last up-to-two digits as an integer (`n%100`) are less than sixty (`<60`), chops them off (`n/100`) and multiplies by a recursive call `*f(...)` until an input of zero is reached (`n<1or`) at which point `True` is returned. If at any stage the check fails a `False` is placed in the multiplication, which will then evaluate to `0` (a falsey value).

---

* Only `f(0)` evaluates to `True`, but `set((True, 1, 1, ..., 1))` evaluates to `{True}` due to the equivalence of `True` and `1` in Python.

# Answer
> 5 votes
# Java 8, 38 bytes

```
n->n%100<60&n%1e4<6e3&n%1e6<24e4&n<1e6

```

Try it online!

Basically an improvement of @Kevin Cruijssen's solution; I don't have enough reputation for a comment.

# Answer
> 4 votes
# Perl 5 `-p`, ~~27~~ ~~22~~ 18 bytes

*Saved 4 bytes when @NahuelFouilleul pointed out that it doesn't need to be a look-ahead in the regex*

```
$_=!/[6-9].(..)*$/

```

Try it online!

Since the input is guaranteed to be less than 236000, the hours can be ignored as they will always be valid. This pattern match checks if there is a 6, 7, 8, or 9 in the tens digit of the minutes or seconds. The match is then negated to get truthy for valid dates and falsy for invalid ones.

# Answer
> 4 votes
# Jelly, ~~13~~ 7 bytes

```
bȷ2<60Ạ

```

Try it online!

A monadic link taking an integer and returning `1` for true and `0` for false.

Thanks to @KevinCruijsen for saving 6 bytes!

# Answer
> 4 votes
# LibreOffice Calc, 43 bytes

```
=MAX(MOD(A1,100),MOD(A1/100,100),A1/4e3)<60

```

Basically a ~~blatant rip-off~~ respectful port of @RGS excellent Python answer so go and upvote them. Only posted as I have not seen a LibreOffice Calc answer on here before and I was messing about while calculating my tax return this evening (code golf is much more fun). Screenshot of some test cases below.

# Answer
> 4 votes
# Retina 0.8.2, 12 bytes

```
[6-9].(..)?$

```

Try it online! Link includes test cases. Accepts input from `0` to `239999` and outputs `0` for times, `1` for non-times. Explanation: Simply checks whether the second or fourth last digit is greater than `5`.

# Answer
> 3 votes
# , ~~32~~ ~~26~~ ~~23~~ 16 bytes

```
60*/ .>100#.inv]

```

Try it online!

*-16 bytes (!!) thanks to Adam. This new solution uses the approach from his APL answer so be sure to upvote that.*

Convert the input to base 100, check that all digits are less than 60.

Note the most significant digit is guaranteed to be less than 24 by the allowed inputs.

# Answer
> 3 votes
# Java 8, ~~45~~ 43 bytes

```
n->n%100<60&n%1e4/100<60&n%1e6/1e4<24&n<1e6

```

Improved by *@Joja*'s Java answer by removing the divisions, so make sure to upvote him/her as well!

Try it online.

**Explanation:**

```
n->              // Method with integer parameter and boolean return-type
  n%100<60       //  Check whether the seconds are smaller than 60
  &n%1e4/100<60  //  and the minutes are smaller than 60
  &n%1e6/1e4<24  //  and the hours are smaller than 24
  &n<1e6         //  and the entire number is smaller than 1,000,000

```

# Answer
> 3 votes
# Charcoal, 11 bytes

```
‹⌈⍘Ｎ⭆¹⁰⁰℅ι<

```

Try it online! Link is to verbose version of code. Accepts input from `0` to `239999` and outputs a Charcoal boolean, `-` for times, no output for non-times. Explanation:

```
     ¹⁰⁰    Literal 100
    ⭆       Map over implicit range and join
         ι  Current index
        ℅   Unicode character with that ordinal
   Ｎ        Input as a number
  ⍘         Convert to string using string as base
 ⌈          Character with highest ordinal
‹           Is less than
          < Character with ordinal 60
            Implicitly print

```

`BaseString` always returns `0` for a value of `0` (bug?) but fortunately this is still less than `<`.

Alternative solution, also 11 bytes:

```
⌈⍘Ｎ⭆¹⁰⁰›ι⁵⁹

```

Try it online! Link is to verbose version of code. Accepts input from `0` to `239999` and outputs `0` for times, `1` for non-times. Explanation:

```
    ¹⁰⁰     Literal 100
   ⭆        Map over implicit range and join
        ι   Current index
       ›    Greater than
         ⁵⁹ Literal 59
  Ｎ         Input as a number
 ⍘          Convert to a string using string as base
⌈           Maximum
            Implicitly print

```

`BaseString` doesn't require the string base to have distinct characters, so this string just has 60 `0`s and 40 `1`s.

Unfortunately taking the base numerically returns an empty list for an input of zero, which takes an extra three bytes to handle, pushing the byte count above 11. But fortunately I can substitute an acceptable non-zero number in only two bytes, so another 11-byte alternative is possible:

```
›⁶⁰⌈↨∨Ｎχ¹⁰⁰

```

Try it online! Link is to verbose version of code. Accepts input from `0` to `239999` and outputs a Charcoal boolean, `-` for times, no output for non-times. Explanation:

```
 ⁶⁰         Literal 60
›           Is greater than
      Ｎ     Input as a number
     ∨      Logical Or
       χ    Predefined variable `10`
    ↨   ¹⁰⁰ Convert to base 100 as a list
   ⌈        Maximum
            Implicitly print

```

# Answer
> 3 votes
# Turing Machine Code, ~~336~~ 548 bytes

Prints 't' for true and 'f' for false.

```
0 * * r !
! * * r "
! _ _ l b
b * _ l t
" * * r £
" _ _ l c
c * * l c
c _ _ r 4
£ * * r $
£ _ _ l d
d * * l d
d _ _ r 3
$ * * r ^
$ _ _ l e
e * * l e
e _ _ r 2
^ * * r &
^ _ _ l g
g * * l g
g _ _ r 1
& * * l &
& _ _ l O
O 1 1 r a
O 2 2 r 1
O * * * f
a * * r 2
1 0 0 r 2
1 1 1 r 2
1 2 2 r 2
1 3 3 r 2
1 * * * f
2 0 0 r 3
2 1 1 r 3
2 2 2 r 3
2 3 3 r 3
2 4 4 r 3
2 5 5 r 3
2 * * * f
3 * * r 4
4 0 0 r t
4 1 1 r t
4 2 2 r t
4 3 3 r t
4 4 4 r t
4 5 5 r t
4 * * * f
f * * l f
f _ _ r n
n * _ r n
n _ f * halt
t * * l t
t _ _ r y
y * _ r y
y _ t r halt

```

Try it online!

*Added a chunk of bytes thanks to @Laikoni for spotting my misread of the question.*

# Answer
> 3 votes
# K (ngn/k), ~~14~~ 9 bytes

-5 bytes thanks to ngn

```
*/60>100\

```

Try it online!

Based on Adám's APL solution and Kevin Cruijssen's suggestion.

# Answer
> 3 votes
# Japt, 7 bytes

```
ìL e<60

```

Try it

# Answer
> 3 votes
# x86-16, IBM PC DOS, ~~46~~  ~~44~~  39 bytes

```
00000000: d1ee 8a0c ba30 4c88 5401 03f1 4ed1 e9fd  .....0L.T...N...
00000010: b303 ad86 e0d5 0a4b 7502 b628 3ac6 7d02  .......Ku..(:.}.
00000020: e2f0 d6b4 4ccd 21                        ....L.!

```

Build and test `ISTIME.COM` with `xxd -r`.

**Unassembled listing:**

```
D1 EE       SHR  SI, 1              ; SI = 80H
8A 0C       MOV  CL, BYTE PTR[SI]   ; CX = input length
BA 4C30     MOV  DX, 4C30H          ; DH = 60+16, DL = '0'
88 54 01    MOV  BYTE PTR[SI+1], DL ; 'zero' pad byte to the left of input
03 F1       ADD  SI, CX             ; SI to end of input string
4E          DEC  SI                 ; remove leading space from length
D1 E9       SHR  CX, 1              ; CX = CX / 2
FD          STD                     ; read direction downward
B3 03       MOV  BL, 3              ; counter to test if third iteration (meaning hours)
        LOD_LOOP:
AD          LODSW                   ; AX = [SI], SI = SI - 2
86 E0       XCHG AH, AL             ; endian convert
D5 0A       AAD                     ; binary convert
4B          DEC  BX                 ; decrement count
75 02       JNZ  COMP               ; if not third time through, go compare
B6 28       MOV  DH, 40             ; if third, set test to 24+16
        COMP:
3A C6       CMP  AL, DH             ; is number less than DL?
7D 02       JGE  NOT_VALID          ; if not, it's invalid
E2 F0       LOOP LOD_LOOP           ; otherwise keep looping
        NOT_VALID:
D6          SALC                    ; Set AL on Carry
B4 4C       MOV  AH, 4CH            ; return to DOS with errorlevel in AL
CD 21       INT  21H                ; call DOS API

```

A standalone PC DOS executable. Input via command line, output DOS exit code (errorlevel) `255` if Truthy `0` if Falsy.

**I/O:**

Truthy:

Falsy:

Thanks to @PeterCordes for:

* -2 bytes use DOS exit code for Truthy/Falsy result
* -3 bytes eliminate ASCII conversion before `AAD`

# Answer
> 2 votes
# Red, 63 bytes

```
f: func[n][either n % 100 > 59[return 0][if n > 1[f n / 100]]1]

```

Try it online!

Of course the recursive function with integers is much shorter than the below version that works on strings.

# Red, ~~139~~ ~~130~~ 115 bytes

```
func[s][s: pad/left/with s 6 #"0"
not any collect[foreach n collect[loop 3[keep to 1 take/part s 2]][keep n > 60]]]

```

Try it online!

# Answer
> 2 votes
# MathGolf, ~~18~~ 9 bytes

```
◄+░2/i╙╟<

```

Try it online.

**Explanation:**

```
◄+        # Add builtin 10,000,000 to the (implicit) input-integer
  ░       # Convert it to a string
   2/     # Split it into parts of size 2: [10,hh,mm,ss]
     i    # Convert each to an integer
      ╙   # Pop and push the maximum
       ╟< # And check if it's smaller than builtin 60
          # (after which the entire stack joined together is output implicitly)

```

# Answer
> 2 votes
# JavaScript (V8), ~~50~~ ~~48~~ 46 bytes

*-2 bytes each thanks to @kanine and @l4m2*

```
a=>a.padStart(6,0).match(/../g).every(x=>x<60)

```

Try it online!

# Answer
> 2 votes
# Bash, ~~33~~ 32 bytes

```
p=%100\<60;echo $[$1$p&$1/100$p]

```

Try it online!

Input is passed as an argument.

Output is 0 (falsey) or 1 (truthy).

(I've deleted an earlier 45-byte version that used egrep.\]

# Answer
> 2 votes
# Zsh, 28 bytes

```
e=%100/60;(($1$e||$1/100$e))

```

Try it online!

Returns via exit code.

Since `$parameters` are expanded before `((arithmetic))`, $e expands to `%100/60` before arithmetic is done.

There are 2 other 28 byte solutions I found as well, albeit not as interesting:

```
((h=100,$1%h/60||$1/h%h/60))

```

```
(($1%100/60||$1/100%100/60))

```

# Answer
> 2 votes
# T-SQL, ~~42~~ 41 bytes

Saved 1 byte thanks to @Neil

Supports all positive integer input

Returns 1 for true, 0 for false

```
DECLARE @ INT=235959

PRINT-1/~(@/240000+@/100%100/60+@%100/60)

```

# Answer
> 2 votes
# \[JavaScript (Node.js)\], 26 bytes

```
f=>!/[6-9].(..)?$/.test(f)

```

Simple Javascript Regular Expression

JavaScript (Node.js) – Try It Online

# Answer
> 2 votes
# Turing Machine Simulator, ~~299~~ ~~272~~ 269 bytes

```
0 _ _ l 1
0 * * r 0
1 * _ l 2
* _ t * t
2 6 f * f
2 7 f * f
2 8 f * f
2 9 f * f
2 * _ l 3
3 * _ l 4
4 6 f * f
4 7 f * f
4 8 f * f
4 9 f * f
4 * _ l 5
5 0 _ l 6
5 1 _ l 6
5 2 _ l 6
5 3 _ l 6
5 * _ l 7
6 _ t * t
6 1 t * t
6 2 t * t
6 * f * f
7 _ * * t
7 1 _ * t
7 * f * f

```

Run in Turing Machine Simulator. Halts with `t` on the tape for true inputs and a prefix of the input and `f` for false inputs.

# Answer
> 2 votes
# VBA, 177 bytes

```
Sub a()
x=1: i=""
If Len(i)<6 Then Do Until Len(i)=6: i="0"&i: Loop
s = Right(i, 2): m = Left(Right(i,4),2): h = Left(i,2)
If s>59 Or m>59 Or h>23 Then x=0
Debug.Print s
End Sub

```

Works for values above 235959, assigns x to output 1 or 0 with input as i

# Answer
> 1 votes
# Wolfram Language (Mathematica), 76 bytes

supports ***any*** number

```
!FreeQ[FromDigits/@Join@@@IntegerDigits/@Tuples[Range/@{24,6,10,6,10}-1],#]&

```

Try it online!

# Answer
> 1 votes
# T-SQL, 64 bytes

```
SELECT*FROM t WHERE 60>LEFT(RIGHT('000'+v,4),2)AND 60>RIGHT(v,2)

```

Input is taken from pre-existing table *t* with varchar field *v*, per our input standards.

Outputs 1 row (with the original value) for "true", and 0 rows for "false".

Accepts only values in the specified range (`0` to `235959`), so doesn't validate the first 2 digits.

# Answer
> 1 votes
# Python 3, ~~90~~ 85 bytes

```
lambda t:{t}&s
s={0}
import time
while len(s)<86400:s|={int(time.strftime("%H%M%S"))}

```

Try it online!

The idea is to simply create a set of all valid time (as int), then check if the given number is in the set. The set is created by repeatedly adding the current time to the set until all `86400` distinct values are added. Returns: non-empty set if `t` is valid time, otherwise empty set.

# Answer
> 1 votes
# JavaScript (ES6),  ~~27 26~~  21 bytes

Takes input as an integer in `hhmmss` format. Returns \\$0\\$ or \\$1\\$.

```
n=>n%100<60&n%1e4<6e3

```

Try it online!

### How?

```
n=>n%100<60&n%10000<6000

```

is just as long as:

```
n=>n%100<60&n/100%100<60

```

But from there we can use the scientific notation to save 3 bytes:

```
n%10000<6000
n%1e4<6e3

```

# Answer
> 1 votes
# JavaScript (Babel Node), ~~71~~ 52 bytes

```
t=i=>{[,,m,,s]=(i+'').padStart(6,0);return m<6&&s<6}

```

Try it online!

# Answer
> 1 votes
# PHP, 60 bytes

```
<?=preg_match('#\d+([01]\d|2[0-3])([0-5]\d){2}#',$argn+1e6);

```

Try it online!

Basically regex and not much golfable, but fun. Inputs above 235959 are indeterminate.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 44 bytes

```
#&@@TimeObject[x=IntegerDigits[#,100,3]]==x&

```

Try it online!

Works for values above `235959`!

The built-in `TimeObject` command can automatically round up each element!

### Explanation

```
x=IntegerDigits[#,100,3]

```

Split input in base-100 (i.e. in chunks of 2 digits), padded to length 3. Store that list in `x`.

```
TimeObject[...]

```

Convert that to a `TimeObject`.

```
#&@@...

```

Extract the rounded string

```
...==x

```

Check if that is equal to `x` (i.e. nothing rounded up).

## The boring version, 28 bytes

```
Max@IntegerDigits[#,100]<60&

```

Try it online!

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

```
f(n){n=n%100<60&n/100%100<60;}

```

Doesn't check hours.

Try it online!

# C (gcc), 39 bytes

```
f(n){n=n%100<60&n/100%100<60&n/1e4<24;}

```

Checks hours.

Try it online!

# Answer
> 1 votes
## MUMPS, ~~74 70 64~~ 40 bytes

```
t(t) s l=$l(t)-5 f f=l:2:7 q:$e(t,f,f+1)>$s(f-l:59,1:23)
 q f>5

```

Ah, I didn't consider that you only need to handle values up to 239999. That drops it from 64 to 40.

```
t(t) f f=$l(t)-3:2:7 q:$e(t,f)>5
 q f>5

```

# Answer
> 1 votes
# Jelly, 7 bytes

```
ṚHÐoṀ<6

```

**Try it online!**

### How?

```
ṚHÐoṀ<6 - Link: integer, n                 e.g.  236059
Ṛ       - (implicit digits of n) reversed        [9  , 5  , 0  , 6  , 3  , 2  ]
  Ðo    - apply to odd indices:
 H      -   halve                                [4.5, 5  , 0  , 6  , 1.5, 2  ]
    Ṁ   - maximum                                6
      6 - six                                    6
     <  - less than?                             0

```

---

Alternative 7:

```
ṚḊm2Ṁ<6 - reverse, dequeue, modulo-2-slice, maximum, less than 6?

```

# Answer
> 1 votes
# PowerShell, 56 bytes

```
param($a)!(1-in(0..2|%{$a%100-ge60;$a/=100})-or$a-ge.24)

```

Try it online.

# Answer
> 1 votes
# ArnoldC, 676 bytes

```
IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP 0
GET YOUR ASS TO MARS n
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE s
YOU SET US UP 0
GET TO THE CHOPPER s
HERE IS MY INVITATION n
I LET HIM GO 100
ENOUGH TALK
HEY CHRISTMAS TREE m
YOU SET US UP 0
GET TO THE CHOPPER m
HERE IS MY INVITATION n
HE HAD TO SPLIT 100
I LET HIM GO 100
ENOUGH TALK
HEY CHRISTMAS TREE o
YOU SET US UP 0
GET TO THE CHOPPER o
HERE IS MY INVITATION 60
LET OFF SOME STEAM BENNET m
ENOUGH TALK
GET TO THE CHOPPER o
HERE IS MY INVITATION 60
LET OFF SOME STEAM BENNET s
KNOCK KNOCK o
ENOUGH TALK
TALK TO THE HAND o
YOU HAVE BEEN TERMINATED

```

Try it online!

# Answer
> 1 votes
# PowerShell, 25 bytes

port of Neil's solution

```
$args-match'[6-9].(..)?$'

```

Try it online!

Accepts input from 0 to 239999 and outputs `$null` for times and the input for non-times.

# Answer
> 0 votes
# Perl 5, ~~42~~ 39 +1 (-p) = 40 bytes

```
$_=0|!($_%100>59|$_/1e4%10>5|$_/1e5>23)

```

Saved 3 bytes by changing to exponent notation (1000 =\> 1e4)

Try it online!

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
твà60‹

```

Only works for the range \\$\[0, 235959\]\\$.

Try it online or verify all test cases.

**Explanation:**

```
тв      # Convert the (implicit) input-integer to base-100 as list
  à     # Pop and push the maximum
   60‹  # Check if it's smaller than 60
        # (after which the result is output implicitly)

```

# Answer
> 0 votes
# PowerShell, 40 bytes

```
param($n)($n%100-lt60)-and($n%1e4-lt6e3)

```

Try it online!

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