title: Schrödinger's cat program

text:
# Question
Title: Schrödinger's cat program
`Sandbox`

Your challenge is to write a program that when first run, will do one of the actions below at random with equal chances of both:

* A cat program

+ A standard cat program: read everything from `STDIN` and put it on `STDOUT` (or your language's closest equivalent).
* Do nothing and halt

+ This shouldn't output anything.

The behaviour is permanent - once the program chooses between the two options, it should do that no matter how much times you run the script. It's fine if this resets when you reboot.

Please provide an explanation on how to reset the program (which file to delete for example)

Standard loopholes are forbidden.

This is a , so the shortest code (in bytes or equivalent) wins.

# Answer
> 9 votes
# Python 3, 94 bytes

```
from random import*
s=randint(0,1)*"print(open(0).read())"
open(__file__,"w").write(s)
exec(s)

```

Try it online!

Picks one of  or `print(open(0).read())` and replaces the contents of the file with it. Then, executes that code once.

To reset it, you will have to copy-paste this code into the file again, since it overwrites the file itself. This perseveres so long as the file exists and is not modified, so it is remembered through reboots and even if you move the file to another computer.

-5 bytes thanks to Jonathan Allan
(Also -5 thanks to Jakque by using `choice(["print(open(0).read())",""])` instead of `randint(0,1)*"print(open(0).read())"` \- both are excellent golfs; I just chose the first one.)

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

*Edit: -1 byte thanks to Giuseppe*

```
{q=rt(1,1)<0;function(x)if(q)cat(x)}

```

Try it online!

Function that acts randomly as cat or no-op on first call, and then stays with this behaviour forever (or until deleted).

---

# , 83 bytes

```
if(!F)write(paste("F=",F<-sample(1:2,1)),".Rprofile");if(F<2)show(scan("stdin",""))

```

Try it online!

Full program: saves state into ".Rprofile" file in directory from which  or `Rscript` is launched: delete this to reset program behaviour.

# Answer
> 4 votes
# Haskell, 89 bytes

This method uses no special files. In fact it doesn't store data anywhere.

To set up your `randomize_va_space` should be set to zero (linux).

You can check this with:

```
sysctl -anr "e_v"

```

I won't tell you *how* to set it to `0` since in general this should not be set to `0`, and setting it to `0` represents a possible security risk. Don't play with your kernel unless you know what you are doing or have nothing to lose on the device.

```
import Unsafe.Coerce
main=([[interact id],[pure()]]>>=([0..7]>>))!!mod(unsafeCoerce(+))16

```

Try it online!

TIO is stuck on cat and I have no way to reset it. You can switch the `+` to a `:` to see a version that is stuck on the noop.

To reset it locally it should be enough to set the `randomize_va_space` to `2` run the program once and then set it back to `0`.

## Explanation

*More detailed explanation here*

In Haskell, all complex objects including functions are internally represented as a pointer. This is a number in binary that "points" to a specific location in memory. This is because we want to pass these values by reference, since copying the whole thing is expensive, and since Haskell disallows mutation we can with no problem.

However simple objects like ints are passed by value since they are so small that copying them is about as expensive as copying a pointer would be. unsafeCoerce is a super unsafe function which just takes the raw bytes from one object and reinterprets it as the raw bytes for another type.

So if we use unsafeCoerce from a function to an `Int`, the resulting `Int` is just the value of the pointer to the object. And the value of that simple object is dependent only on where the complex object is located not anything about what it is.

When `randomize_va_space` is on, this means the value of `unsafeCoerce(+)` is a random multiple of 8. However when it's off, it is fixed to one value which depends on some factors about the machine.

# Answer
> 4 votes
# Bash \+ coreutils, 64 bytes

```
awk -va=$(awk '!/E/{$0=(systime()-$1)%88}1' /proc/uptime) 'a<44'

```

Try it online!

Here's how it works.

`AWK` is called with a variable `a` which is a floating point number greater than or equal to 0 and less than 88. So it uses the `a<44` test to get a 50/50 chance to decide what action to take. If that evaluates as true, then it prints STDIN to STDOUT. If it's false, it silently consumes STDIN.

The value of `a` is set by the inner `AWK` call. That logic read the first numeric value in `/proc/uptime`, which is the number of seconds since the system was booted. The it subtracts that "uptime" from the current date/time to get the boot time of the OS. Then it computes a modulo of 88 seconds to deal with the (very annoying) fact that the calculations aren't consistent at the seconds level.

Essentially it's using the boot time of the OS to decide whether or not to "cat" or "discard" the input. So it will make the same decision each time it's run until the system is rebooted.

# Answer
> 3 votes
# Zsh, <sup>~~29~~</sup> 21 bytes

```
X=$[RANDOM%2]
f()>&$X
```

Attempt This Online!

A function which either does`>&1` (copy input to STDOUT) or `>&0` (write to STDIN, which doesn't work).

Can be shorter.

---

If using the PID as a source of randomness is allowed (which doesn't work on Attempt This Online because of how the sandbox works):

## Zsh, 11 bytes

```
f()>&$[$%2]
```

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

Anonymous lambda. Takes one or two dummy arguments. Requires 0-based indexing.

```
{6::∇a∘←?2⋄a:⍞}

```

Try it online!

You can reset the program by erasing its global state `a`.

`{``}` "dfn":

`6::` if we hit a value error:

`a∘←` globally assign to `a`:

`?2` a random 0 or 1

now try:

`a:` if `a` \[is 1\]:

read STDIN \[and implicitly return and print it\]

# Answer
> 2 votes
# JavaScript (ES2020), browser, ~~56~~ 52 bytes

```
(localStorage.d||=Math.random())>.5&&alert(prompt())

```

Sets the `d` property of localStorage if it's undefined. Stacksnippets doesn't like setting localstorage, so run this in your console to see.

Full program. -4 thanks to tsh.

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

Stores either `s` or `u` into the `user.a` extended attribute of the executable. `setxattr()` doesn't replace an already-existing value, so I just write the value and then retrieve it to see whether to cat the input (`s`) or not (`u`).

To reset the program, run `setfattr -x user.a {programname}`

```
main(a,v,s)char*v,*s;{char r[]="user.a";srand(time(0));s=r+rand()%2;setxattr(*v,r,s,1,1);getxattr(*v,r,s,1);if(*s&2)while(~(a=getchar()))putchar(a);}

```

Try it online!

# Answer
> 1 votes
## Batch, 53 bytes

```
@if "%c%"=="" set/ac=%random%%%2
@if %c%==1 find/v""

```

Use `set c=` to reset the flag. Explanation: If `c` is empty, the first line sets `c` to a random value that is either `0` or `1`, then the second line copies STDIN to STDOUT only if `c` is `1`. I don't know why the builtin `find` command fails to find the empty string in any input, but it's consistent, so we can simply invert the condition, thus turning `find` into a `cat` program.

# Answer
> 1 votes
# AWK, 48 bytes

```
BEGIN{a=systime()%2;getline a<"_";print a>"_"}
a

```

Try it online!

`systime()` is used to decide whether to print or not. State is saved in the file `_`. `getline` does not clobber variables if it doesn't read anything.

# Answer
> 0 votes
# Python 3, ~~66~~ 62 bytes

```
import random
if random.randint(1,2)==1:print(str(input("I")))

```

Gets a random value and if it's 1, it gets and prints user input. I just put an I (for input) because my Python interpreter allows you to give input even when not asked for.

# Answer
> 0 votes
# Zsh, 35 bytes

```
((RANDOM&1))&&p='<&0'&&<&0
<<<$p>$0

```

Try it online!

Randomly overwrites the file with either `<&0` (equivalent to `cat`) or nothing.

# Answer
> 0 votes
# MATLAB/Octave, ~~80~~ 60 bytes

```
global x;if x;else;x=randi(1:2);end;if x>1;input('','s');end

```

Will either do nothing, or whatever the user inputs to `ans=` (considered "STDOUT" for our purpose), then stick with that choice.

When first used a global variable (`x` here) is empty. Empty values evaluate to false. If `x` is false, it will set it to a random integer of either 1 or 2. This will then never evaluate false again, so the first part of the program will then never run again.

If `x` is 2, then the program will request user input (considered "STDIN" for our purpose). If `x` is 1, will do nothing at all.

---

Relies on the fact that a global variable is persistent once created, and will only reset if the user clears all variables ("reboots" for our purpose).

I would add a TIO link, but unfortunately that doesn't seem to want to handle global variables.

---
Tags: code-golf, random, stateful
---


# Question
Title: Shortest way to remove the first and last element of a list and print both
The challenge is simple: Print the first and last element of a list and print them

# Rules:

* You will take only 1 line of input, and that is the list (e.g. `[1, 5, 6, 4, 2]`)
* You are allowed to print the 2 numbers in any order with or without spaces between them
* Output the 2 numbers on 1 line and the remaining list on the second line

A simple example is `print(list.pop()+list.pop(0))` in Python3, since pop removes the element and returns it at the same time

This is code-golf, so shortest code wins!

# Answer
# Jelly, 5 bytes

```
Ḣ³ṪṄṛ

```

Try it online!
> 3 votes

# Answer
# Vyxal `aṠj`, 8 bytes

```
₌₍htḢṪWṠ

```

Try it Online!
> 5 votes

# Answer
# JavaScript (ES6), 25 bytes

```
a=>alert(a[0]+''+a.pop())

```

```
f=
a=>alert(a[0]+''+a.pop())

console.log(f([1,2,3,4,5]))
```
> 2 votes

# Answer
# Retina 0.8.2, 9 bytes

```
(?=,).*,

```

Try it online! Explanation: Just removes the commas and anything in between. The lookahead deals with the case when there are only two elements in the list.
> 2 votes

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


title: Adding fractions

text:
# Question
Title: Adding fractions
Write a program or a function that takes two non-empty lists of the same length as input and does the following:

* uses elements of first list to get numerators,
* uses elements of the second list to get denominators,
* displays resulting fractions after simplification `(2/4=>1/2)`, separated by "+"s,
* displays "=" and result of addition after last fraction.

## Example:

### Input

```
[1, 2, 3, 3, 6]
[2, 9, 3, 2, 4]

```

### Output

```
1/2+2/9+1+3/2+3/2=85/18

```

## About rules

* elements of lists will be positive integers,
* elements can be separated by spaces, eg: `1/2 + 2/9 + 1 + 3/2 + 3/2 = 85/18` is ok,
* trailing newline is allowed,
* lists can be taken in other formats than above, eg.: `(1 2 3 3 6)` or `{1;2;3;3;6}`, etc.,
* `1` can be expressed as `1/1`,
* instead of printing you can return appropriate string,
* you do not need to handle wrong input,
* **shortest code wins**.

# Answer
> 3 votes
# , ~~12~~ 11 bytes

```
÷µFj”+;”=;S

```

This is a dyadic link. Due to a bug, it doesn't work as a full program. `F` is also required due to a bug.

Try it online!

### How it works

```
÷µFj”+;”=;S  Dyadic link. Left argument: N. Right argument: D

÷            Perform vectorized division, yielding an array of fractions (R).
 µ           Begin a new, monadic chain. Argument: R
  F          Flatten R. R is already flat, but j is buggy and has side effects.
   j”+       Join R, separating by '+'.
      ;”=    Append '='.
         ;S  Append the sum of R.

```

# Answer
> 7 votes
# Ruby 2.4, ~~54~~ 53 characters

```
->n,d{a=n.zip(d).map{|n,d|n.to_r/d};a*?++"=#{a.sum}"}

```

Thanks to:

* Value Ink for the Ruby 2.4 specific version (-3 characters)
* Value Ink for optimizing the `Rational` initialization (-1 character)

### Ruby, ~~58~~ ~~57~~ 56 characters

```
->n,d{t=0;n.zip(d).map{|n,d|t+=r=n.to_r/d;r}*?++"=#{t}"}

```

Sample run:

```
irb(main):001:0> puts ->n,d{t=0;n.zip(d).map{|n,d|t+=r=n.to_r/d;r}*?++"=#{t}"}[[1, 2, 3, 3, 6], [2, 9, 3, 2, 4]]
1/2+2/9+1/1+3/2+3/2=85/18

```

Try it online!

# Answer
> 6 votes
## Mathematica, 33 bytes

```
Row@{Row[#/#2,"+"],"=",Tr[#/#2]}&

```

input

> \[{1, 2, 3, 3, 6}, {2, 9, 3, 2, 4}\]

# Answer
> 3 votes
# Python 3, 104 bytes

9 bytes thanks to Felipe Nardi Batista.

```
from fractions import*
def f(*t):c=[Fraction(*t)for t in zip(*t)];print('+'.join(map(str,c)),'=',sum(c))

```

Try it online!

# Answer
> 3 votes
# Perl 6,  ~~77~~  73 bytes

```
{join('+',($/=[@^a Z/ @^b]).map:{.nude.join('/')})~"="~$/.sum.nude.join('/')}

```

Try it

```
{($/=[@^a Z/@^b])».nude».join('/').join('+')~'='~$/.sum.nude.join('/')}

```

Try it

## Expanded:

```
{  # bare block lambda with two placeholder params ｢@a｣ and ｢@b｣

  (
    $/ = [              # store as an array in ｢$/｣ for later use

      @^a Z/ @^b        # zip divide the two inputs (declares them)

    ]

  )».nude\              # get list of NUmerators and DEnominators
  ».join('/')           # join the numerators and denominators with ｢/｣

  .join('+')            # join that list with ｢+｣

  ~
  '='                   # concat with ｢=｣
  ~

  $/.sum.nude.join('/') # get the result and represent as fraction
}

```

# Answer
> 3 votes
## Clojure, 71 bytes

```
#(let[S(map / % %2)](apply str(concat(interpose '+ S)['=(apply + S)])))

```

Yay for built-in fractions!

# Answer
> 2 votes
# Mathematica, 61 bytes

```
t=#~ToString~InputForm&;Riffle[t/@#,"+"]<>"="<>t@Tr@#&[#/#2]&

```

# Answer
> 2 votes
## JavaScript (ES6), 111 bytes

Takes the lists in currying syntax `(a)(b)`.

```
let f =

a=>b=>a.map((v,i)=>F(A=v,B=b[i],N=N*B+v*D,D*=B),N=0,D=1,F=(a,b)=>b?F(b,a%b):A/a+'/'+B/a).join`+`+'='+F(A=N,B=D)

console.log(f([1, 2, 3, 3, 6])([2, 9, 3, 2, 4]))
```

# Answer
> 2 votes
# Java, 225 bytes

```
int c(int a,int b){return b>0?c(b,a%b):a;}
(N,D)->{int n=0,d=1,i=0,g;String s="";for(;i<N.length;g=g(N[i],D[i]),N[i]/=g,D[i]/=g,s+=(i>0?"+":"")+N[i]+"/"+D[i],n=n*D[i]+N[i]*d,d*=D[i++],g=g(n,d),n/=g,d/=g);return s+"="+n+"/"+d;}

```

`N` and `D` are both `int[]`, contextualized.

I reused Kevin Cruijssen's GCD function.

See it and test it online!

# Answer
> 2 votes
## Julia v0.4+, ~~66~~ 53 bytes

*-13 bytes thanks to Dennis*

```
a^b=replace(join(a.//b,"+")"=$(sum(a.//b))","//","/")

```

Try it Online!

Alternately, if fractions can be displayed using `//` rather than `/`, the following works for **35 bytes**:

```
a^b=join(a.//b,'+')"=$(sum(a.//b))"

```

# Answer
> 2 votes
# setlX, 103 bytes

```
f:=procedure(a,b){i:=1;l:=[];while(i<=#a){l:=l+[a[i]/b[i]];i+=1;}s:=join(l,"+");return s+"="+eval(s);};

```

Creates a function called `f` where your insert two lists.

ungolfed:

```
f := procedure (a,b) {
    i:=1;
    l:=[];
    while(i<=#a){
        l:=l+[a[i]/b[i]];
        i+=1;
    }
    s:=join(l,"+");
    return s+"="+eval(s);
};

```

with named variables and annotations:
setlX doesn't provide a comment feature so let's just pretend that we can comment with `%`

```
f := procedure(firstList,secondList) {
    count := 1;
    list := [];
    while(count <= #firstList) {
        % calculate every fraction and save it as a list
        list := list + [firstList[count]/secondList[count]];
        count += 1;
    }
    % Seperate every list entry with a plus ([2/3,1] -> "2/3+1")
    str := join(list, "+");
    % eval executes the string above and thus calculates our sum
    return str + "=" + eval(str);
};

```

# Answer
> 1 votes
# 05AB1E, ~~35~~ 34 bytes

```
‚øvyy¿÷'/ý'+}¨'=¹.¿©¹÷²*O®‚D¿÷'/ýJ

```

Try it online!

# Answer
> 1 votes
# Jelly, 31 bytes

```
,:gj”/
ṙJ$ṖP×Sç⁸P¤,ç@"j”+$¥Ṛj”=

```

Try it online!

# Answer
> 1 votes
# F#, ~~244~~ ~~241~~ 239 bytes

```
let rec g a=function|0->abs a|b->g b (a%b)
let h a b=g a b|>fun x->a/x,b/x
let s,n,d=List.fold2(fun(s,n,d)N D->
 let(N,D),(n,d)=h N D,h(n*D+N*d)(d*D)
 s@[sprintf"%i/%i"N D],n,d)([],0,1)nom div
printf"%s=%i/%i"(System.String.Join("+",s))n d

```

Try it online!

# Answer
> 1 votes
# PHP\>=7.1, 190 Bytes

```
<?function f($x,$y){for($t=1+$x;$y%--$t||$x%$t;);return$x/$t."/".$y/$t;}[$n,$d]=$_GET;for($p=array_product($d);$x=$n[+$k];$e+=$x*$p/$y)$r[]=f($x,$y=$d[+$k++]);echo join("+",$r)."=".f($e,$p);

```

Online Version

+14 Bytes for replacement `return$x/$t."/".$y/$t;` with `return$y/$t>1?$x/$t."/".$y/$t:$x/$t;` to output `n` instead of `n/1`

# Answer
> 1 votes
# setlX, 62 bytes

```
[a,b]|->join([x/y:[x,y]in a><b],"+")+"="++/[x/y:[x,y]in a><b];

```

### ungolfed:

```
[a,b]|->                  define a function with parameters a and b
  join(
    [ x/y :               using set comprehension, make a list of fractions
      [x,y] in a><b       from the lists zipped together
    ],
    "+"
  )                       join them with "+"
  + "="                   concat with an equals sign
  +                       concat with
  +/[x/y:[x,y]in a><b]    the sum of the list
;

```

# Answer
> 1 votes
# Haskell (Lambdabot), ~~94~~ ~~91~~ 86 bytes

```
t=tail.((\[n,_,d]->'+':n++'/':d).words.show=<<)
a#b|f<-zipWith(%)a b=t f++'=':t[sum f]

```

Try it online!

Thanks @Laikoni for `-8` bytes!

### Ungolfed

```
-- convert each fraction to a string (has format "n%d", replace '%' with '/' and prepend '+' ("+n/d"), keep the tail (dropping the leading '+')
t = tail.((\[n,_,d]->'+':n++'/':d).words.show=<<)
-- build a list of fractions
a # b = let f = zipWith(%) a b in
-- stringify that list, append "=" and the stringified sum of these fractions
  t f ++ "=" ++ t [sum f]

```

# Answer
> 1 votes
# Google Sheets, ~~83~~ 81 bytes

```
=ArrayFormula(JOIN("+",TRIM(TEXT(A:A/B:B,"?/???")))&"="&TEXT(sum(A:A/B:B),"?/???"

```

Saved 2 bytes thanks to Taylor Scott

Sheets will automatically add 2 closing parentheses to the end of the formula.

The two arrays are input as the *entirety* of columns `A` and `B`. Empty rows below the inputs will throws errors.

# Answer
> 0 votes
# Perl 6, ~~72 bytes~~ 65 bytes

Native and automatic rationals *should* make this easy, but default stringification is still as decimal, so we have to `.nude` (*nu*merator and *de*nominator) which kills our score and makes the 1 ugly :(

```
my \n = 1,2,3,3,6; my \d = 2,9,3,2,4;
(n Z/d)».nude».join("/").join("+")~"="~([+] n Z/d).nude.join("/")

```

Update: Removed unneeded brackets, kill more space and use smarter map. Saves characters over Brad's solution at the cost of no not being a lambda sub.

# Answer
> 0 votes
# MATL, 32 bytes

```
/YQv'%i/%i+'wYD3L)61yUYQVwV47b&h

```

Try at MATL online!

### Explanation

Consider `[1, 2, 3, 3, 6]`, `[2, 9, 3, 2, 4]` as input.

```
/         % Implicit inout. Divide element-wise
          % STACK: [0.5 0.222 1 1.5 1.5]
YQ        % Rational approximation (with default tolerance)
          % STACK: [1 2 1 3 3], [2 9 1 2 2]
v         % Conctenate all stack elements vertically
          % STACK: [1 2; 2 9; 1 2; 3 2; 3 2]
'%i/%i+'  % Push this string (sprintf format specifier)
          % STACK: [1 2; 2 9; 1 2; 3 2; 3 2], '%i/%i+'
wYD       % Swap, sprintf
          % STACK: '1/2+2/9+1/1+3/2+3/2+'
3L)       % Remove last entry
          % STACK: '1/2+2/9+1/1+3/2+3/2'
61        % Push 61 (ASCII for '=')
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61
y         % Duplicate from below
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61, '1/2+2/9+1/1+3/2+3/2'
U         % Evaluste string into a number
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61, 4.722
YQ        % Rational approximation
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61, 85, 18
VwV       % Convert to string, swap, convert to string
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61, '18', '85'
47        % Push 47 (ASCII for '/')
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61, '18', '85', 47
b         % Bubble up in stack
          % STACK: '1/2+2/9+1/1+3/2+3/2', 61, '85', 47, '18'
&h        % Concatenate all stack elements horizontally. Implicitly display
          % STACK: '1/2+2/9+1/1+3/2+3/2=85/18'

```

# Answer
> 0 votes
# R, 109 bytes

```
f=MASS::fractions;a=attributes
g=function(n,d)paste(paste(a(f(n/d))$f,collapse='+'),a(f(sum(n/d)))$f,sep='=')

```

requires the `MASS` library (for its `fractions` class). the function `g` returns the required output as a string.

Try it online! (R-fiddle link)

# Answer
> 0 votes
# TI-BASIC, 100 bytes

```
:L₁⁄L₂                                              //Creates a fraction from Lists 1 & 2, 7 bytes
:toString(Ans→Str1                                  //Create string from list, 7 bytes
:inString(Ans,",→A                                  //Look for commas, 9 bytes
:While A                                            //Begin while loop, 3 bytes
:Str1                                               //Store Str1 to Ans, 3 bytes
:sub(Ans,1,A-1)+"+"+sub(Ans,A+1,length(Ans)-A→Str1  //Replace "," with "+", 33 bytes
:inString(Ans,",→A                                  //Check for more commas, 9 bytes
:End                                                //End while loop, 2 bytes
:Str1                                               //Store Str1 to Ans, 3 bytes
:sub(Ans,2,length(Ans)-2                            //Remove opening and closing brackets, 13 bytes
:Ans+"="+toString(expr(Ans                          //Add "=" and answer, 11 bytes

```

Note the  at the beginning, different from `/`. This makes the fractions hold their forms. It **does** work with negative fractions.

*Sigh*. TI-BASIC is *horrible* with strings. If all we had to do was print the fractions, and then their sum, the code would be:

### TI-BASIC, 12 bytes

```
:L₁⁄L₂    //Create fractions from lists, 7 bytes
:Disp Ans //Display the above fractions, 3 bytes
:sum(Ans  //Display the answer, 2 bytes

```

That means that **88 bytes** of my code is spent just formatting the answer! *Hmph*.

# Answer
> 0 votes
# C, 171 bytes

**Try Online**

```
i;t;x;y;f(int s,int*a,int*b){x=*a;y=*b;while(++i<s)x=(y-b[i])?(x*b[i])+(a[i]*y):(x+a[i]),y=(y-b[i])?(b[i]*y):y;for(i=1;i<=(x<y?x:y);++i)t=(x%i==0&&y%i==00)?i:t;x/=t;y/=t;}

```

# Answer
> 0 votes
# Axiom, 212 bytes

```
C==>concat;S==>String;g(a)==C[numerator(a)::S,"/",denom(a)::S];h(a:List PI,b:List PI):S==(r:="";s:=0/1;#a~=#b or #a=0=>"-1";for i in 1..#a repeat(v:=a.i/b.i;s:=s+v;r:=C[r,g(v),if i=#a then C("=",g(s))else"+"]);r)

```

test

```
(5) -> h([1,3,4,4,5,6], [2,9,5,5,6,7])
   (5)  "1/2+1/3+4/5+4/5+5/6+6/7=433/105"
                                                             Type: String
(6) -> h([1,3,4,4], [2,9,5,5,6,7])
   (6)  "-1"
                                                             Type: String

```

# Answer
> 0 votes
# Casio Basic, 161 Bytes

```
Dim(List 1)->A
for 1->I to A step 1
3*I-2->B
List 1[I]->C
List 2[I]->D
locate 1,B,C
locate 1,B+1,"/"
locate 1,B+2,D
C/D+E->E
next
locate 1,B+3,"="
locate 1,B+4,E

```

Explanation:

* Number of input is saved in `A`
* `A` iterations
* `B` acts as a counter for correct displaying
* `I`'th item of List 1 and 2 saved in `C` and `D`
* Displaying of Variable `C` / Variable `D`
* save `C`/`D`+`E` in `E`
* After last number locate `=` and `E`

# Answer
> 0 votes
# Vyxal , 12 bytes

```
/₌≬vS\+j∑\=$

```

Try it Online!

10 bytes of this is just getting the formatting right... /:

## Explained

```
/₌≬vS\+j∑\=$
/           # divide the lists, vectorising
 ₌≬vS\+j     # join each fraction on "+" (there's a bug where they get converted to decimal without vS :/)
       ∑    # get the sum of the fractions.
        \=$ # place a "=" between the two
            # the Ṫ flag prints the entire stack without spaces. If it wasn't for the aforementioned joining bug, the last $ could be a j and the flag wouldn't be needed.

```

---
Tags: code-golf, math, rational-numbers
---


# Question
Title: Sort the distinct elements of a list in descending order by frequency
Write a function which takes a list or array, and returns a list of the distinct elements, sorted in descending order by frequency.

Example:

Given:

```
["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]

```

Expected return value:

```
["Doe","Harry","John","Dick"]

```

# Answer
## APL (14)

```
{∪⍵[⍒+⌿∘.≡⍨⍵]}

```

This is a function that takes a list, e.g.:

```
      names
 John  Doe  Dick  Harry  Harry  Doe  Doe  Harry  Doe  John
      {∪⍵[⍒+⌿∘.≡⍨⍵]} names
 Doe  Harry  John  Dick

```

Explanation:

* `∘.≡⍨⍵`: compare each element in the array to each other element in the array, giving a matrix
* `+⌿`: sum the columns of the matrix, giving how many times each element occurs
* : give indices of downward sort
* `⍵[`...`]`: reorder  by the given indices
* : get the unique elements
> 13 votes

# Answer
## Python 3 - 47 43; Python 2 - 40 39

For Python 3:

```
f=lambda n:sorted(set(n),key=n.count)[::-1]

```

For Python 2:

```
f=lambda n:sorted(set(n),cmp,n.count,1)

```

Demo:

```
>>> names = ["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]
>>> f(names)
['Doe', 'Harry', 'John', 'Dick']

```
> 8 votes

# Answer
## Mathematica, 31

```
Sort[GatherBy@n][[-1;;1;;-1,1]]

```

> `{"Doe", "Harry", "John", "Dick"}`

(With `n = {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry", "Doe", "John"}`)
> 5 votes

# Answer
## Mathematica (26 ~~37~~)

With `n = {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry",
 "Doe", "John"}`:

```
Last/@Gather@n~SortBy~Length//Reverse

```

> {"Doe", "Harry", "John", "Dick"}

---

**Mathematica V10+ (26)**:

```
Keys@Sort[Counts[n],#>#2&]

```
> 4 votes

# Answer
# Perl 6 (36 bytes, 35 characters)

`»` can be replaced with `>>`, if you cannot handle UTF-8. I'm almost sure this could be shorter, but the `Bag` class is relatively strange in its behavior (sadly), and isn't really complete, as it's relatively new (but it can count arguments). `{}` declares an anonymous function.

```
{(sort -*.value,pairs bag @_)».key}

```

Sample output (from Perl 6 REPL):

```
> my @names = ("John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John")
John Doe Dick Harry Harry Doe Doe Harry Doe John
> {(sort -*.value,pairs bag @_)».key}(@names)
Doe Harry John Dick

```
> 3 votes

# Answer
# Ruby: 34 ~~37~~ characters

```
f=->a{a.sort_by{|z|-a.count(z)}&a}

```

(edited: previous 30-char solution was the body of the function)
> 3 votes

# Answer
## GolfScript, 14 chars (19 as named function, also 14 as full program)

```
:a.|{[.]a\-,}$

```

This code takes an array on the stack and sorts its unique elements in descending order by number of occurrences. For example, if the input array is:

```
["John" "Doe" "Dick" "Harry" "Harry" "Doe" "Doe" "Harry" "Doe" "John"]

```

then the output array will be

```
["Doe" "Harry" "John" "Dick"]

```

**Note:** The code above is a bare sequence of statements. To turn it into a named function, wrap it in braces and assign it to a name, as in:

```
{:a.|{[.]a\-,}$}:f;

```

Alternatively, to turn the code into a full program that reads a list from standard input (using the list notation shown above) and prints it to standard output, prepend `~` and append ``` to the code. The `[.` can be omitted in this case (since we know there will be nothing else on the stack), so that the resulting 14-character program will be:

```
~:a.|{]a\-,}$`

```

---

### How does it work?

* `:a` saves a copy of the original array in the variable `a` for later use.
* `.|` computes the set union of the array with itself, eliminating duplicates as a side effect.
* `{ }$` sorts the de-duplicated array using the custom sort keys computed by the code inside the braces. This code takes each array element, uses array subtraction to remove it from the original input array saved in `a`, and counts the number of remaining elements. Thus, the elements get sorted in decreasing order of frequency.

**Ps.** See here for the original 30-character version.
> 3 votes

# Answer
## R: 23 characters

```
n <- c("John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John")

names(sort(table(n),T))
## [1] "Doe"   "Harry" "John"  "Dick"

```

But it uses the not so nice shortcut of `T` to `TRUE`...
> 2 votes

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

```
>#'=:

```

Try it online!

* `=:` group the input, building a dictionary mapping unique values to the indices in which they appear
* `#'` take the count of each set of indices
* `>` sort the keys of the dictionary by their values, descending
> 2 votes

# Answer
if this could fit here : `In sql-server`

```
create table #t1 (name varchar(10))
insert into #t1 values ('John'),('Doe'),('Dick'),('Harry'),('Harry'),('Doe'),('Doe'),('Harry'),('Doe'),('John')

select name from #t1 group by name order by count(*) desc

```

OR

```
with cte as
(

select name,count(name) as x from #t1 group by name
)

select name from cte order by x desc

```

# see it in action
> 1 votes

# Answer
# PHP, 63 62 61 chars

```
function R($a){foreach($a as$v)$b[$v]++;arsort($b);return$b;}

```

Demo:

```
$c = array("John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John");
$d = print_r(R($c));

Array ( [Doe] => 4 [Harry] => 3 [John] => 2 [Dick] => 1 )

```
> 1 votes

# Answer
# Ruby: 59 characters

```
f=->n{n.group_by{|i|i}.sort_by{|i|-i[1].size}.map{|i|i[0]}}

```

Sample run:

```
irb(main):001:0> f=->n{n.group_by{|i|i}.sort_by{|i|-i[1].size}.map{|i|i[0]}}
=> #<Proc:0x93b2e10@(irb):2 (lambda)>

irb(main):004:0> f[["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]]
=> ["Doe", "Harry", "John", "Dick"]

```
> 1 votes

# Answer
# Mathematica, 39 characters

```
f = Reverse[First /@ SortBy[Tally@#, Last]] &

names = {"John", "Doe", "Dick", "Harry", "Harry",
         "Doe", "Doe", "Harry", "Doe", "John"};

f@names

```

> {Doe, Harry, John, Dick}
> 1 votes

# Answer
# JavaScript (ECMAScript5): ~~118~~ 113 characters

```
function f(n){m={}
for(i in n){m[n[i]]=m[n[i]]+1||1}
return Object.keys(m).sort(function(a,b){return m[b]-m[a]})}

```

http://jsfiddle.net/mblase75/crg5B/
> 1 votes

# Answer
# C#: 111 characters

```
List<string>M(List<string>l){return l.GroupBy(q=>q).OrderByDescending(g=>g.Count()).Select(g=>g.Key).ToList();}

```

(inside a class)

```
var names = new List<string> {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry", "Doe", "John"};
foreach(var s in M(names))
{
    Console.WriteLine(s);
}

```

> Doe
>
> Harry
>
> John
>
> Dick

A simple solution using LINQ.
> 1 votes

# Answer
**Haskell - 53 Characters**

```
import Data.List
import Data.Ord

f :: (Eq a, Ord a) => [a] -> [a]
f=map head.(sortBy$flip$comparing length).group.sort

```

Explanation: the first two lines are necessary imports, the next line of code is the type signature (generally not necessary), the actual function is the last line. The function sorts the list by its natural ordering, groups equal elements into lists, sorts the list of lists by descending size, and takes the first element in each list.

total length including imports: 120

w/o imports but with type signature: 86

function itself: 53
> 1 votes

# Answer
# Clojure: 43 characters

Function:

```
#(keys(sort-by(comp - val)(frequencies %)))

```

Demo (in repl):

```
user=> (def names ["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"])
#'user/names
user=> (#(keys(sort-by(comp - val)(frequencies %))) names)
("Doe" "Harry" "John" "Dick")

```
> 1 votes

# Answer
# J, 8 bytes

```
~.\:#/.~

```

## Usage

The names are stored as an array of boxed strings.

```
   'John';'Doe';'Dick';'Harry';'Harry';'Doe';'Doe';'Harry';'Doe';'John'
┌────┬───┬────┬─────┬─────┬───┬───┬─────┬───┬────┐
│John│Doe│Dick│Harry│Harry│Doe│Doe│Harry│Doe│John│
└────┴───┴────┴─────┴─────┴───┴───┴─────┴───┴────┘
   f =: ~.\:#/.~
   f 'John';'Doe';'Dick';'Harry';'Harry';'Doe';'Doe';'Harry';'Doe';'John'
┌───┬─────┬────┬────┐
│Doe│Harry│John│Dick│
└───┴─────┴────┴────┘

```

## Explanation

```
~.\:#/.~   Input: A
    #/.~   Finds the size of each set of identical items (Frequencies)
~.         List the distinct values in A
           Note: the distinct values and frequencies will be in the same order
  \:       Sort the distinct values in decreasing order according to the frequencies
           Return the sorted list implicitly

```
> 1 votes

# Answer
## CJam, 15 bytes

```
q~$e`{0=W*}$1f=

```

This may use CJam features from after this challenge was posted. I'm too lazy to check.
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
ÙΣ¢}R

```

Try it online.

**Explanation:**

```
Ù    # Uniquify the (implicit) input-list
 Σ   # Sort this uniquified list by:
  ¢  #  Get its count in the (implicit) input-list
 }R  # After the ascending sort: reverse the list, so it'll become descending
     # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Stax, 7 bytes

```
èó±☻₧╛╗

```

Run and debug it
> 1 votes

# Answer
# Jelly, 6 bytes

```
Qċ@ÞṚ⁺

```

Try it online!

There are quite a few ways to formulate this, but I find this to be the most amusing of several 6-byte alternatives. `ċ@Þ@QṚ` comes rather close.

```
Q         Unique items of the input.
   Þ      Sort them by
 ċ@       how many times they appear in the input
    Ṛ     reversed.
     ⁺    Duplicate the last link: reverse the sorted result.

```
> 1 votes

# Answer
# Husk, 5 bytes

```
u↔Ö#¹

```

Try it online!
> 1 votes

# Answer
# Factor, 33 bytes

```
[ sorted-histogram keys reverse ]

```

Try it online!

## Explanation

```
                 ! { "John" "Doe" "Dick" "Harry" "Harry" "Doe" "Doe" "Harry" "Doe" "John" }
sorted-histogram ! { { "Dick" 1 } { "John" 2 } { "Harry" 3 } { "Doe" 4 } }
keys             ! { "Dick" "John" "Harry" "Doe" }
reverse          ! { "Doe" "Harry" "John" "Dick" }

```
> 1 votes

# Answer
## Perl

to meet given i/o spec I need 120 chars

```
s!"([^"]+)"[],]!$a{$1}++!e while(<>);print 'MostOccuring = [',join(',',map{qq("$_")}sort{$a{$a}<=>$a{$b}}keys %a),"]\n"

```

pure shortest code by taking one item per line and printing one item per line I only need 55 chars

```
$a{$_}++ while(<>);print sort{$a{$a}<=>$a{$b}}keys %a)

```
> 0 votes

# Answer
# Scala (71)

```
(x.groupBy(a=>a)map(t=>(t._1,t._2.length))toList)sortBy(-_._2)map(_._1)

```

Ungolfed:

```
def f(x:Array[String]) =
  (x.groupBy(a => a) map (t => (t._1, t._2.length)) toList)
    sortBy(-_._2) map(_._1)

```
> 0 votes

# Answer
# Perl 5, 51 bytes

```
sub f{my%k;$k{$_}++for@_;sort{$k{$b}-$k{$a}}keys%k}

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: (t)h(e)(i)(r)(m)

text:
# Question
Title: (t)h(e)(i)(r)(m)
Sometimes authors will write `(s)he` as a stand in for `she` or `he` and for some reason they don't want to use singular they. This is ok for the nominative but doesn't work so well when you want to write "her or him". You can write `h(er)(im)` which covers both cases but gives two extra "pronouns"

```
h
her
him
herim

```

In formalizing these patterns we will strings with no parentheses match the exact same string. So `she` matches only `she` etc. Additionally a pattern \\$A\left(B\right)C\\$, where \\$A, B, C\\$ are all patterns, matches everything that \\$AC\\$ and \\$ABC\\$ match and nothing else.

This lets us nest brackets so for the words so the pattern `(they)((s)he)` matches

```
they
she
he

theyshe
theyhe

```

We will measure the effectiveness of a pattern as the number of incorrect words it generates. So from above `(s)he` has the best possible effectiveness with 0, while `h(er)(im)` and `h(er)(is)` both have effectiveness of 2. If `(they)((s)he)` is trying to generate `they`, `she`, and `he` then it has effectiveness 3.

Your program or function will take a non-empty set of words as input.

Your program should figure out the smallest possible effectiveness any pattern can have that matches all the inputs. For example in for `her` and `him` we have shown a pattern with effectiveness 2, and it is impossible to get a pattern with effectiveness less than 2, so you should output 2.

You don't need to output the solution just its effectiveness score. You may take input and output with the usual rules and you may assume the strings will be strictly alphabetic.

This is so answers will be scored in bytes with fewer bytes being better.

## Test cases

Each case has a potential pattern below it, there may be more than one.

```
she -> 0
she
she, he -> 0
(s)he
her, him -> 2
h(er)(im)
her, his -> 2
h(er)(is)
they, she, he -> 3
(they)((s)he)
them, her, him -> 5
(them)(her)(him)
their, her, his -> 5
(their)(her)(his)
their, her -> 2
(thei)(he)r
goca, oc, oca -> 1
(g)oc(a)
goca, soca, oc, goce, soce -> 11
(g)(s)oc(a)(e)
goca, soca, gsocae, goce, soce -> 11
(g)(s)oc(a)(e)
goca, soca, gsxocae, goce, soce, xoce -> 26
(g)(s)(x)oc(a)(e)

```

# Answer
# Python3, 1356 bytes

```
import itertools as i
def w(s,q=[]):
 if s:
  if not q:yield from w(s[1:],q+[(0,[s[0]])]);yield from w(s[1:],q+[(1,[s[0]])])
  else:
   if q[-1][0]:yield from w(s[1:],q[:-1]+[(q[-1][0],q[-1][1]+[s[0]])])
   yield from w(s[1:],q+[(not q[-1][0],[s[0]])])
 else:yield tuple((a,tuple(set(b)))for a, b in q)
def p(s,l=0):
 if len(s)==1:yield tuple(s);return
 n=min(s,key=len)
 if m:=[n[x:y+1]for x in range(len(n))for y in range(x,len(n))if all(n[x:y+1]in a for a in s)]:
  for q in m:
   a,b=[[*filter(None,x)]for x in zip(*[j.split(q,1)for j in s])];x,y=[p(a,1)]if a else [],[p(b,1)]if b else []
   yield from i.product(*(x+[(q,)]+y))
   if not l:yield (*[(u,)for u in dict.fromkeys(a)],q,*[(u,)for u in dict.fromkeys(b)])
  if not l:
   for j in w(s):
    if any(not x[0]for x in j):yield from i.product(*[p(b,1)if a else[b]for a,b in j])
 else:
  s=[x for y in s for x in(y if any(any(j in v for v in s if v!=y)for j in y)else[y])];yield tuple([(u,)for u in sorted(set(s),key=s.index)])
def e(s):
  yield from map(''.join,i.product(*[[k]if isinstance(k,str)else[*e(k),'']for k in s]))
def t(s):
 for i in s:
  if isinstance(i,str):yield i
  elif any(isinstance(j,str)for j in i):yield tuple(t(i))
  else:yield from t(i)
def f(s):
 s=s.split(', ')
 return min([((v:=tuple(t(i))),sum(j not in s for j in e(v)))for i in set(p(s))],key=lambda x:x[1])

```

The central strategy is to build possible paths starting with matching substrings from the input passed to `p` at each call, then surrounding the matching substrings with other possible valid patterns derived from the non-matching remainders.

Try it online!
> 4 votes

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


# Question
Title: determine longest group of consecutive numbers
**INPUT:**

* 10 random numbers
* each number is greater than 0 and less than 100
* list of numbers is presorted, lowest to highest
* the list will not contain any duplicate numbers

**CHALLENGE:**

Write a function that would take in the numbers, and return the count of the longest group of consecutive numbers.

**EXAMPLE OUTPUT:**

```
1 2 33 44 55 66 77 88 90 98 => return of the function would be 2
1 3 23 24 30 48 49 70 75 80 => return of the function would be 2
6 9 50 51 52 72 81 83 90 92 => return of the function would be 3

```

# Answer
## APL, ~~26~~ 21 characters

```
1+⌈/+/^\9 9⍴0,1=-2-/⎕

```

Here's the 26-character solution:

```
i←⎕⋄⌈/{1++/^\⍵↓1=-2-/i}¨⍳9

```

I used Dyalog APL as my interpreter, and `⎕IO` should be set to 0 for the 26-character version.

Example:

```
      1+⌈/+/^\9 9⍴0,1=-2-/⎕
⎕:
      6 7 51 51 53 51 54 55 56 55
3

```

This answer explains most of what I in the 26-character solution, but I might have to write a new one up for the 21-character version.
> 4 votes

# Answer
# Haskell, 54

```
import List
f=maximum.map length.group.zipWith(-)[1..]

```
> 3 votes

# Answer
## GolfScript, 23 characters

```
~]1\{.@-(!@*).@}*;]$)p;

```

Test cases:

```
"1 2 33 44 55 66 77 88 98"  --> 2
"1 3 23 24 30 48 49 70 80"  --> 2
"6 9 50 51 52 72 81 83 92"  --> 3

```
> 3 votes

# Answer
# Jelly, 5 bytes

```
_JŒɠṀ

```

Try it online!

```
_J          Subtract [1,2,3…] from the input.
            This will turn a run like [48,49,50] into something like [45,45,45].
  Œɠ        Get group lengths. (“aaaabbc” → [4,2,1])
    Ṁ       Maximum.

```
> 3 votes

# Answer
## Python

new:

```
def s(q):
    i = r = 1
    l = -1
    for n in q:
        if n == l + 1:
            i += 1
        elif i > r:
            r,i = i,1
        else:
            i=1
        l=n
 return i if i > r else r

```

old (buggy):

```
def s(q):
 i=r=1;l=-1
 for n in q:
  if n==l+1:i+=1
  elif i>r:r,i=i,1
  l=n
 return r

```

test case:

```
x = [1,2,3,50,56,58,60,61,90,100]
print x
print s(x)
>>> 3

```

edit: forgot the input numbers had to be in order. fixed edit2: fixed a problem when all the numbers are a sequence, eg 1,2,3,4,5,6,7,8,9,10, and it returned just '1' edit3: oops, didn't realize it wasn't code golf.
> 2 votes

# Answer
# J, 23

```
>:>./(+*[)/\.(}.=>:&}:)

```

Sample use:

```
   >:>./(+*[)/\.(}.=>:&}:) 1 2 33 44 55 66 77 88 98
2
   >:>./(+*[)/\.(}.=>:&}:) 1 3 23 24 30 48 49 70 80
2
   >:>./(+*[)/\.(}.=>:&}:) 6 9 50 51 52 72 81 83 92
3

```
> 2 votes

# Answer
## Python, 79 characters

```
f=lambda l:max(map(len,''.join(' x'[a-b==1]for a,b in zip(l[1:],l)).split()))+1

```
> 2 votes

# Answer
## Mathematica, ~~50~~ 31 bytes

```
Max[Length/@Split[#,#2-#==1&]]&

```

This is an anonymous function. You can either give it a name, by assigning it to something, or you can just append `@{6, 9, 50, 51, 52, 72, 81, 83, 90, 92}` to use it straight away.

Here is how it works:

`#2-#==1&` is a nested anonymous function, which takes two arguments and returns `True` if the arguments are consecutive integers (and `False` for other integer pairs).

`Split` then partitions the resulting array into runs of elements, for which the above function returns `True`.

Now we map `Length` onto the result to figure out how many numbers each run contains, and select the maximum.

Thanks to David Carraher for eliminating large parts by using a test function in `Split`!
> 2 votes

# Answer
## Scheme/Racket

Here's a trivial answer in Scheme...

```
(define f
  (λ (l)
    (letrec ((g (λ (l M c p)
                  (cond ((null? l)
                         (max M c))
                        ((= (car l) (+ p 1))
                         (g (cdr l) M (+ c 1) (car l)))
                      (else (g (cdr l) (max M c) 1 (car l)))))))
      (g l 1 1 -2))))

(f '(1 2 33 44 55 66 77 88 98)) ;=> 2
(f '(1 3 23 24 30 48 49 70 80)) ;=> 2
(f '(6 9 50 51 52 72 81 83 92)) ;=> 3

```

where

* `l` is the `l`ist
* `M` is the `M`aximum consecutive number count found so far
* `c` is the `c`urrent consecutive number count
* `p` is the `p`revious number in the list
> 1 votes

# Answer
# Ruby

I'm generally not that great at knowing more efficient methods. Might be some ruby standard lib things I'm missing.

```
def consec_count(arr)
  tg = 1
  cg = 1
  l = arr[0]
  arr.each do |v|
    if l + 1 == v
      cg += 1
      tg = cg if tg < cg
    else
      cg = 1
    end
    l = v
  end
  tg
end

```
> 1 votes

# Answer
## JavaScript (80 93 107)

```
for(n=prompt(c=m=1).split(' '),i=9;i;m=++c>m?c:m)c*=!(--n[i]-n[--i])|0;alert(m);

```

Demo: http://jsfiddle.net/QqfY4/3/

**Edit 1**: Replaced `a` with `n[i]` and `b` with `n[i-1]`. Converted `Math.max` to ternary if. Moved initialization statement into `for(`.

**Edit 2**: Reversed iteration direction to eliminate need for `i++` by changing to `--i` in second `n[--i]`. Replaced `i++` with part of `if` body. Changed condition to `i` to take advantage of ending at 0 = false. Hard-code starting value of `9` due to spec `10 random numbers`.
> 1 votes

# Answer
## Python, 87 characters

Recursive solution:

```
def s(l):
 n=1
 while n<len(l)and l[n]-l[0]==n:n+=1
 return max(n,s(l[n:])if l else 0)

```

Testing:

```
>>> s([1, 2, 33, 44, 55, 66, 77, 88, 98])
2
>>> s([1, 3, 23, 24, 30, 48, 49, 70, 80])
2
>>> s([6, 9, 50, 51, 52, 72, 81, 83, 92])
3

```
> 1 votes

# Answer
Since I can't edit code, I'll redefine the Scheme answer (Racket or not, portable and easier to read). Variables have descriptive names and there is only one recursion of the list while being error free (i think). Who cares about characters when you got efficiency?

```
(define (count-consecutive lst)
  (call-with-current-continuation
    (lambda (return)
      (define (test n)
        (unless (integer? n)
          (return (error "Not integer: " n))))
      (define (g best) (f best n (cdr lst)))
      (let ([prev (car lst)] [count 0]) (test prev)
        (let f ([best 0] [prev prev]
                [lst (cdr lst)])
          (if (null? lst) best
              (let ([n (car lst)]) (test n)
                (if (= (- n prev) 1)
                    (let ([count (+ count 1)])
                      (if (> count best) (g count)
                          (g best)))
                    (let ([count 0])
                      (g best))))))))))

```
> 1 votes

# Answer
## Scala

```
def maxconsec(ln:List[Int]):Int=
{
    var (max,current,last)=(1,1,-1)
    for(n<-ln)
    {
        if(n==last+1)
        {
            current+=1;
            if(current>max)max=current
        }
        else
        {
            current=1
        }
        last=n
    }
    return max
}

```

I think this is O(n); is it possible to be more efficient? Can the OP elaborate on how efficiency is being measured here?

Usage: (you can test it on simplyscala.com)

```
maxconsec(List(6,9,50,51,52,72,81,83,90,92))

```
> 1 votes

# Answer
## Python

```
def s(n):
l=0
t=1
for i in range(0,9):
    if n[i]+1==n[i+1]:
        t+=1
    else:
        if l<t:
            l=t
        t=1
return l

```
> 1 votes

# Answer
# , 34 bytes

```
u=rle(1:99%in%scan());max(u$l*u$v)

```

Try it online!

This is a copy-paste of Micky T's answer to this challenge. Upvote him!
> 1 votes

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
∞-γ€gZ

```

Try it online!

Thanks to @Kevin Cruijssen for -1 byte

Code:

```
∞       push endless list [1, 2, 3, 4, 5, ...]
-       subtract that from input
γ       group by equal elements
€g      push lengths of each group
Z       push max length
        implicitly print top of stack

```
> 1 votes

# Answer
# Python 3, 73 bytes

```
def f(l):s=[n-i for i,n in enumerate(l)];return max(s.count(i)for i in s)

```

Try it online!

This works by subtracting the index from each number in the list and finding the greatest frequency in the list.
> 1 votes

# Answer
# Husk, 7 bytes

```
▲mLgz-N

```

Try it online!

### Explanation

```
▲mLgz-N
    z N  zip input and infinite list [1..]
      -  with '-'
   g     group adjacent equal values
 mL      map length
▲        maximum

```
> 1 votes

# Answer
## Java

```
public static int getConsecutiveCount(int[] A) {
    int r = 1, t = 1;
    boolean c = false;
    for (int i = 0; i < A.length; i++) {
        if (i + 1 < A.length) {
            if (A[i + 1] - A[i] == 1) {
                    t++;
                    c = true;
            } else {
                c = false;
            }
        } else {
            c = false;
        }
        if (t > r && !c) {
            r = t;
            t = 1;
        }
    }
    return r;
}

```
> 0 votes

# Answer
## Just for fun, CJam, 24 bytes

```
l~]M\{:H(=+H}*;0a/:,$W=)

```

I know this is not valid as the language did not exist at the time of asking the question, but I thought I will give it a try.

**How it works:**

```
l~]M\                     "Read the input, convert to array, put an empty array M before it";
     {      }*            "For each pair of the array, run the code block";
      :H(                 "Assign the second number from the pair to H and decrement it";
         =+               "Check if it is equal to previous number and put result in M";
           H              "Put back the second number so as to be used in next iteration":
              ;0a         "Drop the trailing last number and put [0] on stack";
                 /        "Split M on [0]";
                  :,      "For each split element, replace it with its length";
                    $W=   "Sort the final array and take its last element";
                       )  "Increment this highest element from the array";

```

Try it online here
> 0 votes

# Answer
# Perl

```
my @o = (1,4,4,6,7,45,46,47,48,98);

sub r{
    $c=1;
    $l=pop@_;
    $m=1;
    while($n=pop@_){
        if($l-$n==1){++$c;$m=$c if $c>$m}
        else{$c=1}
        $l=$n
    }
    $m
}

print "MAX: " . r(@o);

```

**Output:** MAX: 4
> 0 votes

# Answer
# Japt, 9 bytes

```
äa è_¥1ÃÄ

```

Try it online!
> 0 votes

# Answer
# Julia 0.6, 55 bytes

```
a->((d=diff(a))[d.!=1]=x=0;maximum(x=(x+y)y for y=d)+1)

```

Try it online!

Going for \\$ O(n) \\$,

### 82 bytes

```
a->(l=m=0;i=1;while i<length(a);a[i]==a[i+1]-1 ? l+=1 : l=1;l>m&&(m=l);i+=1;end;m)

```

Try it online!

which ungolfed is:

```
function f(a)
    l = m = 0
    i = 1
    while i < length(a)
        a[i] == a[i+1]-1 ? l+=1 : l=1
        if l > m
          m = l
        end
        i += 1
    end
    return m
end

```
> 0 votes

# Answer
# Japt `-h`, 9 bytes

```
í- ò¦ mÊn

```

Try it
> 0 votes

# Answer
# Factor, 45 bytes

```
[ [ - -1 = ] monotonic-split longest length ]

```

Try it online!
> 0 votes

# Answer
# , 30 bytes

```
x=scan();max(rle(x-seq(!x))$l)

```

Try it online!

Approach boringly copied from other answers, but different from (and slightly shorter than) JayCe's earlier R answer.
> 0 votes

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


# Question
Title: Largest SKI output in less than 200 combinators
# The Challenge

Create an **terminating** expression in SKI Combinator Calculus in less than 200 combinators (S, K, I) that reduces to the expression with the most combinators.

There will be no limit on how many parenthesis/applications can be used.

# SKI

SKI expressions are created using S, K, I and parenthesis. They are reduced like so:

```
(((Sx)y)z) => ((xz)(yz))
((Kx)y) => x
(Ix) => x

```

When parenthesis with more than two expressions are in an expression, they are assumed to be nested to the left.

```
(xyz) = ((xy)z)

```

# Scoring

The score will be the number of combinators in the output, the goal is for this to be as large as possible.

# Examples

Here is an example of a reduction in SKI using the rules stated above.

```
(((SI)I)(((SI)I)S))
((I(((SI)I)S))(I(((SI)I)S)))
((((SI)I)S)(I(((SI)I)S)))
(((IS)(IS))(I(((SI)I)S)))
((S(IS))(I(((SI)I)S)))
((SS)(I(((SI)I)S)))
((SS)(((SI)I)S))
((SS)((IS)(IS)))
((SS)(S(IS)))
((SS)(SS))

```

So the expression `(((SI)I)(((SI)I)S))` scores 4.

# Answer
> 21 votes
# 44 combinators, score: \\$\approx f\_{\omega+1}(3\uparrow\uparrow\uparrow\uparrow3)\\$

```
(S (S (K S) (S S K)) (K I)) arrow_diag (S (S (K S) K) (S (S (K S) K) I)) S K
where arrow_diag = S (S (S I (K (S (S (K S) (S (K (S I)) K)) (K I)))) (S (K (S I)) K)) I

```

This reduces to an expression of `S (S (S (...(S K)...)))` which contains `n` copies of `S`, where `n` is the value obtained by repeatedly applying `arrow_diag` function (a 1-input function that diagonalizes over the Knuth's up arrow notation, explained below) `arrow_diag 3` times to the number 3.

**Edit:** Fixed the `arrow_diag` function, and changed 2 to 3 because I found `arrow_diag 2` was just 4. Though I guess `arrow_diag (arrow_diag (arrow_diag (arrow_diag 2)))` would still be insanely large.

The first idea is that we will construct a Church numeral for a very large natural number `n`, which is `\f. \x. f (f (f ... f x))` (`f` applied `n` times to `x`), and then force it by applying `S` and `K` to it. Then the normal form would be `S (S (... S K))` which has exactly `n+1` combinators.

Now, let's find a way to build large numbers. A good start point is the deceptively short power function

```
-- x^y
exp x y = y x
exp = \x. \y. y x

```

Then we can repeat the partially applied `exp` to build tetration and beyond (corresponding to \\$x\uparrow\uparrow y\\$, \\$x\uparrow\uparrow\uparrow y\\$ and so on):

```
-- x^^y = x^(x^...(x^x))
tet x y = y (x^) 1
tet = \x. \y. y (\y. y x) 1
-- x^^^y = x^^(x^^...)
quad x y = y (x^^) 1
quad = \x. \y. y (\y. y (\y. y x) 1) 1
-- in general:
arrow<N> = \x. \y. y (arrow<N-1> x) 1

```

Then we can try converting these into SKI. Since the next arrow notation involves a partially applied previous one, just partially converting gives helpful insights.

```
exp = \x. \y. y x
= \x. S I (K x)
tet = \x. \y. y (\y. y x) 1
= \x. \y. y (S I (K x)) I
= \x. S (\y. y (S I (K x))) (K I)
= \x. S (S I (K (S I (K x)))) (K I)
quad = \x. \y. y (\y. y (\y. y x) 1) 1
= \x. \y. y (S (S I (K (S I (K x)))) (K I)) I
= ...

```

Here we can spot a pattern. Here comes the beauty of pure lambda calculus: we can extract arbitrary subexpression into a lambda. Meanwhile, we can change 1 to `y` to get a higher number and save 1 combinator.

```
\x. \y. y (someexpr) 1
= \x. S (S I (K someexpr)) (K I)
= \x. (\e. S (S I (K e)) (K I)) someexpr

\x. \y. y (someexpr) y
= \x. S (S I (K someexpr)) I
= \x. (\e. S (S I (K e)) I) someexpr

tet' = \x. 1 (\e. S (S I (K e)) I) (S I (K x))
arrow<n> = \x. n (\e. S (S I (K e)) I) (S I (K x))

```

Here `arrow<n> x y` (roughly) calculates \\$x \uparrow^{n+1} y\\$.

Now we diagonalize over the arrow notation, by using `x`, the input value, instead of `n`.

```
arrow_diag2 = \x. x (\e. S (S I (K e)) I) (S I (K x))
= S (S I (K (S (S (K S) (S (K (S I)) K)) (K I)))) (S (K (S I)) K)

```

But it is still a binary function that calculates (roughly) \\$x \uparrow^{x+1} y\\$, so let's make it unary:

```
arrow_diag = \x. arrow_diag2 x x
= S arrow_diag2 I
= S (S (S I (K (S (S (K S) (S (K (S I)) K)) (K I)))) (S (K (S I)) K)) I

```

This has just **22** combinators. To get a non-trivial number (don't forget, we're also adding `S K` at the end to get a deterministic combinator count), we evaluate

```
arrow_diag 3 arrow_diag 3 S K
= (\x y. x y x y) arrow_diag 3 S K
= (S (S (K S) (S S K)) (K I)) arrow_diag (S (S (K S) K) (S (S (K S) K) I)) S K

```

which has just **44** combinators but evaluates to an... extremely large number that I don't know how to express correctly.

---
Tags: number, code-challenge, busy-beaver, combinatory-logic
---


title: Double the diagonal squares

text:
# Question
Title: Double the diagonal squares
Given a positive integer `N`, output this doubling pattern of slash squares/rectangles.

For `N=1`, the base is:

```
/\
\/

```

The next square is added in the bottom right direction for `N=2`:

```
/\
\/\
 \/

```

After that, a 2x1 rectangle is added in the bottom left direction for `N=3`:

```
 /\
/\/\
\ \/
 \/

```

Then a 2x2 square is added in the top left direction for `N=4`:

```
 /\
/  \
\  /\
 \/\/\
  \ \/
   \/

```

A 2x4 rectangle is added in the top right:

```
   /\
  /  \
 /\   \
/  \   \
\  /\  /
 \/\/\/
  \ \/
   \/

```

And so on. The direction in which squares and rectangles are added cycles counterclockwise, and the shape which is added alternates between squares and rectangles.

You may output as an array of lines / matrix of characters, and input may be 0-indexed or 1-indexed. Trailing whitespace in the output is allowed.

Reference implementation

Testcases:

```
1:
/\
\/
2:
/\
\/\
 \/
4:
 /\
/  \
\  /\
 \/\/\
  \ \/
   \/
7:
       /\
      /  \
     /\   \
    /  \   \
   /\  /\  /\
  /  \/\/\/  \
 /    \ \/    \
/      \/      \
\       \      /
 \       \    /
  \       \  /
   \       \/
    \      /
     \    /
      \  /
       \/
10:
               /\
              /  \
             /    \
            /      \
           /        \
          /          \
         /            \
        /              \
       /\               \
      /  \               \
     /    \               \
    /      \               \
   /        \               \
  /          \               \
 /            \               \
/              \               \
\              /\              /\
 \            /  \            /  \
  \          /\   \          /    \
   \        /  \   \        /      \
    \      /\  /\  /\      /        \
     \    /  \/\/\/  \    /          \
      \  /    \ \/    \  /            \
       \/      \/      \/              \
        \       \      /                \
         \       \    /                  \
          \       \  /                    \
           \       \/                      \
            \      /                        \
             \    /                          \
              \  /                            \
               \/                              \
                \                              /
                 \                            /
                  \                          /
                   \                        /
                    \                      /
                     \                    /
                      \                  /
                       \                /
                        \              /
                         \            /
                          \          /
                           \        /
                            \      /
                             \    /
                              \  /
                               \/

```

# Answer
> 10 votes
# Charcoal, 21 bytes

```
↶⁴ＦＮＦ⁵«↷¹Ｘ²÷⁺﹪κ²ι²↷¹¶

```

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

```
↶⁴

```

Make the output upside-down relative to the output Charcoal would like to produce.

```
ＦＮ

```

Loop over each quadrilateral.

```
Ｆ⁵«

```

Draw five sides, so that the cursor is in the correct place to draw the next one.

```
↷¹Ｘ²÷⁺﹪κ²ι²↷¹¶

```

Draw one diagonal of the quadrilateral. The pivots and newline conspire to place the cursor in the correct place to draw the next diagonal.

# Answer
> 5 votes
# JavaScript (ES6), 240 bytes

1. Make it work without giving a dime about leading whitespace.
2. Realize that leading whitespace is not allowed.
3. Add an insane amount of code to start drawing the smallest square at the correct coordinates.
4. Oh well ... post it anyway. :-)

Returns a matrix of characters.

```
n=>(x=1<<(h=n=>n-=n&1||n&3)(n)/2,y=(g=k=>k<4?k:-~g(k-4)*4)(h(n-1)),F=i=>i<n?F(-~i,(g=k=>k--?g(k,(h=Y=>m[Y+=y+k]=m[Y]||Array(1<<n/2+1).fill` `)``[x+k]=h(d)[x+k-d]='\\',h``[X=x+~k]=h(d)[X+d]='/'):x+=i%4%3?-d:d)(d=1<<i/2),y+=i%4?-d:d):m)(m=[])

```

Try it online!

# Answer
> 4 votes
# Python/NumPy, 154 bytes

```
from numpy import*
r=rot90
def f(n):
 a=diag([1,1]);y=x=2-a
 for i in r_[:n]:x=pad(r(x),a);y=pad(r(y),a)|x.T;x^=x.T;a<<=i&1
 return r(choose(y," /\\"),-n)
```

Attempt This Online!

#### Old Python/NumPy, 156 bytes

```
from numpy import*
a=c_[:3]==[1,2]
r=rot90
def f(n):
 y=x=2-a[1:]
 for i in r_[:n]:y,x=pad([r(y),r(x)],a<<i//2);y|=x.T;x^=x.T
 return r(choose(y," /\\"),-n)
```

Attempt This Online!

#### Old Python/Numpy, 159 bytes

```
from numpy import*
a=c_[:3]==[1,2]
r=rot90
def f(n):
 y=x=2-a[1:]
 for i in r_[:n]:y,x=pad([r(y),r(x)],a<<i//2);y|=x.T;x^=x.T
 return r(choose(y,[*" /\\"]),-n)
```

Attempt This Online!

#### Old Python/NumPy, 163 bytes

```
from numpy import*
a=c_[:3]==[1,2]
def f(n):
 y=x=2-a[1:]
 for i in r_[:n]:y,x=pad([rot90(y),rot90(x)],a<<i//2);y|=x.T;x^=x.T
 return rot90(choose(y,[*" /\\"]),-n)
```

Attempt This Online!

#### Old Python/NumPy, 168 bytes

```
from numpy import*
a=c_[:3]==[1,2]
def f(n,o=2*[a[1:]+1]):
 for i in r_[:n]:y,x=b=pad(o,a<<i//2);y|=x.T;x^=x.T;o=rot90(b.T,3).T
 return rot90(choose(o[0],[*" /\\"]),~n)
```

Attempt This Online!

#### Old Python/NumPy, 173 bytes

```
from numpy import*
def f(n,o=2*[mat("2 1;1 2")]):
 for i in r_[:n]:y,x=b=pad(o,eye(3,2,-1,int)<<i//2);y|=x.T;x^=x.T;o=rot90(b.T,3).T
 return rot90(choose(o[0],[*" /\\"]),~n)
```

Attempt This Online!

## How it works

It loops up to size `n` maintaining a full (`y`) and an outline only (`x`) version of the pattern at each size. The patterns are rotated 90° in each step such that the next larger rectangle always is added bottom left. In each step `x` and `y` are padded with whitespace such that the transpose of `x` can serve as the new rectangle. And we can simply `or` `x.T` and `y` to create the next `y`. The new `x` is obtained similarly, only we erase the joining line by using `xor` instead of `or`.

# Answer
> 4 votes
# Python 3, ~~328~~ 239 bytes

* Merged the two fors thanks to @oupson and added `v=i//h` (-3)
* Changed to one space indentation (-2)
* Changed `v=i//h` to `v=i//h*(t+1)` (-2)
* Changed the for to a while (-1)
* Removed the space before `and` (-1)
* Added z=i%h\*-~-t-t (-5)
* And much more, done with @oupson (-75)

```
def f(n):
 t=(1<<~-n//2)*(3-n%2)+1;l=list((" "*~-t+"\n")*t);s=0
 while n:
  w=1<<n//2;h=w>>~n%2;a=h*t;i=w*h
  while i:i-=1;v=i%w*-~t+s;z=i%h*-~-t-t+s;l[v+h],l[a+z]=l[a+v],l[w*t+a+w+z]="\\/"
  s+=(w*t+w,a,0,h)[n%4]//2;n-=1
 print(*l,sep="")

```

Try it online!

I would like to learn from this first experience, so please give me advice and golf bytes away. (Looks like a lot had to be golfed)

I probably took the wrong approach (as in lengthy/inefficient), but still decided to make the best of it.

* The f function creates the matrix and then the string to print.
* The q fonction draws a rectangles of size n to the list l. It is recursive, and for each subsequent call we offset the origin (s in the first version, x and y in the second).

Output of f for n=4 without the recursive call in q:

```
 /\
/  \
\   \
 \   \
  \  /
   \/

```

Moving the origin - where to write the next rectangle - is certainly the part of the program that needs the most improvements.

Original ungolfed version:

```
def f(n):
  t = 2**(n//2) + 2**((n-1)//2)
  lines = [[" "]*t for _ in range(t)]
  def squares(n, x=0, y=0):
    w = 2**(n//2)
    h = 2**((n-1)//2)
    for i in range(w):
      lines[y+i][x+i+h] = lines[y+i+h][x+i] = "\\"
    for i in range(h):
      lines[y+h-i-1][x+i] = lines[y+w+h-i-1][x+w+i] = "/"
    if n>1:
      squares(n-1, x + w//2 * (n%4==0) + h//2*(n%4==3), y + (w//2) * (n%4==0) + (h//2) * (n%4==1))
  squares(n)
  print("\n".join(map("".join, lines)))

```

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

```
n=>[...Array(h(n)+h(n-1))].map((_,y,a)=>a.map((_,x)=>g(n,x,y)))
g=(n,x,y,p=h(n),q=h(--n),r=p+q)=>x>=0&y>=0&x<r&y<r&(x==q+~y|x==q+y|x==y-q|x==r+p+~y)?'\\/'[(x+y+q)%2]:n?g(n,n--&2?x-h(n):x,n&2?y-h(n):y):' '
h=n=>1<<n/2

```

Try it online!

# Answer
> 3 votes
# , 135 bytes

```
' /\\/'{~[:p:inv@{.@q:"+@>({.!.1*[({.!.1|.~*@[*$@])](*+1-])1 p:])&.>/@((<p:1+i.2 2)}.@|.@, ::[[:;/$&(4 2$1|.4#1 _1)*]{.3*/\@,$&4r3 3r2)

```

Try it online!

## the idea

Notice that each iteration is a diagonal rotation of the previous one, layered on top of it. Let's draw this out to clarify. We'll use `.` instead of space in our drawings:

```
  /\.
  \/.   Initial state layer, expanded with spaces down and right.
  ...

  ...
  ./\   Initial state layer, diagonally rotated down and right.
  .\/

  /\.
  \/\   The two layers stacked and "added" together elementwise.
  .\/

```

The "addition" of those two layers (3rd picture) is the new state, with the center `/` repeated. We need to track that, because we want to remove repeats when we iterate again:

```
  ./\.
  .\/\   Current iteration, expanded with spaces down and left.
  ..\/
  ....

  ....
  /\..   Current iteration, diagonally rotated down and left, with all
  \.\.   previous "repeats" removed.
  .\/.

  ./\.
  /\/\   Those two layers stacked and added elementwise.
  \.\/
  .\/.

```

Note that now, in the 3rd picture, we have 3 "repeat" slashes. I'll highlight their locations with `*`:

```
  ./\.
  /**\   Elements that have been added to themselves in any previous
  \.*/   iteration.
  .\/.

```

We continue this process -- expanding, rotating and removing repeats, and "adding" layers. The next direction will be up and left, then up and right, then down and right again, continuing cylically:

```
down & right   down & left   up & left   up & right
\                /           *              *
 \              /             \            /
  *            *               \          /

```

## implementation notes

The entire calculation is a single fold, which begins with the initial 2x2 diamond matrix, and precalculates the magnitude and direction of all the diagonal rotations:

* `]{.3*/\@,$&4r3 3r2` Precalculates the new side of each iteration's square matrix:

```
3 4 6 8 12 16 24 32

```

This is a geomtric series, with an alternating multiplier: Start with 3, multiply by `4/3`, then multiply that result by `3/2`, then that result by `4/3`, and so on.
* `4 2$1|.4#1 _1` A golf for the directions of the diagonal rotations. It evaluates to:

```
 1  1     down/right
 1 _1     down/left
_1 _1     up/left
_1  1     up/right

```
* `(<p:1+i.2 2)` To track repeats, we encode the starting matrix using primes:

```
┌────┐
│3  5│   corresponds to  /\
│7 11│                   \/
└────┘

```

+ And when we "add" the layers we'll use multiplication, with spaces encoded as ones. This lets us detect repeats by checking if a cell is prime.
* `[:p:inv@{.@q:"+` At the very end, each element will either be a prime or a prime power. So we can take the first factor `{.@q:` to recover the "non-repeat" version of each cell. Finally, we use the inverse prime function `p:inv` to turn the pries back into the numbers `1 2 3 4`, which we use to index into `/\\/`.

# Answer
> 1 votes
# Ruby, 339 bytes

```
f=->n{a,j,v={0=>r=t=[0,1],1=>r},[[1,-1],[-2,2]],[1,1]
n.times{|q|a.merge!(a.to_h{|y,x|[y+v[0],[x[0]+v[1],x[-1]+v[1]]]}){|k,x,y|t|=x|=y
x.sort}
v=v.zip(j[q%2]).map{|x,y|x*y}
r,t=[a.keys,t].map &:minmax}
o=(0..r[1]-r[0]).map{" "*(t[1]-t[0])}
a=a.to_h{|y,x|[y-r[0],x.map{|z|z-t[0]}]}
a.each{|y,c|c.map{|x|o[y][x]="/\\"[(x+y+(n>1?1:0))%2]}}
o}
```

Attempt This Online!

* Not the best answer around but I tried at least to do the job.
* Thanks @emanresu A for providing an online compiler(Tio Ruby version didn't work ).
* Returns an array of strings.

We generate an Hash where Keys are row indexes(allowing negative keys) and Value is an Array of written indexes on each row(also negative allowed)

```
/\  0(0,1) > We get bounds.
\/  1(0,1) > Pivot starts at 1,1

```

> Add Pivot to Bounds
> Add to Hash

```
/\   0(0,1)   H<= (1,1)+S
\/\  1(0,1,2)
 \/  2(1,2)    B=0(0,1)1(0,2)2(1,2)

```

next pivot is P\* \[1,-1\]or\[-2,2\] alternately

```
 /\   0(0,1)        H<=(1,-1)+B=
/\/\  1(-1,0,1,2)   1(-1,0)2(-1,1)
\ \/  2(-1,1,2)     3(0,1)
 \/   3(0,1)
B=0(0,1)1(-1,2)2(-1,2)3(0,1)

```

To draw the pattern we take an array of strings of spaces of minMax(Keys,values) dimensions and we iterate our Hash to overwrite / or \ based on modulo2(x+y)

* n=0 and 1 require to invert

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


title: Group a List by Frequency

text:
# Question
Title: Group a List by Frequency
Given a list of integers, group the elements which occur most first, then group the next most and so on until each unique element in the list has been grouped once.

---

# Examples:

**Input:** `[1,2,3]`

**Output:** `[[1,2,3]]`

---

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

**Output:** `[[1],[2,3],[4,5,6]]`

---

**Input:** `[1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]`

**Output:** `[[6, 8],[5],[1],[7],[9,4,-56]]`

---

**Input:** `[]`

**Output:** `[]`

---

**Input:** `(empty input)`

**Output:** `ERROR/Undefined/Doesn't matter`

---

# Rules

* Groupings must go from maximal frequency to minimal frequency.
* Internal order of the groupings are arbitrary (E.G. example 3 could have `[8,6]` instead).
* This is , lowest byte-count wins.

# Related

# Answer
# Pyth, ~~8~~ 7 bytes

```
_{M.g/Q

```

Try it online!

1 byte thanks to FryAmTheEggman.
> 6 votes

# Answer
## Mathematica, 43 bytes

```
Union/@SortBy[l=#,f=-l~Count~#&]~SplitBy~f&

```

Try it online! (Using Mathics.)

Alternatively:

```
SortBy[Union[l=#],f=-l~Count~#&]~SplitBy~f&

```
> 7 votes

# Answer
## JavaScript (ES6), ~~95~~ 101 bytes

```
a=>a.map(x=>(o[a.map(y=>n+=x!=y,n=0)|n]=o[n]||[])[x*x+(x>0)]=x,o=[])&&(F=o=>o.filter(a=>a))(o).map(F)

```

### How?

For each element ***x*** of the input array ***a***, we compute the number ***n*** of elements of ***a*** that are different from ***x***:

```
a.map(y => n += x != y, n = 0) | n

```

We use the indices ***n*** and ***x*** to fill the array ***o***:

```
(o[n] = o[n] || [])[x * x + (x > 0)] = x

```

***Edit****: Because JS doesn't support negative array indices, we need the formula `x * x + (x > 0)` to force positive indices.*

This gives us an array of arrays containing the unique elements of the original list, grouped by frequency and ordered from most frequent to least frequent.

However, both the outer array and the inner arrays potentially have many empty slots that we want to filter out. We do this with the function ***F***, applied to ***o*** and each of its elements:

```
F = o => o.filter(a => a)

```

### Test cases

```
let f =

a=>a.map(x=>(o[a.map(y=>n+=x!=y,n=0)|n]=o[n]||[])[x*x+(x>0)]=x,o=[])&&(F=o=>o.filter(a=>a))(o).map(F)

console.log(JSON.stringify(f([1,2,3]))) // [[1,2,3]]
console.log(JSON.stringify(f([1,1,1,2,2,3,3,4,5,6]))) // [[1],[2,3],[4,5,6]]
console.log(JSON.stringify(f([1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56]))) // [[6, 8],[5],[1],[7],[9,4,-56]]
console.log(JSON.stringify(f([]))) // []
```
> 5 votes

# Answer
# Python 2, ~~145~~ 141 bytes

```
import collections as c,itertools as i;o=lambda n:lambda l:l[n]
print[map(o(0),g)for _,g in i.groupby(c.Counter(input()).most_common(),o(1))]

```

Try it online!

This is my first submission after years of reading.

> It basically it puts all the elements into a Counter (dictionary of how many of each element in the list) and .most\_common() puts the items in decending frequency order. After that, it's just a matter of formatting the items into the right list.

Saved 4 bytes thanks to ovs.
> 5 votes

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

```
QɓċÐ€ĠṚị

```

Try it online!
> 3 votes

# Answer
# PHP, 85 bytes

```
<?$r=[];foreach(array_count_values($_GET)as$k=>$v)$r[$v][]=$k;krsort($r);print_r($r);

```

Try it online!
> 3 votes

# Answer
## Clojure, 74 bytes

```
#(for[[_ g](sort-by(comp - key)(group-by val(frequencies %)))](map key g))

```

Looks quite verbose :/
> 2 votes

# Answer
# Perl 6, 43 bytes

```
*.Bag.classify(-*.value).sort».value».key

```

Test it

## Expanded:

```
*                   # WhateverCode lambda (this is the input)
                    # [1,1,1,2,2,3,3,4,5,6]

.Bag                # turn into a Bag
                    # (1=>3,5=>1,4=>1,3=>2,6=>1,2=>2).Bag

.classify(-*.value) # classify by how many times each was seen
                    # {-2=>[3=>2,2=>2],-3=>[1=>3],-1=>[5=>1,4=>1,6=>1]}

.sort\              # sort (this is why the above is negative)
                    # {-3=>[1=>3],-2=>[3=>2,2=>2],-1=>[5=>1,4=>1,6=>1]}

».value\            # throw out the classification
                    # ([1=>3],[3=>2,2=>2],[5=>1,4=>1,6=>1])

».key               # throw out the counts
                    # ([1],[3,2],[5,4,6])

```
> 2 votes

# Answer
# Bash + GNU utilities, 71 61

```
sort|uniq -c|sort -nr|awk '{printf$1-a?"\n%d":",%d",$2;a=$1}'

```

Input as a newline-delimited list. Output as a newline-delimited list of comma-separated values.

Try it online.
> 2 votes

# Answer
# Mathematica, 79 bytes

```
Table[#&@@@f[[i]],{i,Length[f=GatherBy[Sort[Tally@#,#1[[2]]>#2[[2]]&],Last]]}]&

```

**input**

> \[{1, 1, 1, 4, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 9, 5, 6, 5, 6, 5, 6, 5, 6, -56}\]

**output**

> {{8, 6}, {5}, {1}, {7}, {-56, 9, 4}}
> 2 votes

# Answer
# MATL, 9 bytes

```
9B#uw3XQP

```

Input is a column vector, using `;` as separator.

**Try it online!**

### Explanation

```
9B#u   % Call 'unique' function with first and fourth outputs: unique entries and
       % number of occurrences
w      % Swap
3XQ    % Call 'accumarray' with anonymous function @(x){sort(x).'}. The output is
       % a cell array with the elements of the input grouped by their frequency.
       % Cells are sorted by increasing frequency. Some cells may be empty, but
       % those won't be displayed
P      % Flip cell array, so that groups with higher frequency appear first.
       % Implicitly display

```
> 2 votes

# Answer
# , ~~84~~ 77 bytes

*-7 bytes thanks to mb7744*

```
unique(lapply(x<-sort(table(scan()),T),function(y)as.double(names(x[x==y]))))

```

Reads from stdin; returns a list with subvectors of integers in increasing order. If we could return strings instead of ints, then I could drop 11 bytes (removing the call to `as.double`), but that's about it. R's `table` function does the heavy lifting here, counting the occurrences of each member of its input; then it aggregates them by count (`names`). Of course, that's a string, so we have to coerce it to an integer/double.

Try it online!
> 2 votes

# Answer
# k, 22 bytes

```
{x@!x}{(>x)@=x@>x}#:'=

```

Try it online.

(AW's k seems to require an extra `@` before the `#`, but oK does not.)

Explanation:

```
                     = /group identical numbers in a map/dict
                  #:'  /get number of times each number is repeated
                       /this is almost the answer, but without the inner lists
      {      x@>x}     /order "number of times" greatest to least
            =          /group them (to make the smaller groups)
       (>x)@           /get the actual numbers into place
{x@!x}                 /get values of the map/dict it's in

```
> 2 votes

# Answer
# Brachylog, 10 bytes

```
ọtᵒ¹tᵍhᵐ²|

```

Try it online!

### Explanation

```
Example input: [2,1,1,3]

ọ            Occurences:            [[2,1],[1,2],[3,1]]
 tᵒ¹         Order desc. by tail:   [[1,2],[3,1],[2,1]]
    tᵍ       Group by tail:         [[[1,2]],[[3,1],[2,1]]]
      hᵐ²    Map twice head:        [[1],[3,2]]

         |   Else (Input = [])      Input = Output

```
> 2 votes

# Answer
# JavaScript (ES6), ~~100~~ ~~98~~ ~~96~~ 93 bytes

*Saved 2 bytes thanks to @Neil (plus he fixed an edge-case bug in my code). Saved 3 more bytes thanks to @TomasLangkaas.*

```
a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>a+a).reverse()

```

**Test cases**

```
f=
a=>a.sort().map((_,n)=>a.filter((v,i)=>i-a.indexOf(v)==n&v!=a[i+1])).filter(a=>a+a).reverse()

console.log(JSON.stringify(f([1,2,3])))
console.log(JSON.stringify(f([1,1,1,2,2,3,3,4,5,6])))
console.log(JSON.stringify(f([1,1,1,4,5,6,6,6,7,7,8,8,8,8,8,8,8,9,5,6,5,6,5,6,5,6,-56])))
console.log(JSON.stringify(f([])))
```
> 2 votes

# Answer
# Husk, ~~6~~ 5 bytes

```
↔k#¹u

```

Try it online!

-1 byte from Leo.

## Explanation

```
↔k#¹u
    u uniquify the input
 k#¹  key on frequency in input
↔     reverse

```
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
ÙΣ¢}R.γ¢

```

Try it online or verify all test cases.

**Explanation:**

```
Ù       # Uniquify the (implicit) input-list
 Σ      # Sort this uniquified list by:
  ¢     #  Get its count in the (implicit) input-list
 }R     # After the ascending sort: reverse it to make it descending
   .γ   # Then adjacently group each value by:
     ¢  #  Its count in the (implicit) input-list
        # (after which the result is output implicitly)

```

The  could have been  for the same result.  is the group-by builtin, and  is the adjacently group-by builtin. But since we use a sort first, the result ends up buying the same.
Unfortunately, 05AB1E lacks a sort & group-by as single builtin, so we'll have to do it in two steps instead (like most existing answers tbh).
> 2 votes

# Answer
# Factor, 63 bytes

```
[ histogram unzip swap zip expand-keys-push-at values reverse ]

```

## Explanation

```
                     ! { 1 1 1 2 2 3 3 4 5 6 }
histogram            ! H{ { 1 3 } { 2 2 } { 3 2 } { 4 1 } { 5 1 } { 6 1 } }
unzip                ! { 1 2 3 4 5 6 } { 3 2 2 1 1 1 }
swap                 ! { 3 2 2 1 1 1 } { 1 2 3 4 5 6 }
zip                  ! { { 3 1 } { 2 2 } { 2 3 } { 1 4 } { 1 5 } { 1 6 }
expand-keys-push-at  ! H{ { 1 V{ 4 5 6 } } { 2 V{ 2 3 } } { 3 V{ 1 } } }
values               ! { V{ 4 5 6 } V{ 2 3 } V{ 1 } }
reverse              ! { V{ 1 } V{ 2 3 } V{ 4 5 6 } }

```
> 2 votes

# Answer
# Python 3, 85 bytes

```
def f(l):
 r=[[]for _ in l]
 for x in{*l}:r[-l.count(x)]+=x,
 return[*filter(bool,r)]

```

Try it online!

-12 thanks to tips from @ovs!
> 2 votes

# Answer
# , ~~60~~, 54 bytes

```
ÚòÍ¨¼¾©î±/± ±òHòø
pkJjòú!
Ç¨^ƒ ©î±/o
Îf ld|;D
òV{Jk

```

Try it online!

Hexdump:

```
00000000: daf2 cda8 bc81 bea9 eeb1 2fb1 20b1 f248  ........../. ..H
00000010: f2f8 200a 706b 4a6a f2fa 210a c7a8 5e83  .. .pkJj..!...^.
00000020: 20a9 81ee b12f 6f0a ce66 206c 647c 3b44   ..../o..f ld|;D
00000030: 0af2 567b 4a6b                           ..V{Jk

```

As much as I love V, I'm pretty sure this is the worst possible language for the task. Especially considering it has no support for lists, and basically no support for numbers. Just string manipulation.
> 1 votes

# Answer
**PowerShell, 77, 70 bytes**

```
($a=$args)|group{($a-eq$_).count}|sort n* -Des|%{,($_.group|sort -u)}

```

NB: To see that these results are correctly grouped (since visually there's no deliniation between the contents of each array), you may wish to append `| write-host` to the end of the above line.

**Acknowledgements**

Thanks to:

* TessellatingHeckler for saving 7 bytes by massively refactoring / rewriting to a way more golfed approach.

---

**Previous**

*77 bytes*

```
param($x)$x|group|sort count -desc|group count|%{,($_.group|%{$_.group[0]})}

```
> 1 votes

# Answer
## C#, 119 bytes

Just a quick stab at it:

```
using System.Linq;
a=>a.GroupBy(x=>x)
    .GroupBy(x=>x.Count(),x=>x.Key)
    .OrderBy(x=>-x.Key)
    .Select(x=>x.ToArray())
    .ToArray()

```
> 1 votes

# Answer
# Ruby, 62 bytes

```
->a{a.group_by{|e|a.count(e)}.sort_by{|x,_|-x}.map{|_,i|i|[]}}

```

Try it online!

There has got to be a shorter way to do this.
> 1 votes

# Answer
# , 66 bytes

```
(l=lapply)(l(split(x<-table(scan()),factor(-x)),names),as.integer)

```

Try it online!

If in the output the integers may be in string format, can drop to **48 bytes** (as mentioned in @Giuseppe's answer).

---

Ungolfed:

```
input <- scan(); # read input
x <- table(input); # count how many times each integer appears, in a named vector
y <- split(x, factor(-x)) # split the count into lists in increasing order
z <- lapply(y, names) # access the the original values which are still
                      # attached via the names
lapply(z, as.integer) # convert the names back to integers

```
> 1 votes

# Answer
# Perl 5 `-pa`, 89 bytes

```
map$k{$_}++,@F;$_="@{[sort{$k{$b}-$k{$a}}keys%k]}";s/\S+ /$&.'| 'x($k{1*$&}!=$k{1*$'})/ge

```

Try it online!
> 1 votes

# Answer
# Groovy, 71 bytes

```
{a->a.groupBy{a.count(it)}.sort{-it.key}.values().collect{it.unique()}}

```

I actually just learned about groupBy after creating this. I didn't know collect wasn't my only choice.

---

```
{
    a->                 // [1,2,1,2,3,3,3,6,5,4]
    a.groupBy{
        a.count(it)     // [2:[1,2,1,2],3:[3,3,3],1:[6,5,4]]
    }.sort{
        -it.key         // [3:[3,3,3],2:[1,2,1,2],1:[6,5,4]]
    }.values().collect{ // [[3,3,3],[1,2,1,2],[6,5,4]]
        it.unique()
    }                   // [[3],[1,2],[6,5,4]]
}

```
> 0 votes

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


title: Which Advent is it?

text:
# Question
Title: Which Advent is it?
I know, a bit late.

# Challenge

Your challenge is, given a date, output if it's not an Advent Sunday, or the Advent Sunday of the year.

# Rules

* The \\$4^\text{th}\\$ Advent is determined by the Sunday before Christmas day (the \\$25^\text{th}\\$ of December). The \\$3^\text{rd}\\$ Advent is the Sunday before the \\$4^\text{th}\\$ Advent, and so on until the \\$1^\text{st}\\$ Advent.
* If Christmas Day falls on a Sunday, then the Sunday before is still the \\$4^\text{th}\\$ Advent.
* Input will consist of day, month and year, as an iterable with any order, or a string, or 3 separate integers.
* Input will be a valid date, numerically and also calendrically.
* Output should be falsey (0 or Boolean False) if the date is not an Advent Sunday, or else an integer denoting which Advent Sunday it is.
* This is , so the shortest answer wins.

# Examples

```
[In]: [2, 12, 2021]
[Out]: 0

[In]: [6, 5, 2023]
[Out]: False

[In]: [12, 12, 2021]
[Out]: 3

[In]: [30, 11, 1997]
[Out]: 1

[In]: [25, 12, 2011]
[Out]: false

[In]: [21, 12, 3000]
[Out]: 4

```

Good Luck!

# Answer
> 6 votes
# Excel, ~~71~~ 66 Bytes

Saved 5 bytes thanks to Taylor Raine

*Aside: At the time of posting, this answer has the smallest byte count. That is baffling. Score one for Excel's date handling, I guess.*

```
=LET(a,4-(INT(("12/23/"&YEAR(A1))/7)*7+1-A1)/7,(LEN(a)=1)*(a<5)*a)

```

Input is in cell `A1`. Output is wherever the formula is. Returns a number 1-4 for advent Sundays and a 0 for all other dates.

```
LET(a,4-(INT(("12/23/"&YEAR(A1))/7)*7+1-A1)/7

```

The first part calculates which advent Sunday an input is and does most of the heavy lifting.

* `("12/23/"&YEAR(A1))` finds Christmas Eve Eve (CEE) in the year of the input. We find Eve Eve hear because it saves us some extra bytes of adjustment later.
* `INT(~/7)*7` takes that date, divides by 7 (b/c 7 days per week), rounds it down, then multiplies it by 7. This finds the Saturday before CEE. If CEE *is* a Saturday, then it returns that date.
* `(INT(~/7)*7+1-A2)/7` adds one to get Sunday, subtracts the input, and divides by 7 to get the number of weeks between the input and the Sunday before Christmas. This may not be a whole number.
* `4-(~)` subtracts that result from 4 to invert the result. I.E., the Sunday before Christmas needs to be the 4th Sunday, not the 1 week before.

```
LET(a,~,(LEN(a)=1)*(a<5)*a)

```

Now that the heavy lifting is out of the way, we can examine the results. Note that using TRUE and FALSE values in math will treat TRUE = 1 and FALSE = 0. By multiplying various statements that will evaluate to either TRUE or FALSE, we can filter out undesirable results.

* `(LEN(a)=1)` filters out any non-integers as well as negative integers. This removes every non-Sunday in the advent calendar and all dates before the first Sunday. This does *not* filter out the 0th Sunday but the end result will still be 0 so it works.
* `(a<5)` filters out Sundays *after* the 4th Sunday.
* `(~)*(~)*a` returns the value if it has passed both those filters. Otherwise, it returns 0.

In this screenshot, I have added a column to return the value of `a` since that's so much of the calculation. I have also extended the data beyond the samples above to show some edge cases.

# Answer
> 5 votes
# Factor \+ `calendar.holidays.us`, 85 bytes

```
[ <date> dup christmas-day 4 [ dup last-sunday ] times 0 5 narray reverse nip index ]

```

Takes input as three integers in \<year\> \<month\> \<day\> order. The `last-sunday` word postdates build 1525, the one TIO uses, so here's a screenshot of running the above code in build 2101's listener:

## Explanation

```
                             ! 2021 12 12
<date>                       ! 2021-12-12
dup                          ! 2021-12-12 2021-12-12
christmas-day                ! 2021-12-12 2021-12-25
4 [ dup last-sunday ] times  ! 2021-12-12 2021-12-25 2021-12-19 2021-12-12 2021-12-5 2021-11-28
0 5 narray                   ! 2021-12-12 2021-12-25 { 2021-12-19 2021-12-12 2021-12-5 2021-11-28 0 }
reverse                      ! 2021-12-12 2021-12-25 { 0 2021-11-28 2021-12-5 2021-12-12 2021-12-19 }
nip                          ! 2021-12-12 { 0 2021-11-28 2021-12-5 2021-12-12 2021-12-19 }
index                        ! 3

```

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

```
(y,m,d)=>/Su/.test(c=new Date(y,m-1,d))*'01234'[(c-new Date(y,9,51))/6048e5|0]

```

Try it online!

Falsy may be 0 or NaN. Add 2 bytes (append `|0`) to always get 0. User must run this program with computer configured to UTC timezone or any other timezone that: 1. No DST shift during Nov 20 to Dec 31, 2. Name of timezone (in system language) does not contain substring `"Su"` (case sensitive).

`new Date(y,9,51)` is Nov 20 in JavaScript.

# Answer
> 3 votes
# Python3, 152 bytes:

```
from datetime import*
t=lambda x:0if x>=date(x.year,12,25)else 1+t(x+timedelta(days=7))
f=lambda x:(s:=date(*x)).weekday()==6and(0<(j:=(5-t(s)))<5)and j

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 116 bytes

```
3=`
;
\d+
$*_
((_*)\2\2\2_*);((_*)\4\4\4_*)
$4$3$2$1$1$1$1$1
\G_{7}

-_{12}-
____
-_{11}-_{26}

^(_{7}){1,4}$|.+
$#1

```

Try it online! Link includes test cases. Takes input in ISO date format. Explanation:

```
3=`
;

```

Separate the year from the century.

```
\d+
$*_

```

Convert to unary.

```
((_*)\2\2\2_*);((_*)\4\4\4_*)
$4$3$2$1$1$1$1$1
\G_{7}

```

Perform Zeller's congruence on the 25th of December of the input year.

```
-_{12}-
____
-_{11}-_{26}

```

Add this to the day of the month, adding an extra 4 for December or subtracting 26 for November 26 or later. Other months get ignored and fail to match the next stage at all.

```
^(_{7}){1,4}$|.+
$#1

```

Count the number of whole weeks, but the result must be an integer between `1` and `4` inclusive.

# Answer
> 3 votes
# Wolfram Language (Mathematica),  ~~88~~  79 bytes

> Input format should be `{year, month, day}`.

```
Ramp[4-DayCount[#,{#&@@#,12,24},s=Sunday]]Boole[DayName@#==s&&Rest@#!={12,25}]&

```

Try it online!

Output:

```
0
0
3
1
0
4

```

79 bytes - Thanks to @att

# Answer
> 3 votes
# C (gcc), ~~215~~ ~~202~~ 192 bytes

```
#import<time.h>
i;*t;*l;f(d,m,y){5[t=calloc(9,8)]=y-1900;t[4]=m-1;t[3]=d;l=mktime(t);i=6[t=gmtime(&l)];y=t[7];t[4]=11;t[3]=25;l=mktime(t);d=7[t=gmtime(&l)]-y;m=4-d/7-!t[6];i=i|!d|m<1|m>4?0:m;}

```

Try it online!

*Saved 13 bytes thanks to ceilingcat!!!*

Inputs the day, month and year as separate parameters.
Returns which Advent Sunday it is or \\$0\\$ otherwise.

# Answer
> 3 votes
# Python 3.8 (pre-release), 114 bytes

```
lambda a,b,c:(y:=int((c+10.5)/7))%5+y//5 if date(a,b,c).weekday()==6 and[b,c]!=[12,25]else 0
from datetime import*

```

Try it online!

# Answer
> 2 votes
# Python 3.8,  ~~128~~  116 bytes

```
lambda q:max(x*(date(*q)==(M:=date(q[0],11,27))+timedelta(7*x+~M.weekday()))for x in(1,2,3,4))
from datetime import*

```

**Try it online!**

# Answer
> 2 votes
# Perl 5, 144 bytes

```
sub{$_=join$",map{@t=gmtime$_*604800+3e5;19000100+$t[5]*1e4+$t[4]*100+$t[3]}1..6e4;pop=~/..../;/ $&$'( $&\d+)+/;$_=6-$&=~y///c/9;/^[1-4]$/?$_:0}

```

Try it online!

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


title: An ASCII self-referential sequence

text:
# Question
Title: An ASCII self-referential sequence
The sequence A109648 starts with the following numbers

```
53, 51, 44, 32, 53, 49, 44, 32, 52, 52, 44, 32,
51, 50, 44, 32, 53, 51, 44, 32, 52, 57, 44, 32,
52, 52, 44, 32, 51, 50, 44, 32, 53, 50, 44, 32,
53, 50, 44, 32, 52, 52, 44, 32, 51, 50, 44, 32,
53, 49, 44, 32, 53, 48, 44, 32, 52, 52, 44, 32,
51, 50, 44, 32, 53, 51, 44, 32, 53, ...

```

and has the description of

> Sequence is its own ASCII representation (including commas and spaces).

This is the unique sequence with the property. Your task is compute this sequence.

Standard rules and I/O methods apply. The shortest code in bytes wins.

# Answer
> 12 votes
# Python 2, 41 bytes

```
f=lambda n:ord(`map(f,n*[n/4])+[5]`[1+n])
```

Attempt This Online!

Thanks to @loopywalt

Uses Python's string representation of tuples to get the `,`  parts of the sequence (`44, 32`).

## Python 2, 42 bytes

```
f=lambda n:ord("5"[n:]or`f(n/4),1`[1+n%4])
```

Attempt This Online!

Here are some variations, but I've not been able to get any of them shorter:

```
f=lambda n:ord(`5*(n<1)or f(n/4),1`[1+n%4])
f=lambda n:ord(`0**n*5or f(n/4),1`[1+n%4])
f=lambda n:ord(`[5][n:]or[f(n/4)]*n`[1+n])
f=lambda n:ord(`[5]+[n and f(n/4)]*n`[1+n])
f=lambda n:ord(`0**n*-5or[f(n/4)]*n`[1+n])
f=lambda n:ord(`-~-n*"5"or[f(n/4)]*n`[1+n])

```

# Answer
> 7 votes
# Wolfram Language (Mathematica), ~~58~~ ~~57~~ ~~55~~ 48 bytes

-1 (-2) thanks to alephalpha

```
Nest[Rest@*ToCharacterCode@*ToString,!5,#][[#]]&

```

Try it online!

Returns the \\$n\\$th element, 1-indexed.

---

### Wolfram Language (Mathematica), 68 bytes

```
If[#<1,53,Join[48+IntegerDigits@#0@⌊#/4⌋,{44,32}][[#~Mod~4+1]]]&

```

Try it online!

Implements the formula given on the OEIS page.

# Answer
> 7 votes
# JavaScript (Node.js), 39 bytes

```
f=n=>n?[...f(n>>2)+'',28,16][n%4]^48:53

```

Try it online!

# Answer
> 6 votes
# Vyxal, 10 bytes

```
5?(‛, jC)Ẏ

```

Try it Online!

Outputs the first n terms, although it actually calculates the first n^3 terms.

```
5          # Starting with 5
 ?(     )  # input times...
   ‛, j    # Join by `, `
       C   # Get charcodes
         Ẏ # At end, get first n

```

# Answer
> 6 votes
# Charcoal, 26 bytes

```
≔⊗⊖⊗Ｎθ≔5ηＷ‹Ｌηθ≔⪫Ｅη℅κ, η…ηθ

```

Try it online! Link is to verbose version of code. Outputs the first `n` elements, joined with comma and space. Explanation:

```
≔⊗⊖⊗Ｎθ

```

Calculate the length of the desired output.

```
≔5η

```

Start with the initial `5`, whose ASCII code starts with itself.

```
Ｗ‹Ｌηθ

```

Until the string is long enough...

```
≔⪫Ｅη℅κ, η

```

... join its ASCII codes with comma space.

```
…ηθ

```

Output the desired number of terms.

# Answer
> 4 votes
# Haskell + hgl, 24 bytes

```
q=53:tl(Or<ic", "(sh<q))

```

This defines `q` an infinite list representing the sequence.

If you want the actual string of the sequence you can do that for 1 more byte:

```
q=ic", "$sh<Or<('5':tl q)

```

## Explanation

So here we define `q` in terms of itself.

A naive answer might look like:

```
q=Or<ic", "(sh<q)

```

Which takes `q` maps `show` across it to convert all the numbers to strings, intercalates `", "` with `ic`, to get the string and maps `Or` to get the char points.

However if we define this the resulting list is just an infinite loop and never manages to produce the first element. So we need to tell it what the first element is. To do this we take what we had, chop off the first element and put the correct answer in it's place.

This allows Haskell to skip to the second element when calculating this list which it can calculate in terms of the first element just fine. And from there every successive element can be calculated just fine.

# Answer
> 3 votes
# , 40 37 bytes

```
$_2".@}.[:,0&(]', ',~"#.3":"+@u:":)&5

```

Try it online!

-3 thanks to Bubbler's idea of taking first `n` terms with `$` instead of returning the nth term

Inspired by emanrasu A's answer

Yikes.

# Answer
> 3 votes
# Stax, 10 bytes

```
▓░δΓ╙öâ'╜Ä

```

Run and debug it

freezes at 10.

# Answer
> 3 votes
# , ~~83~~ ~~79~~ ~~74~~ 59 bytes

```
function(n){x=5
for(i in 1:n)x=utf8ToInt(toString(x))
x[n]}

```

Try it online!

Credit to Dominic van Essen for -4 bytes

# Answer
> 3 votes
# C (gcc), 76 bytes

```
f(n){char*s=calloc(n,8),*t=s;for(*s=53;n--;)t+=sprintf(t,"%d, ",*s++);n=*s;}

```

Try it online!

Inputs a \\$0\\$-based index \\$n\\$.
Returns the \\$n^\text{th}\\$ element.

# Answer
> 3 votes
# BQN, ~~63~~ ~~35~~ 28 bytes

*Edit: -28 and then -7 more bytes (!) thanks to Razetime*

```
{↑{-⟜@¨∾∾⟜", "¨•Fmt¨}⍟⥊5}

```

Try it at BQN online REPL

Outputs first n elements of sequence for input n. But, to get this, calculates the first 4^n elements. So times-out (or crashes) on the online REPL for even moderate n.

Ungolfed, commented (try it here):

```
Log10 ← 10⊸⋆⁼                                        # base 10 logarithm
N2d ← Number_to_digits ← {(10⋆⌽↕⌈Log10 )(10|·⌊÷)˜} # get base 10 digits
N2s ← Number_to_string ← '0'⊸+¨ N2d                  # string representation
S2a ← String_to_ASCII ← @⊸(-˜)¨                      # ASCII codes of string

ASCII_srs ← {↑{S2a∾´(∾⟜", ")∘N2s¨}⍟ ⟨5⟩}
                                       ⟨5⟩}  # start with ⟨5⟩,
                                    ⍟       # repeat input times:
                              N2s¨}         #  get string representations,
                    (∾⟜", ")∘               #  join ", " to each,
                  ∾´                         #  join it all together,
              {S2a                           #  and convert to ASCII codes;
           {↑                               # finally get input elements.

```

# Answer
> 2 votes
# Ruby, 40 bytes

```
->n{a=*5
n.times{a=(a*", ").bytes}
a[n]}

```

Try it online!

a lambda that returns the n-th element

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

```
a@1={53};a[n_]:=a[n]=Join[a[n-1],ToCharacterCode@StringTake[ToString@a[n-1],{n+1}]]

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 49 bytes

```
f(n)=if(n,Vec(Vecsmall(Str(f(n-1)))[2..n+1]),[5])

```

Try it online!

1-indexed. Based on the PARI/GP code on the OEIS page.

# Answer
> 1 votes
# Perl 5 \+ `-pa`, 42 bytes

```
$_=53;$_.=", ".ord+(/./g)[++$;]while"@F">$

```

Try it online!

## Explanation

Naiive approach, builds the string from `53` and appends the `ord`inal values. 0-indexed, prints up to the `n`th term.

Uses `$;` to store the counter to save a byte at the end from the `-p` flag.

# Answer
> 1 votes
# Japt, 15 bytes

```
@Zq,ú2)cY}h#5ìL

```

Try it

# Answer
> 1 votes
# Excel VBA, ~~69~~ 50 bytes

Saved 19 bytes thanks to a total re-write by Taylor Raine

```
?"53";:t=3:Do:k=", "&Asc(t):t=Mid(t &k,2):?k;:Loop

```

The function is typed directly into the immediate window and output is in the same window. It will run until it's stopped (`ESC`) or it hits a software / hardware limitation like running out memory.

Colons are line line breaks in VBA. Here's a version with some nicer formatting and comments.

```
?"53";                 ' Print "53" without a line break at the end
t = 3                  ' Seed the value for t
Do                     ' Start a loop
   k = ", " & Asc(t)   ' Store the ASCII value for the first character in t
   t = Mid(t & k, 2)   ' Set t be everything in t & k except the first character
   ?k;                 ' Print the value of k without a line break at the end
Loop                   ' Go back to "Do"

```

# Answer
> 0 votes
# APL+WIN, 60 bytes

Prompts for required term number. Index origin = 0

```
i←0⋄s←53 51 44 32⋄⍎∊(n←⎕)⍴⊂'s←s,(⎕av⍳⍕s[i←i+1]),44 32⋄'⋄s[n]

```

TIO examples generate the first column of the tabular form of the series as depicted in the question.

Try it online! Thanks to Dyalog Classic

# Answer
> 0 votes
# Husk, 17 bytes

```
↑¹!¡ȯmcJ", "ms;53

```

Try it online!

---

# Husk, 16 bytes

```
↑¹!¡ȯJ", "mosc"5

```

With output as character string (ASCII values represent sequence A109648)

Try it online!

# Answer
> 0 votes
# 05AB1E, 9 bytes

```
5Δ„, ýÇI£

```

Outputs the first \\$n\\$ results.

Try it online.

**Explanation:**

```
5          # Start with a 5
 Δ         # Loop until the result no longer changes:
  „, ý     #  Join with ", " delimiter
      Ç    #  Convert it to a list of its codepoint integers
       I£  #  Only leave the first input amount of values
           # (after the loop, the resulting list is output implicitly)

```

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