title: Is it an alphadrome?

text:
# Question
Title: Is it an alphadrome?
An alphadrome is a word in which each letter in the first half of the word "reflects" its alphabetical "opposite" in the second half of the word. Write a program or function that returns truthy if the given word is an alphadrome and falsey otherwise.

For example, `BEEB` is a palindrome. Its first letter `B` "reflects" its last letter `B`, and its second letter `E` reflects its second-to-last letter `E`.

In contrast, `BEVY` is an ***alphadrome***. Its first letter `B` is the second letter of the alphabet, and it reflects the word's last letter `Y`, which is the second-to-last letter of the alphabet. Likewise, its second letter `E` is the 5th letter of the alphabet, and it reflects `V`, the 5th-from-the-end letter of the alphabet.

Like palindromes, an alphadrome can have an odd number of letters, too. `WORLD` is an alphadrome. `W` is the 4th-from-the-end letter of the alphabet and `D` is the 4th letter; `O` is the 12th-from-the-end letter of the alphabet and `L` is the 12th letter. The center `R` reflects itself.

Any single-letter word is an alphadrome.

## Rules

## Test cases

```
A        true
ABA      false
ABZ      true
ABBA     false
BEVY     true
GOLF     false
ZOLA     true
WIZARD   true
BIGOTRY  true
RACECAR  false
ABCDEFGHIJKLMNOPQRSTUVWXYZ  true

```

# Answer
# , 25 24 bytes

```
[:*/155=3,~inv@(+|.)@u:]

```

Try it online!

*-1 thanks to ovs*

Based on the observation that this is essentially just requiring that the sum of the ascii codes of the input and its reverse add to 155.

The only exception is that, in the odd case, the middle element can be anything. The inverse of self-append in J `,~inv` returns the first half of a list, but "rounds down" in the odd case, and so does what we need.

That is, we can take the sums of the ascii codes as described, take the `,~inv` of that result, and check if they are all 155.
> 11 votes

# Answer
# Python 3, 58 bytes

```
f=lambda s:len(s)<2or ord(s[0])+ord(s[-1])==155*f(s[1:-1])

```

Try it online!

Takes lowercase letters as input.

*-3 bytes thanks to pxeger*
> 9 votes

# Answer
# Excel (ms365), ~~147~~, ~~111~~, ~~110~~, ~~98~~ 89 bytes

-15 bytes thanks to @jdt
-4 bytes thanks to @EngineerToast

```
=LET(l,LEN(A1),n,SEQUENCE(l/2),IF(l>1,SUMSQ(CODE(MID(A1,n,1))+CODE(RIGHT(A1,n))-155),)=0)

```

| A | B |
| --- | --- |
| A | TRUE |
| ABA | FALSE |
| ABZ | TRUE |
| ABBA | FALSE |
| BEVY | TRUE |
| GOLF | FALSE |
| ZOLA | TRUE |
| WIZARD | TRUE |
| BIGOTRY | TRUE |
| RACECAR | FALSE |
| ABCDEFGHIJKLMNOPQRSTUVWXYZ | TRUE |

Uploading a small screenshot was not possible at time of posting. Also, the byte-count is high and I'm eager to see if fellow Excel enthusiasts can bring this down.
> 8 votes

# Answer
# C (clang), ~~53~~ 44 bytes

-9 bytes thanks to c--!!!

```
f(*s,*e){return--e<=s||*s+*e==155&f(s+1,e);}

```

Try it online!
> 7 votes

# Answer
# Vyxal, ~~8~~ 7 bytes

```
Ḃ+⁺6oLṅ

```

Try it Online!

-1 thanks to a trick from @Kevin Cruijssen's 05AB1E answer.
> 7 votes

# Answer
# Raku, 37 bytes

```
{155==all .ords[^(*+>1)]Z+.flip.ords}

```

Try it online!

* `.ords` is a string method that returns a list of Unicode codepoints.
* `^(* +> 1)` is an anonymous function that returns a list of numbers from 0 to one less than the argument shifted one bit to the right. (`* div 2` would be more readable, but is longer.)
* When a list is subscripted with a function, the list's length is passed to the function, and whatever the function returns is used to index into the list. Most often this is used to index from the end of the list (eg `@list[* - 1]`) but here, the result is a slice of the first half of the list, not including the middle element, if any.
* `.flip` is a string method that returns the reverse of the original string. `.flip.ords` is thus the list of the input string's Unicode codepoints in reverse order.
* `Z+` zips the two lists of codepoints with addition, up to the length of the shorter list.
* `155 == all ...` is a junction which is truthy if all of the added codepoints are equal to 155.
> 6 votes

# Answer
# JavaScript (Node.js), 34 bytes

*-1 and a bug fixed thanks to @l4m2 (on both versions)*

Expects an array of ASCII codes. Returns *true* for non-alphadrome or *false* for alphadrome.

```
a=>a.some((_,i)=>a.pop()+a[i]-155)

```

Try it online!

---

# JavaScript (Node.js), 51 bytes

Expects a string. Returns *true* for non-alphadrome or *false* for alphadrome.

```
s=>(a=[...Buffer(s)]).some((_,i)=>a.pop()+a[i]-155)

```

Try it online!
> 5 votes

# Answer
# x86-64 machine code, 16 bytes

```
AC 83 EF 02 78 09 02 04 3E 3C 9B 74 F3 31 C0 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the string in EDI and its address in RSI, and returns a value in EAX, nonzero if and only if the string is an alphadrome.

In assembly:

```
f:  lodsb               # Load a byte from the string into AL, advancing the pointer.
    sub edi, 2          # Subtract 2 from the length in EDI.
    js e                # Jump to the end if the result is negative.
                        #  In this case, the string is an alphadrome.
                        #  AL (which is the low byte of EAX) is nonzero.
    add al, [rsi + rdi] # Add the opposite-positioned byte in the string to AL.
    cmp al, 'A'+'Z'     # Compare the sum with the sum of 'A' and 'Z'.
    je f                # Jump back, to repeat, if they are equal.
    xor eax, eax        # If not, the string is not an alphadrome. Set EAX to 0.
e:  ret                 # Return.

```
> 5 votes

# Answer
# Perl 5, 49 bytes

```
sub f{pop=~/.\K.*\B/?155-ord($`)-ord$'?0:f($&):1}

```

Try it online!
> 5 votes

# Answer
# Jelly, 8 bytes

```
+Un155SỊ

```

Try it online!

-1 thanks to Jonathan Allan
> 5 votes

# Answer
# , ~~34~~ ~~35~~ 24 bytes

*Edit: +1 byte to fix bug spotted by Kamil Drakari*
*Edit2: saved 11 bytes by changing to same approach as my Nibbles answer*

```
\(x)sum(x+rev(x)!=155)<2

```

Attempt This Online!

Input is vector of codepoints.
> 5 votes

# Answer
# Raku, 35 bytes

```
{2>grep *-155,(.ords Z+[R,] .ords)}

```

Try it online!

Anonymous code block that takes a string and returns a boolean.

# Explanation

```
{2>grep *-155,(.ords Z+[R,] .ords)}
{                                 }  # Anonymous code block
              (.ords Z           )   # Zip the codepoints of the string
                      +                # Adding them
                       [R,]            # To the reverse
                            .ords      # of the codepoints
   grep *-155,                       # From this, filter out the 155s
 2>                                  # And check if there is exactly 1 or 0 of them

```
> 5 votes

# Answer
# Fig, \\$9\log\_{256}(96)\approx\\$ 7.408 bytes

```
M'>2Lo155+$

```

Try it online!

(link includes extra code for test cases)
> 4 votes

# Answer
# Pyth, 14 bytes

```
!t-+VJCMz_J219

```

Try it online!

### Explanation:

```
     JCMz         assign input codepoints to J and return list
         _J       reverse J
   +V             map addition over two lists
  -        219    remove all instance of 219 from this list
!t                list has no more than 1 element

```
> 4 votes

# Answer
# Haskell, 54 bytes

```
f s=[1]<[1|(x,y)<-zip<*>reverse$fromEnum<$>s,x+y/=219]

```

Try it online!

Zip input with its reverse, there can be at most one pair not summing to 219, the one in the centre of an odd lengthy string.
So by yielding *1* for unbalanced pairs we must have a list less or equal than \[1\]

Saved a byte by inverting the output and using greater than \[1\]
> 4 votes

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
Count[ToCharacterCode@#//#+Reverse@#&,Except@155]<2&

Count[#+Reverse@#&@*ToCharacterCode@#,Except@155]<2&

(*   52 bytes too,using @*    diff is just "@*" and "//"    *)

```

Try it online!

**I'm new to codegolf, any suggestion will be appreciated.**

The code means, convert string to charactercode list, add it with its reversal, count number of element!=155, judge whether the number is less than 2.

one interesting thing is that, among 26 letter, there's no letter such that CharacterCode==155/2

**so this algorithm is absolutely true for input string formed from 26 upper letters**
> 4 votes

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

```
cÈ+UÔcYÃk'Û Å

```

Try it

Takes input as a lowercase string. Outputs an empty string for `true` and a non-empty string for `false`.

```
cÈ+UÔcYÃk'Û Å
cÈ            # Map the charcode of each input character through:
   UÔcY       #  Get the charcode at the same index in the input reversed
  +           #  Add them together
       Ã      # Treat the results as charcodes for a new string
        k'Û   # Remove the character "Û" whenever it appears
            Å # Remove the first remaining character if possible
              # Implicitly print the result

```
> 3 votes

# Answer
# Nibbles, 7.5 bytes (15 nibbles)

```
- 2,|!\$@+%155

```

Input is array of codepoints. All positive integers are truthy in Nibbles, zero and negative integers are falsy.

```
- 2,|!\$@+%155
     !          # zip together
      \$        # the reverse of the input
        @       # and the input
         +      # by addition,
    |           # then filter the list
                # to keep only truthy elements upon
          %155  # modulo 155,
   ,            # get the length of the resulting list,
- 2             # and subtract it from 2
                # (so only zero or one non-155 element
                # will give a truthy >0 output)

```
> 3 votes

# Answer
# Factor \+ `math.unicode`, ~~35~~ 29 bytes

```
[ halves reverse v+ ""⊂ ]

```

Try it online!

```
             ! "BIGOTRY"
halves       ! "BIG" "OTRY"
reverse      ! "BIG" "YRTO"
v+           ! { 155 155 155 }
""           ! { 155 155 155 } { 155 }   (string with non-printable char 155)
⊂           ! t     (subset?)

```
> 3 votes

# Answer
# Ruby, 44 bytes

```
f=->w{/.(.*)./!~w||w.sum-$1.sum==155&&f[$1]}

```

Try it online!
> 3 votes

# Answer
# Japt, 11 bytes

Input as an array of lowercase codepoints, outputs `false` for truthy & `true` for falsey.

```
£v +UoÃd-#Û

```

Try it (includes all test cases, footer reverses output)

```
£v +UoÃd-#Û     :Implicit input of charcode array U
£               :Map
 v              :  Remove & return first element of U
   +            :  Add
    Uo          :  Remove & return last element of U
      Ã         :End map
       d        :Any truthy
        -       :  Subtract
         #Û     :  219

```
> 3 votes

# Answer
# sed `-E`, ~~103~~ 102 bytes

*-1 byte thanks to user41805*

```
:a
s/./\L&/
y/abcdefghijklmnopqrstuvwxyz/ZYXWVUTSRQPONMLKJIGHFEDCBA/
/../!cT
T
s/^(.)(.*)\1$/\2/
ta
cF

```

Attempt This Online!
> 3 votes

# Answer
# C# (.Net 6), 73 bytes

```
int i=0;while(i<s.Length/2)if(s[i++]+s[^i]!=155)return false;return true;

```

Try it here
> 3 votes

# Answer
# 05AB1E, 7 bytes

```
ÇÂ+ƵsKg!

```

Input as a list of capital codepoint-integers (although could alternatively be in lowercase as well by changing `s` to `\`). Outputs an 05AB1E truthy result (`1`) if it's an alphadrome, and an 05AB1E falsey result (in this case any other integer) if it's not.

Try it online or verify all test cases.

**Explanation:**

```
Â        # Bifurcate the (implicit) input-list; short for Duplicate & Reverse copy
 +       # Add the values at the same positions in the lists together
  Ƶs     # Push compressed integer 155
    K    # Remove all 155 from the list
     g   # Pop and push the length
      !  # Get the factorial of this length
         # (0 becomes 1; 1 remains 1; any other integer just increases)
         # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶs` is `155` (and `Ƶ\` is `219`).
> 3 votes

# Answer
# Pip, ~~23~~ 17 bytes

*-6 bytes thanks to DLosc!*

```
#(_!=155FIg+Rg)<2

```

Try It Online!

Takes in input as a list of codepoints in the arguments. Port of the R answer, so make sure to upvote that too!

```
#(_!=155FIg+Rg)<2     ; Input = list of codepoints = g
#(            )       ; Get the length of...
          g+Rg        ; the vectorized sum of g and its reverse...
  _!=155FI            ; filtered by if each element is not equal to 155...
               <2     ; and test if the length is less than 2
                      ; (after which the result is implicitly printed out)

```
> 3 votes

# Answer
# Go, ~~104~~ 73 bytes

```
func f(s string)bool{l:=len(s)
return l<2||s[0]+s[l-1]==155&&f(s[1:l-1])}

```

Attempt This Online!

Based on @Manish Kundu's answer

* -31 bytes by @Jordan, @Steffan: Combining the `if`s into a single expression
> 2 votes

# Answer
# Retina 0.8.2, 49 bytes

```
T`L`RL`^.(.)*(?!(?<-1>.)*$)
+`^(.)(.*)\1$
$2
^.?$

```

Try it online! Link includes test cases. Explanation:

```
T`L`RL`^.(.)*(?!(?<-1>.)*$)

```

Transliterate the first half of the word, flipping between `A-Z` and `Z-A`.

```
+`^(.)(.*)\1$
$2
^.?$

```

Test whether this results in a palindrome. (This turns out to be the same method as @ovs's answer to Shortest code to determine if a string is a palindrome so I might have remembered the approach.)
> 2 votes

# Answer
# Charcoal, 15 bytes

```
⬤∕θ²⁼⌕αι⌕⮌α§⮌θκ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for an alphadrome, nothing if not. Explanation:

```
  θ             Input string
 ∕ ²            First half (excluding middle character if any)
⬤               All characters satisfy
     ⌕          Index of
       ι        Current character
      α         In predefined variable uppercase alphabet
    ⁼           Equals
        ⌕       Index of
             θ  Input string
            ⮌   Reversed
           §    Indexed by
              κ Current index
          α     In predefined variable uppercase alphabet
         ⮌      Reversed
                Implicitly print

```
> 2 votes

# Answer
# Behaviour, ~~40~~ 37 bytes

```
~(a*=ascii\:i<-#a/2a%i+a%(-i-1)~=155)

```

`a` must contain input string

```
a = "ABA"
@~(a*=ascii\:i<-#a/2a%i+a%(-i-1)~=155)

```

ungolfed and commented:

```
~(              // invert the result of the following sequence
  a *= ascii    // convert string input to a list of ascii values
  \:i <- #a/2   // iterate from 0 to half the input size
    a%i+a%(-i-1)~=155   // stop if opposites values don't sum to 155
)

```
> 2 votes

# Answer
# Julia 1.0, ~~50~~ ~~48~~ ~~44~~ 41 bytes

```
~x=sum((a=Int[x...]).+reverse(a).!=155)<2

```

Try it online!

Saved 2 bytes thanks to Sʨɠɠan's suggestion: use the return value of the variable assignment.

Saved 4 bytes thanks to amelies: replace `collect(x)` with `[x...]`.

Saved 3 bytes thanks to MarcMush: replace `Int.([x...])` with `Int[x...]`.
> 2 votes

# Answer
# \>\<\>, ~~17~~ 15 bytes

Saved 2 bytes thanks to Jo King

```
l<*=""+{$n?(3

```

Try it online

**Explanation**

```
l<                # initialize as truthy (length of the input) and reverse direction
l        n?(3     # output when the stack holds at most 1 letter (if odd)
      +{$         # add the first and unhandeled letter
   =""            # compare with 155
  *               # multiply with current truthy/false value

```
> 2 votes

# Answer
# Knight (v2), 52 bytes

```
;=tT;=n/L=pP2;W+1=n-nT=t&?155+A Gp nT A Gp--LpTnTtOt

```

Try it online!
> 1 votes

# Answer
# Desmos, 59 bytes

```
k=l.length
f(l)=∏_{n=1}^{k/2-.5}0^{(155-l[n]-l[k-n+1])^2}

```

Try It On Desmos!

Try It On Desmos! - Prettified

Takes in a list of codepoints because Desmos doesn't support strings.
> 1 votes

# Answer
# jq, 54 bytes

Using recursion (54 bytes)

```
def f:length<2or(.[1:-1]|f)and.[0]+last==155;explode|f

```

Try it online!

Using mappings (55 bytes)

```
explode|[.,reverse]|[transpose[]|add==155,true]|sort[1]

```

Try it online!
> 1 votes

# Answer
# Pushy, 16 bytes

```
L2/:{+v;O155K=P#

```

Try it online!

```
L2/:                 \ floor(length/2) times do:
    {                \    Cyclic shift the stack left
     +               \    Add the top two items
      v;             \    More the result to the second stack.
        O            \ Go to the second stack
         155         \ Push 155
            K=       \ Check equality in place, replacing every stack element with 0 or 1
              P#     \ Print the product of these

```
> 1 votes

# Answer
# C (101 bytes)

```
a;main(z,s)char**s;{int l=strlen(s[1])-1;while(l/2>a)if(s[1][a]-65^90-s[1][l-a++])exit(0);puts("1");}

```
> 1 votes

# Answer
# Thunno 2, 6 bytes

```
Ḳ+ṇ6oḣ

```

Try it online!

Output with inverted booleans. Add the `!` flag to take the logical NOT.

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
Ḳ+ṇ6oḣ  # Implicit input
Ḳ+      # Bifurcate and add
  ṇ6o   # Remove 155s
     ḣ  # Remove the first item
        # Implicit output

```
> 1 votes

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


title: Chunky vs. Smooth Strings

text:
# Question
Title: Chunky vs. Smooth Strings
Consider a string of length N, such as `Peanut Butter` with N = 13. Notice that there are N-1 pairs of neighboring characters in the string. For `Peanut Butter`, the first of the 12 pairs is `Pe`, the second is `ea`, the last is `er`.

When the pairs are mostly different characters, the string has a chunky quality, e.g. `chUnky`.
When these pairs are mostly the same character, the string has a smooth quality, e.g. `sssmmsss`.

Define the *chunkiness* of a string to be the ratio of the number of pairs with two different characters to the total number of pairs (N-1).

Define the *smoothness* of a string to be the ratio of the number of pairs with two identical characters to the total number of pairs (N-1).

For example, `Peanut Butter` only has one pair with identical characters (`tt`), so its smoothness is 1/12 or 0.0833 and its chunkiness is 11/12 or 0.9167.

**Empty strings and strings with only one character are defined to be 100% smooth and 0% chunky.**

## Challenge

Write a program that takes in a string of arbitrary length and outputs either its chunkiness or smoothness ratio as a floating point value.

* Take input via stdin or the command line, or you may write a function that takes a string.
* You can assume the input string only contains printable ASCII characters (and hence is single-line).
* Print the float to stdout to 4 or more decimal places, or you can choose to return it if you wrote a function. Decimal places that convey no information are not required, e.g. `0` is fine instead of `0.0000`.
* Choose chunkiness or smoothness as you prefer. Just be sure to say which one your program outputs.

**The shortest code in bytes wins.**

## Examples

`Peanut Butter` → Chunkiness: `0.91666666666`, Smoothness: `0.08333333333`
`chUnky` → Chunkiness: `1.0`, Smoothness: `0.0`
`sssmmsss` → Chunkiness: `0.28571428571`, Smoothness: `0.71428571428`
`999` → Chunkiness: `0.0`, Smoothness: `1.0`
`AA` → Chunkiness: `0.0`, Smoothness: `1.0`
`Aa` → Chunkiness: `1.0`, Smoothness: `0.0`
`!` → Chunkiness: `0.0`, Smoothness: `1.0`
\[empty string\] → Chunkiness: `0.0`, Smoothness: `1.0`

*Bonus question: Which do you prefer chunky or smooth strings*

# Answer
> 7 votes
# APL, 10 bytes

This reads input from stdin and prints the chunkiness to stdout. The algorithm is the same one used for the J solution.

```
(+/÷⍴)2≠/⍞

```

# Answer
> 19 votes
# CJam, 19 bytes

```
q_1>_@.=:!1b\,d/4mO

```

100% chunky source code that calculates **chunkiness**.

Try this chunky goodness online.

### How it works

```
q_                  e# Read from STDIN and push a copy.
  1>_               e# Discard the first character and push a copy.
     @              e# Rotate the original on top.
      .=            e# Vectorized comparison (1 if equal, 0 if not).
        :!          e# Mapped logical NOT (0 if equal, 1 if not).
          1b        e# Base 1 conversion (sum).
            \,      e# Swap with the shortened string and push its length.
              d/    e# Cast to double and divide.
                4mO e# Round to four decimal places.

```

Obviously, NaN rounded to 4 decimal places is 0.

# Answer
> 13 votes
# Pyth, ~~13~~ 12 bytes

```
csJnVztz|lJ1

```

Fully chunky code calculating chunkiness.

Demonstration. Test harness.

```
csJnVztz|lJ1
                 Implicit: z = input()
   nV            n, !=, vectorized over
     z           z
      tz         z[:-1]
                 V implitly truncates.
  J              Store it in J.
 s               sum J
c                floating point divided by
         |       logical or
          lJ     len(J)
            1    1

```

# Answer
> 8 votes
# TI-BASIC, 46 bytes

```
Input Str1
If 2≤length(Str1
mean(seq(sub(Str1,X,1)=sub(Str1,X-1,1),X,2,length(Str1
Ans

```

`sub(x1,x2,x3` gives the substring of string `x1` starting (one-based) at number `x2` and ending at number `x3`, then `seq(` builds a sequence.

Gives the smoothness value. The `Ans` variable is `0` by default, so we don't need an `Else` to the `If` statement, or to store anything to `Ans` beforehand.

# Answer
> 7 votes
## Matlab (~~37~~ 36 bytes)

This can be done with the following anonymous function, which returns chunkiness:

```
f=@(x)nnz(diff(x))/max(numel(x)-1,1)

```

Comments:

* In old Matlab versions (such as R2010b) you need `+` to cast the char array `x` to a double array:

```
f=@(x)nnz(diff(+x))/max(numel(x)-1,1)`

```

But that's not the case in recent versions (tested in R2014b), which saves one byte. Thanks to Jonas for his comment.
* The expression with `max` handles the one-character and zero-character cases (for chunkiness)

Example:

```
>> f=@(x)nnz(diff(x))/max(numel(x)-1,1)
f =
    @(x)nnz(diff(x))/max(numel(x)-1,1)

>> f('Peanut Butter')
ans =
   0.9167

```

# Answer
> 6 votes
# \>\<\>, ~~40~~ 36 bytes

```
00ii:0(?v:@=1$-{+{1+}}20.
~:0=+,n;>~

```

This program returns the chunkiness of a string.

## Explanation

```
00i         Push 0 (# unequal pairs), 0 (length of string - 1) and read first char

[main loop]

i           Read a char
:0(?v       If we've hit EOF, go down a row
:@=1$-      Check (new char != previous char)
{+          Add to unequal pairs count
{1+         Increment length by 1
}}20.       Continue loop

[output]

~~          Pop last two chars (top one will be -1 for EOF)
:0=+        Add 1 to length if zero (to prevent division by zero errors)
,           Divide, giving chunkiness
n;          Output and halt

```

---

## Previous submission (37 + 3 = 40 bytes)

```
l1)?v1n;
n,$&\l1-}0& \;
l2(?^$:@=&+&>

```

This program returns the smoothness of a string. Input is via the `-s` flag, e.g.

```
py -3 fish.py chunkiness.fish -s "Peanut Butter"

```

# Answer
> 6 votes
## **C#, ~~94~~ 89 bytes**

Sub 100 bytes, so I guess that's some form of victory in itself?

This is a function definition (allowed as per the spec) which returns the **smoothness** of the input string:

```
Func<string,float>(s=>s.Length>1?s.Zip(s.Skip(1),(a,b)=>a==b?1f:0).Sum()/(s.Length-1):1);

```

Pretty straightforward, if the length is 0 or 1 it returns 1, otherwise it compares the string to itself less the first character, then returns the number of identical pairs divided by the number of pairs.

*Edit - replaced Substring with Skip. Rookie mistake!*

# Answer
> 5 votes
## J, ~~14~~ 13 bytes

Computes the chunkiness. Kudos to J for defining `0 % 0` to be equal to 0.

```
(]+/%#)2~:/\]

```

Try it online

Here is an explanation:

```
   NB. sample input
   in =. 'sssmmsss'

   NB. all infixes of length 2
   2 ]\ in
ss
ss
sm
mm
ms
ss
ss

    NB. are the parts of the infix different?
    2 ~:/\ in
0 0 1 0 1 0 0

    NB. sum and item count of the previous result
    (+/ , #) 2 ~:/\ in
2 7

    NB. arithmetic mean: chunkiness
    (+/ % #) 2 ~:/\ in
0.285714

    NB. as a tacit verb
    (] +/ % #) 2 ~:/\ ]

    NB. 0 divided by 0 is 0 in J
    0 % 0
0

```

# Answer
> 4 votes
## CJam, 23 bytes

```
q_,Y<SS+@?2ew_::=:+\,d/

```

Explanation:

```
q                           e# read input
 _,                         e# its length
   Y<                       e# is less than 2?
     SS+                    e# then a smooth string
        @?                  e# otherwise the input
          2ew               e# pairs of consecutive characters
             _::=           e# map to 1 if equal, 0 if not
                 :+         e# sum (number of equal pairs)
                   \,       e# total number of pairs
                     d/     e# divide

```

This outputs the smoothness ratio.

# Answer
> 4 votes
# CJam, 16 bytes

```
1q2ew::=_:+\,d/*

```

Cheaty source code that calculates **smoothness**.

For inputs of length 0 or 1, this prints the correct result before exiting with an error. With the Java interpreter, error output goes to STDERR (as it should).

If you try the code online, just ignore everything but the last line of output.

### How it works

```
1q               e# Push a 1 and read from STDIN.
  2ew            e# Push the overlapping slices of length 2.
                 e# This will throw an error for strings of length 0 or 1,
                 e# so the stack (1) is printed and the program finishes.
     ::=         e# Twofold vectorized comparision.
        _:+      e# Push a copy and add the Booleans.
           \,    e# Swap with the original and compute its length.
             d/  e# Cast to double and divide.
               * e# Multiply with the 1 on the bottom of the stack.

```

# Answer
> 3 votes
# Nim, ~~105~~ ~~96~~ 91 bytes

```
proc f(s):any=
 var a=0;for i,c in s[.. ^2]:a+=int(s[i+1]!=c)
 a.float/max(s.len-1,1).float

```

Trying to learn Nim. This calculates the chunkiness of a string.

<sup>*(~~If I try to read this as Python the indentation looks all messed up...~~ Now it looks more like Ruby...)*</sup>

# Answer
> 3 votes
# Julia, 52 bytes

Smoothness!

```
s->(n=length(s))<2?1:mean([s[i]==s[i+1]for i=1:n-1])

```

This creates an unnamed function that accepts a string and returns a numeric value.

If the length of the input is less than 2, the smoothness is 1, otherwise we calculate the proportion of identical adjacent characters by taking the mean of an array of logicals.

# Answer
> 3 votes
# Python 3, 63 Bytes

This is an anonymous lambda function which takes a string as the argument, and returns it's chunkiness.

```
lambda n:~-len(n)and sum(x!=y for x,y in zip(n,n[1:]))/~-len(n)

```

To use it, give it a name and call it.

```
f=lambda n:~-len(n)and sum(x!=y for x,y in zip(n,n[1:]))/~-len(n)
f("Peanut Butter") -> 0.08333333333333333
f("!")             -> 0
f("")              -> -0.0

```

# Answer
> 3 votes
# Python 3, 52 bytes

```
lambda s:sum(map(str.__ne__,s,s[1:]))/(len(s)-1or 1)

```

This calculates chunkiness, and outputs `-0.0` for the empty string. If don't like negative zeroes you can always fix that with an extra byte:

```
lambda s:sum(map(str.__ne__,s,s[1:]))/max(len(s)-1,1)

```

# Answer
> 2 votes
# Haskell, 64 bytes

```
f[]=1
f[_]=1
f x=sum[1|(a,b)<-zip=<<tail$x,a==b]/(sum(x>>[1])-1)

```

Outputs smoothness. e.g. `f "Peanut Butter"` -\> `8.333333333333333e-2`.

How it works:

```
f[]=1                               -- special case: empty list
f[_]=1                              -- special case: one element list

f x=                                -- x has at least two elements
         (a,b)<-zip=<<tail$x        -- for every pair (a,b), drawn from zipping x with the tail of itself
                            ,a==b   -- where a equals b
      [1|                        ]  -- take a 1
   sum                              -- and sum it
              /                     -- divide  by
                   (x>>[1])         -- map each element of x to 1
               sum                  -- sum it
                           -1       -- and subtract 1

```

`sum(x>>[1])` is the length of x, but because Haskell's strong type system requires to feed fractionals to `/`, I can't use `length` which returns integers. Converting integers to fractionals via `fromInteger$length x` is far too long.

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

### Smoothness, 56 bytes

```
f=x=>(z=x.match(/(.)(?=\1)/g))?z.length/--x.length:+!x[1]

```

### Chunkiness, 55 bytes

```
f=x=>(z=x.match(/(.)(?!\1)/g))&&--z.length/--x.length||0

```

### Demo

Calculates smoothness, as that is what I prefer. Only works in Firefox for now, as it is ES6.

```
f=x=>(z=x.match(/(.)(?=\1)/g))?z.length/--x.length:+!x[1]

O.innerHTML += f('Peanut Butter') + '\n';
O.innerHTML += f('chUnky') + '\n';
O.innerHTML += f('sssmmsss') + '\n';
O.innerHTML += f('999') + '\n';
O.innerHTML += f('AA') + '\n';
O.innerHTML += f('Aa') + '\n';
O.innerHTML += f('!') + '\n';
O.innerHTML += f('') + '\n';
```

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

# Answer
> 2 votes
# Ruby, ~~69~~ 66 bytes

```
->s{(c=s.chars.each_cons(2).count{|x,y|x!=y}.to_f/~-s.size)>0?c:0}

```

Try it online!

Shaved of a few bytes with comments from IMP. Also, with the upcoming version 2.7.0 of Ruby it's possible to save some bytes by replacing `|x,y|x!=y` with `@1!=@2`

# Answer
> 2 votes
# KDB(Q), 30

Returns smoothness.

```
{1^sum[x]%count x:1_(=':)(),x}

```

# Explanation

```
                         (),x    / ensure input is always list
                x:1_(=':)        / check equalness to prev char and reassign to x
   sum[x]%count                  / sum equalness divide by count N-1
 1^                              / fill null with 1 since empty/single char will result in null
{                             }  / lamdba

```

# Test

```
q){1^sum[x]%count x}1_(=':)(),x}"Peanut Butter"
0.08333333
q){1^sum[x]%count x:1_(=':)(),x}"sssmmsss"
0.7142857
q){1^sum[x]%count x:1_(=':)(),x}"Aa"
0f
q){1^sum[x]%count x:1_(=':)(),x}"aa"
1f
q){1^sum[x]%count x:1_(=':)(),x}"chUnky"
0f
q){1^sum[x]%count x:1_(=':)(),x}"!"
1f
q){1^sum[x]%count x:1_(=':)(),x}""
1f

```

# Answer
> 1 votes
# Python 3, 69 bytes

No one has posted a Python solution yet, so here's a fairly straightforward implementation of a "chunkiness" function. It short-circuits on a string of length `1`, and prints `0` (which is an integer rather than a float but seems to be allowed according to the rules).

On an empty string, it outputs `-0.0` rather than `0.0`. Arguably this is could be considered acceptable, as `-0.0 == 0 == 0.0` returns `True`.

```
def c(s):l=len(s)-1;return l and sum(s[i]!=s[i+1]for i in range(l))/l

```

Examples:

```
>>> c(''); c('a'); c('aaa'); c("Peanut Butter")
-0.0
0
0.0
0.916666666667
>>> -0.0 == 0 == 0.0
True

```

(Python 3 is used for its default float division.)

# Answer
> 1 votes
# C, 83 bytes

```
float f(char*s){int a=0,b=0;if(*s)while(s[++a])b+=s[a]!=s[a-1];return--a?1.*b/a:b;}

```

A function returning **chunkiness**.

### Explanation

```
float f(char *s) {

```

Accept a C string, and return a float (double would work but is more chars).

```
int a=0, b=0;

```

Counters - `a` for total pairs, `b` for non-matching pairs. Using `int` limits the "arbitrary length" of the string, but that's only a minor violation of the requirements and I'm not going to fix it.

```
if (*s)

```

Special case the empty string - leave both counters zero.

```
    while (s[++a])

```

Non-empty string - iterate through it with pre-increment (so first time through the loop, `s[a]` will be the second character. If the string has only one character, the loop body will not be entered, and `a` will be 1.

```
        b += s[a]!=s[a-1];

```

If the current character differs from the previous, increment `b`.

```
return --a ? 1.*b/a : b;
}

```

After the loop, there are three possibilities: 'a==0,b==0' for an empty input, 'a==1,b==0' for a single-character input or 'a\>1,b\>=0' for multi-character input. We subtract 1 from `a` (the `?` operator is a sequence point, so we're safe), and if it's zero, we have the second case, so should return zero. Otherwise, `b/a` is what we want, but we must promote `b` to a floating-point type first or we'll get integer division. For an empty string, we'll end up with a negative zero, but the rules don't disallow that.

### Tests:

```
#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv)
        printf("%.6f %s\n", f(*argv), *argv);
}

```

Which gives:

```
./chunky 'Peanut Butter' chUnky sssmmsss 999 AA Aa '!' ''
0.916667 Peanut Butter
1.000000 chUnky
0.285714 sssmmsss
0.000000 999
0.000000 AA
1.000000 Aa
0.000000 !
-0.000000

```

as required.

# Answer
> 1 votes
# Perl, 69

Function returning **smoothness**:

```
sub f{($_)=@_;$s=s/(.)(?!\1)//sgr;chop;!$_||length($s)/length;}

```

### Explanation

```
sub f {
    # read argument into $_
    ($_) = @_;

    # copy $_ to $s, removing any char not followed by itself
    # /s to handle newlines as all other characters
    $s = s/(.)(?!\1)//sgr;

     # reduce length by one (unless empty)
    chop;

    # $_ is empty (false) if length was 0 or 1
    # return 1 in that case, else number of pairs / new length
    !$_ || length($s)/length;
}

```

### Tests

```
printf "%.6f %s\n", f($a=$_), $a foreach (@ARGV);

0.083333 Peanut Butter
0.000000 chUnky
0.714286 sssmmsss
1.000000 999
1.000000 AA
0.000000 Aa
1.000000 !
1.000000

```

# Answer
> 1 votes
## Mathematica, ~~73~~ 72 bytes

This doesn't win anything for size, but it's straightforward:

Smoothness

```
N@Count[Differences@#,_Plus]/(Length@#-1)&@StringSplit[#,""]&

In[177]:= N@Count[Differences@#,_Plus]/(Length@#-1)&@StringSplit[#,""] &@"sssmmsss"

Out[177]= 0.285714

```

# Answer
> 1 votes
# Ruby, 63 Bytes

Outputs chunkiness.

`f=->s{s.chars.each_cons(2).count{|x,y|x!=y}/[s.size-1.0,1].max}`

Similar to @daniero's solution, but slightly shortened by directly dividing by the string length - 1 and then relying on .count to be zero with length 0 & 1 strings (the .max ensures I won't divide by 0 or -1).

# Answer
> 1 votes
# GeL: ~~76~~ 73 characters

Smoothness.

```
@set{d;0}
?\P$1=@incr{d}
?=
\Z=@lua{c=@column -1\;return c<1and 1or $d/c}

```

Sample run:

```
bash-4.3$ for i in 'Peanut Butter' 'chUnky' 'sssmmsss' '999' 'AA' 'Aa' '!' ''; do
>     echo -n "$i -> "
>     echo -n "$i" | gel -f smooth.gel
>     echo
> done
Peanut Butter -> 0.083333333333333
chUnky -> 0
sssmmsss -> 0.71428571428571
999 -> 1
AA -> 1
Aa -> 0
! -> 1
 -> 1

```

(GeL = Gema + Lua bindings. Much better, but still far from winning.)

# Gema: ~~123~~ 120 characters

Smoothness.

```
@set{d;0}
?\P$1=@incr{d}
?=
\Z=@subst{\?\*=\?.\*;@cmpn{@column;1;10;10;@fill-right{00000;@div{$d0000;@sub{@column;1}}}}}

```

Sample run:

```
bash-4.3$ for i in 'Peanut Butter' 'chUnky' 'sssmmsss' '999' 'AA' 'Aa' '!' ''; do
>     echo -n "$i -> "
>     echo -n "$i" | gema -f smooth.gema
>     echo
> done
Peanut Butter -> 0.0833
chUnky -> 0.0000
sssmmsss -> 0.7142
999 -> 1.0000
AA -> 1.0000
Aa -> 0.0000
! -> 1.0
 -> 1.0

```

(Was more an exercise for myself to see what are the chances to solve it in a language without floating point number support and generally painful arithmetic support. The 2nd line, especially the `\P` sequence, is pure magic, the last line is real torture.)

# Answer
> 1 votes
# Java 8, ~~84~~ 82 bytes

```
s->{float l=s.length()-1,S=s.split("(.)(?=\\1)").length-1;return l<1?1:S<1?0:S/l;}

```

Outputs Smoothness.

Try it online.

**Explanation:**

```
s->{                     // Method with String parameter and float return-type
  float l=s.length()-1,  //  Length of the input-String minus 1 (amount of pairs in total)
        S=s.split("(.)(?=\\1)").length-1;
                         //  Length of the input split by duplicated pairs (with lookahead)
  return l<1?            //  If the length of the input is either 0 or 1:
          1              //   Return 1
         :S<1?           //  Else-if `S` is -1 or 0:
          0              //   Return 0
         :               //  Else:
          S/l;}          //   Return duplicated pairs divided by the length-1

```

# Answer
> 1 votes
# Coconut, 38 bytes

```
s->sum(map((!=),s,s[1:]))/-~len(s[2:])

```

Try it online!

A Python 3 port would be 50 bytes.

# Answer
> 0 votes
## PowerShell, 55 bytes

Smoothness

```
%{$s=$_;@([char[]]$s|?{$_-eq$a;$a=$_;$i++}).count/--$i}

```

Seems a little bit silly to get a variable in stdin and then give it an identifier, but its quicker than having a function.

# Answer
> 0 votes
# Python 3, 61 Bytes

calculate chunkiness:

```
f=lambda s: sum(a!=b for a,b in zip(s,s[1:]))/max(len(s)-1,1)

```

# Answer
> 0 votes
# K (22)

tweaked WooiKent's Q solution:

```
{1^(+/x)%#x:1_=':(),x}

```

# Answer
> 0 votes
# Mathematica, 107 bytes

Calculates chunkiness by taking half of the Levenshtein distance between each digraph and its reverse.

```
f[s_]:=.5EditDistance@@{#,StringReverse@#}&/@StringCases[s,_~Repeated~{2},Overlaps->All]//Total@#/Length[#]&

```

If you'd prefer an exact rational answer, delete `.5` and place a `/2` before the last `&` for no penalty. The program itself has chunkiness 103/106, or about .972.

# Answer
> 0 votes
# K5, 24 bytes

```
{(r;1)@^r:(#&=':x)%#1_x}

```

Calculates smoothness. Seems to use a very different algorithm from K/Q/J/APL answers.

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

```
=ƝÆm
 Ɲ   // For all pairs of neighbouring elements,
=    // return 1 if they're equal, 0 otherwise.
  Æm // Take the arithmetic mean of the resulting list.

```

Computes smoothness.
Cut off three bytes thanks to Dennis.

Try it online!

# Answer
> 0 votes
# Forth (gforth), 92 bytes

```
: f 1e dup 1 > if 1- dup s>f 0e 0 do dup i + dup 1+ c@ swap c@ = s>f f- loop fswap f/ then ;

```

Try it online!

Takes in a string (as the Forth standard combo of address and length) and returns the smoothness. Result is placed on the floating point stack

## Explanation

```
1e                \ places 1 on the floating point stack, to use as a "default" value
dup 1 > if        \ duplicates the length of the string and checks if it's greater than 1
   1- dup s>f     \ subtract 1 from length and copy it to the floating point stack
   0e             \ places 0 on the floating point stack
   0 do           \ sets up a loop from 0 to length - 1
      dup i +     \ get the current character's address by adding index to string start
      dup 1+      \ copy address and add 1 to get the next character's address
      c@ swap c@  \ get the character at each of the addresses
      = s>f       \ compare the two characters and move to the floating point stack
      f-          \ subtract result from counter (true in Forth defaults to -1)
   loop           \ end the loop
   fswap f/       \ swap the counter and the total and divide to get result
then              \ end the loop

```

# Answer
> 0 votes
# JavaScript, 46/47 bytes

```
f=x=>[...x].map(c=>n+=c!=x[L++],n=L=-1)|L>0&&n/L

f=x=>[...x].map(c=>n+=c==x[++L],n=L=0)|L<2||n/--L

```

# Answer
> 0 votes
# F# (.NET Core), 100 bytes

Whew, exactly 100 bytes. Too bad it's a bit verbose, I want to get it below 100. Determines **chunkiness**.

```
fun s->Seq.pairwise s|>fun s->Seq.sumBy(fun(x,y)->if x=y then 0. else 1.)s/float(max(Seq.length s)1)

```

Try it online!

# Answer
> 0 votes
# Kotlin, 52 bytes

Chunkiness:

```
{it.zipWithNext().count{(f,n)->f!=n}/(it.length-1f)}

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 7 bytes

```
ḣZ€Uḷḅm

```

Try it online!

Outputs smoothness. Change  to `1Q` for chunkiness.

#### Explanation

```
ḣZ€Uḷḅm  # Implicit input
ḣZ       # Get the overlapping pairs
  €U     # Uniquify each pair of characters
    ḷḅ   # Does the length of each equal one?
      m  # Take the mean of the list
         # Implicit output

```

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


title: Running second maximum of a list

text:
# Question
Title: Running second maximum of a list
Given a list of integers, your task is to output the second largest value in the first *k* elements, for each *k* between 2 and the length of the input list.

In other words, output the second largest value for each prefix of the input.

You can output an arbitrary value for the first element (where *k* = 1), or simply omit this value, as there isn't a second maximum for a list of 1 element. You may assume there are at least 2 elements in the input.

Shortest code wins.

## Examples

```
Input:
1 5 2 3 5 9 5 8
Output:
  1 2 3 5 5 5 8
Input:
1 1 2 2 3 3 4
Output:
  1 1 2 2 3 3
Input:
2 1 0 -1 0 1 2
Output:
  1 1 1 1 1 2

```

# Answer
> 6 votes
# 05AB1E, 5 bytes

```
ηεà\à

```

Try it online!

Returns `[]` (arbitrary value) for first.

# Answer
> 6 votes
# Husk, ~~9~~ 7 bytes

Saved a byte or two thanks to @Zgarb

```
mȯ→hOtḣ

```

Returns `0` for the first "second maximum"

### Explaination

```
         -- implicit input, e.g          [1,5,3,6]
      ḣ  -- prefixes                     [[],[1],[1,5],[1,5,3],[1,5,3,6]]
     t   -- remove the first element     [[1],[1,5],[1,5,3],[1,5,3,6]]
mȯ       -- map the composition of 3 functions
    O    --   sort                       [[1],[1,5],[1,3,5],[1,3,5,6]]
   h     --   drop the last element      [[],[1],[1,3],[1,3,5]
  →      --   return the last element    [0,1,3,5]
         -- implicit output

```

Try it online!

# Answer
> 4 votes
# Python 2, 54 bytes

```
lambda x:[sorted(x[:i])[-2]for i in range(2,1+len(x))]

```

Try it online!

# Answer
> 4 votes
# Nekomata, 4 bytes

```
poil

```

Attempt This Online!

```
p     Prefix
 o    Sort
  i   Init (remove the last element)
   l  Last

```

Accidentally, poil means hair in French.

# Answer
> 3 votes
## JavaScript (ES6), ~~58~~ ~~51~~ 50 bytes

*Saved 1 byte thanks to @Neil*

Appends `undefined` for ***k = 1***.

```
a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[])

```

### Test cases

*NB: This snippet uses `JSON.stringify()` for readability, which -- as a side effect -- converts `undefined` to `null`.*

```
let f =

a=>a.map(e=>(b=[e,...b]).sort((a,b)=>b-a)[1],b=[])

console.log(JSON.stringify(f([1, 5, 2, 3, 5, 9, 5, 8]))) // 1 2 3 5 5 5 8
console.log(JSON.stringify(f([1, 1, 2, 2, 3, 3, 4])))    // 1 1 2 2 3 3
console.log(JSON.stringify(f([2, 1, 0, -1, 0, 1, 2])))   // 1 1 1 1 1 2
```

# Answer
> 3 votes
# Python 2, 45 bytes

```
f=lambda l:l[1:]and f(l[:-1])+[sorted(l)[-2]]

```

Try it online!

The right side of the code is self-explanatory. However, what do we put to the left of the `and`? Because we are concatenating parts of a list recursively, we need the left side to be truthy if `l` has 2 or more elements, and an empty list otherwise. `l[1:]` satisfies this criterion nicely.

# Answer
> 2 votes
# Jelly, 8 bytes

```
ḣJṢ€Ṗ€Ṫ€

```

Try it online!

The first value will be 0, always, and the following numbers will be the second maximums of each prefix.

## Explanation

```
ḣJṢ€Ṗ€Ṫ€  Input: array A
 J        Enumerate indices, [1, 2, ..., len(A)]
ḣ         Head, get that many values from the start for each, forms the prefixes
  Ṣ€      Sort each
    Ṗ€    Pop each, removes the maximum
      Ṫ€  Tail each

```

# Answer
> 2 votes
# Pyth, 8 bytes

```
m@Sd_2._

```

**Try it online!** or **Try the Test Suite!**

---

# How?

This outputs the first element of the list as the first value in the list, as per the spec *You can output an arbitrary value for the first element*.

```
m@Sd_2._   - Full program with implicit input.

m     ._Q  - Map over the prefixes of the input with a variable d.
  Sd       - Sorts the current prefix.
 @         - Gets the element...
    _2       - At index - 2 (the second highest).
           - Print implicitly.

```

# Answer
> 2 votes
# Java (OpenJDK 8), ~~87~~ 86 bytes

```
a->{int x,y=x=1<<-1;for(int c:a){if((c>x?x=c:c)>y){x=y;y=c;}System.out.print(x+" ");}}

```

Try it online!

# Answer
> 2 votes
# J, 13 bytes

```
_2&{@/:~ ::#\

```

Try it online! The first element is always 1.

# Explanation

```
_2&{@/:~ ::#\
            \  Apply to prefixes
_2&{@/:~        Sort and take second-to-last atom
     /:~         Sort upwards
_2 {             Take second-to-last atom
         ::     If there's an error (i.e only one atom)
           #     Return the length of the list (1)

```

The space matters.

# Answer
> 2 votes
# Jelly, 5 bytes

```
Ṣ-ịƊƤ

```

Try it online!

Outputs the first value of the input as the first value in the output. This can be removed for adding one byte.

## How it works

```
Ṣ-ịƊƤ - Main link. Takes l on the left
    Ƥ - Generate the prefixes of l
   Ɗ  - Run the following code over each prefix:
Ṣ     -   Sort the prefix
 -ị   -   Take the -1th index.
      -     Jelly lists are 1 indexed and modular. This means that the 0th index of a list is the final element and -1 the second to last element

```

# Answer
> 2 votes
# Scala, <sup>~~58~~</sup> 46 bytes

```
x=>2 to x.size map(x take _ sortBy(-_)apply 1)

```

Try it online!

Takes a List as an argument, and returns a Vector.

-12 bytes from user.

# Answer
> 2 votes
# Zsh, 32 bytes

```
for x;a+=($x)&&<<<${${(On)a}[2]}

```

Try it online!

Reverse `O`rder `n`umerically, `<<<` print the `[2]`nd element.

# Answer
> 2 votes
# Desmos, 44 bytes

```
f(x)=[x[1...i].sort[i-1]fori=[2...x.length]]

```

Try it on Desmos!

# Answer
> 2 votes
# Thunno 2, 5 bytes

```
ƒıṠṫt

```

Try it online!

Uses `[]` as the (arbitrary) first value.

#### Explanation

```
ƒıṠṫt  # Implicit input
ƒ      # Prefixes of the input
 ı     # Map over this list:
  Ṡ    #  Sort this list
   ṫt  #  Second-last item
       # Implicit output

```

# Answer
> 1 votes
# Ohm, ~~10~~ 8 bytes

*-2 bytes thanks to ETHproductions.*

```
∙p»îS2~ª

```

Try it online!

~~Uh, this is odd but I don't know how else to push a negative number...~~ I don't *really* know Ohm. :P

# Answer
> 1 votes
# CJam, 16 bytes

```
{_,,:)\f{<$-2=}}

```

Try it online!

Returns first element for first.

-2 thanks to Challenger5.

# Answer
> 1 votes
# C# (Mono), 81 bytes

```
using System.Linq;a=>a.Select((_,i)=>a.Take(++i).OrderBy(n=>n).Skip(i-2).First())

```

Try it online!

# Answer
> 1 votes
# Japt, ~~12~~ 10 bytes

The output array consists of the first element in the input array followed by the desired sequence.

```
£¯YÄ n< g1

```

Test it

---

## Explanation

Implicit input of array `U`.

```
£

```

Map over `U`, where `Y` is the current index.

```
¯YÄ

```

Slice `U` from `0` to `Y+1`.

```
n<

```

Sort descending.

```
g1

```

Get the second element.

Implicitly output the resulting array.

# Answer
> 1 votes
# Brachylog, 10 bytes

```
a₀ᶠb{okt}ᵐ

```

Try it online!

# Answer
> 1 votes
# , 54 49 bytes

Thanks to Giuseppe -5 bytes. I did not know this feature of `seq()`.

```
for(i in seq(x<-scan()))cat(sort(x[1:i],T)[2],"")

```

Try it online!

# Answer
> 1 votes
## Batch, 123 bytes

```
@set/af=s=%1
@for %%n in (%*)do @call:c %%n
@exit/b
:c
@if %1 gtr %s% set s=%1
@if %1 gtr %f% set/as=f,f=%1
@echo %s%

```

# Answer
> 1 votes
# APL (Dyalog), 15 bytes

```
(2⊃⍒⊃¨⊂)¨1↓,\∘⊢

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 5 bytes

Found another 5-byter, *very* different from Erik's solution. The arbitrary value is the first element of the list.

```
ηε{Áθ

```

Try it online!

---

# Explanation

```
ηε{Áθ  - Full program that reads implicitly from STDIN and outputs to STDOUT.

η      - Push the Prefixes of the list.
 ε     - Apply to each element (each prefix):
  {      - Sort the prefix list.
   Á     - Shift the list to the right by 1, such that the first element goes to the
           beginning  and the second largest one becomes the last.
    θ    - Get the last element (i.e. the second largest)
         - Print implicitly.

```

---

Let's take an example, to make it easier to understand.

* First we get the implicit input, let's say it's `[1, 5, 2, 3, 5, 9, 5, 8]`.
* Then, we push its prefixes using `η` \- `[[1], [1, 5], [1, 5, 2], [1, 5, 2, 3], [1, 5, 2, 3, 5], [1, 5, 2, 3, 5, 9], [1, 5, 2, 3, 5, 9, 5], [1, 5, 2, 3, 5, 9, 5, 8]]`.
* Now, the code maps through the list and sorts each prefix using `{` \- `[[1], [1, 5], [1, 2, 5], [1, 2, 3, 5], [1, 2, 3, 5, 5], [1, 2, 3, 5, 5, 9], [1, 2, 3, 5, 5, 5, 9], [1, 2, 3, 5, 5, 5, 8, 9]]`.
* We then take the very last element and move it to the beginning: `[[1], [5, 1], [5, 1, 2], [5, 1, 2, 3], [5, 1, 2, 3, 5], [9, 1, 2, 3, 5, 5], [9, 1, 2, 3, 5, 5, 5], [9, 1, 2, 3, 5, 5, 5, 8]]`.
* Of course, now the code gets the last element of each sublist using `θ` \- `[1, 1, 2, 3, 5, 5, 5, 8]` (the first one being the arbitrary value.

# Answer
> 1 votes
# MATL, ~~19~~ 10 bytes

*Thanks to Luis Mendo for shaving off 9 bytes!*

```
"GX@:)SP2)

```

Try it here.

### Explanation

```
"GX@:)SP2)
"                  for all the values in the input
 G                 get input
  X@:)             get values up to the iteration
      SP           sort it in descending order
        2)         get the second value
                   implicit end of loop and output

```

# Answer
> 1 votes
# , 13 bytes

```
{x(>x)1}'1_,\

```

Try it online!

```
           ,\ /sublists of increasing lengths (scan concat)
         1_   /remove the first sublist
{      }'     /for each sublist:
  (>x)        /    indices to permute sublist into largest to smallest
      1       /    get second index
 x            /    get sublist[that index]

```

# Answer
> 1 votes
# Factor \+ `grouping.extras`, 41 bytes

```
[ head-clump rest [ 1 kth-largest ] map ]

```

Try it online!

* `head-clump rest` Prefixes without the first
* `[ 1 kth-largest ] map` Map each to the second-largest element

# Answer
> 1 votes
# Arturo, ~~45~~ 44 bytes

```
$->a->map..2size a=>[last chop sort take a&]

```

Try it

```
$->a->                  ; a function taking an argument a
    map..2size a => [   ; map over the indices of a sans the first few
        last            ; the last element
        chop            ; of a block without its last element
        sort            ; sorted
        take a &        ; prefix of input given current index
    ]                   ; end map

```

# Answer
> 0 votes
# Mathematica, 45 bytes

```
Sort[s[[;;i]]][[-2]]~Table~{i,2,Length[s=#]}&

```

Try it online!

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

```
say+(sort{$b-$a}@F[0..$_])[1]for 1..$#F

```

Try it online!

# Answer
> 0 votes
# Swift 3, 67 bytes

```
func g(l:[Int]){print((1..<l.count).map{l[0...$0].sorted()[$0-1]})}

```

**Test Suite.**

# Swift 3, 65 bytes

```
{l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]

```

**Test Suite.**

---

### How to run these?

The first one is a complete function that takes the input as a function parameter and prints the result. You can use them exactly as shown in the testing link. I decided to add instructions though, because the second type of function is used very rarely and most people don't even know of its existence. **Usage:**

```
g(l: [1, 1, 2, 2, 3, 3, 4] )

```

The second one is an anonymous function, like lambdas. You can use it exactly as you'd do it Python, declaring a variable `f` and calling it:

```
var f = {l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int]

print(f([1, 1, 2, 2, 3, 3, 4]))

```

**or** wrap it between brackets and call it directly (`(...)(ArrayGoesHere)`):

```
print(({l in(1..<l.count).map{l[0...$0].sorted()[$0-1]}}as([Int])->[Int])([1, 1, 2, 2, 3, 3, 4]))

```

# Answer
> 0 votes
# PHP, 53 bytes

```
for(;a&$n=$argv[++$i];rsort($a),print$a[1]._)$a[]=$n;

```

takes input from command line arguments. Output delimited, lead and trailed by semicola.
Run with `-nr` or try it online.

Yields a warning in PHP 7.1; replace `a&` with `""<` to fix.
Or use `for(;++$i<$argc;rsort($a),print$a[1]._)$a[]=$argv[$i];` (54 bytes)

# Answer
> 0 votes
## Mathematica 42 Bytes

Independently arrived at a answer very similar to @Jenny\_mathy but 3 bytes shorter

```
Sort[#[[;;i]]][[-2]]~Table~{i,2,Length@#}&

```

Realized that the 1st running max takes only 15 bytes and two function calls!:

```
Max~FoldList~#&

```

This can be done so concisely because `Max` has the attributes `Flat` and `OneIdentity` but that's not true for `RankedMax` which would be the logical replacement. Unfortunately defining attributes or modifying them on existing functions takes up way too many bytes, so the flattening must be done by other means.

All of the nth running maxes can be found in 48 bytes:

```
PadLeft[Sort/@Flatten/@FoldList[{##}&,{},#&@#]]&

```

# Answer
> 0 votes
## JavaScript (ES6), ~~43~~ 51 bytes

**Edit:** *Added 8 bytes since numerical sorting is desired.* `:(`

```
a=>a.map((_,b)=>a.slice(0,b+1).sort((a,b)=>b-a)[1])

```

Keeping this one here, though, as it is shorter providing one wants lexicographical ordering:

```
a=>a.map((_,b)=>a.slice(0,b+1).sort()[b-1])

```

Both expressions produce `undefined` for the first element.

### Test code

```
const golfed =

a=>a.map((_,b)=>a.slice(0,b+1).sort((a,b)=>b-a)[1])

const inputs = [
  [1, 5, 2, 3, 5, 9, 5, 8],
  [1, 1, 2, 2, 3, 3, 4],
  [2, 1, 0, -1, 0, 1, 2]
];
console.log(inputs.map(x => golfed(x)));
// [ [ undefined, 1, 2, 3, 5, 5, 5, 8 ],
//   [ undefined, 1, 1, 2, 2, 3, 3 ],
//   [ undefined, 1, 1, 1, 1, 1, 2 ] ]
```

# Answer
> 0 votes
# Pyth, 15 bytes

`FNr2hlQ@_S<QN1`

Try it here: https://pyth.herokuapp.com/?code=FNr2hlQ%40\_S%3CQN1&input=%5B1%2C+5%2C+2%2C+3%2C+5%2C+9%2C+5%2C+8%5D&debug=0

# Explanation

`FNr2hlQ` \- For loop with counter 2 \<= N \<= list length

`@_S<QN1` \- 2nd element when the first N elements of the list are sorted in ascending order and then reversed (sorted in descending order)

# Answer
> 0 votes
# Octave, 51 bytes

```
@(a){[~,I]=cummax(a);a(I(2:end))=-inf;cummax(a)}{3}

```

\- An arbitrary value returned for the first element.

Try it online!

# Answer
> 0 votes
## Clojure, 56 bytes

```
#(for[i(drop 2(reductions conj[]%))](nth(sort-by - i)1))

```

Maybe there is a better way to generate those prefixes.

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


title: Is it Christmas?

text:
# Question
Title: Is it Christmas?
# Challenge

Given that Christmas is:

* December
* Month 12
* Day 25

Every year, determine today's date, and whether or not today is Christmas. If it is Christmas, you must print `"It's Christmas"`. If it is not Christmas, you must somehow wait until Christmas and then print `"It's Christmas"`.

# Example

From this Stack Overflow Question

```
import time
while time.strftime("%b, %d", time.localtime()) != "Dec, 25":
    time.sleep(60)
print "It's Christmas"

```

Python in 115 Characters

# Rules

Here are the rules:

* Assume that the computer's clock is always right.
* Your code must be able to be started at any time.
* Your code must print `"It's Christmas"` on Christmas.
* Looping is certainly not necessary, but once started your code should not stop until it has printed.
* Shortest code wins.

# Answer
> 30 votes
# Unix, 39 bytes

```
echo{,} "It\'s christmas"|at -t12252359

```

With help from Dennis, thanks for that.

# Answer
> 18 votes
## PowerShell, 45 ~~46~~ chars

```
for(;(date).date-ne'12/25'){}"It's Christmas"

```

It's certainly not very power-efficient, so a laptop battery might die before Christmas (reason to wish for a new one, maybe). But not sleeping is definitely *shorter*.

This is also locale-agnostic. And thanks to Jaykul for a nice trick in reducing this further.

## Abusing the rules a bit, 45 chars

```
for(){"It's Christmas"*((date)-like'12/25*')}

```

This will print empty lines until it's Christmas, upon which it will print “It's Christmas”.

It ...

* ... can be started at any time.
* ... prints “It's Christmas” on Christmas. Several times. The whole day long. (The rules didn't say anything about how often it may be printed.)
* ... does *not* print “It's Christmas” on not-Christmas (although it prints an empty line in that case; can be rectified by sacrificing another character, but then this gains nothing over the more sane solution above).
* ... does not ever stop (not even after it has printed “It's Christmas” but *definitely* not before).

# Answer
> 18 votes
## Perl + Unix, 40 chars

```
1until`date`=~/c 25/;say"It's Christmas"

```

This is the same as J B's Perl solution, except that I save a few chars by using the external `date` command instead of Perl's `localtime`.

# Answer
> 12 votes
**PostScript, 90**

```
(%Calendar%)currentdevparams begin{Month 12 eq Day 25 eq and{exit}if}loop(It's Christmas)=

```

Don't run on a printer, it doesn't print a page, and it will only DoS your printer until Christmas day. Then again, getting your printer back would be a nice present.

# Answer
> 7 votes
## Mathematica, 47

```
While[Date[][[2;;3]]!={12,25}];"It's Christmas"

```

# Answer
> 5 votes
## Perl, 44 ~~45~~

```
perl -E'1until localtime=~/c 25/;say"It's Christmas"'

```

Wouldn't GMT time be sufficient? (3 characters off ;-)

# Answer
> 5 votes
## Perl, 45

```
{localtime=~/c 25/&&die"It's Christmas";redo}

```

## Perl, 44

using ternary operator (Thanks to Ilmari Karonen).

```
{localtime=~/c 25/?say"It's Christmas":redo}

```

# Answer
> 5 votes
## Javascript, 51 chars

It's a CPU killer:

```
while(!/c 25/.test(Date()));alert("It's Christmas")

```

# Answer
> 5 votes
# **R (47)**

```
while(!grepl("c 25",date())){};"It's Christmas"

```

# Answer
> 4 votes
I wanted to do this without parsing strings. Subsequently, there's a lot of magic numbers in my code.

I did some approximation to account for leap years. No one said that it had to print it out right on 00:00:00, Dec. 25!

## Perl, 80 69 57 characters

```
{(time-30931200)%31557600<86399?die"It's Christmas":redo}

```

Edited for more concise looping!

# Answer
> 3 votes
## Python, 66 68

```
import time
while'c 25'not in time.ctime():1
print"It's Christmas"

```

# Answer
> 3 votes
# TI-BASIC, ~~42~~ 38

```
Repeat 769=sum(getDate²,2
End
"It's Christmas

```

Expects the date format to be YYYY/MM/DD.

getDate creates a three-element list `{year,month,day}`; only on Christmas is month^2 + day^2 equal to 769.

23 bytes are used for the string because lowercase letters are two bytes each, except for i which is displayed as the imaginary unit token.

# Answer
> 2 votes
## Batch file, 68 chars

```
:l
@date/t|findstr/c:"-12-25">nul&&echo It's Christmas&&exit
@goto l

```

Not usable interactively, as it kills the session. Solving that would require 5 more characters.

Also locale-sensitive. This works on my locale which uses ISO 8601 date format.

But hey, it's a batch file (by most not even regarded as a programming language). And shorter than Javascript (and on par with Python).

# Answer
> 2 votes
# Groovy, 55

```
while(!new Date()==~/.*c 25.*/);
println"It's Christmas"

```

Think it works, but still waiting for output.

# Answer
> 2 votes
## Ruby, 53

```
until Time.now.to_s=~/c 25/
end
puts"It's Christmas!"

```

# Answer
> 2 votes
## (pdf)eTeX - 180 chars only December 1-25.

```
\lccode`m`~\let\e\expandafter\def~{\ifdim900pt<\pdfelapsedtime
sp\pdfresettimer\else\e~\fi}\lowercase\e{\e\scantokens\e
{\romannumeral\numexpr (25 - \day)*96000}}It's Christmas!\bye

```

TeX only has a way to access the date when the program starts, and the time elapsed since the start, capped at 32768 seconds, so I need to compute the number of seconds to wait, and for each second do a loop which waits for the elapsed time to reach `1s` and reset the time. (Precisely, I'm doing blocks of 900 seconds.)

Working for any month requires more work: 355 chars.

```
\lccode`m=`~\let\o\or\let\y\year\let\n\numexpr\let\e\expandafter
\def\b#1{\ifnum#1=\n(#1/4)*4\relax+1\fi}\def~{\ifdim
900pt<\pdfelapsedtime sp\pdfresettimer\else\e~\fi}\lowercase
\e{\e\scantokens\e{\romannumeral\n(25-\day+\ifcase\month\o334\b\y
\o303\b\y\o275\o244\o214\o183\o153\o122\o91\o61\o30\o0\ifnum25<\day
365\b{\n\y+1}\fi\fi)*96000}}It's Christmas!\bye

```

# Answer
> 2 votes
## MySQL, 180 chars

Because what are you using your database engine for, anyway?

```
DELIMITER $$
CREATE FUNCTION c() RETURNS CHAR(14) BEGIN a: LOOP IF DAY(NOW())=25 && MONTH(NOW())=12 THEN RETURN 'It\'s Christmas'; END IF; END LOOP a; END$$
DELIMITER ;
SELECT c();

```

Not very competitive lengthwise, but hey, it's doable!

# Answer
> 2 votes
# PHP, 40 bytes

```
<?while(date(dm)-1225);?>It´s Christmas;

```

Loop until 25th of December; then exit to plain mode and print.

Run with default settings (don´t display notices).

# Answer
> 2 votes
# 8086 machine code, 33 bytes

```
00000000  b4 2a cd 21 81 fa 19 0c  75 f6 b4 09 ba 12 01 cd  |.*.!....u.......|
00000010  21 c3 49 74 27 73 20 43  68 72 69 73 74 6d 61 73  |!.It's Christmas|
00000020  24                                                |$|
00000021

```

# Answer
> 2 votes
# Forth (gforth), 84 bytes

```
: f begin time&date drop 12 = 0<> swap 25 = 0<> and until s" It's Christmas!" type ;

```

Try it online!

Yet another stack language. Somehow not the longest answer.

The `time&date` word is very convenient here.

A stack overflow happens since time&date values are left on stack every iteration.

# Answer
> 1 votes
## Javascript, ~~93~~ ~~89~~ ~~78~~ 77 chars

`function x(){Date().match("c 25")?alert("It's Christmas"):setTimeout(x,1)}x()`

# Answer
> 1 votes
## D, 130

```
import std.datetime,std.stdio;
main(){
do{
auto t = Clock.currTime();
}while(t.month!=12||t.day!=25);
writeln("It's Christmas");
}

```

# Answer
> 1 votes
## Q, 63 chars

```
system"t 1000";.z.ts:{$["12.25"~-5#-3!.z.d;1"It's Christmas";]}

```

will work for christmas day on every year

# Answer
> 1 votes
# SQL\*Plus + PL/SQL - 100

```
EXEC LOOP EXIT WHEN TO_CHAR(SYSDATE,'DDMM')='2512';END LOOP;DBMS_OUTPUT.put_line('It''s Christmas');

```
* Assuming `SERVEROUTPUT ON`
* Shorter then the MySql solution (eat that, MySql!)
* Too late for last year, but in time for this year
* Tried `DBMS_OUTPUT.put` instead of `DBMS_OUTPUT.put_line` but that doesn't print anything.

# Answer
> 1 votes
## C# (126)

```
using System;class P{static void Main(){while(DateTime.Now.Date.ToString("Md")!="1225");Console.WriteLine("It's Christmas");}}

```

Nicer for your battery:

## C# (163)

```
using s=System;class P{static void Main(){s.Threading.Thread.Sleep(s.DateTime.ParseExact("1225","Md",null)-s.DateTime.Now);s.Console.WriteLine("It's Christmas");}}

```

*edit*

The second ("nicer for your battery") version does have a bit of an issue dec. 26th to dec. 31st I just thought of :P

Both versions can probably be shortened a bit more.

# Answer
> 1 votes
# SmileBASIC, ~~49~~ 47 bytes

```
DTREAD OUT,M,D?"It's Christmas"*(M/D==.48)EXEC.

```

`month/day` will be `0.48` on December 25th.

# Answer
> 1 votes
# Japt, 27 bytes

```
Ks f"c 25" ?`It's CËItµs`:P

```

To test against today's date : Replace `c 25` with this month's last letter (shorthand) + space + day of the month. `Feb 02` == `b 02`

Try it online!

# Answer
> 1 votes
# VBA, 58 Bytes

Anonymous VBE immediates window function that takes no input and runs until it's Christmas day, at which time it outputs `It's Christmas` to the VBE immediates window.

```
While Left(Now,5)<>"12/25":DoEvents:Wend:?"It's Christmas"

```

# Answer
> 1 votes
# 05AB1E, <sup>~~28~~</sup> 21 bytes

```
[že25Qžf12Q&#}”It'sŒÎ

```

Try it online!

Noncompeting, I suppose(Beats the other non-competing answer, ha).

My first 05AB1E answer.

-7 bytes from ovs.

## Explanation

```
[že25Qžf12Q&#”It'sŒÎ
[                            start an infinite loop
 že                          push current day
   25                        25
     Q                       are they equal?
      žf                     push current month
        12                   12
          Q                  are they equal?
           &                 logical and
            #                break if both conditions are true
             ”It'sŒÎ         push "It's Christmas"
                             implicit output

```

# Answer
> 1 votes
# Thunno 2, 23 bytes

```
(kNkM,¿⁺P¿Q)’It's ñẈmas

```

Try it online!

#### Explanation

```
(kNkM,¿⁺P¿Q)’It's ñẈmas  '# Full program
(          )              # Loop until this returns false:
 kNkM,                    #   Push [current month, current day]
      ¿⁺P¿Q               #   Not equal to [12, 25]
            ’It's ñẈmas  '# Push "It's Christmas"
                          # Implicit output

```

# Answer
> 0 votes
### bash-n-date: 69 chars:

```
sleep $(($(date -d"12/25" +%s)-$(date +%s))) && echo "It's X-Ray    "

```

But it will fail on Dec. 26th to Dec. 31th.

# Answer
> 0 votes
## Q (60)

```
 system"t 1000";.z.ts:{if[.z.d~2012.12.25;1"It’s Christmas"]}

```

# Answer
> 0 votes
# PHP - 49 Characters

I got this quite short, so yeah.

```
<?while(date("dm")!="2512");echo"It's Christmas";

```

EDIT: Whoops, I printed something else than `It's Christmas` x3

# Answer
> 0 votes
## Rebol (53 chars)

```
wait difference 25-Dec-14 now
print "It's Christmas"

```

Of course the above will only wait till Xmas 2014 :)

Here's a version that will wait for next Xmas day:

```
next-xmas: does [
    d: now
    make date! reduce [25 12 either all [d/month = 12 d/day > 25][d/year + 1][d/year]]
]

wait difference next-xmas now
print "It's Christmas"

```

# Answer
> 0 votes
# Befunge-98 (36 chars)

Requires a Unicode-capable interpreter (`'` is used for a literal 65536 and `'ఙ` for 3097):

```
aa+y'%'ఙ-!#v_
s Christmas"<@,kd"It'

```

Explanation:

* Use `y` with an argument of 20 to get the date field (`aa+y`)
* Mask off the month & day portion by reducing mod-65536 (`'%`)
* Subtract 3097 (= *month* * 256 + *day*) (`'ఙ-`)
* If zero, print the string (abuses edge wrapping)
* Otherwise repeat

# Answer
> 0 votes
### J, 54

```
'It''s Christmas'[(-^:(3 :'-.12 25-:1 2{6!:0''''')^:_)1

```

# Answer
> 0 votes
# Factor \+ `calendar.holidays.us math.unicode`, 54 bytes

```
[ now dup christmas-day ≠ ] loop [I It's ChristmasI]

```

Attempt This Online!

# Answer
> -2 votes
# Groovy - 88

```
new Timer().schedule({print"It's Christmas"}as TimerTask,Date.parse("yyddMM","112512"))

```

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


# Question
Title: Number of bits needed to represent the product of the first primes
# Input

An integer \\$n\\$ greater than or equal to 1.

# Output

The number of bits in the binary representation of the integer that is the product of the first \\$n\\$ primes.

# Example

The product of the first two primes is 6. This needs 3 bits to represent it.

Given unlimited memory and time your code should always output the correct value for `n <= 1000000`.

# Answer
> 8 votes
# Factor, 24 bytes

```
[ primorial bit-length ]

```

Try it online!

```
primorial  ! get the primorial of the input
bit-length ! how many bits does it have?

```

# Answer
> 7 votes
# JavaScript (ES12), 75 bytes

*-1 byte thanks to @tsh*

Expects a BigInt.

```
n=>eval("for(p=k=1n;p;d?0:p*=n--&&k)for(d=k++;k%d--;)p.toString(2).length")

```

Try it online!

---

# JavaScript (ES12), 76 bytes

```
n=>eval("for(p=k=1n;n;d?0:p*=n--&&k)for(d=k++;k%d--;);p.toString(2).length")

```

Try it online!

### Commented

This is a version without `eval()` for readability.

```
n => {                 // n = input
  for(                 // outer loop:
    p =                //   p = product
    k = 1n;            //   k = current prime candidate
    n;                 //   stop when n = 0
    d ?                //   if d is not 0:
      0                //     do nothing
    :                  //   else:
      p *= n-- && k    //     decrement n and multiply p by k
  )                    //
    for(               //   inner loop:
      d = k++;         //     start with d = k and increment k
      k % d--;         //     decrement d until it divides k
    );                 //
  return p.toString(2) // convert the final product to base 2
         .length       // and return the length
}                      //

```

# Answer
> 6 votes
# Jelly, 5 bytes

```
Ẓ#PBL

```

A full program that accepts an integer from STDIN that prints the result.

**Try it online!**

### How?

Straight forward, just saving a byte over the monadic Link `ÆN€PBL`

```
Ẓ#PBL - Main Link: no arguments
 #    - starting at {implict k=0} find the first {STDIN} k for which:
Ẓ     -   is prime?
  P   - product
   B  - to binary
    L - length

```

# Answer
> 6 votes
# PARI/GP, 30 bytes

```
n->#binary(vecprod(primes(n)))

```

Attempt This Online!

# Answer
> 5 votes
# Python, 70 bytes

```
f=lambda n,x=1,i=1:n and f(n-(b:=x**i%i>0),x*i**b,i+1)or len(bin(x))-2

```

Try it online!

The idea is that if `x` is the product of every prime number up to `n`, then the next prime number must not share any prime factors with `x`. This is done by calculating the first `i` greater than `n` such that `x**i%i>0`. This works because if `i` isn't the next prime, all of its prime factors are below `n`, so it will easily divide `x**i`. Raising `x` to the `i`th power makes sure that prime powers are also caught, since `x` by itself only contains each prime factor once.

# Answer
> 4 votes
# Vyxal, 34 bitsv2, 4.25 bytes

```
ʁǎΠbL

```

Try it Online!

Very simple

## Explained

```
ʁǎΠbL
ʁǎ     # A list of the first n primes
  Π    # Take the product of that
   bL  # And get the length of the binary representation

```

Created with the help of Luminespire.

# Answer
> 4 votes
# Arturo, 58 bytes

```
$=>[0x:∏select.first:&2..∞=>prime? while->x>0[1+'x/2]]

```

Unfortunately, I have to count bits by counting how many halvings it takes to get to zero since both `log` and `as.binary` no longer work properly once values get into bignum territory. Perhaps there is a smarter way...?

Try it!

```
$=>[                ; a function where input is assigned to &
    0               ; push 0 -- we'll use this to count bits later
    x:              ; to x, assign...
    ∏               ; product of
    select.first:&  ; the first <input> number of
    2..∞=>prime?    ; prime numbers in [2..∞]
    while->x>0[     ; while x is greater than zero...
        1+          ; increment our bit count
        'x/2        ; divide x by two in place
    ]               ; end while
]                   ; end function

```

# Answer
> 4 votes
# Ruby `-rprime`, 39 bytes

```
->n{'%b'%Prime.take(n).inject(:*)=~/$/}

```

Attempt This Online!

# Answer
> 4 votes
# Pari/GP, 26 bytes

-3 Thanks to alephalpha:

```
n->#binary(lcm(primes(n)))

```

Try it online!

### Pari/GP, 29 bytes (original)

```
n->logint(lcm(primes(n)),2)+1

```

Try it online!

# Answer
> 4 votes
# MATLAB, 35 bytes

*upd. use `nthprime` instead of `primes(n)`(get all primes up to n)*

```
@(n)ceil(log2(prod(nthprime(1:n))))

```

Full code with test cases:

```
f=...
@(n)ceil(log2(prod(nthprime(1:n))));
disp(arrayfun(f,1:57));

```

# Answer
> 3 votes
# Thunno 2 `L`, 4 bytes

```
Æppḃ

```

Try it online!

#### Explanation

```
Æppḃ  # Implicit input
Æp    # First n primes
  p   # Product
   ḃ  # To binary
      # Take the length
      # Implicit output

```

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
ÅpPbg

```

Try it online!

#### Explanation

```
ÅpPbg  # Implicit input
Åp     # First n primes
  P    # Product
   b   # To binary
    g  # Take the length
       # Implicit output

```

# Answer
> 3 votes
# Excel, ~~98~~ ~~94~~ 92 bytes

*2 bytes saved thanks to Taylor Alex Raine*

```
=LET(
    a,ROW(1:99),
    LEN(BASE(PRODUCT(TAKE(FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2),A1)),2))
)

```

Input in cell `A1`.

Fails for `A1>13`.

# Answer
> 3 votes
# Rust + num + num-prime, 59 bytes

```
|n|num_prime::nt_funcs::primorial::<num::BigUint>(n).bits()

```

# Answer
> 2 votes
# , 18 bytes

```
f=:3 :'##:*/p:i.y'

```

Try it online!

# Answer
> 2 votes
# Charcoal, 26 bytes

```
Ｎθ→→Ｗ‹Ｌυθ¿⬤υ﹪ⅈκ⊞υⅈＭ→ＩＬ↨Πυ²

```

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

```
Ｎθ

```

Input `n`.

```
→→

```

Start searching for primes at `2`.

```
Ｗ‹Ｌυθ

```

Stop when `n` primes have been found.

```
¿⬤υ﹪ⅈκ

```

If none of the primes found so far is a factor of the current value, then...

```
⊞υⅈ

```

... push the current value to the list of primes.

```
Ｍ→

```

Otherwise increment the current value. (Note that after a prime is pushed, the value is not immediately incremented, but if more primes are needed then it will "fail" the divisibility test and get incremented that way.)

```
ＩＬ↨Πυ²

```

Output the length of the base `2` representation of the product.

# Answer
> 2 votes
# JavaScript (Node.js), 74 bytes

```
n=>eval("for(i=s=p=1;n;s*=j?1:n--&&i)for(j=i++;s*i<2?i%j--:[++p,s/=2];)p")

```

Try it online!

Little RAM. Assumes n#(Product of first n primes) don't get too near to \\$2^k\\$ and therefore need confirm.

# JavaScript (Node.js), 73 bytes basically by Arnauld

```
n=>eval("for(p=k=i=1n;n;d?0:p*=n--&&k)for(d=k++;k%d--;);for(;p/=2n;)++i")

```

Try it online!

# Answer
> 2 votes
# Python, 67 bytes

```
f=lambda N,P=1,p=1:len(-N*f"{P:b}")or f(N-P**p%-~p,P-P**p%~p*P,p+1)

```

Attempt This Online!

Disclaimer: This one has one flaw which is that it is "zero-based" which is stretching the rules, I suppose. But I'd still very much like to show it off.

Obviousy, this is heavily based on @dingledooper's answer.

## How?

This leverages a bit of elementary number theory, i.e. Fermat's little theorem, to squeeze out a few bytes.

The basic strategy is the same as dingledooper's: Use the nascent primorial to identify the next prime.What we do differently is when testing the next prime number candidate \\$p\\$ we raise the primorial \\$P\\$ to one less power, \\$P^{p-1}\mod p\\$ instead of \\$P^p \mod p\\$ That way we know the value can only be \\$1\\$ (iff \\$p\\$ is indeed a prime) or \\$0\\$. The value can, for example, directly be used to decrement the prime number counter. The conditional update of the primorial is also streamlined.

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

Try it online!

```
Length@IntegerDigits[Times@@Prime~Array~#,2]&

```

---
Tags: code-golf, primes
---