title: Digitangular numbers

text:
# Question
Title: Digitangular numbers
A triangular number is a number that can be expressed as the sum of consecutive positive integers, starting at 1. They can also be expressed with the formula `n(n + 1) / 2`, where `n` is some positive integer.

A number's digitangular counterpart is calculated in the following way:

1. Split a number into an array of its digits e.g. `613 => [6 1 3]`
2. For each number in the array, calculate the `n`th triangular number; `[6 1 3] => [21 1 6]`
3. Sum the resultant array; `[21 1 6] => 28`

Your task is, given an integer `n`, repeatedly calculate `n`'s digitangular counterpart, until the result is equal to 1, then output all values that were calculated. You may output the values in any order, and with an optional inclusion of the original number at the start of the array. This is a so the shortest code wins.

## Test cases

```
23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1

```

# Answer
> 10 votes
# Husk, 6 bytes

```
U¡(ṁΣd

```

Try it online!

### Explanation

```
U¡(ṁΣd
 ¡(       Iterate the following function on the input:
     d       Split the number into digits
   ṁΣ        Map each digit to its triangular number, then sum the results
U         Take the results of iteration until before the first repeated one

```

# Answer
> 7 votes
# 05AB1E, ~~6~~ 5 bytes

```
Δ=SLO

```

Try it online! Edit: Saved 1 byte thanks to @Emigna. Explanation:

```
Δ       Repeat until value doesn't change
 =      Print current value
  S     Split into characters
   L    Turn each character into range from 1 to N
    O   Sum

```

# Answer
> 4 votes
# APL (Dyalog), ~~23~~ ~~20~~ 17 bytes

*3 bytes saved thanks to @ngn*

```
{⍵∪⍨+/∊⍳¨⍎¨⍕⊃⍵}⍣≡

```

Try it online!

**How?**

`⍵∪⍨` \- prepend current array to the

`+/` \- sum of

\- flattened

`⍳¨` \- ranges of each

`⍎¨⍕` \- digit of the

`⊃⍵` \- previous value

`⍣≡` until convergence. The usage of  (union) makes sure after the first 1 is joined, the next will be excluded due to set uniqueness, and the array will converge.

# Answer
> 4 votes
# J, <sub>~~20~~</sub> 19 bytes

```
(1#.2!1+,.&.":)^:a:

```

Try it online!

Outputs the original number, too.

# Explanation

```
(1#.2!1+,.&.":)^:a:
               ^:a:  Apply until input converges, storing all results in an array
(1#.2!1+,.&.":)      Digitangular sum
        ,.&.":         Split to digits
          &.":           Convert to string, apply left function, then undo conversion
        ,.               Ravel items (make array of singleton arrays of items)
                         This ensures that when cast back to integers, the digits are split.
      1+               Add 1 to each
    2!                 Compute (n choose 2) on each (nth triangular number)
 1#.                   Sum (debase 1)

```

# Answer
> 3 votes
## Haskell, ~~51~~ ~~47~~ 46 bytes

```
f 1=[1]
f x=x:f(sum$do d<-show x;[1..read[d]])

```

Try it online!

```
f 1=[1]                     -- if x == 1, return the singleton list [1]
f x=                        -- else
         do d<-show x       --  for each char 'd' in the string representation of x
                            --    (using the list monad)
           [1..read[d]]     --  make a list of [1..d]
                            --    (the list monad concatenates all those lists into a single list)
        sum                 --  sum those numbers
      f                     --  call f on it
    x:                      --  and put x in front of it

```

Edit: @H.PWiz saved a byte. Thanks!

# Answer
> 2 votes
# Python 2, 62 bytes

```
f=lambda x:x<2and[1]or[x]+f(sum(-~int(i)*int(i)/2for i in`x`))

```

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~43~~ 41 bytes

```
Echo@#>1&&#0[#.(#+1)/2&@IntegerDigits@#]&

```

Try it online!

## How it works

The expression `#.(#+1)/2&@IntegerDigits@#` gives the digitangular counterpart of `#`. We `Echo` the input, use short-circuit evaluation with `&&` to stop if we've reached `1`, and otherwise recurse on the digitangular counterpart.

---

*-2 bytes thanks to Martin Ender for the `.` trick: we don't have to use `Tr` to sum the digits if we replace the multiplication `#(#+1)/2` by the dot product `#.(#+1)/2`.*

# Answer
> 2 votes
## Wolfram Language (Mathematica), ~~49~~ ~~42~~ 39 bytes

*Thanks to Misha Lavrov for saving 3 bytes.*

```
#//.x_:>(y=IntegerDigits@Echo@x).++y/2&

```

Try it online! (TIO needs parentheses around the `++y` for some reason. In my local Mathematica installation it works without them, as it should.)

Prints each value on its own line, preceded by `>>`, and includes the starting number.

# Answer
> 1 votes
# Ruby, ~~60 47~~ 42 bytes

-13 bytes by @JustinMariner

-5 bytes by @GB

```
->x{p x=x.digits.sum{|k|k*-~k/2}while x>1}

```

Try it online!

# Answer
> 1 votes
# Japt, ~~19~~ ~~17~~ 10 bytes

Doesn't include the input as the first element.

```
Æ=ì cò xÃâ

```

Try it

```
Æ=ì cò xÃâ     :Implicit input of integer U
Æ              :Map the range [0,U)
 =             :  Reassign to U
  ì            :  Convert to digit array
    c          :  Flat map
     ò         :    Range [0,digit]
       x       :  Reduce by addition
        Ã      :End map
         â     :Deduplicate

```

# Answer
> 1 votes
## Retina, 21 bytes

```
;{:G`
.
$*1¶
1
$%`1
1

```

Try it online! (The outputs of the individual cases aren't well separated, but each output ends with a `1`.)

Prints each number on its own line, in order, including the starting number.

### Explanation

```
;{:G`

```

This is just some configuration of the program. `{` makes the program loop until it fails to change the result (which happens once we get to `1`), `:` prints number before each iteration, and `;` prevents the final result from being printed twice at the end of the program. The `G` is just my usual way of creating a no-op stage.

```
.
$*1¶

```

Convert each digit to unary and put it on its own line.

```
1
$%`1

```

Compute the triangular number on each line, by replacing each `1` with its prefix. We could also use `M!&`1+` here, which gives us all suffixes of each line.

```
1

```

Count all `1`s, which sums up all the triangular numbers and converts the result back to decimal.

# Answer
> 1 votes
# Ohm v2,  ~~9~~  7 bytes

```
·Ω}#ΣΣu

```

Try it online!

**Explanation**

```
          Implicit input as a string
·Ω        Evaluate until the result has already been seen, pushing intermediate results
  }       Split digits
   #      Range from 0 to N
    ΣΣ    Sum
      u   Convert to string

```

# Answer
> 1 votes
# Befunge-93, 51 bytes

```
p&>>:25*%:1+*2/v
  |:/*52p00+g00<
00<vp000_@#-1.::g

```

Try it online!

James Holderness cleverly reshaped my progarm into a 51-byte form. Thanks!

# Answer
> 1 votes
# Pushy, ~~24~~ ~~22~~ ~~21~~ 17 bytes

```
[sL:R{;Svc^#&1=?i

```

**Try it online!**

## Explanation

```
[sL:R{;Svc^#&1=?i

[           &1=?i   \ Loop until result == 1:
 s                  \   Split last result into digits
  L:  ;             \   For each digit n:
    R{              \       Push the range (1, n) inclusive
       S            \   Sum the ranges
        vc^         \   Delete all stack items, except the sum
           #        \   Print result

```

# Answer
> 0 votes
# , 70 bytes

```
f=function(n)"if"(n-1,c(n,f((d=n%/%10^(nchar(n):0)%%10)%*%(d+1)/2)),n)

```

Try it online!

Returns the original value as well.

# , 80 bytes

```
function(n){o={}
while(n-1){n=(d=n%/%10^(nchar(n):0)%%10)%*%(d+1)/2
o=c(o,n)}
o}

```

Try it online!

Does not return the original value.

# Answer
> 0 votes
# Lua, 91 bytes

```
function f(n)x=0 for d in((0|n)..""):gmatch"."do x=x+d*(d+1)/2 end print(x)c=x==1or f(x)end

```

Try it online!

# Answer
> 0 votes
# 05AB1E, ~~20~~ 12 bytes

*Saved 2 bytes thanks to caird coinheringaahing*

```
ΔD,þ€iLO}O}}

```

Try it online!

## Explanation

(old version)

```
Δþ€iD>*;}OD1›iD,}}1,  Main program
Δ                }    Repeat until there is no changes
 þ                    Push digits of the input number
  €i    }             Apply for each digit
    D>*;              Calculate the triangular number for given digit
         O            Sum all numbers
          D1›iD,}     Print if greater than 1
                  1,  Print 1 at the end

```

# Answer
> 0 votes
# JavaScript, ~~61~~ 57 bytes

```
f=a=>a-1?([...a+[]].map(b=>a+=b++*b/2,a=0),a)+' '+f(a):''

```

Try it online!

# Answer
> 0 votes
# Python 2, 69 bytes

```
def f(x):
 while x>1:
  x=sum(-~int(z)*int(z)/2for z in`x`)
  print x

```

Try it online!

# Answer
> 0 votes
# , 19 bytes

```
{+/(+/1+!"I"$)'$x}\

```

Unsurprisingly works similarly to the already posted APL and J solutions

```
               $x    cast x (implicit var of lambda) to string
   (         )'      apply composition (function train) to each character of string
    +/1+!"I"$        cast character to number, create list from 1 to n, sum it
 +/                  sum triangular numbers
{                }\  iterate lambda until result converges, appending each result

```

# Answer
> 0 votes
# Charcoal, 18 bytes

```
Ｗ⊖Ｉθ«≔ＩΣ⭆θΣ…·0κθθ⸿

```

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

```
   θ                Input
  Ｉ                 Cast to integer
 ⊖                  Decrement
Ｗ   «               Loop while not zero
         θ          Current value
        ⭆           Map over characters and concatenate
             0      Literal character 0
              κ     Current character
           …·       Inclusive range
          Σ         Concatenate
       Σ            Sum of digits
      Ｉ             Cast to string
     ≔         θ    Assign back to value
                θ   Output latest value
                 ⸿  Move to start of next line

```

# Answer
> 0 votes
# dc, 62 bytes

```
?sj[0soljZ1-[dljr10r^/10%d1+*2/lo+sod1-r0<i]dsixlopdsj1<b]dsbx

```

Try it online!

# Answer
> 0 votes
# Jelly, 7 bytes

```
DRFSµÐĿ

```

Try it online!

* `DRFSµÐĿ`: Full program / monadic link.
* `ÐĿ`: Loop until results are no longer unique (if something other than 1 would occur twice, then the given input does not have a defined result, since it would never reach 1).
* `D`: Convert from integer to decimal.
* `R`: Range (1-indexed). Vectorizes.
* `F`: Flatten and `S`: Sum (`µ` just creates a new monadic chain)

# Answer
> 0 votes
# dc, 31 bytes

```
[[I~d1+*2/rd0<m+]dsmxpd1<f]dsfx

```

The function `m` computes the digitangular function of its input; `f` repeats this until the result reaches 1.

Note that we use the input radix to extract digits - this means it will work in any base system, not only decimal.

## Demo

```
for i in 23 72 55 78 613 8392 11111 8592025 999999999
    do echo $i '=>' $(dc -e $i'[[I~d1+*2/rd0<m+]dsmxpd1<f]dsfx')
done

```

```
23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1

```

# Answer
> 0 votes
# Python 2, 76 bytes

```
f=lambda k,s=0:k+s<2and[1]or[k]*(s<1)+f(*[k/10,s,s+k%10*(k%10+1)/2][k<1::2])

```

Try it online!

# Answer
> 0 votes
# Neim, 8 bytes

```
ͻtD÷D

```

Explanation:

```
ͻ             Start infinite loop
             Split top of stack into each of its characters
  t           Push infinite list of triangular numbers
             For each of the characters, get the nth element in the above list.
              Sum.
     D         Duplicate.
      ÷        If top of stack is equal to 1, break.
       D       Duplicate.
               Implicitly print all elements in the stack, concatenated.

```

Try it online!

Formatted output

# Answer
> 0 votes
# C, 72 bytes

```
s;F(n){for(s=0;n;n/=10)for(;n%10;n--)s+=n%10;printf("%d ",s);s<2?:F(s);}

```

Try it online!

# Answer
> 0 votes
# , 140 bytes

```
import std.algorithm,std.range,std.conv,std.stdio;void f(T)(T n){n=n.text.map!(u=>u.to!T-48+(u.to!T-48).iota.sum).sum;n.writeln;if(n-1)n.f;}

```

Try it online!

# Answer
> 0 votes
# PHP, 71+1 bytes

```
for(;1<$n="$s"?:$argn;print$s._)for($i=$s=0;$p--||~$p=$n[$i++];)$s+=$p;

```

Run as pipe with `-nR` or try it online. (requires PHP 5.3 or later for the Elvis operator)

# Answer
> 0 votes
# Add++, 32 bytes

```
D,f,@,EDBFEREss
+?
y:1
W!,$f>x,O

```

Try it online!

Doesn't output the first value

## How it works

```
D,f,@,   - Create a monadic function, f.
         - Example argument: [613]
      ED - Digits;   STACK = [[6 1 3]]
      BF - Flatten;  STACK = [6 1 3]
      ER - Range;    STACK = [[1 2 3 4 5 6] [1] [1 2 3]]
      Es - Sum each; STACK = [21 1 6]
      s  - Sum;      STACK = [28]

           f calculates n's digitangular counterpart

+?       - Take input;     x = 613; y = 0
y:1      - Set y to 1;     x = 613; y = 1
W!,      - While x != y...
   $f>x, -   Call f;       x =  28; y = 1
   O     -   Print x;

```

# Answer
> 0 votes
# Perl 6, 36 bytes

```
{$_,{sum map {sum 1..$_},.comb}...1}

```

Try it online!

Includes the input number in the output list.

# Answer
> 0 votes
# K (oK) / K4, 17 bytes

**Solution:**

```
{+/,/!:'1+.:'$x}\

```

Try it online!

**Examples:**

```
{+/,/!:'1+.:'$x}\23
23 9 45 25 18 37 34 16 22 6 21 4 10 1
{+/,/!:'1+.:'$x}\72
72 31 7 28 39 51 16 22 6 21 4 10 1
{+/,/!:'1+.:'$x}\999999999
999999999 405 25 18 37 34 16 22 6 21 4 10 1

```

**Explanation:**

Converge over lambda returning all results along the way:

```
{+/,/!:'1+.:'$x}\ / the solution
{              }\ / lambda {}, converge \
             $x   / string input, 613 => "613"
          .:'     / value (.:) each (') "613" => 6 1 3
        1+        / add 1, 6 1 3 => 7 1 4
     !:'          / til (!:) each (') to generate ranges
   ,/             / flatten list
 +/               / sum list

```

# Answer
> 0 votes
# Pyt, 17 bytes

```
`Đą△ƩĐ1≠?ŕł:;ŕ↔ŕ↔

```

Explanation:

```
                        Implicit input
`         ł             Loop ... while top of stack is not zero
 Đ                      Duplicate the top of the stack
  ą△Ʃ                   Get the digitangular sum of the top of the stack
     Đ1≠                Is it not equal to 1?
        ?  :;           If top of stack is 1, Then continue; Else jump to ':'
         ŕ              Remove top of stack
          ł             Loop back to ` if top of stack is 1
           :;           If top of stack isn't 1, then continue from ':'
             ŕ↔ŕ↔       Remove top and bottom of stack
                        Implicit print

```

Try it online!

---
Tags: code-golf, math
---


title: LED Numbers and Letters

text:
# Question
Title: LED Numbers and Letters
The program must print the following block of text of LED numbers exactly.

```
+-----------------------------------------------------------------+
|                                                                 |
| 000   1 222 333 4 4 555 666 777 888 999 AAA B   CCC   D EEE FFF |
| 0 0   1   2   3 4 4 5   6     7 8 8 9 9 A A B   C     D E   F   |
| 0 0   1 222 333 444 555 666   7 888 999 AAA BBB C   DDD EEE FFF |
| 0 0   1 2     3   4   5 6 6   7 8 8   9 A A B B C   D D E   F   |
| 000   1 222 333   4 555 666   7 888 999 A A BBB CCC DDD EEE F   |
|                                                                 |
+-----------------------------------------------------------------+

```

Notice the 1-char padding inside the borders. The trailing newlines, and the types of the newlines are not significant. However, the whitespaces are the spaces you get when you press spacebars (ASCII 32).

Shortest code wins. Using data encoding (base64, gzip), or compressing with other Unicode characters is discouraged. You cannot use programs like `cat` or `gzip` since they are not programming languages.

The character count *must* be less than 600 to qualify.

# Answer
> 7 votes
## Golfscript, 142 137 chars

Unfortunately some of the characters are control codes, so I'm going to have to post a hexdump and a link rather than a direct copy of the source:

```
00000000  27 2b 27 3a 28 27 2d 27  36 35 2a 3a 5e 28 6e 27  |'+':('-'65*:^(n'|
00000010  7c 27 3a 29 27 20 27 3a  7c 36 34 2a 3a 40 27 20  ||':)' ':|64*:@' |
00000020  7c 0a 7c 20 27 3a 76 5b  27 77 12 5d 5b 3a 6b 6f  ||.| ':v['w.][:ko|
00000030  52 7f 7b 7e 2f 65 1f 6d  6c 27 7b 7d 2f 5d 3a 24  |R.{~/e.ml'{}/]:$|
00000040  2c 2c 7b 3a 78 3b 5b 27  60 40 50 20 00 10 2c 08  |,,{:x;['`@P ..,.|
00000050  1a 04 00 02 05 01 03 27  7b 7d 2f 5d 7b 24 78 3d  |.......'{}/]{$x=|
00000060  26 21 5b 34 38 78 2e 31  30 2f 37 2a 2b 2b 5d 7c  |&![48x.10/7*++]||
00000070  2b 3d 7d 25 33 2f 7d 25  7a 69 70 7b 7c 2a 7d 25  |+=}%3/}%zip{|*}%|
00000080  76 2a 76 40 29 6e 28 5e  28                       |v*v@)n(^(|

```

leds.gs

Note that all of the characters are 7-bit values and legal Unicode code points, so the number of characters is the same as the number of bytes in UTF-8.

Basically there are two hard-coded arrays. The first is a 15-element bitmap indicating which of the 7 segments control each grid cell. The second is the 7-segment encoding of the 16 characters. Then it's just a case of using bitwise and to work out which segments are turned on and doing some string manipulation.

# Answer
> 6 votes
## Python, 216 chars

```
S=' '
E='|\n| '
H=B='+'+'-'*65+'+\n|'+S*65+E
X='%(x)X'
M=[X+S+S,S+S+X,X+S+X,X+X+X]
for i in range(5):
 for n in range(16):H+=M[0xcf33ed703ec2bbdefbb55fb3dcd7addf37557ab>>10*n+2*i&3]%{'x':n}+S
 H+=E
print H+B[-6::-1]

```

# Answer
> 6 votes
## Java, 302 characters

```
class A{public static void main(String[]a){String d="w$]m.k{%o?zS|[#!% \" $ :(L 0 @ p` ",s="";for(int y=0;y<9;y++){s+=y%8==0?"+-":"| ";for(int x=0;x<64;x++)s+=y%8==0?"-":y!=1&&y!=7&&((d.charAt(8+x%4+y*4)-32)&d.charAt(x/4))>0?(char)((x<40?48:55)+x/4):" ";s+=y%8==0?"+\n":"|\n";}System.out.println(s);}}

```

Expanded :

```
public class A {
    public static void main(String[] args) {
        String d = "w$]m.k{%o?zS|[#!% \" $ :(L 0 @ p` ", s = "";
        for (int y = 0; y < 9; y++) {
            s += y % 8 == 0 ? "+-" : "| ";
            for (int x = 0; x < 64; x++)
                s += y % 8 == 0 ? "-" :
                    y != 1 && y != 7 && ((d.charAt(8 + x % 4 + y * 4) - 32) & d.charAt(x / 4)) > 0 ?
                            (char) ((x < 40 ? 48 : 55) + x / 4) : " ";
            s += y % 8 == 0 ? "+\n" : "|\n";
        }
        System.out.println(s);
    }
}

```

The digits shapes are encoded in a byte with the following pattern:

```
  1 1 1
2       4
2       4
2       4
  8 8 8
16      32
16      32
16      32
  646464

```

e.g number 5 is 1|2|8|32|64 = 107

When outputting the text, each "pixel" (character) is set only if some "lines" of digits are enabled. For example, the upper-left character of a digit is set only if the line 1 or 2 are enabled. The lower-down character is set only if lines 32 or 64 are enabled.

# Answer
> 3 votes
For the sheer fun of it...

**BrainFuck** *611*

Note: Can probably be golfed further.

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

# Answer
> 2 votes
### Scala, 267 characters, with bitwise encoding since everything else is worse.

```
val a="+"+"-"*65+"+"
(a+:(""+:BigInt("sbnatrnet3het8h2l21ala42h2hetrn2trn8trl2g8ha58laha4e5rhesbnatrn8",32).toString(2).grouped(64).map(x=>x.indices.map(i=>if(x(i)=='0')" "else"%X".format((i/4)%16)).mkString).toSeq:+"").map(s=>"|%65s|".format(s)):+a).foreach(println)

```

# Answer
> 0 votes
## JavaScript 327 characters

It's the best I can do here...

`_='console.log("?;%0*K , 77&A:!CCC!/!2!3KK 5!6J7@@ 9 H :!C! < *K4,!&A:BI!DD/ 2J3!4!5 6 6!7@@!H : I!D<0*!,!& :BICC DD>!|;|G?")J #====-$!!!!!!!%|G| 0&7@88 99H*0!1 222 333,4 555 666/>FF % 0!1:A B;G|$$$ < D E!F!%=--->D EEE F?+#####+@ 8G\\nH9 AIB CJ! K 4';for(Y in $='KJIHG@?>=<;:/,*&%$#!')with(_.split($[Y]))_=join(pop());eval(_)`

# Answer
> 0 votes
# C (clang), ~~279~~ ~~269~~ 273 bytes

Too many printf()s; too many for loops.

```
(*P)()=printf;f(i,j,k,h){char*t="ckoOc;P5Z5UlolOoB0RXI=??_o7",u[66]={0};P("+%s+\n|%66c\n",memset(u,45,65),'|');for(h=0,i=5;i--;P("|\n"))for(P("| "),j=0;j<16;j++,P(" "),h=h>2?t++,0:h+2)for(k=3;k--;)P("X    XX XXXX"[k+((*t-48>>h)&3)*3]^88?" ":"%X",j);P("|%66c\n+%s+",'|',u);}

```

Try it online!

# Answer
> -1 votes
**Perl, 486 characters, obviously not even trying hard.**

```
sub p {print @_};p("+",'-'x65,"+\n");p('|',' 'x65,"|\n");
p("| 000   1 222 333 4 4 555 666 777 888 999 AAA B   CCC   D EEE FFF |\n");
p("| 0 0   1   2   3 4 4 5   6     7 8 8 9 9 A A B   C     D E   F   |\n");
p("| 0 0   1 222 333 444 555 666   7 888 999 AAA BBB C   DDD EEE FFF |\n");
p("| 0 0   1 2     3   4   5 6 6   7 8 8   9 A A B B C   D D E   F   |\n");
p("| 000   1 222 333   4 555 666   7 888 999 A A BBB CCC DDD EEE F   |\n");
p('|',' 'x65,"|\n");p("+",'-'x65,"+\n");

```

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


title: Bracket Expansion!

text:
# Question
Title: Bracket Expansion!
Your challenge is to expand some brackets in a program's input as shown:

1. Find a string *s* between two matching brackets `[` and `]`, with a single digit *n* after the closing bracket.
2. Remove the brackets.
3. Replace *s* with itself repeated *n* times. (If *n* is 0, simply remove *s*.)
4. Go to step 1 until there are no more matching brackets in the input.

Additional rules and clarifications:

* You will take input and give output via any allowed means.
* A trailing newline in the output is allowed.
* You only need to handle printable ASCII in the input.
* You may assume that all brackets match, i.e. you will never receive the input `[]]]]` or `[[[[]`.
* You may assume that each closing bracket `]` has a digit after it.

Test cases:

```
Input                -> Output
[Foo[Bar]3]2         -> FooBarBarBarFooBarBarBar
[one]1[two]2[three]3 -> onetwotwothreethreethree
[three[two[one]1]2]3 -> threetwoonetwoonethreetwoonetwoonethreetwoonetwoone
[!@#[$%^[&*(]2]2]2   -> !@#$%^&*(&*($%^&*(&*(!@#$%^&*(&*($%^&*(&*(
[[foo bar baz]1]1    -> foo bar baz
[only once]12        -> only once2
[only twice]23456789 -> only twiceonly twice3456789
[remove me!]0        ->
before [in ]2after   -> before in in after

```

As this is , the shortest answer in each language wins. Good luck!

# Answer
> 13 votes
# Gema, 17 characters

```
[#]?=@repeat{?;#}

```

Sample run:

```
bash-4.4$ gema '[#]?=@repeat{?;#}' <<< '[three[two[one]1]2]3'
threetwoonetwoonethreetwoonetwoonethreetwoonetwoone

```

# Answer
> 8 votes
# Retina, ~~24~~ ~~23~~ 22 bytes

```
+`\[([^][]*)](.)
$2*$1

```

Try it online! This is practically a builtin in Retina 1. Edit: Saved 1 byte thanks to @Kobi. ~~47~~ 45 bytes in Retina 0.8.2:

```
].
]$&$*¶
{+`\[([^][]*)]¶
$1[$1]
\[([^][]*)]

```

Try it online!

# Answer
> 7 votes
# Haskell, ~~101~~ 96 bytes

```
fst.(""%)
infix 4%
s%']':d:r=(['1'..d]>>s,r)
s%'[':r|(t,q)<-""%r=s++t%q
s%x:r=s++[x]%r
s%e=(s,e)

```

Try it online! Instead of using regular expression like most of the other answers, this implements a recursive parser.

*-5 bytes thanks to BMO!*

# Answer
> 7 votes
# Perl 5, ~~34~~ ~~33~~ 29 + 1 (`-p`) = 30 bytes

```
s/.([^[]*?)](.)/$1x$2/e&&redo

```

Try it online!

Cut it down with some help from @Shaggy and @TonHospel.

# Answer
> 5 votes
# Japt v2, ~~21~~ ~~20~~ 19 bytes

*Saved 2 bytes thanks to @Shaggy*

```
e/.([^[]*?)](./@YpZ

```

Test it online!

`e` is recursive replace, which makes one replacement at a time until there are no more matches. In this case, matches of the regex `/\[([^[]*?)](\d)/g` are replaced with with \<inner text\> repeated \<digit\> times until there are no more matches.

According to what I have planned (here), this regex should eventually be at least ~~3~~ 2 bytes shorter:

```
‹[“⁽[»₋”]“.›

```

# Answer
> 4 votes
# JavaScript, ~~71~~ ~~67~~ 66 bytes

I *had* a 54 byte solution but it got screwed over by the second test case! :(

```
f=s=>s!=(x=s.replace(/.([^[]*?)](.)/,(_,y,z)=>y.repeat(z)))?f(x):x

```

---

## Test Cases

```
f=s=>s!=(x=s.replace(/.([^[]*?)](.)/,(_,y,z)=>y.repeat(z)))?f(x):x
o.innerText=`[Foo[Bar]3]2
[one]1[two]2[three]3
[three[two[one]1]2]3
[!@#[$%^[&*(]2]2]2
[[foo bar baz]1]1
[only once]12
[only twice]23456789
[remove me!]0
before [in ]2after`.split`\n`.map(x=>x.padEnd(22)+`:  `+f(x)).join`\n`
```

```
<pre id=o></pre>
```

# Answer
> 4 votes
# Python 3, ~~110~~ ~~93~~ 92 bytes

```
import re
f=lambda s:f(re.sub(r'\[([^][]+)\](.)',lambda m:m[1]*int(m[2]),s))if'['in s else s

```

Try it online!

-17 bytes thanks to pizzapants184 -1 byte thanks to Kevin Cruijssen

# Answer
> 4 votes
# Scala, 173 bytes

```
l.foreach{x=>def r(c:String):String={val t="""\[([^\[\]]*)\](.)""".r.unanchored;c match{case t(g,h)=>r(c.replaceAllLiterally(s"[$g]$h",g*h.toInt));case _=>c}};println(r(x))}

```

Try it online!

### Expanded:

```
l.foreach { x =>
  def remove(current: String): String = {
    val test ="""\[([^\[\]]*)\](.)""".r.unanchored
    current match {
      case test(g, h) => remove(current.replaceAllLiterally(s"[$g]$h", g * h.toInt))
      case _ => current
    }
  }

  println(remove(x))
}

```

# Old solution

# Scala, ~~219~~ ~~215~~ ~~213~~ ~~212~~ ~~199~~ bytes

```
l.foreach{x=>def r(c:String):String={"""\[([^\[\]]*)\](.)""".r.findFirstMatchIn(c).map{x=>val g=x.group(1);val h=x.group(2).toInt;r(c.replaceAllLiterally(s"[$g]$h",g*h))}.getOrElse(c)};println(r(x))}

```

Try it online!

### Expanded:

```
l.foreach { x =>
  def remove(current: String): String = {
    """\[([^\[\]]*)\](.)""".r.findFirstMatchIn(current).map { x =>
      val g = x.group(1)
      val h = x.group(2).toInt
      remove(current.replaceAllLiterally(s"[$g]$h", g * h))
    }.getOrElse(current)
  }
  println(remove(x))
}

```

Where l is the list of strings that we will process.

Thanks Kevin Cruijssen for -1 byte

Went from 212 to 199 by removing an unused parameter, didn't pay attention.

# Answer
> 3 votes
# Stacked, ~~39~~ 38 bytes

*Saved 1 byte thanks to Shaggy, golfed the regex!*

```
['\[([^[\]]+)](.)'{.y x:x#~y*}recrepl]

```

Try it online!

Simply recursively replaces a regex `'\[([^[\]]+)](.)'` with the repetition rule.

# Answer
> 3 votes
# JavaScript \- ~~77~~ ~~75~~ 72 bytes

```
f=a=>a.replace(/(.*)\[([^[]*?)](.)(.*)/,(a,b,c,d,e)=>f(b+c.repeat(d)+e))

```

Edit: updated regex with Shaggy's recommendation

**Snippet:**

```
const test = ["[Foo[Bar]3]2", "[one]1[two]2[three]3", "[three[two[one]1]2]3", "[!@#[$%^[&*(]2]2]2", "[[foo bar baz]1]1", "[only once]12", "[only twice]23456789", "[remove me!]0", "before [in ]2after"];

const f=a=>a.replace(/(.*)\[([^[]*?)](.)(.*)/,(a,b,c,d,e)=>f(b+c.repeat(d)+e))

d.innerHTML=test.map(f).join("<br>");
```

```
<p id="d">
```

# Answer
> 3 votes
# Python 3, ~~155~~ ~~148~~ ~~101~~ 97 bytes

```
def f(x):
 a=x.rfind('[')
 if~a:b=x.find(']',a);x=f(x[:a]+x[a+1:b]*int(x[b+1])+x[b+2:])
 return x

```

Try It Online

Thanks to HyperNeutrino and Mego for -47 bytes and user202729 for -4 bytes.

# Answer
> 2 votes
# Java 8, ~~250~~ ~~249~~ ~~241~~ 239 bytes

```
s->{for(;s.contains("[");)for(int i=0,j,k;i<s.length();)if(s.charAt(i++)==93){String t="",r=t;for(j=k=s.charAt(i)-48;j-->0;)t+=s.replaceAll(r="(.*)\\[([^\\]]+)\\]"+k+"(.*)","$2");s=k<1?t:s.replaceFirst(r,"$1$3").replace("",t);}return s;}

```

-2 bytes thanks to *@JonathanFrech* (code contains two unprintable ASCII characters now, which can be seen in the TIO-link below).

Sigh... Java with regex is so damn limited.. I'll just quote myself from another answer here:

> *Replacing `WWWW` with `222W` is easy in Java, but with `4W` not..* If only Java had a way to use the regex capture-group for something.. Getting the length with `"$1".length()`, replacing the match itself with `"$1".replace(...)`, converting the match to an integer with `new Integer("$1")`, or using something similar as Retina (i.e. `s.replaceAll("(?=(.)\\1)(\\1)+","$#2$1"))` or JavaScript (i.e. `s.replaceAll("(.)\\1+",m->m.length()+m.charAt(0))`) would be my number 1 thing I'd like to see in Java in the future to benefit codegolfing.. \>.\> I think this is the 10th+ time I hate Java can't do anything with the capture-group match..
> Quote from here.

**Explanation:**

Try it online.

```
s->{                           // Method with String as both parameter and return-type
  for(;s.contains("[");)       //  Loop as long as the String contains a block-bracket
    for(int i=0,j,k;i<s.length();)
                               //   Inner loop over the characters of the String
      if(s.charAt(i++)==93){   //    If the current character is a closing block-bracket:
        String t="",r=t;       //     Create two temp-Strings, starting empty
        for(j=k=s.charAt(i)-48;//     Take the digit after the closing bracket
            j-->0;)            //     Loop that many times:
          t+=s.replaceAll(r="(.*)\\[([^\\]]+)\\]"+k+"(.*)","$2");
                               //      Append `t` with the word inside the block brackets
        s=k<1?                 //     If the digit was 0:
           t                   //      Replace the input with an empty String as well
          :                    //     Else:
           s.replaceFirst(r,"$1$3").replace("",t);}
                               //      Replace the word between brackets by `t`,
                               //      and remove the digit
  return s;}                   //  Return the modified input-String as result

```

# Answer
> 2 votes
# QuadR with the  argument, ~~30~~ 28 bytes

```
\[[^[]+?].
∊(⍎⊃⌽⍵M)⍴⊂1↓¯2↓⍵M

```

Try it online!

`\[[^[]+?].` replace "`[`non-`[` stuff`]`character" with

`¯2↓⍵M` drop the last two characters of the **M**atch ("`]`digit")
`1↓` drop the first character ("`[`")
enclose to be treated as a whole
`(``)⍴`**r**eshape to length:
`⌽⍵M` reverse the **M**atch
pick the first (the digit)
evaluate
**ϵ**nlist (flatten)

repeat until no more changes happen

---

The equivalent Dyalog APL function is 47 bytes:

```
'\[[^[]+?].'⎕R{∊(⍎⊃⌽⍵.Match)⍴⊂1↓¯2↓⍵.Match}⍣≡

```

Try it online!

# Answer
> 2 votes
# C, ~~407~~ 368 bytes

Thanks to Jonathan Frech for saving bytes.

golfed (file bracket.c):

```
i,j,k,l,n;char*f(a,m)char*a;{for(i=0;a[i];++i){a[i]==91&&(j=i+1);if(a[i]==93){k=a[i+1]-48;if(!k){for(l=i+2;l<m;)a[++l-i+j-4]=a[l];a=realloc(a,m-3);return f(a,m-3);}for(l=j;l<i;)a[~-l++]=a[l];for(l=i+2;l<m;)a[++l-4]=a[l];m-=3;n=m+~-k*(i---j--);a=realloc(a,n);for(l=i;l<m;)a[l+++~-k*(i-j)]=a[l];for(m=0;m<k;++m)for(l=j;l<i;)a[l+++m*(i-j)]=a[l];return f(a,n);}}return a;}

```

ungolfed with program:

```
#include <stdlib.h>
#include <stdio.h>

// '[' = 133
// ']' = 135
// '0' = 48

i, j, k, l, n;

char* f(a,m) char*a;
{
  for (i=0; a[i]; ++i) {
    a[i]==91&&(j=i+1);

    if (a[i]==93) {
      k=a[i+1]-48;

      if (!k) {
        for (l=i+2; l<m; )
          a[++l-i+j-4] = a[l];

        a = realloc(a,m-3);
        return f(a,m-3);
      }
      for (l=j;l<i;)
        a[~-l++] = a[l];
      for (l=i+2; l<m; )
        a[++l-4] = a[l];
      m -= 3;
      n = m+~-k*(i---j--);
      a = realloc(a,n);

      for (l=i; l<m; )
        a[l+++~-k*(i-j)] = a[l];
      for (m=0; m<k; ++m)
        for (l=j; l<i;)
          a[l+++m*(i-j)] = a[l];

      return f(a,n);
    }
  }
  return a;
}

int main()
{
  char c[]="[Foo[Bar]3]2";
  char *b;

  char cc[]="[remove me!]0";
  char *bb;

  char ccc[]="[only once]12";
  char *bbb;

  b=malloc(13);
  bb=malloc(14);
  bbb=malloc(14);

  for (i=0; i<13; ++i)
    b[i] = c[i];

  for (i=0; i<14; ++i)
    bb[i] = cc[i];

  for (i=0; i<14; ++i)
    bbb[i]=ccc[i];

  printf("%s\n", f(b, 13));
  printf("%s\n", f(bb, 14));
  printf("%s\n", f(bbb, 14));

  return 0;
}

```

Compiled with gcc 5.4.1, `gcc bracket.c`

# Answer
> 2 votes
# Red, 147 bytes

```
f: func[t][a: charset[not"[]"]while[parse t[any a some[remove["["copy h any a"]"copy d a](insert/dup v: copy""h to-integer d)insert v | skip]]][]t]

```

Ungolfed:

```
f: func [t][
    a: charset [not "[]"]                          ; all chars except [ and ]
    while [ parse t [                              ; repeat while parse is returning true
        any a                                      ; 0 or more chars other than [ and ]
        some [                                     ; one or more block:
            remove ["[" copy h any a "]" copy d a] ; remove the entire block, store the
                                                   ; substring between the [] in h,
                                                   ; the digit into d
            (insert/dup v: copy "" h to-integer d) ; makes d copies of h
            insert v                               ; and inserts them in place
            | skip ]                               ; skip if no match
        ]
    ][]                                            ; empty block for 'while'
    t                                              ; return the modified string
]

```

I started learning Red's Parse dialect only yesterday, so I'm sure my code can be improved further. Parse is incomparably more verbose than regex, but is very clear, flexible and readable and can be freely mixed with the rest of the Red language.

Try it online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), 86 bytes

```
#//.s_:>StringReplace[s,"["~~x:Except["["|"]"]...~~"]"~~d_:>""<>x~Table~FromDigits@d]&

```

Try it online!

# Answer
> 1 votes
# Jelly, 30 bytes

```
œṡ”]µḢUœṡ”[ẋ€1¦Ṫ©Ḣ$FṚ;®
Çċ”]$¡

```

Try it online!

---

## Explanation.

```

œṡ”]µḢUœṡ”[ẋ€1¦Ṫ©Ḣ$FṚ;®    Helper link 1, expand once.
                           Assume input = "ab[cd]2ef".

œṡ      Split at first occurence of
  ”]      character "]".
    µ   Start new monadic chain. Value = "ab[cd","2ef".

Ḣ       ead. "ab[cd"
 U      **U**pend. "dc[ba"
  œṡ”[  Split at first occurence of "[". | "dc","ba".

ẋ€        Repeat ...
  1¦        the element at index **1**...
          by ...
    Ṫ Ḣ$    the ead of the ail of ...
          the input list ("ab[cd","2ef") (that is, 2)

          The command  also pop the head '2'. The remaining
            part of the tail is "ef".
     ©    Meanwhile, store the tail ("ef") to the register.

          Current value: "dcdc","ba"
FṚ        **F**latten and everse. | "abcdcd"
  ;®      Concatenate with the value of the register. "abcdcdef"

Çċ”]$¡    Main link.

 ċ”]$     Count number of "]" in the input.
     ¡    Repeatedly apply...
Ç           the last link...
            that many times.

```

# Answer
> 1 votes
# C,381 bytes

Compact version:

```
while(1){int t=strlen(i);int a,c=-1;char*w;char*s;char*f;while(c++<t){if(i[c]==']'){int k=c-a;w=calloc((k--),1);memcpy(w,&i[a+1],k);s=calloc((t-c-1),1);memcpy(s,&i[c+2],t-c-2);i[a]=0;int r=i[c+1]-48;if(r==0){f=calloc(t,1);sprintf(f,"%s%s",i,s);}else{f=calloc((t+k),1);sprintf(f,"%s%s[%s]%d%s",i,w,w,r-1,s);}free(i);i=f;break;}else if(i[c]=='[')a=c;}free(w);free(s);if(c>=t)break;}

```

Full version:

```
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void proceed(char* input)
{
  while(1)
  {
    int t=strlen(input);
    int start,cursor=-1;
    char* word;
    char* suffix;
    char* final;
    while(cursor++<t)
    {
      if(input[cursor]==']')
      {
        int wordlength = cursor-start;
        word=calloc((wordlength--),sizeof(char));
        memcpy(word, &input[start+1], wordlength );
        suffix=calloc((t-cursor-1),sizeof(char));
        memcpy( suffix, &input[cursor+2], t-cursor-2 );
        input[start]='\0';
        int rep=input[cursor+1]-'0';
        if(rep==0)
        {
          final=calloc(t,sizeof(char));
          sprintf(final,"%s%s",input,suffix);
        }
        else
        {
          final=calloc((t+wordlength+5),sizeof(char));
          sprintf(final,"%s%s[%s]%d%s",input,word,word,rep-1,suffix);
        }
        free(input);
        input=final;
        break;
      }
      else if(input[cursor]=='[')
        start=cursor;
    }
    free(word);
    free(suffix);

    if(cursor>=t)break;
  }
}

int main()
{
  char* input=calloc(256,sizeof(char));
  sprintf(input,"a[[toto]2b]2[ana]3");
  printf("in : %s\n",input);
  proceed(input);
  printf("out: %s\n",input);
  return 0;
}

```

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


title: Undulant numbers

text:
# Question
Title: Undulant numbers
An ***undulant*** number is a number where its digits alternate between *up* and *down* like the following number: 461902 or 708143, or even 1010101, but not 123, because 2 \< 3.

Write a program or function which returns a truthy value if a number is *undulant*, and a falsy value otherwise. The shortest code wins.

**Note**: Single digit numbers are a valid input but are not considered *udulant*, thus `isUndulant` returns false for n \< 10.

# Answer
**(pdf)eTeX, 129 chars**

```
\def\a#1#2{\if#2?\ifx\r\s\def\s{1}\else
True\end\fi\fi\edef\t{\pdfstrcmp{#2}{#1}}\ifx\s\t
False\end\fi\let\s\t\a#2}\expandafter\a

```

Compiling with `pdfetex filename.tex 1324?` gives a pdf output. TeX is primarily a typesetting language, and outputting instead to stdout would take around 20 more chars. Also the strange requirement for one-digit numbers (false rather than true) takes me 26 chars.
> 6 votes

# Answer
### Ruby, 72 70 characters

```
Q=10;k=->n,v{(n%Q-n/Q%Q)*v<0?k[n/Q,-v]:n<Q};u=->n{n>9&&k[n,-1]|k[n,1]}

```

Usage and testcases:

```
p u[10101]   # <= true
p u[708143]  # <= true
p u[2421]    # <= false
p u[1231]    # <= false
p u[873]     # <= false

```

Single digits yield *false*:

```
p u[5]       # <= false

```

Consecutive identical digits also return *false*:

```
p u[66]      # <= false
p u[1221]    # <= false

```
> 6 votes

# Answer
## J, 45

```
*./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=.

```

Sample use:

```
   *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 461902
1
   *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 708143
1
   *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 1010101
1
   *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 123
0
   *./(n>9),(}:(=-)}.)(}:*@-}.)n#:~10$~>.10^.n=. 5
0

```

I'm pretty sure there's a finer way of twisting Insert `/` to do more of the work in a go, but I've been J-less for months, I need to get back to it.
> 6 votes

# Answer
# J, 30 bytes

```
*/0<(#,]*{.*1 _1$~#)2-/\a.i.":

```

A different approach than the other J answers.

```
   */0<(#,]*{.*1 _1$~#)2-/\a.i.":461902
1
   */0<(#,]*{.*1 _1$~#)2-/\a.i.":708143
1
   */0<(#,]*{.*1 _1$~#)2-/\a.i.":1010101
1
   */0<(#,]*{.*1 _1$~#)2-/\a.i.":123
0
   */0<(#,]*{.*1 _1$~#)(}.-}:)a.i.":5
0

```

Would be 3 characters shorter if 5 were considered undulant.
> 6 votes

# Answer
## Haskell, 88 77 73 65 characters

```
z=tail>>=zipWith compare
q[]=0>1
q s=all(/=EQ)$s++z s
u=q.z.show

```

This requires the commonly used language pragma (or `-X` flag): `NoMonomorphismRestriction`. If you don't admit that, we have to add 4 characters and define `z` thus:

```
z s=zipWith compare s$tail s

```
> 5 votes

# Answer
# Sage, 83 76 bytes

```
f=lambda x:uniq(cmp(*`x`[i-2:i][::(-1)^i])for i in[2..len(`x`)])in[[1],[-1]]

```

Got the idea to use cmp(\*\[..\]) from JBernardo. In Sage, `uniq(...)` is an alias for `list(set(...))`.

Edit: just noticed that for x \< 10, `uniq(cmp(...)) == []`, which isn't on `[[1],[-1]]`. If x were input as a string, instead of an integer, I could get another 4 characters out!
> 4 votes

# Answer
### Python: ~~101~~ 100 characters

Before minification:

```
undulate = (lambda n: n > 9
            and all(cmp(*digits) == (i % 2) * 2 - 1
                    for i, digits
                    in enumerate(zip(min(`n`,`n`[1:]),
                                     max(`n`,`n`[1:])))))

```

After minification:

```
a=lambda b:b>9and all(cmp(*c)==d%2*2-1 for d,c in enumerate(zip(min(`b`,`b`[1:]),max(`b`,`b`[1:]))))

```
> 4 votes

# Answer
## Python, ~~134~~ 129 chars

```
def f(x):d=[cmp(*i)for i in zip(`x`,`x`[1:])]if x>9 else[0];n=d[0]>0;return all(i<0 for i in d[n::2])&all(i>0 for i in d[n<1::2])

```

Ungolfed:

```
def f(x):
    if x>9:
        d = [cmp(*i)for i in zip(`x`,`x`[1:])] #difference of x[i] and x[i+1]
    else:
        d = [0]       #trick to return False if x<10 using less chars
    n = d[0]>0        #First digit is -1 or 1?
    neg = d[n::2]     #negative numbers if x is Undulant
    pos = d[not n::2] #positive numbers if x is Undulant

    #check if all negs are -1 and all pos are 1 and return value
    return all(i<0 for i in neg) and all(i>0 for i in pos)

```
> 3 votes

# Answer
## JavaScript, 88 chars

```
function _(i){i+='';c=i[0];f=i[a=x=1];for(g=f<c;d=i[x++];c=d)g^=a&=g?d<c:d>c;return!f^a}

```

In essence, turn the number into a string and compare adjacent characters, flipping the expectation for each.
> 3 votes

# Answer
# Python, ~~119~~ 108 bytes

```
def u(x):l=[cmp(i,j)for i,j in zip(`x`,`x`[1:])];print x>9and all([i*j<0 for i,j in zip(l,l[1:])])and l!=[0]

```
> 3 votes

# Answer
# Haskell, 82 bytes

```
c=cycle[(<),(>)]
l!n=n>9&&and(zipWith3($)l(show n)$tail$show n)
u n=c!n||((>):c)!n

```

Try it online!
> 3 votes

# Answer
# J, 44 39 36 31 bytes

```
*/2(0<#@],0>*/\)*2-/\".;' ',.":

```

Usage as before.

I hadn't noticed that my last edit made the inequality with 0 check completely unnecessary. :-)

Previous answer (+ explanation):

```
(0=+/2=/\u)*(1<#u)**/2~:/\2<:/\u=.".;' ',.":

```

Usage:

```
    (0=+/2=/\u)*(1<#u)**/2~:/\2<:/\u=.".;' ',.":461902
1

```

The answer has four parts:

1. `u=.".;' ',.":` This reads in the number as a string `":`, splits it into a list of characters preceded by spaces `' ',.`, stitches it back together `;`, converts it back to numbers `".` and then stores the result `u=.` This basically turns 461902 into 4 6 1 9 0 2 which I find easier to process in J.
2. `*/2~:/\2<:/\` This operates on the value stored in u. It takes each pair of characters and checks if the left one is less than or equal to the right one `2<:/\` so 4 6 1 9 0 2 becomes 1 0 1 0 1. It then takes the result of this and checks each pair of numbers for inequality `2~:/\` so 1 0 1 0 1 becomes 1 1 1 1. Finally it multiplies them all together to get either a 0 or a 1 `*/` At this point we could return the answer if it weren't for 2 things: a single digit returns 1 when the question requires a 0; and equal numbers are treated the same as 'less than' so 461900 returns 1 instead of 0. Bummer. On we go...
3. `(1<#u)` This checks if the number of items stored in u `#u` is greater than 1 and returns false if it's just a single digit number.
4. `(0=+/2=/\u)` This takes each pair of numbers stored in u and checks for equality `2=/\u`. It then sums the answers and checks if it has 0.

The results of parts 2, 3 and 4 are then multiplied together to (hopefully) produce a 1 when the number meets the requirements specified in the question.
> 3 votes

# Answer
# CoffeeScript, ~~98~~ ~~67~~ 53 bytes

```
(n)->0!in((n[i]>=c^(n[0]<n[1])+i)%2for c,i in n[1..])

```

Tests:

```
[
    '01010101' # true
    '12345'    # false
    '1010101'  # true
    '887685'   # false
    '9120734'  # true
    '090909'   # true
]

```

Uncompressed:

```
undulant = (n) ->
    direction = n[0] < n[1]
    return n.split('').every (cur, i) ->
        prev = arr[i-1] or 10 * direction
        +(prev >= cur) is (direction+i)%2

```
> 3 votes

# Answer
# K, 41 bytes

```
{(x>9)&~max(=). 1_'-':'1_'(<':;>':)@\:$x}

```

E.g.

```
{(x>9)&~max(=). 1_'-':'1_'(<':;>':)@\:$x}1212130659
1b

```
> 3 votes

# Answer
## Python, 155 chars

```
g=lambda a,b:all(x>y for x,y in zip(a,b))
u=lambda D:g(D[::2],D[1::2])&g(D[2::2],D[1::2])
def U(n):D=map(int,str(n));return(n>9)&(u(D)|u([-d for d in D]))

```
> 2 votes

# Answer
# C++, 94 chars

```
bool u(int N){int K,P,Q,U=1,D=1;while(N>9)P=N%10,Q=(N/=10)%10,K=D,D=U&Q<P,U=K&Q>P;return U^D;}

```

same method as my Erlang awnser with a for loop rather than recursion.
> 2 votes

# Answer
## Python ~~105~~ ~~101~~ 100 chars

```
c=lambda r,t:len(r)<2 or(cmp(*r[:2])==t and c(r[1:],-t))
u=lambda x:x>9and c(`x`,cmp(*`x`[:2])or 1)

```

Recursive solution. `c(r,t)` checks if first char of `r` is less `(t==-1)` or greater `(t==1)` of second char, and call opposite check on shortened string.
> 2 votes

# Answer
# GolfScript, 48 bytes

```
[`..,(<\1>]zip{..$=\-1%.$=-}%(\{.@*0<*}/abs

```

Hoping to beat J, my first time using GolfScript. Didn't quite succeed.
> 2 votes

# Answer
# Perl/re, 139 bytes

Doing **everything** in regex is kind of a bad idea.

```
/^(?:(.)(?{local$a=$1}))?(?:(?>((.)(?(?{$a lt$3})(?{local$a=$3})|(?!)))((.)(?(?{$a gt$5})(?{local$a=$5})|(?!))))*(?2)?)(?(?{pos>1})|(?!))$/

```

I'm using Perl 5.12 but I think this will work on Perl 5.10. Pretty sure 5.8 is out though.

```
for (qw(461902 708143 1010101 123 5)) {
    print "$_ is " . (/*crazy regex goes here*/ ? '' : 'not ') . "undulant\n";
}

461902 is undulant
708143 is undulant
1010101 is undulant
123 is not undulant
5 is not undulant

```
> 2 votes

# Answer
# JavaScript, ~~66~~ ~~65~~ ~~62~~ 60 bytes

Takes input as a string, returns `true` for undulant numbers, an empty string (falsey) for single digit numbers and `false` otherwise.

```
([s,...a])=>a+a&&a.every(x=>eval(s+"<>"[++y%2]+x,s=x),y=s<a)

```

---

## Try it

Run the Snippet below to test `0-9` and 25 random numbers `<10,000,000`.

```
f=
([s,...a])=>a+a&&a.every(x=>eval(s+"<>"[++y%2]+x,s=x),y=s<a)
tests=new Set([...Array(10).keys()])
while(tests.add(Math.random()*1e7|0).size<35);
o.innerText=[...tests].map(x=>(x=x+``).padStart(7)+` = `+JSON.stringify(f(x))).join`\n`
```

```
<pre id=o></pre>
```

---

## Explanation

A few fun little tricks in this one so I think it warrants a rare explanation to a JS solution from me.

```
()=>

```

We start, simply, with an anonymous function which takes the integer string as an argument when called.

```
[s,...a]

```

That argument is immediately destructured into 2 parameters: `s` being the first character in the string and `a` being an array containing the remaining characters (e.g. `"461902"` becomes `s="4"` and `a=["6","1","9","0","2"]`).

```
a+a&&

```

First, we concatenate `a` with itself, which casts both occurrences to strings. If the input is a single digit number then `a` will be empty and, therefore, become and empty string; an empty string plus an empty string is still an empty string and, because that's falsey in JS, we stop processing at the logical AND and output our empty string. In all other cases `a+a` will be truthy and so we continue on to the next part of the function.

```
a.every(x=>)

```

We'll be checking if every element `x` in `a` returns `true` when passed through a function.

```
y=s<a

```

This determines what our first comparison will be (`<` or `>`) and then we'll alternate from there. We check if the string `s` is less than the array `a`, which gets cast to a string in the process so, if `s` is less than the first character in `a`, `y` will be `true` or `false` if it's not.

```
s+"<>"[++y%2]+x

```

We build a string with the current value of `s` at the beginning and `x` at the end. In between, we index into the string `"<>"` by incrementing `y`, casting its initial boolean value to an integer, and modulo by 2, giving us `0` or `1`.

```
eval()

```

Eval that string.

```
s=x

```

Finally, we pass a second argument to `eval`, which it ignores, and use it to set the value of `s` to the current value of `x` for the next iteration.
> 2 votes

# Answer
# Erlang, 137 123 118 chars

```
u(N)->Q=N div 10,u(Q,N rem 10,Q>0,Q>0). u(0,_,D,U)->D or U;u(N,P,D,U)->Q=N rem 10,u(N div 10,Q,U and(Q<P),D and(Q>P)).

```
> 1 votes

# Answer
## Scala, 141 133 129 97 bytes

```
def u(n:Int):Boolean=n>9&&{
val a=n%10
val b=(n/10)%10
a!=b&&n<99||(a-b*b-(n/100)%10)<0&&u(n/10)}

```

With a = n % 10, b = (n/10) % 10, c = (n/100) % 10

```
if a > b and b < c or
   a < b and b > c

```

Then `a-b * b-c` is either `x*-y` or `-x*y` with `x` and `y` as positive numbers, and the product is in both cases negative, but for `-x*-y` or `x*y` (a \< b \< c or a \> b \> c) the product is always positive.

The rest of the code is handling special cases: one digit, two digits, two identical digits.
> 1 votes

# Answer
## PowerShell, 88

Naïve and trivial. I will golf later.

```
filter u{-join([char[]]"$_"|%{if($n){[Math]::Sign($n-$_)+1}$n=$_})-notmatch'1|22|00|^$'}

```

My test cases.
> 1 votes

# Answer
# JavaScript, 112

```
function(n,d,l,c,f){while(l=n%10,n=n/10|0)d=n%10,c?c>0?d>=l?(f=0):(c=-c):d<=l?(f=0):(c=-c):(c=d-l,f=1);return f}

```

You only need to pass it one argument. I could probably golf this further with a for loop.
> 1 votes

# Answer
# Q, 71 bytes

```
{$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]}

```

Sample usage:

```
q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 5
0b
q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 10101
1b
q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 01010
1b
q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 134679
0b
q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 123456
0b
q){$[x>9;any all a=#[;(1 -1;-1 1)](#)a:1_signum(-':){"I"$x}each -3!x;0b]} 132436
1b

```
> 1 votes

# Answer
# Perl, 78 bytes

```
sub u{@_=split//,$_=shift;s/.(?=.)/($&cmp$_[$+[0]])+1/ge;chop;$#_&&!/00|1|22/}

```
> 1 votes

# Answer
# Mathematica, 46 bytes

```
#!=Sort@#&&#!=Reverse@Sort@#&[IntegerDigits@n]

```

Examples (spaces are not required):

```
# != Sort@# && # != Reverse@Sort@# &[IntegerDigits@5]
# != Sort@# && # != Reverse@Sort@# &[IntegerDigits@123]
# != Sort@# && # != Reverse@Sort@# &[IntegerDigits@132]
# != Sort@# && # != Reverse@Sort@# &[IntegerDigits@321]

(*  out *)
False  False  True  False

```
> 1 votes

# Answer
# CJam, 30 bytes

CJam is newer than this challenge, so this does not compete for the green checkmark, but it's not a winner anyway (although I'm sure this can actually be golfed quite a bit).

```
l"_1=\+{_@-\}*;]"_8'*t+~{W>},!

```

Test it here.

## How it works

Firstly, I'm doing some string manipulation (followed by eval) to save 5 bytes on duplicate code:

```
"..."_8'*t+~
"..."        "Push this string.":
     _       "Duplicate.";
      8'*t   "Replace the 8th character (the -) with *.";
          +~ "Concatenate the strings and evaluate.";

```

So in effect my code is

```
l_1=\+{_@-\}*;]_1=\+{_@*\}*;]{W>},!

```

First, here is how I deal with the weird special case of a single digit. I copy the digit at index `1` and prepend it to the number. We need to distinguish 3 cases:

* The first two digits are different, like `12...`, then we get `212...`, so the start is undulant, and won't affect whether the entire number is undulant.
* The first two digits are the same, like `11...`, then we get `111...`. Now the start is not undulant, but the number wasn't undulant anyway, so this won't affect the result either.
* If the number only has one digit, the digit at index `1` will be the first digit (because CJam's array indexing loops around the end), so this results in two identical digits, and the number is *not* undulant.

Now looking at the code in detail:

```
l_1=\+{_@-\}*;]_1=\+{_@*\}*;]{W>},!
l                                   "Read input.";
 _1=\+                              "Prepend second digit.";
      {_@-\}*                       "This fold gets the differences of consecutive elments.";
             ;]                     "Drop the final element and collect in an aray.";
               _1=\+                "Prepend second element.";
                    {_@*\}*         "This fold gets the products of consecutive elments.";
                           ;]       "Drop the final element and collect in an aray.";
                             {W>},  "Filter out non-negative numbers.";
                                  ! "Logical not.";

```

I'm sure there is a shorter way to actually check digits (of length greater 1) for whether they are undulant (in particular, without using two folds), but I couldn't find it yet.
> 1 votes

# Answer
### Prolog 87 bytes

```
u(X) :- number_codes(X,C),f(C).
f([_,_]).
f([A,B,C|L]) :- (A<B,B>C;A>B,B<C),f([B,C|L]).

```

To run it, just save it as golf.pl, open a prolog interpreter (e.g. gprolog) in the same directory then do:

```
consult(golf).
u(101010).

```

It will give `true` if the number is undulant, otherwise just no.
> 1 votes

# Answer
# Julia 0.6, 62 bytes

```
f(x,a=sign.(diff(digits(x))))=x>9&&-a*a[1]==(-1).^(1:endof(a))

```

Takes in a number, returns `true` for Undulant, and `false` for not. Eg `f(163)` returns `true`.

```
f(x,a=sign.(diff(digits(x))))=x>9&&-a*a[1]==(-1).^(1:endof(a))
f(x,                        )                                   # function definition
    a=sign.(diff(digits(x)))                                    # default 2nd argument is array of differences of signs of digits
                              x>9&&                             # short circuiting and to catch cases under 10
                                   -a*a[1]                      # make the first element of a always -1
                                          ==(-1).^(1:endof(a))  # check that a is an array of alternating -1 and 1 of correct length

```

Try it online!
> 1 votes

# Answer
# , ~~91~~ ~~94~~ 86 bytes

Takes input from stdin, outputs `TRUE` or `FALSE` as appropriate.

```
all(-(z=sign(diff((x=scan())%/%10^(1:nchar(x)-1)%%10)))*z[1]==(-1)^(1:(l=sum(1|z))))&l

```

Try it online!

This uses basically the same algorithm as gggg's Julia answer, but it's a little more verbose.

Added 3 bytes as the first version didn't account for numbers of length `1` always being nonundulant ("unundulant"?). Removed 8 bytes thanks to some golfing of redundant parts.
> 1 votes

# Answer
## PHP, 151 chars

```
function i($n){$n=str_split($n);@$p=$n[1]==null?:($m=($n[0]>=$n[1])?-1:1)*10;foreach($n as$k=>$v)if(($k%2*2-1)*($v-$p)*@$m<=0&$p=$v)return!1;return!0;}

```

ungolfed(-ish):

```
function is_undulant($n){

      $n=str_split($n);
      @$p=$n[1]==null?:($m = ($n[0] >= $n[1])? -1 : 1)*10;
      foreach ($n as$k=>$v)
        if ( ($k%2 * 2 - 1) * ($v - $p) * @$m <= 0 & $p=$v ) return !1;

      return !0;
}

```
> 0 votes

# Answer
# Python, 124 bytes

```
def undulant(x):
    x = `x`
    return any((int(x[1])-int(x[0]))*-1**i*(int(x[i])-int(x[i-1]))>0 for i in range(2,len(x)))

```

Different approach I think.
> 0 votes

# Answer
## Scala, 194 characters

```
def u(i:Int):Boolean={val x=i.toString;if(!x.matches("(\\d)\\1")){"(?<=.*)(\\d)(?=(\\d).*)".r.replaceAllIn(x,m=>if(m.group(1)<m.group(2))"<"else">").matches("((<>)+<?)|((><)+>?)\\d")}else false}

```

Hmm...regex seemed like a good idea at the time...
> 0 votes

# Answer
# C#, ~~147~~ 142 bytes

```
bool U(int i){if(i<10)return 0>1;var s=i+"";var b=s[0]>s[1];for(int j=2;j<s.Length;j++){var x=s[j-1]>s[j];if(x==b)return 0>1;b=x;}return 1>0;}

```

Working sample: http://ideone.com/b8ubr
> 0 votes

# Answer
# Python 2, ~~79~~ ~~77~~ 69 bytes

```
a=raw_input()
print{cmp(a[i+1],a[i])for i in range(len(a)-1)}=={-1,1}

```
> 0 votes

# Answer
# APL (Dyalog), ~~43~~ 21 bytes

ASCII is way too limited! :P

```
{⍵≤9:0⋄∧/2≠/×2-/⍎¨⍕⍵}

```

In standard APL fashion, it returns 1 for true and 0 for false.

Usage:

```
  {⍵≤9:0⋄∧/2≠/×2-/⍎¨⍕⍵}461902
1
  {⍵≤9:0⋄∧/2≠/×2-/⍎¨⍕⍵}708143
1
  {⍵≤9:0⋄∧/2≠/×2-/⍎¨⍕⍵}123
0
  {⍵≤9:0⋄∧/2≠/×2-/⍎¨⍕⍵}6
0

```

Explanation:

* `⍵≤9:0⋄`: If the argument is smaller or equal to `9`, it's not an undulant number. Otherwise...
* `⍎¨⍕⍵`: evaluate each character in the string representation of  (giving a list of digits)
* `2-/`: subtract each pair of consecutive digits from each other (i.e. `(4-6),(6-1),(1-9),(9-0),(0-2)`)
* `×`: find the sign of each number in that list
* `2≠/`: for each pair of consecutive signs, see if they are not equal
* `∧/`: check if this is true for all pairs
> 0 votes

# Answer
# Python 2.7, 89 chars

```
def f(a):z=[cmp(*x)for x in zip(a[1:],a)];return{(a&b)-(a^b)for a,b in zip(z[1:],z)}=={3}

```
> 0 votes

# Answer
# C (Clang), 78 bytes

```
u(i){int d,p=0;while(i>9){d=i%10-(i/=10)%10;if(d*p>0|!d)i=d=0;p=d;}return!!p;}

```

Expanded code with test harness:

```
u(i){
  int d,p=0;
    while(i>9) {
      d=i%10-(i/=10)%10;
      if(d*p>0|!d)i=d=0;
      p=d;
  }
  return !!p;
}

void test(int i) {
  printf("%8d = %d\n", i, u(i));
}

int main(int argc, char *argv[]) {
  test(132);
  test(123);
  test(5);
  test(1332);
  test(176823);
}

```

(compiled with Apple clang version 3.1)

Results:

```
     132 = 1
     123 = 0
       5 = 0
    1332 = 0
  176823 = 1

```
> 0 votes

# Answer
# APL, 19 characters

```
{a≡⍳⍴a←|-\×2-/⍎¨⍕⍵}

```
> 0 votes

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


title: Minimalist Hex Clock

text:
# Question
Title: Minimalist Hex Clock
Your challenge is to create a clock that displays the time as a hex number, and the background color as the hex color code of the time.

Requirements: No input. In the center of your output you should display the number sign and the current time in 24 hour format as "#hhmmss". The program should update to the current time at least once every second. The text must be centered and white (or a light color that stands out). The background should be entirely the color of the hex code. Shortest code wins, but creative answers are encouraged.

Live example. Idea from r/InternetIsBeautiful.

# Answer
> 1 votes
# python3 (142) or (123 with flickering)

```
import time;from turtle import*;tracer(0)
while 1:reset();ht();color([1]*3);a=time.strftime("#%H%M%S");write(a,0,"center");bgcolor(a);update()

```

using turtles, **142** bytes, will probably not be the shortest, but I simply wanted to ~~use~~ play with turtles again.

This example updates the screen often enough en does what is asked, but it is not pretty, as it goes on and off. Then it is only **123** bytes. (not a specified quality)

```
import time;from turtle import*
while 1:reset();ht();color([1]*3);a=time.strftime("#%H%M%S");write(a,0,"center");bgcolor(a)

```

ungolfed:

```
import time
from turtle import*
tracer(0)                           #1 not every change should be propagated immediatly
while 1:
    reset()                         #2 remove previous drawing
    ht()                            #3 hide the turtle
    color([1]*3)                   #4 set color to snow, which is white for as far I can see
    a=time.strftime("#%H%M%S")      #5 generate the color from time
    write(a,0,"center")             #6 print time
    bgcolor(a)                      #7 change bgcolor
    update()                        #8 propagate changes

```

btw, because of the while 1, I'd recommend running it from terminal. As it can be quite difficult to close :D (you'll need ctrl+c)

# Answer
> 5 votes
# HTML/CSS/JavaScript 207 183 180 161 152

Tested and working in the latest Firefox and Chrome browsers.

```
<body id=b onload=setInterval("b.innerHTML=b.bgColor=Date().replace(/.*(..):(..):(..).*/,'#$1$2$3')",0) text=#fff style=position:fixed;top:50%;left:47%>

```

**Demo Here**

# Answer
> 1 votes
# Processing, 162 bytes

```
void draw()
{
 int h=hour(),m=minute(),s=second();
 background(color(h,m,s));
 textAlign(CENTER);
 text("#"+(h<10?"0"+h:h)+(m<10?"0"+m:m)+(s<10?"0"+s:s),50,50);
}

```

Screenshot:

I don't know if it's against the rules, but the actual drawing area is the 100x100px square on the center of the window. For some reason, Processing can't scale down the window to that size, so it adds the gray margins around the drawing area. Here's another version without the gray margins, but slightly larger **(198 bytes)**:

```
void setup()
{
 size(200,200);
}

void draw()
{
 int h=hour(),m=minute(),s=second();
 background(color(h,m,s));
 textAlign(CENTER);
 text("#"+(h<10?"0"+h:h)+(m<10?"0"+m:m)+(s<10?"0"+s:s),100,100);
}

```

# Answer
> 1 votes
# SmileBASIC, 65 bytes

```
T$=TIME$T$[2]="
LOCATE 21,14T$[4]"
GCLS VAL("&H"+T$)?"#";T$EXEC.

```

# Answer
> 0 votes
# HTML + Javascript (184)

This uses the `=>` notation which is currently only supported in Firefox. It does not use any libraries.

```
<body text=white onload='(b=document.body).bgColor=b.innerHTML="#"+[(d=new Date()).getHours(),d.getMinutes(),d.getSeconds()].map(x=>("00"+x).slice(-2)).join("");setTimeout(b.onload)'>

```

With indentation:

```
<body
 text=white
 onload='
       (b=document.body).bgColor =
       b.innerHTML =
             "#"+[ (d=new Date()).getHours(),
                    d.getMinutes(),
                    d.getSeconds()].map(
                        x=>("00"+x).slice(-2)
                    ).join("");
       setTimeout(b.onload)
'>

```

# Answer
> 0 votes
# C# 357, 325 with minor cheating

Yea, C# isn't gonna win many codegolf prizes against other languages. Still, fun!

Cheating (not *exactly* centre, and only centre with .NET 4.5's default form size of 300x300, Mono may do other funny stuff):

```
using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){new P().ShowDialog();}public P(){var l=new Label(){Top=125,Left=120,ForeColor=Color.White};Controls.Add(l);new Timer(){Enabled=true,Interval=1}.Tick+=(s,e)=>{BackColor=ColorTranslator.FromHtml(l.Text=System.DateTime.Now.ToString("#HHmmss"));};}}

```

Golfed:

```
using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){new P().ShowDialog();}public P(){var l=new Label(){Dock=(DockStyle)5,TextAlign=(ContentAlignment)32,ForeColor=Color.White};Controls.Add(l);new Timer(){Enabled=true,Interval=1}.Tick+=(s,e)=>{BackColor=ColorTranslator.FromHtml(l.Text=System.DateTime.Now.ToString("#HHmmss"));};}}

```

Ungolfed:

```
using System.Windows.Forms;
using System.Drawing;

class P : Form
{
    static void Main()
    {
        new P().ShowDialog();
    }

    public P()
    {
        var l = new Label() { Dock = (DockStyle)5, TextAlign = (ContentAlignment)32, ForeColor = Color.White };
        Controls.Add(l);
        new Timer() { Enabled = true, Interval = 1 }.Tick += (s, e) =>
        {
            BackColor = ColorTranslator.FromHtml(l.Text = System.DateTime.Now.ToString("#HHmmss"));
        };
    }
}

```

# Answer
> 0 votes
# Python 3, 122 characters

```
from turtle import*
import time
color(1,1,1)
ht()
while 1:_=time.strftime("#%H%M%S");bgcolor(_);write(_,0,"center");undo()

```

Takes advantage of Python 3 turtle's `undo()` capability to clear just the previous text. Doesn't exhibit the intense flickering of turtle `reset()` caused by it resetting *everything* about the turtle.

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


title: Get Two from One

text:
# Question
Title: Get Two from One
As we saw in this question complex logical statements can be expressed in terms of the simple connectives of generalized Minesweeper. However Generalized minesweeper still has redundancies.

In order to avoid these redundancies we define a new game called "Generalized-1 Minesweeper".

Generalized-1 Minesweeper is a version Minesweeper played on an arbitrary graph. The graph has two types of vertex, an "indicator" or a "value". A value can be either on or off (a mine or a dud) however its state is unknown to the player. An indicator tells that exactly one of the adjacent cells is on (a mine). Indicators do not count as mines themselves.

For example the following board for Generalized Minesweeper tells us that cells A and B are either both mines or neither of them are mines.

*(In the diagram indicators are marked in gray while values are white)*

Unlike in normal minesweeper where you click values that are off to reveal indicators, there is no such mechanic in Generalized Minesweeper. A player simply determines for what states of the graph can satisfy its indicators.

Your goal is to make a `2` in Generalized-1 Minesweeper. You will build a structure in Generalized-1 Minesweeper such that there are 8 specific cells for which all possible configurations of values have *exactly* two cells on. This means it behaves exactly as the `2` does in traditional minesweeper. When you write your solution you should not have specific values in mind for value cells. (In answer to H.PWiz's question it is allowed that some value cells might be deducible from the state)

## Scoring

You answers will be scored by the number of vertices in the final graph minus 8 (for the 8 inputs) with a lower score being better. If two answers tie in this metric the tie breaker will be the number of edges.

# Answer
## 42 vertices, 56 edges

Each variable is a value vertex, and each box is an indicator vertex with edges to the variables inside it. The inputs are *x1*, ..., *x8*. For example, here's a solution with mines at *x3* and *x5*, with mines highlighted in green.

The horizontal constraints ensure that exactly one of the *a*'s and exactly one of the *b*'s has a mine. In those two columns, *r* does not hold a mine, but it does in the other six columns. (Note that *a* and *b* can't both have a mine in the same column.) Each input *x* is opposite the *r* in its column, so exactly two inputs have mines as desired.

For `k` inputs, this uses `5k+2` vertices (`3k` value and `2k+2` indicator), and `7k` edges. Here, `k=8` inputs gives 42 vertices and 56 edges.
> 7 votes

# Answer
# 50 Vertices, 89 edges

Based on the logic gate from H.PWiz's answer.

```
  A&B      C&D      E&F      G&H
   |        |        |        |
b--1--a  d--1--c  f--1--e  h--1--g
|  |  |  |  |  |  |  |  |  |  |  |
1--?--1  1--?--1  1--?--1  1--?--1
|     |  |     |  |     |  |     |
A     B  C     D  E     F  G     H

```

Each `*` is on when the two respective inputs are on. To handle the case of a single input, we use the intermediate values `a=A&!B` etc. Connecting all three values `a`, `b` and `A&B` to the input of a secondary level of gates gives us an effective input of `A|B` (this saves vertices over `!(!A&!B)`):

```
      *              *
      |              |
   #--1--#        #--1--#
   |  |  |        |  |  |
   1--?--1        1--?--1
  |||   |||      |||   |||
  A|B   C|D      E|F   G|H

```

These `*`s are on if two of their inputs (corresponding to four of the original inputs) are on, except in the case of the pairs already covered above. Meanwhile, we can connect the `#*#` nodes to a final gate. We therefore have the following results:

```
A&B
C&D
E&F
G&H
(A|B)&(C|D)         [4 cases]
(E|F)&(G|H)         [4 cases]
(A|B|C|D)&(E|F|G|H) [16 cases]

```

These cover all 28 of the cases of two inputs. It then remains to connect a final indicator to these seven values. If fewer than two inputs are on, then none of these will be on, so the indicator will be off. If more than two inputs are on, then more than one of these will be on, and the indicator will be off.
> 3 votes

# Answer
# 197 Vertices, 308 edges

I came up with this answer last night, but withheld posting it because it was such a high score. However, since it beats the other answer by so much, I though I should post it.

I use the following set up on all 28 pairs of values cells in `ABCDEFGH`

```
   ?*
   |
?--1--?
|  |  |
1--?--1
|     |
A     B

```

`?` represents an value cell not in `ABCDEFGH`. Here, when `?*` is **ON**, `A` and `B` are both on. Otherwise, `A` and `B` could be in any other configuration.

I connect all 28 `?*`s to one indicator cell. This means that only one pair in `ABCDEFGH` will have two **ON**. Which is sufficient to enforce that exactly two of my output cells will be **ON**
> 2 votes

# Answer
# 354 nodes, 428 edges

Just to prove it's possible. I will improve this later with some caching.

(hopefully no code error)

I tried to write a Mathematica program here to check program validity, but it doesn't work probably because there are too many variables.

The result was generated by computer program: Try it online!

---

I use a gate that looks like this:

```

               (f)
                |
                |
               (#)
              /   \
             /     \
           (d)     (e)
          /           \
         /             \
       (#) --- (c) --- (#)
     .'                  '.
   .'                      '.
(a)                          (b)

```

where `(#)` are 1-indicators, `(a)` .. `(f)` are values.

Then,

```

c = (not a) and (not b)
d = (not a) and      b
e =      a  and (not b)
f =      a  xnor     b

```

Also, this gate

```

(a) ----- (#) ----- (b)

```

gives

```

b = not a

```

. Use those two types of gates you can build any expressions.

Of course, this one is for asserting that `(a)` must be true:

```

(a) ----- (#)

```
> 1 votes

# Answer
## 81 Nodes, 108 Edges

Using 13 nodes and 14 edges, we create the following Adder gate (C(arry) = X AND Y, S(um) = X XOR Y):

```
X--1--------------?
   |              |
   ?--1--S--1--?--1
   |  |           |
   |  C           |
Y--1--------------?

```

Use four Adders M1, M2, M3, M4 to add A+B, C+D, E+F, G+H, respectively, with the resulting carry C1, C2, C3, C4, and sum S1, S2, S3, S4.

Use two Adders M5, M6 to add S1+S2, S3+S4, with the resulting carry C5, C6, and sum S5, S6.

Use one Adder M7 to add S5+S6 to get C7 and S7.

Now connect all carries to a single indicator node like the following:

```
C1-|
C2-|
C3-|
C4-+-1
C5-|
C6-|
C7-|

```

and force S7 (the modulo 2 of sum of 8 values) to be 0 by this circuit:

```
S7--1--?--1

```

I argue that this circuit forces exactly two values from `ABCDEFGH` to be ON, since it can only be an even number (since S7 is 0), and there cannot be more than 3 ON values (since only one of C1-C7 is ON).
> 1 votes

---
Tags: math, code-challenge, game, graph-theory, atomic-code-golf
---


title: Visible Buildings

text:
# Question
Title: Visible Buildings
This puzzle is derived from CodinGame SamSi's "Heart of the City" puzzle.

## Description

You decide to take a walk in an `n` * `n` tile city and go to the center tile. All of the buildings are infinitely small, but you have super vision and can see everything close up and far away.

## Constraints

`n` is always odd

You can see any building that is not directly obstructed by another one

## Task

Mark each building visible with `*`. The building is visible iff it is not blocked by another building on the exact same line of vision.

In other words, if `@` is the origin, the building is visible iff the x-coordinate and the y-coordinate are co-prime to each other.

## Example input and output

Input:

```
7

```

Output:

```
 ** **
* * * *
*******
  *@*
*******
* * * *
 ** **

```

`*` is a visible building,  is an invisible building, and `@` is where you are.

# Scoring

Remember, this is , so the answer with the least bytes wins.

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

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

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

# Answer
> 9 votes
# Excel-VBA, (47\*n^2) bytes and 121 bytes

**Instruction:**

Excel turns out to be very handy for this challenge and there are combination of Excel formulas to get the exact pattern as the OP's shown for a given input. Luckily enough for me, Excel has a GCD function - a built-in formula to return greatest common divisor of positive integers so I don't have to create one using Euclidean algorithm. Why do I need a GCD function here? **It's because two numbers are called coprime, if their greatest common divisor equals 1**. The numbers here is the coordinate of the position, `x` and `y`, relative to the origin, `@`. Here is the Excel formula

```
=IF(GCD(ABS(COLUMN()-m),ABS(m-ROW()))=1,"*","")

```

where `m` is the name of a reference cell and it's equal to the smallest integer greater than or equal to `n/2`, ceiling(`n/2`), where `n` is the name of a reference cell for the input. Paste this formula in cell A1, then drag all over range with the size `n x n`. The length of the formula is 47 bytes but you have to replicate it `n x n` times, so it's equal to (47\*n^2) bytes.

To automate the process and to reduce the use of characters, we can use VBA since it's integrated with Excel. First thing first, set a worksheet Excel like the following:

Then put the following code in the Immediate Window

```
n=[A1]:m=Int(n/2)+1:Range("A1",Cells(n,n))="=IF(GCD(ABS(COLUMN()-"&m &"),ABS("&m &"-ROW()))=1,""*"","""")":Cells(m,m)="@"

```

**Ungolfed the code:**

```
Sub A()
    n = [A1]
    m = Int(n / 2) + 1
    Range("A1", Cells(n, n)) = "=IF(GCD(ABS(COLUMN()-" & m & "),ABS(" & m & "-ROW()))=1,""*"" ,"""")"
    Cells(m, m) = "@"
End Sub

```

**Explanation:**

1. `n = [A1]` : Set n as the input and assign the value of cell A1 to n.
2. `m = Int(n / 2) + 1` : Custom way to return the same output as the ceiling function for argument `n/2`.
3. `Range("A1", Cells(n, n)) = "=IF(GCD(ABS(COLUMN()-" & m & "),ABS(" & m & "-ROW()))=1,""*"" ,"""")"` : Paste the formula above to every cell in the range with size `n x n` start from cell A1.
4. `Cells(m, m) = "@"` : Assign the center of the range with a character `@`.

**Output:**

Figure below is the example output for the input `n = 11`

I set the font color to red to make it look more attractive. Even better

# Answer
> 4 votes
# Jelly, 16 bytes

```
:2ạḶgþ`«2ị“* @”Y

```

Try it online!

### How it works

```
:2ạḶgþ`«2ị“* @”Y  Main link. Argument: 2n + 1

:2                Perform integer division by 2, yielding n.
   Ḷ              Yield [0, ..., 2n].
 ạ                Take the absolute difference of the result to both sides.
                  This yields A := [n, ... 0, ... n].
      `           Call the quicklink to the left with left and right argument A.
     þ              Table; call the link to the left for all x in A and all y in A.
    g                 Yield the GCD of x and y.
       «2         Truncate the GCD at 2, leaving 0 for the origin, 1 for coprime
                  coordinates, and 2 otherwise.
         ị“* @”   Index into that string, mapping [1, 2, 0] to ['*', ' ', '@'].
               Y  Join, separating by linefeeds.

```

# Answer
> 3 votes
# C, ~~147~~ ~~145~~ ~~135~~ 133 bytes

**2 bytes thanks to Dennis.**

**10 bytes thanks to Arnauld.**

**2 bytes thanks to H Walters.**

```
r,m,i,j;g(a,b){r=b?g(b,a%b):a;}main(n){scanf("%d",&n);for(m=n/2,i=-m;i<=m;putchar(r?r*r-1?32:42:64),i+=++j%n<1&&puts(""))g(i,j%n-m);}

```

Ideone it!

Golfing advice welcome as always.

# Answer
> 3 votes
# J, 24 bytes

```
'@* '{~2<.[:+./~<.@-:-i.

```

A port of Dennis' answer in Jelly.

# Answer
> 3 votes
# Perl 6, 77 or 74 bytes

Full program *(77 bytes)*:

```
my \h=Int(get/2);say |map {$_|$^j??2>$j gcd$_??'*'!!' '!!'@'},-h..h for -h..h

```

(try it online)

If it is acceptable to return the output from a lambda as a list of lists of 1-character strings *(74 bytes)*:

```
{my \h=$_ div 2;map {map {$^i|$_??2>$i gcd$_??'*'!!' '!!'@'},-h..h},-h..h}

```

(try it online)

# Answer
> 3 votes
## Javascript (ES6), ~~114~~ ~~113~~ 105 bytes

This started as a port of Leaky Nun's C version and was then further optimized. Most optimizations are specific to JS.

```
n=>(r=j=>i<n?('*@*'[1+(g=(i,j)=>j?g(j,i%j):i)(i-m,j-m)]||' ')+(++j<n?'':(i++,`
`))+r(j%n):'')(i=0,m=n>>1)

```

Example:

```
let f =
n=>(r=j=>i<n?('*@*'[1+(g=(i,j)=>j?g(j,i%j):i)(i-m,j-m)]||' ')+(++j<n?'':(i++,`
`))+r(j%n):'')(i=0,m=n>>1)

console.log(f(7))
```

# Answer
> 3 votes
# S.I.L.O.S, 236 bytes

```
GOTO s
funcg
if q p
r=p
return
lblp
t=p
t%q
p=q
q=t
GOSUB g
return
lbls
readIO
m=i
m/2
a=i
lbla
a-1
a-m
b=i
lblb
b-1
b-m
p=a
p|
q=b
q|
GOSUB g
r-1
A=r
A|
r/A
r*-1
r+1
p=r
r*r
r*6
p*4
r+p
r+32
printChar r
b+m
if b b
printLine
a+m
if a a

```

Try it online!

Port of my answer in C.

# Answer
> 2 votes
## GolfScript, ~~98~~ 83 bytes

```
~:l.2/~):o:i;{o{.abs i abs.!!{{.@\%.}do}*;1={'*'}{' '}if\.i|!{\;'@'\}*)}l*;i):i;n}*

```

Try it online!

***Input = 11***

```
 **** ****
* * * * * *
** ** ** **
* * * * * *
***********
    *@*
***********
* * * * * *
** ** ** **
* * * * * *
 **** ****

```

# Answer
> 2 votes
# Pyth, 40 bytes

```
L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2

```

I'm very new to Pyth, so this can likely be golfed further.

Try it online

**How it works**

```
L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2

L@"@* "hS[b2)                              Lambda y. Input: b
L                                          Declare lambda
         [b2)                              List [b, 2]
        S                                  Sort ascending
       h                                   Head. Yield first element a, clamping to max 2
  "@* "                                    String literal "@* "
 @                                         Index into string with a, yielding string[a]

             jsMcQyM.aMiM*.**2[r_/Q2h/Q2   Program. Input: Q
                                _/Q2 /Q2   -Q//2 and Q//2
                                    h      Head. Q//2+1
                               r           Range [-Q//2, Q//2+1]
                              [            List
                            *2             Duplicate
                          .*               Splat. Unpack
                         *                 Cartesian product. Yield all coordinate pairs
                       iM                  Map GCD over above
                    .aM                    Map absolute value over above
                  yM                       Map y over above, yielding required characters
                cQ                         Chunk. Split above into Q pieces
              sM                           Map concatenate over above
             j                             Join on newlines
                                           Implicitly print

```

# Answer
> 1 votes
# APL (Dyalog Classic), 23 bytes

```
'@ * '[3⌊∨/|↑(⊖-⌽)⍳2⍴⎕]

```

Try it online!

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


title: Tell me how to flop

text:
# Question
Title: Tell me how to flop
As computer scientists, you're probably all familiar with the basic list operations of *pop* and *push*. These are simple operations that modify a list of elements. However, have you ever heard of the operation *flop*? (as in *flip-**flop***)? It's pretty simple. Given a number **n**, reverse the first **n** elements of the list. Here's an example:

```
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a.flop(4)
[4, 3, 2, 1, 5, 6, 7, 8, 9, 10]

```

The cool thing about the flop operation, is that you can use it do some cool things to a list, such as sorting it. We're going to do something similar with flops:

> Given a list of integers, "Neighbor it". In other words, sort it so that every duplicate element appears consecutively.

This can be done with flops! For example, take the following list:

```
>>> a = [3, 2, 1, 4, 3, 3, 2]
>>> a.flop(4)
[4, 1, 2, 3, 3, 3, 2]
>>> a.flop(3)
[2, 1, 4, 3, 3, 3, 2]
>>> a.flop(6)
[3, 3, 3, 4, 1, 2, 2]

```

This leads us to the definition of today's challenge:

> Given a list of integers, output any set of flops that will result in the list being neighbored.

Using the last list as an example, you should output:

```
4
3
6

```

because flopping the list by 4, then by 3, then by 6 will result in a neighbored list. Keep in mind that you do *not* need to print the shortest possible list of flops that neighbors a list. If you had printed:

```
4
4
4
3
1
1
6
2
2

```

instead, this would still be a valid output. However, you may *not* ever output a number larger than the length of the list. This is because for a list `a = [1, 2, 3]`, calling `a.flop(4)` is nonsensical.

Here are some examples:

```
#Input:
[2, 6, 0, 3, 1, 5, 5, 0, 5, 1]

#Output
[3, 7, 8, 6, 9]

#Input
[1, 2]

#Output
<any list of integers under 3, including an empty list>

#Input
[2, 6, 0, 2, 1, 4, 5, 1, 3, 2, 1, 5, 6, 4, 4, 1, 4, 6, 6, 0]

#Output
[3, 19, 17, 7, 2, 4, 11, 15, 2, 7, 13, 4, 14, 2]

#Input
[1, 1, 1, 1, 2, 2, 2, -1, 4]

#Output
[]

#Input
[4, 4, 8, 8, 15, 16, 16, 23, 23, 42, 42, 15]

#Output
[12, 7]

```

Keep in mind that in each of these examples, the output given is just one potential valid output. As I said before, *any set of flops that neighbors the given list is a valid output*. You can use this python script to verify if a given list of flops correctly neighbors a list.

You may take input and output in any reasonable format. For example, function arguments/return value, STDIN/STDOUT, reading/writing a file etc. are all valid. As usual, this is , so make the shortest program you can, and have fun! :)

# Answer
> 8 votes
# Haskell, ~~98~~ 71 bytes

```
h.r
h(x:s)|(a,b)<-span(/=x)s=l b:l s:h(b++r a)
h e=e
r=reverse
l=length

```

Try it online!

### Explanation

For a list of length  `n` this method produces `2*n` flops. It works by looking at the last element of the list, looking for the same element in the list before and flipping it to the second to last position. Then the list with the last element removed is recursively "neighboured".

For the list `[1,2,3,1,2]` the algorithm works like this:

```
[1,2,3,1,2]  flip longest prefix that ends in 2: flop 2
[2,1,3,1,2]  bring first element to second to last position: flop n-1 = flop 4
[1,3,1,2,2]  recursively work on n-1 list
[1,3,1,2]    there is no other 2: flop 0
[1,3,1,2]    flop n-1 = flop 3
[1,3,1,2]    recurse
[1,3,1]      flop 1
[1,3,1]      flop 2
[3,1,1]      recurse
[3,1]        flop 0
[3,1]        flop 1
 ...

```

All together this yields the flops `[2,4,0,3,1,2,0,1,0,0]` and the neighboured list `[3,1,1,2,2]`.

# Answer
> 6 votes
# Wolfram Language (Mathematica), 71 bytes

```
If[(n=Tr[1^#])<1,{},{i=Last@Ordering@#,n,n-1,i-1}~Join~#0[#~Drop~{i}]]&

```

Try it online!

## How it works

Given an array of length `n`, outputs a sequence of `4n` flops that sort the array in increasing order: in particular, putting duplicate elements next to each other.

The idea is that to sort an array, we move its largest element to the end, and then sort the first `n-1` elements of the array. To avoid implementing the flop operation, we move the largest element to the end in a way which does not disturb the other elements:

```
{3, 2, 1, 5, 3, 3, 2}    starting array, with largest element in position 4
{5, 1, 2, 3, 3, 3, 2}    flop 4 to put the largest element at the beginning
{2, 3, 3, 3, 2, 1, 5}    flop 7 to put the largest element at the end
{1, 2, 3, 3, 3, 2, 5}    flop 6 (7-1) to reverse the effect of flop 7 on other elements
{3, 2, 1, 3, 3, 2, 5}    flop 3 (4-1) to reverse the effect of flop 4 on other elements

```

In general, if the largest element is in position `i`, the sequence of flops that moves it to the end is `i, n, n-1, i-1`.

# Answer
> 3 votes
# Jelly, ~~19~~ 17 bytes

```
ỤỤạ‘Ḣ
ỤÇÐƤĖµUż’ṚF

```

Sorts the list.

Try it online!

# Answer
> 3 votes
# Python 2, 69 bytes

```
l=input()
while l:k=l.index(max(l));print-~k,len(l),;l=l[:k:-1]+l[:k]

```

Try it online!

# Answer
> 3 votes
# Clean, 88 bytes

I think there's a possibly shorter one with guards, but I haven't found it yet.

```
import StdEnv
$[h:t]#(a,b)=span((<>)h)t
=map length[b,t]++ $(b++r a)
$e=e
r=reverse

```

#

```
$o r

```

Try it online!

As a function literal. Works the same way as Laikoni's Haskell answer, but golfed slightly differently, and of course also in a different language.

# Answer
> 1 votes
# JavaScript, 150 bytes

```
(a,f=n=>(a=[...a.slice(0, n).reverse(),...a.slice(n)],n),l=a.length,i=0)=>a.reduce(c=>[...c,f(a.indexOf(Math.max(...a.slice(0, l-i)))+1),f(l-i++)],[])

```

Try it online!

# JavaScript, 151 bytes

```
a=>{f=n=>(a=[...a.slice(0,n).reverse(),...a.slice(n)],n),r=[];for(i=a.length+1;--i>0;)r.push(f(a.indexOf(Math.max(...a.slice(0, i)))+1),f(i));return r}

```

Try it online!

Both basically sort the array by flipping the max number to the beginning and then flipping it to the back, repeating this with the remaining array. The first one uses reduce, the second one uses a for loop.

## Ungolfed:

```
array => {
  let flop = n => {
    array = [...array.slice(0, n).reverse(), ...array.slice(n)];
    return n;
  }
  let flops = [];
  for (let i = array.length + 1; --i > 0;)
  {
    let maxIndex = array.indexOf(Math.max(...array.slice(0, i)));
    flops.push(flop(maxIndex + 1), flop(i));
  }
  return flops;
}

```

# Answer
> 1 votes
# C (gcc), ~~165~~ 160 bytes

```
m,j,t;f(A,l)int*A;{for(j=0;j+j<l;A[j]=A[l+~j],A[l+~j++]=t)t=A[j];}F(A,l)int*A;{for(;l;f(A,++m),printf("%d,%d,",m,l),f(A,l--))for(j=m=0;j<l;j++)m=A[j]>A[m]?j:m;}

```

# Answer
> 1 votes
# Perl 5.10 (or higher), 66 bytes

Includes `+3` for `-n` The `use 5.10.0` to bring the language to level perl 5.10 is considered free

```
#!/usr/bin/perl -n
use 5.10.0;
$'>=$&or$.=s/(\S+) \G(\S+)/$2 $1/*say"$. 2 $."while$.++,/\S+ /g

```

Run with the input as one line on STDIN:

```
flop.pl <<< "1 8 3 -5 6"

```

Sorts the list by repeatedly finding any inversion, flopping it to the front then flopping the inversion and flopping everything back to its old position.

It was surprisingly hard to get in the same ballpark as python on this one :-)

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