title: Stack the rocks

text:
# Question
Title: Stack the rocks
This is a rock:

```
*

```

Rocks can be stacked. Apart from the bottom-most layer, each rock must rest on two other rocks, like this:

```
 *
* *

```

You have a pile of rocks, and your boss wants you to pile them *symmetrically*, taking up the least horizontal space possible.

Your challenge is to take a number of rocks as input, and output that many rocks stacked *symmetrically*, on *as small* a base as possible.

For example, with input `4`:

You can't fit a pile of 4 rocks on a base of 2. With a base of 3, you can, but you can't make it symmetrical - you end up with something like

```

 *
* * *

```

So you need a base size of 4, which uses up all your rocks, so the result is:

```

* * * *

```

Any trailing or leading whitespace is allowed in the output, and you may use any two distinct characters instead of `*` and . If there are multiple ways to stack the inputted number of rocks symmetrically with the same base, any of them are valid.

# Scoring

This is , shortest wins!

# Testcases

```
4 =>
* * * *

7 =>
 * * *
* * * *

8 =>
    *
   * *
* * * * *

9 =>
  * *
 * * *
* * * *

12 =>
  * * *
 * * * *
* * * * *

13 =>
    * *
 * * * * *
* * * * * *

or

  *     *
 * * * * *
* * * * * *

17 =>
   *   *
  * * * *
 * * * * *
* * * * * *

19 =>
   *     *
  * *   * *
 * * * * * *
* * * * * * *

Or
      *
     * *
    * * *
 * * * * * *
* * * * * * *

20 =>
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

56 =>
      * * * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
 * * * * * * * * * *
* * * * * * * * * * *

or
         * *
        * * *
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
 * * * * * * * * * *
* * * * * * * * * * *

```

# Answer
> 19 votes
# Ruby, ~~124 117 112~~ 110 bytes

```
->n{b=0
a=*a,"* "*b+=1while(n-=b)>0||n==-2
~n%2*n<0&&a[2][2]=' '
a.map{|j|q=n<0?2:0;n+=2;j[q..~q].center b*2}}

```

Try it online!

Incorporated ideas from dingus and G B, and also removed the deletion loop completely by using the output loop to perform its function (it truncates the first and last `*` rather than overwriting them).

# Ruby, ~~163~~ 137 bytes

```
->n{a=[];b=x=0
(a<<"* "*b+=1)while(x+=b)<n||2==c=x-n
(-~c/2).times{|i|a[i][0]=a[i][-2]=' '}
~c%2*c>0&&a[2][2]=' '
a.map{|j|j.center b*2}}

```

Try it online!

This is a fast algorithm with no searching.

**Explanation**

Where `T` is a triangular number greater than the input, the only solution for `T-1` is to delete the top `*` and the only solution for `T-4` is to delete the top two rows and the `*` from the middle of the next row, forming a diamond shape.

For `T-1-2n` or `T-4-2n` a possible solution is to also delete the `*` at the beginning and the end of each row. In practice there are always enough asterisks to delete; If you run out it means that there is a triangular number smaller than `T` which would give a smaller base (This is fairly easy to prove so I'll not explain here.)

For `T-2` there is no solution and we are forced to use a triangle with the next larger base.

See examples below for odd and even numbers of deletions (numbers represent the number of deletions `O` not the number of `*`).

```
            1                  3                  7
            O                  O                  O
           * *                O O                O O
          * * *              * * *              O * O
         * * * *            * * * *            O * * O
        * * * * *          * * * * *          * * * * *

            4                  6                  8
            O                  O                  O
           O O                O O                O O
          * O *              O O O              O O O
         * * * *            * * * *            O * * O
        * * * * *          * * * * *          * * * * *

```

**Commented code**

```
->n{a=[];b=x=0                         #a[] = empty array for solution;b = base size; x = asterisk count
(a<<"* "*b+=1)while(x+=b)<n||2==c=x-n  #Add rows to a while asterisk count is below n, or the count is exactly 2 above n. Save the difference between the count and the required in c
(-~c/2).times{|i|a[i][0]=a[i][-2]=' '} #Overwrite the excess asterisks with spaces by looping (c+1)/2 times. An odd number of asterisks is deleted because there is only one on the 1st row.
~c%2*c>0&&a[2][2]=' '                  #If there was a positive even number of excess asterisks, we still need to delete the middle asterisk on row 2.
a.map{|j|j.center b*2}}                #Return an array of strings, each centred to width b*2

```

# Answer
> 8 votes
# Jelly, ~~53~~ 43 bytes

```
ŒṗQƑƇḂ⁹ƤḄ_’ʋⱮ3Ȧ$ƇṀÞḢµạṀIḂ’+Ʋ⁶ẋ;"b1KḣƊ€z⁶ZŒB

```

Try it online!

A monadic link taking an integer and returning a list of lists. \>50% of the code is focused on the ASCII art aspect. If a list of integers indicating row sizes were permissible, this would be 20 bytes.

In brief, this is the algorithm:

1. Generate all integer partitions of n
2. Keep only those made of distinct integers
3. Keep only those where there is no length 2 subsequence of odd numbers and no length 3 subsequence that is odd, even, even.
4. Keep one of the lists with the smallest maximum integer
5. Left pad the list of integers with spaces; in general, this is max integer minus current integer, but where there are two even numbers in a row, there is one less space.
6. Half the integer, rounding up, convert to unary and separate with spaces, with an extra space if the integer is even
7. Right pad with spaces to make each line the same length.
8. Palindromise each line

Full explanation to follow.

---

As an alternative, here’s a translation of @LevelRiverSts clever Ruby solution:

# Jelly, 49 bytes

```
ŻÄ_=2o<ʋ0Tðb1K€a3¦€3¦S_Ḃo¬Ɗɗ^Ø.¦"S_HĊʋb1ɗŻṛ¡"U{o⁶

```

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~69~~ ~~60~~ 56 bytes

~~Very~~ slow bruteforcing approach. Generates all triangles of with the right number of stars in increasing size.

```
[N>L©ODULI.ÆεXLå}vy®£0δ.ýJ.c0ð:D.BÐíQs…1 1ƵA:€Sø€ü@PP*iq

```

Try it online!

If we sacrifice the performance, two more bytes can be saved: Try it online!

Some high-level comments:

```
[                   # for N in 0, 1, ...
  N>L©O             # K = (N+1-th triangular number)
  DULI.ÆεXLå}       # all length K lists of 0's and 1's that sum to the input
  vy                # for each list y
    ®£0δ.ýJ.c0ð:D.B # format as a pyramid with 1's and spaces
    ÐíQ             # is it symmetric?
    …1 1ƵA:         # make the pyramid "dense", fill the gaps between 1's
    €Sø€ü@PP*       # check if each column is supported
    iq              # if so, exit and implicitly print

```

# Answer
> 3 votes
# JavaScript (ES7), 186 bytes

A rather naive search, but reasonably fast.

```
f=(n,W)=>(g=(w,x=2**w-1,o='',t=n,p=o,X=x)=>x?(i=t,s='',h=k=>k--&&(q=(x&X)>>k&1)|2*h(k,i-=q,s+=' X'[q]+' '))(w)==x&&g(w-1,x&x/2,p+s+`
`+o,i,p+' ')||o&&g(w,x-1,o,t,p,X):!t&&o)(W)||f(n,-~W)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 54 bytes

```
ＮθＷ∨›θ⁰⁼θ±²≧⁻Ｌ⊞Ｏυωθ↘Ｅυ⭆⁻Ｌυκ§ *⎇∧κλ∨﹪θ²¬∧θ⁼²⁺κλ›⊕⊗⁺κλ±θ

```

Try it online! Link is to verbose version of code. Explanation: Uses @LevelRiverSt's observations.

```
Ｎθ

```

Input `n`.

```
Ｗ∨›θ⁰⁼θ±²≧⁻Ｌ⊞Ｏυωθ

```

Subtract increasing number of rocks from `n` until the result is no longer positive, but subtract the next number if the result is exactly `-2`.

```
↘Ｅυ⭆⁻Ｌυκ§ *⎇∧κλ∨﹪θ²¬∧θ⁼²⁺κλ›⊕⊗⁺κλ±θ

```

Print a triangle of rocks, but remove rocks symmetrically from both sides as necessary, and also the rock directly below the topmost rock if necessary.

# Answer
> 2 votes
# K (ngn/k), 176 170 bytes

```
g:{r:,1+&b:1+#**|x
  s:(,'/2#,:)'x@&b>2*#'*:'x
  s:x@&2!b+#'*:'x:s,x
 ?x,((,!0),0^@\:[;!b]'{(&-2!x-#*y),/:y}[b]'s),\:r}
f:{*(x=+//')#({~(x=#**|:y)||/x=+//'y}[x])g/(,,,1)}

```

Try it online!

-6 bytes : @Adám

Recursively build up structures by placing either one or two smaller such structures on top of a base wide enough to accommodate them.

Could probably use a better heuristic for impossible answers. Currently just iterates until the base is as wide as the target.

---
Tags: code-golf, ascii-art, hexagonal-grid
---


title: Expand tabs (implement expand(1))

text:
# Question
Title: Expand tabs (implement expand(1))
Your task this time is to implement a variant of the POSIX `expand(1)` utility which expands tabs to spaces.

Your program is to take a *tabstop specification* and then *read input on standard in* and replace tab characters in the input with the appropriate amount of spaces to reach the next tabstop. The result should be *written to standard out*.

### Tabstop specification

A *tabstop specification* consists of either a single number, or a comma-separated list of tabstops. In the case of a single number, it is repeated as if multiples of it occurred in a comma-separated list (i.e. `4` acts as `4,8,12,16,20,...`). Each entry in a comma-separated list is a positive integer optionally prefixed by a `+`. A `+` prefix indicates a relative difference to the previous value in the comma-separated list. The first value in the list must be absolute (i.e. unprefixed). The tabstops specify the column of the next non-space character (following the expanded tab), with the leftmost column taken as number 0. Tabs should always expand to at least one space.

### Input/output

The tabstop specification is either to be taken as the first command-line parameter to the program, or read from standard in as the first line of input (terminated by a newline), at your discretion. After the tabstop has been read, the remaining input (all input, in the former case) until EOF is to be processed and expanded. The expanded output shall be written to standard out.

All expanded tabstops, and all input, is assumed to be a maximum of 80 columns wide. All expanded tabstops are strictly increasing.

---

## Example

Tabstop specification `4,6,+2,+8` is equivalent to `4,6,8,16`, and with both the input

```
ab<Tab>c
<Tab><Tab>d<Tab>e<Tab>f

```

is expanded into ( indicates a space)

```
ab␣␣c
␣␣␣␣␣␣d␣e␣␣␣␣␣␣␣f

```

```
01234567890123456   (Ruler for the above, not part of the output)
          1111111

```

---

Scoring is pure ; shortest code wins.

# Answer
## GolfScript (77 75 chars)

```
n/(','/{'+'/{~t++}*~:t}%81,{t*}%+:T;{[0\{.9={;T{1$>}?(.)@-' '*}*\)}/;]n+}/;

```

I'm quite pleased with the tabspec parsing.

```
# Split on commas
','/
# For each element:
{
    # Split on '+'
    '+'/
    # We now have either ["val"] or ["" "val"]
    # The clever bit: fold
    # Folding a block over a one-element array gives that element, so ["val"] => "val"
    # Folding a block over a two-element array puts both elements on the stack and executes,
    # so ["" "val"]{~t++}* evaluates as
    #     "" "val" ~t++
    # which evaluates val, adds the previous value, and concatenates with that empty string
    {~t++}*
    # Either way we now have a string containing one value. Eval it and assign to t
    ~:t
}%

```

Then I add multiples of the last element until I'm guaranteed to have enough to reach the end of the 80 columns:

```
81,{t*}%+

```

This gives the desired behaviour when only one tabstop was specified, and is otherwise only relevant in cases which the spec doesn't mention. (NB it makes the list of tab-stops dip back to 0 and then repeat the last parsed element, but that's irrelevant because when it comes to using the list I look for the first element greater than the current position).

The rest is pretty straightforward.
> 2 votes

# Answer
## C, 228 chars

Here is a C solution to start things off. There's still a lot of golfing to do here (look at all those `if`s and `for`s and `putchar`s...). Tested with the example testcase, as well as with the same input but `4` and `8` for the tab spec.

```
S[99],i;L,C;main(v){for(v=1;v;)v=scanf("+%d",&C),v=v>0?C+=L:scanf("%d",&C),
v&&(S[L=C]=++i,getchar());for(;i==1&&C<80;)S[C+=L]=1;for(C=L=0;C=~getchar();)
if(C+10)putchar(~C),L+=C+11?1:-L;else for(putchar(32);!S[++L];)putchar(32);}

```
> 2 votes

# Answer
# Ruby 161 145

Reads the tabstop specification on the first line of input.

```
i=t=[]
gets.scan(/(\+)?(\d+)/){t<<i=$2.to_i+($1?i:0)}
81.times{|j|t<<j*i}
while gets
$_.sub!$&," "*(t.find{|s|s>i=$`.size}-i)while~/\t/
print
end

```

edit: Added two lines that makes the last read tabstop repeat so that tabstop specifications of a single number also works correctly

`i` is a temporary variable for holding the last parsed tabstop. `t` is the list of tabstobs, parsed from the `gets.scan` line. For good measure we add 81 multiples of the last parsed tabstop. the `while gets` loop keeps going until there is no more input. For each line of input we substitute tabs for spaces, one tab at the time because the string moves as we add the spaces and we must recalculate the correct tabstop.
> 2 votes

# Answer
## Pascal, 441 B

* The Pascal programming language is standardized by ISO standards 7185 (“Standard Pascal”) and 10206 (“Extended Pascal”). Since the notion of command-line arguments something highly specific, not universally found on all computing systems, Pascal lacks of a standardized facility to access command-line arguments (if such exist). Therefore the following complete `program` expects the tabulator specification given on the first line of `input`.
* The tabulator stop specification reading algorithm uses the built‑in `read` procedure. Such will allow and ignore leading blanks. Thus `8, 12, 14, 15` is accepted, too. However, relative tabulator stop specifications are only processed correctly if the plus sign is immediately adjacent to the comma.
* With respect to (POSIX™ locale) blank characters, the Pascal programming language only guarantees there is *a* space character. The provision of a tabulator character is an implementation-defined characteristic. Obviously the following program requires that there is a horizontal tabulator character in the utilized implementation.
* The golfed version omits certain verification steps (non-empty `input`, first tabulator specification must be non-relative). It is unclear whether such vigorous enforcement is required by the task specification.

```
program e(input,output);var t:set of 1..80;c,p:1..80;begin
read(p);t:=[p];while','=input^do begin
get(input);if'+'=input^then begin read(c);p:=p+c end else
read(p);t:=t+[p]end;readLn;if[]=t-[p]then begin for c:=1
to 80 do if c mod p=0 then t:=t+[c]end;p:=1;while not EOF
do begin if EOLn then begin writeLn;p:=1 end else begin
if' '=input^then repeat p:=p+1;write(' ')until p-1 in t
else begin write(input^);p:=p+1 end end;get(input)end end.

```

Ungolfed:

```
program expand(input, output);

    const
        { The character count of the longest line this program can process. }
        lineIndexMaximum = 80;

    type
        { A valid character index in an `input` line. }
        lineIndex = 1‥lineIndexMaximum;
        { A set of valid character indices. }
        lineIndices = set of lineIndex;

    var
        { This mimics a mechanical typewriter implementation
          that has retractable pins installed catching the carriage. }
        tabulatorStop: lineIndices;
        { Where are we at in the currently processed line. }
        position: lineIndex;

    { Processes an input line containing a tabulator stop specification. ┈┈┈ }
    procedure processTabulatorStopSpecification;
        var
            { In Pascal `for`-loop counter variables must be declared
              in the _closest_ containing block. }
            column: lineIndex;
        begin
            { A negative number will be caught by the `lineIndex` data type. }
            read(input, position);
            tabulatorStop ≔ [position];

            while input↑ = ',' do
            begin
                { Skip comma. }
                get(input);

                { “A `+` prefix indicates a relative difference
                   to the previous value in the comma-separated list.” }
                if input↑ = '+' then
                begin
                    read(input, column);
                    position ≔ position + column;
                end
                else
                begin
                    read(input, position);
                end;

                tabulatorStop ≔ tabulatorStop + [position];
            end;

            { Discard the rest of the line, especially the end-of-line mark. }
            readLn(input);

            { “In the case of a single number, it is repeated as if
               multiples of it occurred in a comma-separated list.” }
            if tabulatorStop − [position] = [] then
            begin
                for column ≔ 1 to lineIndexMaximum do
                begin
                    if column mod position = 0 then
                    begin
                        tabulatorStop ≔ tabulatorStop + [column];
                    end;
                end;
            end;
        end;

    { Expands `input` lines according to `tabulatorStop`. ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈ }
    procedure expandTabulatorCharacters;
        begin
            position ≔ 1;

            while not EOF(input) do
            begin
                if EOLn(input) then
                begin
                    { `Input` is a variable possessing the data type `text`.
                      A `text` file automatically replaces
                      the character (sequence) that indicates the end-of-line
                      with a single space character (`' '`).
                      The only /universally/ valid way to
                      emit an end-of-line character (sequence) is `writeLn`. }
                    writeLn(output);
                    { Reset `position` to the beginning of a new line. }
                    position ≔ 1;
                end
                else
                begin
                    { Note, as this might not be properly displayed,
                      this checks for a tabulator character. }
                    if input↑ = '   ' then
                    begin
                        { “Tabs should always expand to at least one space.”
                          Ergo elect a `repeat … until` loop. }
                        repeat
                        begin
                            write(output, ' ');
                            { Cannot fail: “All expanded tabstops […] is
                              assumed to be a maximum of 80 columns wide.” }
                            position ≔ position + 1;
                        end
                        until position − 1 in tabulatorStop;
                    end
                    else
                    begin
                        write(output, input↑);
                        { Note, fatal error if exceding `lineIndexMaximum`. }
                        position ≔ position + 1;
                    end;
                end;
                { Advance the reading cursor. }
                get(input);
            end;
        end;

    { ─── MAIN ───────────────────────────────────────────────────────────── }
    begin
        { Accessing `input↑` is invalid if `input` is an empty file. }
        if not EOF(input) then
        begin
            { “The first value in the list must be absolute […]” }
            if input↑ ≠ '+' then
            begin
                processTabulatorStopSpecification;
                expandTabulatorCharacters;
            end;
        end;
    end.

```
> 0 votes

---
Tags: code-golf, string, parsing, whitespace
---


title: What's the time, chap?

text:
# Question
Title: What's the time, chap?
I honestly cannot believe that this is not a question yet on Code Golf, but....

Print the local time (with a.m. or p.m.) as a string to the console, preceded by "It's ".

Example:

```
Run code....

```

**Output:**

```
It's 12:32p.m.

```

Shortest code wins.

Code away!

### Leaderboard

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

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

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

# Answer
## Bash, ~~39~~ 33 bytes

```
date "+It's %I:%M%P."|sed s/m/.m/

```

Wasted a bunch of chars because the spec requires `a.m.` or `p.m.` while `date` outputs `am` or `pm`. Thanks to @DigitalTrauma for saving 6 bytes!

This might not be very portable. It works on Ubuntu 15.04.

A solution that uses essentially the same method in Ruby~~, which is surprisingly the exact same length~~:

## Ruby, 39 bytes

```
$><<`date "+It's %I:%M%P"`[0..-3]+'.m.'

```
> 18 votes

# Answer
# AppleScript, 198

Because AppleScript. Because why not:

```
set AppleScript's text item delimiters to {":"," "}
set d to (current date)'s time string's every text item
"It's "&d's item 1&":"&d's item 2&string id ((d's item 4's first character's id)+32)&".m."

```

That was painful.
> 13 votes

# Answer
# PHP, ~~35~~ 33 bytes

Using the wrong tool for the job!

```
It's <?=trim(date('h:ia'),m)?>.m.

```

It simply removes the `m` at the end of `am` or `pm`, to allow to add the dots. The date comes as `00:00am`, and with `trim` it becomes `00:00a`.

---

**Old answer (PHP 5.4+ only):**

```
It's <?=date('h:i'),date(a)[0]?>.m.

```

This works because you can de-reference a value returned from a function. This isn't possible in PHP5.3 or older.
> 8 votes

# Answer
## Visual Basic 6 / VBA, ~~42~~ 41 bytes

```
MsgBox"It's "&Format(Now,"h:mma/p")&".m."

```

Using `MsgBox`, as VB6 does not have a console (unless you intercept the linking, link as a console executable, use some Windows API hacks, and do some other *dodgy* stuff).
> 5 votes

# Answer
# Julia, ~~74~~ ~~54~~ 43 bytes

```
print(strftime("It's %I:%M%P\b.m.",time()))

```

You can try it online!

The `time()` function returns the current time. When passed to `strftime` with the format `%I:%M%P`, this results in `HH:MMam/pm`, where the hours are per a 12-hour clock. We back up one character with `\b` to remove the `m`, leaving a trailing `a` or `p`, then tack `.m.` onto the end.

Saved **31 bytes** thanks to Glen O!
> 4 votes

# Answer
# R, ~~68~~ ,~~59~~ ~~62~~ ~~60~~ 55

```
cat("It's",sub("m",".m",format(Sys.time(),"%I:%M%P.")))

```

(Thanks to @Alex.A. and @flodel for the comments) Takes the current system time (`Sys.time()`), formats it correctly using `%I:%M%P` combination, adds a dot at the end, and replaces the `m` with `.m.`.
> 4 votes

# Answer
# Pyth, ~~38~~ 36 bytes

```
s["It's "|%J.d6K12K\:.d7?gJK\p\a".m.

```

Saved 2 bytes thanks to @Jakube!
> 3 votes

# Answer
# Mathematica ~~49 90 92 90~~ 84 bytes

-6 bytes thanks to user202729

The solution is straightforward, but a bit wordy, in Mathematica.

```
(d=DateString)@{"It's ","Hour12",":","Minute"}<>(d@"AMPM"/."AM"->"a.m."/."PM"->"p.m .")

```
> 3 votes

# Answer
# Haskell, 135 bytes

```
import Data.Time.Format
import Data.Time.LocalTime
main=getZonedTime>>=putStr.(++".m.").init.formatTime defaultTimeLocale"It's %I:%M%P"

```

I found a much more amusing `main` that's five bytes longer:

```
getZonedTime>>=putStr.formatTime(TimeLocale[][]("a","p")""""""""[])"It's %I:%M%P.m."

```

Or 66 bytes on Unix:

```
import System.Cmd;main=system"date \"+It's %I:%M%P.\"|sed s/m/.m/"

```
> 3 votes

# Answer
# Perl 5, 74 bytes

A small showcase of how the variables are evaluated from right to left.

```
($s,$m,$h)=localtime;printf"It's %d:%02d%s.m.",$h<13?$h:$h%12,$m,$h<12?a:p

```

### Using POSIX: 80 bytes

```
use POSIX;$_=strftime"It's %I:%Mx.m.",@_=localtime;$x=$_[1]<13?a:p;s/x/$x/;print

```

### Using POSIX with time locale dependence & switches : 54 bytes (48 + 6)

```
$_=strftime"It's %I:%M%P",localtime;s/m/.m./;say

```

**Test**

```
$ export LC_TIME="en_DK.UTF-8"
$ perl -MPOSIX -M5.01 whatsthetimechap.pl
It's 3:09p.m.

```
> 3 votes

# Answer
# MATLAB, 59 bytes

```
disp(sprintf('It''s%s\b.m.',lower(datestr(now,'HH:MMam'))))

```

> It's 5:38p.m.

If it's allowed to have a whitespace between time and a.m./p.m., then it could be as low as **52 bytes**:

```
disp(sprintf('It''s%s\b.m.',lower(datestr(now,16))))

```

> It's 5:39 p.m.
> 3 votes

# Answer
# Perl 5.10+, ~~58~~ 62 bytes

```
localtime=~/(..)(:..)/;say"It's ",$1%12||12,$2,$1>11?p:a,".m."

```

Must be run with the `-M5.010` command line flag to get `say`.

I didn't account for a couple of edge cases in my original solution (namely, `00:**` and `12:**`); fixed at a cost of 4 additional bytes.

## How it works

In scalar context, `localtime` returns a string like this:

```
Sat Sep 12 03:13:22 2015

```

The minutes field is already zero-padded, which saves some bytes (in list context, `localtime` returns numbers instead of strings, so you have to pad them yourself).

Here it is ungolfed:

```
localtime=~/(..)(:..)/;  # Store hour in $1 and minutes in $2
say"It's ",              # Print "It's " followed by...
   $1%12||12,            # hour in 12-hour format
   $2,                   # minutes
   $1>11?p:a,            # "p" if hour > 11, otherwise "a"
   ".m."'                # ".m."

```

---

# Perl 5.14+, 57 bytes

(Just for fun, since it stretches the rules a bit.)

```
say"It's ",(strftime"%l:%M%P",localtime)=~s/m/.m./r

```

51 bytes + 6 bytes for `-MPOSIX`. Must also be run with the `-M5.010` command line flag to get `say`.

This solution is dependent on your locale, so will not work on all systems. It also uses the POSIX module, which might be stretching the definition of a "built-in", even though it is a core module.

Perl 5.14+ is required for the non-destructive `r` modifier to the substitution operator. An equivalent solution that works on 5.10+ is:

```
$_=strftime"%l:%M%P",localtime;chop;say"It's $_.m."

```

This is also 57 bytes (51 bytes + 6 bytes for `-MPOSIX`).
> 3 votes

# Answer
# CJam, 40 bytes

```
"It's "et3=CmdCe|\'p'a?':et4=s2Ue[@".m."

```

Try it online in the CJam interpreter.

### How it works

```
"It's " e# Push that string.
et3=    e# Select the fourth element of the date/time array (hours).
Cmd     e# Push quotient and remainder of the hour divided by 12.
Ce|     e# Logical OR with 12 to map 0 to 12.
\'p'a?  e# Select 'p' if the quotient is 1 and 'a' if it is 0.
':      e# Push that character.
et4=    e# Select the fifth element of the date/time array (minutes).
s2Ue[   e# Cast to string and left-pad with zeroes to a length of 2.
@".m."  e# Rotate 'a' or 'p' on top of the stack and push ".m.".

```
> 3 votes

# Answer
# T-SQL (2012+), ~~67~~ 65 bytes

SQL Server 2012 finally gave us a reasonable formatting function for dates. I still had to muck around with the AM/PM to get the format right though.

```
PRINT 'It''s '+LOWER(STUFF(FORMAT(GETDATE(),'hh:mmtt.'),7,0,'.'))

```

In previous versions it would have needed something like this (93 bytes)

```
PRINT'It''s'+LOWER(STUFF(STUFF(RIGHT(CONVERT(VARCHAR,GETDATE(),109),15),6,7,''),8,0,'.'))+'.'

```
> 2 votes

# Answer
# PHP, 49 bytes

If only it were `am/pm` instead of `a.m./p.m.`...

```
It's <?=@preg_replace(~Ð¤ž’¢Ð,~ÛÏÑ,date(~˜Å–ž));

```

I used a lot of nasty bytes to save a bit of length so here's the hex:

```
00000000: 49 74 27 73 20 3C 3F 3D - 40 70 72 65 67 5F 72 65 |It's <?=@preg_re|
00000010: 70 6C 61 63 65 28 7E D0 - A4 9E 92 8F A2 D0 2C 7E |place(~       ,~|
00000020: DB CF D1 2C 64 61 74 65 - 28 7E 98 C5 96 9E 29 29 |   ,date(~    ))|
00000030: 3B                      -                         |;|
00000031;

```

Readable version:

```
It's <?=preg_replace("/[amp]/", "$0.", date("g:ia"));

```
> 2 votes

# Answer
# SQL (PostgreSQL), ~~42~~ 41 bytes

Another SQL variant, however this one is in a query.

```
select to_char(now(),'"It''s" HH:MIa.m.')

```

As a note either p.m. or a.m. works to get the am/pm part. The formatting options in PostgreSQL are really quite flexible. Thanks to @manatwork for the tip to move the `it's` into the format string.

SQLFiddle
> 2 votes

# Answer
# Javascript, 103 bytes

Javascript executed from the console.

```
d="It's "+new Date().toLocaleTimeString();l=d.length;d.slice(0,l-6)+d.slice(-2,l-1).toLowerCase()+'.m.'

```

# C#, 63 bytes

C# executed from the immediate window.

```
?"It's "+System.DateTime.Now.ToString("h:MMt").ToLower()+".m.";

```
> 2 votes

# Answer
# C, 103 94 bytes

```
int main(){time_t r;char b[80];time(&r);strftime(b,80,"It's %I:%M %p",localtime(&r));puts(b);}

```

**Ungolfed**

```
int main()
{
  time_t r;
  char b[80];
  time(&r);
  strftime(b,80,"It's %I:%M %p",localtime(&r));
  puts(b);
}

```
> 2 votes

# Answer
# PHP, 41 bytes

`It's <?=strtr(date('g:ia'),['m'=>'.m.']);`

First time I've played this. Not sure if I'm supposed to update/edit the previous PHP answer (49 bytes) or just add my own...
> 2 votes

# Answer
# C, 154 bytes

```
#include <time.h>
#define l localtime(&r)
main(){time_t r=time(0);printf("It's %02i:%02i%c.m.",(l->tm_hour+11)%12+1,l->tm_min,(l->tm_hour>=12)?'p':'a');}

```

In contrast to the other C answer, this one uses the correct "a.m."/"p.m." format. The other poster omitted `#include <time.h>` – if your compiler allows this, we get down to 136 bytes. Which one should we count?
> 2 votes

# Answer
# Bash, 44 characters

Pure Bash, just shell builtins, no \***utils.

```
printf -vt "It's %(%I:%M%P)T"
echo ${t%m}.m.

```

Sample run:

```
bash-4.3$ printf -vt "It's %(%I:%M%P)T";echo ${t%m}.m.
It's 01:04p.m.

```
> 2 votes

# Answer
# Powershell, 49 bytes

```
"It's {0:hh:mm}$("ap"[($d=date).hour/23]).m."-f$d

```

`(date).hour/23` seems to work as an index for `"ap"` because it rounds to `0` for hours less than 12 and `1` for 12 and above.
> 2 votes

# Answer
# Locale-dependent

For browser environments that have the locale set to `en-CA` or any locale that outputs a 12-hour time by default:

## CoffeeScript, 81 bytes

```
alert "It's #{(x=(new Date).toLocaleTimeString().toLowerCase())[..4]} #{x[9]}.m."

```

## JavaScript (ES5), 90 bytes

```
alert("It's "+(x=(new Date).toLocaleTimeString().toLowerCase()).slice(0,5)+' '+x[9]+".m.")

```

# Locale-independent

## CoffeeScript, ~~113~~ 96 bytes

```
alert "It's #{(h=(d=new Date).getHours())%12}:#{('0'+d.getMinutes())[-2..]} #{'ap'[+(h>11)]}.m."

```

Previous:

This one works in all browser environments regardless of locale. Requires Chrome 24+, Firefox 29+, IE 11+, Opera 15+ or any derivatives of such. Does not work in Safari. See `Intl.DateTimeFormat`.

```
alert "It's #{new Intl.DateTimeFormat('en',{hour:f='2-digit',minute:f}).format(new Date).toLowerCase()[..-2]}.m."

```
> 2 votes

# Answer
## **Swift - 124 102 bytes**

```
import Cocoa
var f=NSDateFormatter()
f.dateFormat="hh:mma"
print("It's \(f.stringFromDate(NSDate()))")

```
> 2 votes

# Answer
# Python 3, ~~117~~ ~~87~~ 79 bytes

```
from datetime import*
print(datetime.now().strftime("It's %I:%M%P")[:-1]+".m.")

```

This gets the hours and minutes from a 12-hour clock using the format `%I:%M`, plus `am` or `pm` using `%P`. We then select everything but the last `m` and append `.m.`.

Saved a few bytes thanks to Ruth Franklin!
> 1 votes

# Answer
## Moonscript - 56 bytes

```
print "It's "..(os.date'%I:%M%p'\gsub 'M','.M.')\lower!

```

Unfortunately the Lua standard library only implements %p for uppercase AM/PM, so I have to call the method lower.
> 1 votes

# Answer
# SpecBAS - 64 bytes

```
PRINT "It's ";LOW$(REPLACE$(TIME$(TIME,"h:mm p$"),"M",".M."))

```

The built-in `p$` of the time function returns AM or PM, so this then has to be formatted with `REPLACE$` to change it so it has a full stop before/after that letter.

Then the time output had to be converted to lowercase.
> 1 votes

# Answer
# Python 2, ~~75~~ ~~67~~ 66 bytes

```
import time;print"It's %s.m."%time.strftime("%I:%M%p")[:6].lower()

```

old version, 75 bytes

```
import time
t=time.strftime("%I:%M%p")
print"It's",t[:5]+t[5].lower()+".m."

```

old version, 75 bytes

```
import time
print"It's",time.strftime("%I:%M%p").lower().replace("m",".m.")

```
> 1 votes

# Answer
# MATLAB, 66 bytes

```
['It''s' lower(datestr(now,'HH:MMam'))];disp([ans(1:end-1),'.m.'])

```

Displays:

```
It's 2:48p.m.

```
> 1 votes

# Answer
# AutoIt, 73 bytes

Even though AutoIt is generally a verbose language, this is quite short (converts time from 24h format):

```
$h=@HOUR>12
ConsoleWrite("It's "&@HOUR-12*$h&":"&@MIN&($h?"p":"a")&".m.")

```

# , 56 bytes

```
H=@HOUR>12µ€"It's "&@HOUR-12*H&":"&@MIN&H?"p.m.":"a.m.")

```
> 1 votes

# Answer
## Excel VBA, 33 bytes

```
?"It's "format(now,"h:ma/p")".m."

```

Related to toothbrush's VBA6 solution, but written before I saw it, so I'm allowing myself to post it here.

Most of the code is perfectly explicit: *now* returns a system timestamp, *format* forces the timestamp to the desired format, whilst *It's* and *.m.* are just text strings.

I abused/took advantage of a few things here:

* Implicit concatenation : VBA assumes that when something is put next to a string that a concatenation operation is desired.
* Immediate window printing : This is why I don't claim this is a complete VBA solution, as it relies on being executed from inside an immediate window. The *?* replaces *debug.print* for Excel VBA in an immediate window. This is an obvious gain for VBA where most of the byte cost comes from descriptive/user-friendly function and method names. Toothbrush's solution for example calls *Msgbox* which is 5 bytes more expensive.
* Format abuse : based on Dopapp's comments in this puzzle, we don't need to have double-digit hours. I'm also not forcing double-digit minutes, which might be slightly against the rules of the game, but can easily be corrected by adding an extra *m* between *:* and *m*, but costs 1 byte more.

I might have missed some other tricks, but I think this is about as low as Excel VBA can go. From what I can see so far, I'm pretty surprised that it's scoring so well, but a lot of the very concise languages haven't been used yet...
> 1 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~64~~ 62 bytes

**Binary:**

```
00000000: bf34 01b4 2ccd 218a c5d4 0c75 02b0 0ce8  .4..,.!....u....
00000010: 1400 478a c1e8 0e00 b870 0980 fd0c 7c01  ..G......p....|.
00000020: aaba 2f01 cd21 d40a 86c4 0530 30ab c349  ../..!.....00..I
00000030: 7427 7320 3030 3a30 3061 2e6d 2e24       t's 00:00a.m.$

```

Build and test using `xxd -r` with above.

**Listing:**

```
BF 0134     MOV  DI, OFFSET HH      ; DI point to hours in output string
B4 2C       MOV  AH, 2CH            ; DOS get time function
CD 21       INT  21H                ; CH = hour, CL = minute
8A C5       MOV  AL, CH             ; put hour into AL
D4 0C       AAM  12                 ; AL = AL mod 12, ZF = (AL == 0)
75 02       JNZ  NOT_12             ; is hour 0?
B0 0C       MOV  AL, 12             ; if so, make it 12
        NOT_12:
E8 0126     CALL ACONV              ; ASCII convert AL to [DI]
47          INC  DI                 ; skip ':' in output string
8A C1       MOV  AL, CL             ; put minutes into AL
E8 0126     CALL ACONV              ; ASCII convert AL to [DI]
B8 0970     MOV  AX, 0970H          ; AL = 'p', AH = 9 (DOS write string)
80 FD 0C    CMP  CH, 12             ; set up compare for 12
7C 01       JL   OUTPUT             ; is hours > 11?
AA          STOSB                   ; if so, write 'p' to output string
        OUTPUT:
BA 012F     MOV  DX, OFFSET IT      ; beginning of output string
CD 21       INT  21H                ; display output
        ACONV:
D4 0A       AAM                     ; BCD base 10 convert
86 C4       XCHG AL, AH             ; endian convert
05 3030     ADD  AX, '00'           ; ASCII convert
AB          STOSW                   ; write to output string buffer
C3          RET                     ; return to caller/DOS

        IT  DB  'It',27H,'s '
        HH  DB  '00:'
        MM  DB  '00'
        AP  DB  'a.m.$'

```

I had imagined this being shorter in my head when I started it, but alas. No date "built-ins" at least!

Standalone PC DOS executable `TIMECHAP.COM` file. Output to `STDOUT`.
> 1 votes

# Answer
# 05AB1E, ~~39~~ 37 bytes

```
"It's "ža<12%>žb‚T‰J':ý„apža13@è….m.J

```

-2 bytes thanks to *@ovs*.

Try it online.

**Explanation:**

```
"It's "     # Push string "It's "
ža          # Push the current hours (24 format)
  <         # Decrease it by 1
   12%      # Modulo-12: (hours-1)%12
      >     # Increase it by 1: (hours-1)%12+1
            # (so if the hours was 0, it's now 12; the [1,11] remained the same)
žb‚         # Pair this with the current minutes
   T‰       # Get the divmod-10 of each
     J      # And join the two digits together to a single string
            # (`T‰J` is used to format the hours/minutes with a potential leading 0)
      ':ý  '# Join them together with ":" delimiter
„ap         # Push string "ap"
   ža       # Push the current hours again (24 format)
     13@    # Check if it's >= 13 (1 if truthy; 0 if falsey)
        è   # (0-based) index that into the "ap"
….m.        # Push string ".m."
J           # Join all strings on the stack together
            # (after which the result is output implicitly)

```
> 1 votes

# Answer
# APL (Dyalog Extended), 58 bytes

-6 thanks to @ovs

```
⎕←∊'It is '(⍕h-12×12<h)':'(⍕5⌷⎕ts),'ap'[1+12<h←4⌷⎕ts]'.m.'

```

Try it online!

Original:

```
∊'It is '((':',⍕5⌷⎕ts){⍵>12:∊(⍕(⍵-12))⍺'p'⋄∊(⍕⍵)⍺'a'}4⌷⎕ts)'.m.'

```

Try it online!
> 1 votes

# Answer
# PowerShell, 61 bytes

```
"It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m."

```

My very first PowerShell experiecne // because my linux machine is in the other room.

**EDITED** to be culture-settings robust. Thanks to all commenters below, credit goes to @NeilD
> 0 votes

# Answer
# Octave, 75 bytes

```
disp(["It's " strrep(lower(strftime("%R%p",localtime(time()))),"m",".m.")])

```
> 0 votes

# Answer
# Windows Batch, 113 bytes

```
@set h=%time:~0,2%&@set z=a&@if %h% gtr 11 set z=p&if %h% gtr 12 set /a h-=12
echo It's %h: =0%:%time:~3,2%%z%.m.

```
> 0 votes

# Answer
# JavaScript (ES6), 88

*Edit* Missing "It's"
*Edit 2* Fixed 0 instead of 12
*Edit 3* Added an output statement. I was trying to be in line with other JavaScript answers that I felt ugly, but rules are rules

Test in any EcmaScript 6 compliant browser console (works in Chrome and Firefox).

```
alert(`It's ${1+((h=(d=new Date).getHours())+11)%12}:${d.getMinutes()+'ap'[h>11|0]}.m.`)

// With no ES6 features : 92

alert("It's "+(1+((h=(d=new Date).getHours())+11)%12)+':'+d.getMinutes()+'ap'[h>11|0]+'.m.')

```
> 0 votes

# Answer
# BASH, 50 bytes

```
date +"It's %I:%M%p"|sed s/AM/a.m./|sed s/PM/p.m./

```

Just `date` and two easy `sed`s.
> 0 votes

# Answer
# Perl, ~~88~~ 75 bytes

```
use POSIX;$d=lc strftime"%R%p",localtime;$d=~s/m/.m./;printf("It's %s",$d);

```
> 0 votes

# Answer
# Java, 182 bytes

These solutions are horrendously long. =(

Note: These print in local time, and suppresses leading zeros for the hour. `java.util.Date` has deprecated API.

```
// 183 bytes when linebreaks and indentation are removed
import java.util.Date;
class T{
  public static void main(String[]a){
    Date d=new Date();
    int h=d.getHours();
    System.out.printf("It's %d:%02d%c.m.%n",
      (h+11)%12+1,d.getMinutes(),97+h/12*15);
  }
}

```

---

Alternate solution:

```
// 182 bytes when linebreaks and indentation are removed
class T{
  public static void main(String[]a){
    System.out.println("It's "+new java.text.SimpleDateFormat("h:mma").format(
      new java.util.Date()).toLowerCase().replaceAll("[apm]","$0."));
  }
}

```
> 0 votes

# Answer
# C# - 160 bytes

```
using System;class C{static void Main(string[] a){var n=DateTime.Now;int h=n.Hour,m=n.Minute;Console.Write("It's "+(h<13?h:h-12)+":"+m+(h<12?"a":"p")+".m.");}}

```
> 0 votes

# Answer
# CJam, ~~60~~ 58 bytes

```
"It's "3et=Cmd\'p'a?".m."+\_0>{}{;C}?\":"\4et=_A<{0\@}{\}?

```

### Explanation

```
"It's "                                                         e# Print the string "It's ".
        et                                                      e# Push the local time to the stack.
       3  =                                                     e# Select the third item. (hours)
           C                                                    e# Push 12 to the stack.
            md                                                  e# Push the top stack item modulo the second stack item.
              \                                                 e# Swap the top two stack items.
               'p'a?                                            e# Push "p" or "a" to the stack.
                    ".m."+                                      e# Tack on ".m." to the above.
                          \                                     e# Swap the top two stack items.
                           _                                    e# Duplicate the top stack item.
                            0>                                  e# Determine if the top item is > 0.
                              {}{  }                            e# An if-then statement.
                                    ?                           e# If the top stack item is true.
                                 ;                              e# Remove the top stack item.
                                  C                             e# Push 12 to the stack.
                                     \                          e# Swap the top two stack items.
                                      ":"                       e# Push ":" to the stack.
                                         4  =                   e# Select the fourth item. (minutes)
                                          et                    e# Push the local time to the stack.
                                             _                  e# Duplicate the top stack item.
                                              A<                e# Determine if the top item is < 10.
                                                {   }{ }        e# An if-then statement.
                                                        ?       e# If the top stack item is true.
                                                 0              e# Push 0 to the stack.
                                                  \             e# Swap the top two stack items.
                                                   @            e# Rotate the top three stack items.
                                                      \         e# Swap the top two stack items.

```

You can test it online, here.
> 0 votes

# Answer
# TI-BASIC, 58 bytes

```
getTimeStr(12
"It's "+sub(Ans,1,length(Ans)-2)+sub("ap",2-not(inString(Ans,"P")),1)+".m.

```

An ugly hack to build the correct output from the built-in `getTimeStr(`, which gives something like "8:59 PM". (By the way, the `12` means "12-hour format".)
> 0 votes

# Answer
# JavaScript (ES6), 95 bytes

```
x=(new Date+"").substr(16,5).split(':')
alert(`It's ${x[0]%12||12}:`+x[1]+(x[0]<12?'a':'p')+'.m.')

```
> 0 votes

# Answer
# Hassium, 125 Bytes

```
func main(){print("It's "+date().hour%12+":"+date().minute);if(date().hour%12!=date().hour)print("p.m.");else print("a.m.");}

```

Run it (and for expanded) here
> 0 votes

# Answer
# Octave 54 bytes

5 bytes shorter than the shortest MATLAB submission and 21 bytes shorter than the shortest Octave submission. Uses Octave's "index everywhere" functionality.

```
disp(['It''s ',lower(datestr(now,16))([1:5,7]),'.m.'])
It's 12:34p.m.

```
> 0 votes

# Answer
# Bash, 32 bytes

```
printf "%(It's %H:%M:%S%P^H.m.)T"

```

Where `^H` is a literal backspace character. Here's a hex dump (use `xxd -r` to reverse it):

```
0000000: 7072 696e 7466 2022 2528 4974 2773 2025  printf "%(It's %
0000010: 483a 254d 3a25 5325 5008 2e6d 2e29 5422  H:%M:%S%P..m.)T"

```
> 0 votes

# Answer
# Thunno 2 `j`, 36 bytes

```
ʋ.m.`apkL12®ikKkL⁻12%⁺,TȷḋẸ':s"It's

```

Try it online!

#### Explanation

```
ʋ.m.`apkL12®ikKkL⁻12%⁺,TȷḋẸ':s"It's    # Full program

                              "It's   "# Step 1 (get the prefix string):
                              "It's   "#  Push the string "It's "

             kKkL⁻12%⁺,TȷḋẸ':s        '# Step 2 (get the time):
               kL                      #  Push the current hours (24-hour format)
                 ⁻                     #  Decrement it
                  12%                  #  Modulo by 12
                     ⁺                 #  Increment it
             kK       ,                #  Pair with the current minutes
                        ȷ              #  And to each one:
                       T ḋ             #   Divmod it by 10
                          Ẹ            #  Dump both onto the stack
                           ':s        '#  Push a ":" between the two pairs

ʋ.m.`apkL12®i                          # Step 3 (get the suffix string):
       kL                              #  Push the current hours again
         12®                           #  Check if it's >= 12
    `ap     i                          #  Index this into the string "ap"
ʋ.m.                                   #  Push the string ".m."

                                       # Join the stack into a string, joining
                                       # lists on the stack implicitly as well

                                       # Implicit output

```
> 0 votes

# Answer
## Pascal, 83 B (subject to implementation characteristics)

Extended Pascal, ISO standard 10206, furnishes Pascal with some time-related routines and a data type `timeStamp`. However, the specific behavior of `getTimeStamp`, whether it populates a `timeStamp` with the ”local time“, UTC, wall time or else, is *implementation-defined*. Similarly the format `time` returns is implementation-defined, too. For instance, it could depend on the value of the `LC_TIME` environment variable if the implementation says so. It is therefore not guaranteed that the following implementation meets all task specification requirements in all ISO-compliant Pascal implementations.

```
program t(output);var t:timeStamp;begin getTimeStamp(t);write('It''s ',time(t))end.

```

Note, it is not checked that `t.timeValid` is `true` but in a real-life application it is advisable.
> 0 votes

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


title: Multiplicity of a root of a polynomial

text:
# Question
Title: Multiplicity of a root of a polynomial
Let \\$p(x)\\$ be a polynomial. We say \\$a\\$ is a **root of multiplicity \\$k\\$** of \\$p(x)\\$, if there is another polynomial \\$s(x)\\$ such that \\$p(x)=s(x)(x-a)^k\\$ and \\$s(a)\ne0\\$.

For example, the polynomial \\$p(x)=x^3+2x^2-7x+4=(x+4)(x-1)^2\\$ has \\$1\\$ and \\$-4\\$ as roots. \\$1\\$ is a root of multiplicity \\$2\\$. \\$-4\\$ is a root of multiplicity \\$1\\$.

## Task

Given a nonzero polynomial \\$p(x)\\$ and a root \\$a\\$ of it, find the multiplicity of \\$a\\$.

The coefficients of \\$p(x)\\$ are all integers. \\$a\\$ is also an integer.

You may take the polynomial in any reasonable format. For example, the polynomial \\$x^4-4x^3+5x^2-2x\\$ may be represented as:

* a list of coefficients, in descending order: `[1,-4,5,-2,0]`;
* a list of coefficients, in ascending order:`[0,-2,5,-4,1]`;
* a string representation of the polynomial, with a chosen variable, e.g., `x`: `"x^4-4*x^3+5*x^2-2*x"`;
* a built-in polynomial object, e.g., `x^4-4*x^3+5*x^2-2*x` in PARI/GP.

When you take input as a list of coefficients, you may assume that the leading coefficient (the first one in descending order) is nonzero.

This is , so the shortest code in bytes wins.

## Testcases

Here I use coefficient lists in descending order:

```
[1,2,-7,4], 1 -> 2
[1,2,-7,4], -4 -> 1
[1,-4,5,-2,0], 0 -> 1
[1,-4,5,-2,0], 1 -> 2
[1,-4,5,-2,0], 2 -> 1
[4,0,-4,4,1,-2,1], -1 -> 2
[1,-12,60,-160,240,-192,64,0], 2 -> 6

```

# Answer
> 6 votes
# Jelly, 3 bytes

```
Ærċ

```

Try it online!

Takes input as a list of coefficients in ascending order. The Footer on TIO reverses each of the test cases to fit this.

## How it works

```
Ærċ - Main link. Takes a polynomial P on the left, and a root r on the right
Ær  - Calculate the roots of P, with repeats
  ċ - Count the number of times r appears in the list of roots

```

# Answer
> 6 votes
# JavaScript (ES7), 62 bytes

Expects `(root)(polynomial)`, where *polynomial* is a list of coefficients in ascending order.

```
(r,s=0)=>g=p=>s?-1:1+g(p.map((c,i)=>(s+=c*r**i,c*i)).slice(1))

```

Try it online!

### How?

This simply recursively computes the successive derivatives of the polynomial:

$$P\_{k+1}(x)=\frac{d}{dx}P\_k(x)$$

until \\$P\_k(r)\neq 0\\$ and returns the number of iterations.

### Commented

```
(                   // outer function taking:
  r,                //   the root r
  s = 0             //   the sum s of the polynomial evaluation
) =>                //
g = p =>            // inner recursive function taking the polynomial p[]
s ?                 // if s is not equal to 0:
  -1                //   stop the recursion and decrement the final result
:                   // else:
  1 +               //   increment the final result
  g(                //   do a recursive call with the derivative of p[]:
    p.map((c, i) => //     for each coefficient c at position i in p[]:
      (             //
        s +=        //       add to s:
          c *       //         the coefficient multiplied by
          r ** i,   //         the root raised to the power of i
        c * i       //       set the new coefficient to c * i
      )             //
    ).slice(1)      //     end of map(); remove the leading term
  )                 //   end of recursive call

```

---

# 59 bytes

A version without `slice()` suggested by @tsh.

```
(r,s=k=0)=>g=p=>s?~k:g(p.map(c=>(s+=0|c*r**i,c*i++),i=k--))

```

Try it online!

# Answer
> 4 votes
# Python 3.8 (pre-release), 65 bytes

```
f=lambda p,r,c=0:(q:=[c:=b+c*r for b in p])!=c==0and-~f(q[:-1],r)

```

Try it online!

Divides by the linear factor X-root and recurses if the remainder is zero.

# Answer
> 3 votes
# Factor \+ `math.polynomials`, 58 bytes

```
[ [ 2dup polyval 0 = ] [ dup pdiff swap ] produce length ]

```

Try it online!

Takes `root polynomial` where the polynomial is given as a sequence of coefficients in ascending order. Uses the method described in Arnauld's JavaScript answer. `polyval` evaluates a polynomial given a value and `pdiff` computes the derivative of a polynomial. `produce` creates a list of successive derivatives until one evaluates to nonzero. Then take the length of the list.

# Answer
> 3 votes
# Rust, 105 bytes

```
|a,r|{let mut j=0;while 0==(0..).zip(&mut*a).map(|(i,c)|{let d=*c*r.pow(i);*c*=i as i32;d}).sum(){j+=1}j}

```

Try it online!

It's a `fn(&mut[i32], i32) -> usize`. Uses the same approach as Arnauld's JS answer.

# Answer
> 2 votes
# Mathematica, 19 bytes

```
#~Roots~x~Count~#2&

```

Takes inputs as equations: `polynomial == 0, x == root`.

If this is not allowed:

## Mathematica, 27 bytes:

```
Count[Roots[#==0,x],x==#2]&

```

View them on Wolfram Cloud!

# Answer
> 2 votes
# SageMath, 29 bytes

```
lambda p,a:dict(p.roots())[a]

```

Try it online!

Inputs a polynomial \\$p\\$ and a root \\$a\\$ of \\$p\\$.
Uses `p.roots()` which returns the roots of \\$p\\$ along with their multiplicity as a list of \\$2\\$-element tuples. Turning this into a dictionary requires only a simple lookup of the root to find its multiplicity.

# Answer
> 2 votes
# Maxima, 29 bytes

```
f(p,a):=hipow(factor(p),x-a);

```

Try it online!

Factorises \\$p(x)\\$, taken as a built-in polynomial object, and returns the exponent of \\$x-a\\$.

# Answer
> 2 votes
# Desmos, 103 bytes

```
k=l.length
L=[0...k-1]
I=[n...k-1]
f(l,R)=L[[0^{total(R^{[0...k-n]}I!l[n+1...]/(I-n)!)^2}forn=L]=0].min

```

Try It On Desmos!

Try It On Desmos! - Prettified

Function \\$f(l,R)\\$ takes in a list of coefficients in ascending order and the root \\$R\\$.

Uses Arnauld's strategy of repeatedly taking derivatives, so go upvote his answer too!

There's probably a way of shortening the `L=[...]` `I=[...]` part since they are so similar but I don't see it at the moment.

Might post an explanation if I feel like it, though if you understand Desmos enough it shouldn't be too hard to decipher.

# Answer
> 1 votes
# Charcoal, 21 bytes

```
Ｗ¬↨⮌θη≔ΦＥθ×κλλθＩ⁻ＬＡＬθ

```

Try it online! Link is to verbose version of code. Explanation: Uses the same differentiation trick as @Arnauld's answer.

```
Ｗ¬↨⮌θη

```

While the root is a root of the current polynomial (defaulting to the input polynomial) (using base conversion of the reversed polynomial to evaluate it)...

```
≔ΦＥθ×κλλθ

```

... differentiate the polynomial.

```
Ｉ⁻ＬＡＬθ

```

Output the difference in degree of the input and final polynomial.

# Answer
> 1 votes
# Raku, 51 bytes

```
{((|@^p,0),*[^(*-1)].produce(*×$^r+*)...*[*-1])-2}

```

Try it online!

This is an anonymous function that takes a polynomial as an array of coefficients in descending order, and a root. The arguments are stored in the placeholder variables `@^p` and `$^r` respectively.

The outermost parenthesized expression is a list, where each element is a list of polynomial coefficients followed by a remainder. `(|@p, 0)` is the first element of the list, the input polynomial with a zero remainder appended. Each successive term is the previous polynomial divided by \\$x - r\\$. The iteration ends when the the remainder term, `*[*-1]`, is nonzero/truthy.

`*[^(*-1)]` strips off the final remainder element of the previous coefficient/remainder list, and `.produce(* × $^r + *)` performs polynomial long division by \\$x - r\\$.

Finally, the `- 2` coerces the entire list of polynomials to a number, its length, and subtracting 2 gives the multiplicity of the root.

# Answer
> 1 votes
# , ~~14~~ 11 bytes

-3 bytes thanks to Bubbler

```
+/@E.1{::p.

```

Accepts a list of coefficients in ascending order

Attempt This Online!

```
+/@E.1{::p.
     1{::p. NB. monadic fork
         p. NB. computes boxed result of multipler;roots
     1{::   NB. fetches and lists contents of second box
+/@E.       NB. x E. y finds occurrences of x in y, returns boolean list
  @         NB. atop, executes E. dyadically and +/ monadically
+/          NB. sum reduce

```

# Answer
> 1 votes
# GeoGebra, 66 bytes

```
f=x
InputBox(f
k
InputBox(k
l=Flatten(Factors(f
l(IndexOf(x-k,l)+1

```

Input the polynomial in the first Input Box, and the root in the second Input Box.

All the heavy lifting is done by the built-in `Factors`.

Try It On GeoGebra!

# Answer
> 1 votes
# Japt, 20 bytes

I don't understand the challenge! So a port of Arnauld's solution will have to do for now.

```
T?J:Òß¡T±X*VpY X*YÃÅ

```

Try it

```
T?J:Òß¡T±X*VpY X*YÃÅ     :Implicit input of array U & integer V
T?                       :If T (initially 0) is truthy (not 0) then return
  J                      :  -1
   :                     :Else
    Ò                    :  Negate the bitwise NOT of (i.e., increment)
     ß                   :  Recursive call with argument (The unchanged V is implicit)
      ¡                  :    Map each X at 0-based index Y in U
       T±                :      Increment T by
         X*VpY           :      X multiplied by V raised to the power of Y
               X*Y       :      Return X*Y
                  Ã      :    End Map
                   Å     :    Slice off the first element

```

# Answer
> 1 votes
# PARI/GP, 23 bytes

Naïve solution:

```
(P,r)->valuation(P,x-r)

```

# Answer
> 1 votes
# Scala, 116 bytes

Port of @corvus\_192's Rust answer in Scala.

---

Ungolfed version. Try it online!

```
{(a,r)=>var j=0;while((0 until a.length).zip(a).map{case(i,c)=>val d=c*math.pow(r,i).toInt;a(i)*=i;d}.sum==0)j+=1;j}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val f: (Array[Int], Int) => Int = { (a, r) =>
      var j = 0
      while ((0 until a.length).zip(a).map {
        case (i, c) =>
          val d = c * math.pow(r, i).toInt
          a(i) *= i
          d
      }.sum == 0) j += 1
      j
    }

    assert(f(Array(4, -7, 2, 1), 1) == 2)
    assert(f(Array(4, -7, 2, 1), -4) == 1)
    assert(f(Array(0, 64, -192, 240, -160, 60, -12, 1), 2) == 6)
  }
}

```

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


# Question
Title: CGAC2022 Day 3: \$n\$-dimensional Chocolate Pyramid
Part of **Code Golf Advent Calendar 2022** event. See the linked meta post for details.

---

I've got an infinite supply of \\$n\\$-dimensional chocolate for some positive integer \\$n\\$. The shape of the chocolate is not important. You may assume that they are just \\$n\\$-dimensional hypercubes with side length \\$1\\$.

To celebrate the upcoming Christmas, I want to assemble them into a giant chocolate pyramid with \\$x\\$ layers. The base of the pyramid is an \\$(n-1)\\$-dimensional hypercube with side length \\$x\\$, which contains \\$x^{n-1}\\$ chocolates. The next layer is an \\$(n-1)\\$-dimensional hypercube with side length \\$x-1\\$, which contains \\$(x-1)^{n-1}\\$ chocolates. And so on. The top layer is a single chocolate.

For example, when \\$n=3\\$, the pyramid would contain \\$1^2 + 2^2 + \dots + x^2 = \frac{1}{6}x(x+1)(2x+1)\\$ chocolates.

Interestingly, for any dimension \\$n\\$, the number of chocolates in the pyramid is always a polynomial in \\$x\\$.

* When \\$n=1\\$, this is \\$\sum\_{k=1}^x k^0 = x\\$.
* When \\$n=2\\$, this is \\$\sum\_{k=1}^x k^1 = \frac{1}{2}x^2+\frac{1}{2}x\\$.
* When \\$n=3\\$, this is \\$\sum\_{k=1}^x k^2 = \frac{1}{3}x^3+\frac{1}{2}x^2+\frac{1}{6}x\\$.
* When \\$n=4\\$, this is \\$\sum\_{k=1}^x k^3 = \frac{1}{4}x^4+\frac{1}{2}x^3+\frac{1}{4}x^2\\$.
* When \\$n=5\\$, this is \\$\sum\_{k=1}^x k^4 = \frac{1}{5}x^5+\frac{1}{2}x^4+\frac{1}{3}x^3-\frac{1}{30}x\\$.

The general formula for these polynomials is called the Faulhaber's Formula.

Your task is to find the coefficients of these polynomials.

## Rules

The usual rules apply. So you may:

* Output all the polynomials.
* Take an input \\$n\\$ and output the \\$n\\$-th polynomial.
* ake an input \\$n\\$ and output the first \\$n\\$ polynomial.

You may use \\$0\\$-indexing or \\$1\\$-indexing.

You may output the polynomials in any reasonable format. Here are some example formats:

* a list of coefficients, in descending order, e.g. \\$\frac{1}{5}x^5+\frac{1}{2}x^4+\frac{1}{3}x^3-\frac{1}{30}x\\$ is represented as `[1/5,1/2,1/3,0,-1/30,0]`;
* a list of coefficients, in ascending order, e.g. \\$\frac{1}{5}x^5+\frac{1}{2}x^4+\frac{1}{3}x^3-\frac{1}{30}x\\$ is represented as `[0,-1/30,0,1/3,1/2,1/5]`;
* a function that takes an input \\$k\\$ and gives the coefficient of \\$x^k\\$;
* a built-in polynomial object.

Since the coefficients are not integers, you may output them as rational numbers, floating-point numbers, or any other reasonable format.

You may also take two integers \\$n, k\\$, and output the coefficient of \\$x^k\\$ in \\$n\\$-th polynomial. You may assume that \\$k\le n\\$.

This is , so the shortest code in bytes wins.

## Testcases

Here I output lists of coefficients in descending order.

```
1 -> [1, 0]
2 -> [1/2, 1/2, 0]
3 -> [1/3, 1/2, 1/6, 0]
4 -> [1/4, 1/2, 1/4, 0, 0]
5 -> [1/5, 1/2, 1/3, 0, -1/30, 0]
6 -> [1/6, 1/2, 5/12, 0, -1/12, 0, 0]
7 -> [1/7, 1/2, 1/2, 0, -1/6, 0, 1/42, 0]
8 -> [1/8, 1/2, 7/12, 0, -7/24, 0, 1/12, 0, 0]
9 -> [1/9, 1/2, 2/3, 0, -7/15, 0, 2/9, 0, -1/30, 0]
10 -> [1/10, 1/2, 3/4, 0, -7/10, 0, 1/2, 0, -3/20, 0, 0]
11 -> [1/11, 1/2, 5/6, 0, -1, 0, 1, 0, -1/2, 0, 5/66, 0]
12 -> [1/12, 1/2, 11/12, 0, -11/8, 0, 11/6, 0, -11/8, 0, 5/12, 0, 0]
13 -> [1/13, 1/2, 1, 0, -11/6, 0, 22/7, 0, -33/10, 0, 5/3, 0, -691/2730, 0]
14 -> [1/14, 1/2, 13/12, 0, -143/60, 0, 143/28, 0, -143/20, 0, 65/12, 0, -691/420, 0, 0]
15 -> [1/15, 1/2, 7/6, 0, -91/30, 0, 143/18, 0, -143/10, 0, 91/6, 0, -691/90, 0, 7/6, 0]
16 -> [1/16, 1/2, 5/4, 0, -91/24, 0, 143/12, 0, -429/16, 0, 455/12, 0, -691/24, 0, 35/4, 0, 0]

```

# Answer
> 3 votes
# Python3, 207 bytes:

```
import math
R=range
C=math.comb
B=lambda n,c={0:1,1:0.5}:c[n]if n in c else 1-sum(B(k)/(n-k+1)*C(n,k)for k in R(n))
def r(N):
 d=[0]*-~N
 for i in R(N):d[N-i]+=(1/N)*(-1)**i*C(N,i)*[B(i),-.5][i==1]
 return d

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 73 bytes

*-7 bytes thanks to @Neil*

Expects `(n,k)`, with \\$n\\$ 0-indexed. Returns the coefficient of \\$x^k\\$ in the \\$n\\$-th polynomial as a floating-point number.

```
f=(n,k,p=k)=>p--?f(n,k,p)*(p-n)/~p:(b=j=>j--?b(j)-f(k,j):1)(k)/(n+1-k||1)

```

Try it online!

### Less golfed

```
c = (n, k) => k-- ? c(n, k) * (k - n) / ~k : 1
b = (n, k) => k-- ? b(n, k)- f(n, k) : 1
f = (n, k) => k == n + 1 ? 0 : c(n, k) * b(k, k) / (n + 1 - k)

```

Try it online!

### How?

As a starting point, I used:

* the first alternate expression given on Wikipedia for Faulhaber's formula:

$$\color{grey}{\sum\_{k=1}^n k^p=}\sum\_{k=0}^p\dfrac{(-1)^{p-k}}{k+1}\binom{p}{k}B^-\_{p-k}\color{grey}{n^{k+1}}$$

(note that the convention used here is \\$B^-\_1=-1/2\\$ rather than \\$B^+\_1=+1/2\\$)
* the following recursive formula for Bernoulli numbers (also from Wikipedia):

$$B^-\_m=\delta\_{m,0}-\sum\_{k=0}^{m-1}\binom{m}{k}\dfrac{B^-\_k}{m-k+1}$$

(where \\$\delta\\$ is the Kronecker delta, which means that we have \\$\delta\_{m,0}=1\\$ if \\$m=0\\$ and \\$\delta\_{m,0}=0\\$ otherwise)

We can notice similarities between these formulae. So I've tried to factorize as much code as possible (especially the binomial and the division) and eventually came up with the following recursive functions:

$$b(n,k)=\begin{cases}1&\text{if }k=0\\ b(n,k-1)-f(n,k-1)&\text{if }k\>0\end{cases}$$

$$f(n,k)=\begin{cases}0&\text{if }k=n+1\\ \dfrac{\binom{n}{k}\times b(k,k)}{n+1-k}&\text{if }k\<n+1 \end{cases}$$

The coefficient of \\$x^k\\$ in the 0-indexed \\$n\\$-th polynomial is given by \\$f(n,k)\\$.

In the final JS code, the recursive computation of the binomial is merged into \\$f\\$ and the first argument of \\$b\\$ is actually taken from the scope of the caller.

# Answer
> 2 votes
# Python NumPy, 99 bytes

```
f=lambda n,i=1:q**~-n if i>n else(X:=f(n,i+1))+(q-1)**i/i*X[i-1]
from numpy import*
q=poly1d([1,0])

```

Attempt This Online!

# Python, 103 bytes

```
def f(n):
 Q=8**n;D,N=1,Q**n
 while n:D*=n;s=(2*N//Q**n-~Q)//2%Q-Q//2;N=N*n+Q*(Q-1)**n*s;yield s/D;n-=1

```

Attempt This Online!

Pure Python version using this tip by @xnor.

### Python NumPy, 104 bytes

```
lambda n:[Q:=q**~-n,*[Q:=Q+(q-1)**i/i*Q[i-1]for i in r_[n:0:-1]]][-1]
from numpy import*
q=poly1d([1,0])

```

Attempt This Online!

Now doing the Gauss elimination by hand.

### Python NumPy, 115 bytes

```
lambda n:-q*([q**~-n]*mat([q**n+((q-1)**i-q**i)for i in r_[n:0:-1]])[:,1:].I).A1
from numpy import*
q=poly1d([1,0])

```

Attempt This Online!

Directly solves the linear system of equations that arises from checking terms between p(X) and p(X-1). Uses polynomial (X-1)^k to generate binomial coefficients as needed.

Returns actual polynomials (`poly1d` objects).

### More explanation:

Consider the n+1 dimensional vector space of polynomials of degree \<= n with monomials 1,X,X^2,... as a basis. Changing variables X |-\> X+d for any constant d induces a linear map L\_d from the vector space onto itself as evaluating a polynomial p(X) at X+d yields a new polynomial in X of the same degree. The coefficients of the matrix representing this map will be products of binomial coefficients and powers of d.

Now let us focus on the specific polynomial c(X) this challenge is asking for. This polynomial has the property c(j)-c(j-1)=j^(n-1) for any natural number j. As both sides of this equation are polynomials they must be identical c(X)-c(X-1) = X^(n-1). This can be written in terms of the substitution maps L\_d, viz.:X^(n-1) =(L\_0-L\_-1) c.

What the code does is solving (or asking a library to solve) this equation.

# Answer
> 2 votes
# Desmos, ~~86~~ 84 bytes

```
K=[0...m-1]
S(m)=join(nCr(m,K)/m∑_{k=0}^K∑_{v=0}^k(-1)^vnCr(k,v)(v+1)^K/(k+1),0)

```

My outputs quickly deviate from the actual solutions due to some weird floating point issues, though that is allowed by OP.

Try It On Desmos!

Try it On Desmos! - Prettified

Copying off formulas from Wikipedia go brrr :P

### How?

I first started off from this formula from Wikipedia: $$S\_m(n)=\frac1{m+1}\sum\_{k=0}^m\binom{m+1}kB\_k^+n^{m+1-k}$$ Where (formula also from Wikipedia): $$B\_m^+=\sum\_{k=0}^m\sum\_{v=0}^k(-1)^v\binom kv\frac{(v+1)^m}{k+1}$$ So, $$S\_m(n)=\frac{\displaystyle\sum\_{k=0}^mn^{m+1-k}\binom{m+1}k\sum\_{x=0}^k\sum\_{v=0}^x(-1)^v\binom xv\frac{(v+1)^k}{x+1}}{m+1}$$ But this formula is shifted one to the left of what is expected; for example, \\$S\_3(n)\\$ gives \\$0.25n^4+0.5n^3+0.25n^2\\$, which is actually the expected output for `4`. To fix this, we will have to shift it back to the right; namely, we have to calculate \\$S\_{m-1}(n)\\$ instead. Plugging this into our formula gives: $$S\_{m-1}(n)=\frac{\displaystyle\sum\_{k=0}^{m-1}n^{m-k}\binom mk\sum\_{x=0}^k\sum\_{v=0}^x(-1)^v\binom xv\frac{(v+1)^k}{x+1}}m$$ Notice that this is just a sum of monomials in terms of \\$n\\$, and that the sum goes from higher powers of \\$n\\$ to lower powers of \\$n\\$. So, the list of descending coefficients would be: $$\frac{\displaystyle\binom mk\sum\_{x=0}^k\sum\_{v=0}^x(-1)^v\binom xv\frac{(v+1)^k}{x+1}}m$$ for \\$k=0,1,\ldots,m-1\\$.

But looking back at the formula for \\$S\_{m-1}(n)\\$, the outer sum only goes from monomials in terms of \\$n^m\\$ to \\$n\\$; specifically, we are missing the constant term. This means that the constant term is always \\$0\\$, which have the concatenate to the end of the list.

# Answer
> 2 votes
# Charcoal, 52 bytes

```
Ｎθ≔⟦¹⟧ηＦθ«⊞υ⁻¹↨Ｅυ∕×κ§ηλ⁻⊕ιλ¹⊞η⁰ＵＭη⁺κ§η⊖λ»Ｉ∕Ｅυ×ι§ηκθ0

```

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

```
Ｎθ

```

Input `n`.

```
≔⟦¹⟧η

```

Start with the first row of Pascal's Triangle.

```
Ｆθ«

```

Loop `n` times.

```
⊞υ⁻¹↨Ｅυ∕×κ§ηλ⁻⊕ιλ¹

```

Calculate the next Bernoulli number.

```
⊞η⁰ＵＭη⁺κ§η⊖λ

```

Calculate the next row of Pascal's triangle.

```
»Ｉ∕Ｅυ×ι§ηκθ

```

Output the first `n` coefficients.

```
0

```

Output the constant term.

55 bytes for a version with less floating-point inaccuracy using the newer version of Charcoal on ATO:

```
Ｎθ≔⟦¹⟧η≔Π…·¹θζＦθ«⊞υ⁻ζ↨Ｅ⮌×υη÷κ⁺²λ¹⊞η⁰ＵＭη⁺κ§η⊖λ»Ｉ∕×υη×θζ0

```

Attempt This Online! Link is to verbose version of code. Saves 8 bytes by being able to vectorised multiply two arrays. Explanation: Premultiplies the Bernoulli numbers by `n!` and then divides the final result by an extra `n!`.

# Answer
> 2 votes
# Jelly,  ~~24 23~~  15 bytes

```
c×>ɗþḶZæ*-ṪŻN-¦

```

A monadic Link that accepts a positive integer, \\$n\\$, and yields the coefficients in ascending order.

**Try it online!**

### How?

```
c×>ɗþḶZæ*-ṪŻN-¦ - Link: positive integer, n
     Ḷ          - lowered range (n) -> [0 .. n-1]
    þ           - (i in [1 .. n]) table (j in [0 .. n-1]) with operator:
   ɗ            -   last three links as a dyad f(i,j):
c               -     (i) choose (j)
  >             -     (i) greater than (j)?
 ×              -     multiply -> iCj if i>j else 0
      Z         - transpose
         -      - -1
       æ*       - matrix power
          Ṫ     - tail
           Ż    - prepend a zero
              ¦ - sparse application...
             -  - ...to indices: -1 (penultimate)
            N   - ...action: negate

```

# Answer
> 1 votes
# APL(Dyalog Unicode), ~~25 24 22~~ 20 bytes SBCS

-2 thanks to rak1507

```
-0,⊢⌷∘⌹(1∘+!⍥-⍳)⍤0∘⍳

```

Try it on APLgolf!

Outputs coefficients in ascending order.

# Answer
> 1 votes
# 05AB1E, ~~39~~ 30 (or 29) bytes

```
LIÝδcθāε!©yL/yGü-ā*}®/}*I/`a)˜

```

-9 bytes and increased both speed and floating point accuracy (up to \\$n\leq20\\$) by porting *@Neil*'s Charcoal answer instead.
Therefore also outputs as decimals.

Try it online or verify all test cases.

If we're allowed to output each inner value wrapped in a list, it's 1 byte less by removing the trailing `˜`:
Try it online or verify all test cases.

**Original 39 bytes answer:**

```
ÎLD<δcÅl¾ζÐøU˜nO/тF©X2Føδ*O®}·s-}θ`s(s)

```

Port of *@JonathanAllan*'s Jelly answer, except without the builtins.. :/
Therefore also outputs as decimals in reversed order.

Try it online or verify the first 6 test cases. Very slow. Also rounds the result to 5 decimal points in the footer (feel free to remove the `5.ò` to see the actual unrounded output).

These kind of challenges aren't really 05AB1E's strong suit..

**Explanation:**

```
LIÝδcθ      # Get the input'th Pascal Triangle row:
L           #  Push a list in the range [1, (implicit) input]
 IÝ         #  Push another list in the range [0,input]
   δ        #  Apply double-vectorized over these two lists, creating a table of:
    c       #   Choose (binomial coefficient builtin)
     θ      #  Then only keep the last row of this matrix
āε!©yL/yGü-ā*}®/}
            # Get the first input amount of Bernoulli values:
ā           #  Push a list in the range [1,length] (without popping the list)
 ε          #  Map over each value:
  !         #   Push the factorial of this value
   ©        #   Store it in variable `®` (without popping)
    yL      #   Push a list in the range [1,value]
      /     #   Divide value! by each of these values
  yG        #   Loop the value-1 amount of times:
    ü       #    Map over each overlapping pair:
     -      #    Subtract them from one another
      ā     #    Push a list in the range [1,length] (basically [1,value])
       *    #    Multiply the values at the same positions in the lists
            #    (removing any access items of unequal length lists)
   }        #   Close the loop (resulting in a single wrapped value)
    ®/      #   Divide this wrapped result by the value! we've saved in variable `®`
 }          #  Close the map
*           # Multiply the values at the same positions in the lists together
 I/         # Divide each value by the input
   `a)      # Transform the trailing value to a 0:
   `        #  Pop the list and dump its values to the stack
    a       #  Transform the top value to 0 with an is_alphabetic builtin
     )      #  Wrap the values on the stack back into a list
      ˜     # (Optional: flatten the list of wrapped items to a list of items)
            # (after which the result is output implicitly)

```

`!©yL/yGü-ā*}®/` calculates Bernoulli numbers, based on this CJam answer of @PeterTaylor.
(A 05AB1E port of his answer would start to give incorrect results from around \\$n\>20\\$.)

```
Î           # Push 0 and the input-integer
 L          # Pop and push a list in the range [1,input]
  D<        # Duplicate, and decrease each value to range [0,input)
    δ       # Apply double-vectorized over these two lists, creating a table of:
     c      #  Choose (binomial coefficient builtin)
 Ål         # Get the lower triangle of this matrix
    ζ       # Zip/transpose this triangular matrix,
   ¾        # using 0 as filler for the unequal length rows
 ÐøU˜nO/тF©X2Føδ*O®}·s-}
            # Calculate the Inverse of this matrix:
 Ð          #  Triplicate this matrix
  ø         #  Zip/transpose the now square matrix back in the top copy
   U        #  Pop and put this transposed copy in variable `X`
  ˜         #  Flatten another copy
   n        #  Get the square of each value in this list
    O       #  Then sum it together
     /      #  Divide the values in the matrix by this sum
тF          #  Loop 100 times:
  ©         #   Store the current matrix in variable `®`
   X        #   Push the matrix from variable `X`
    2F      #   Inner loop 2 times:
      ø     #    Zip/transpose; swapping rows/columns
       δ    #    Apply double-vectorized on the two matrices:
        *   #     Multiply the values at the same positions in the matrices together
         O  #    Sum each inner row
          ® #    Push the matrix from variable `®`
     }·     #   After the inner loop: double each inner value in the top matrix
       s    #   Swap so the other matrix is at the top
        -   #   Subtract the values at the same positions of the matrices
 }          #  Close the outer loop
  θ         # Leave the last row of this Inverted matrix
   `        # Pop and dump its values to the stack
    s       # Swap so the second last value as at the top
     (      # Negate it
      s     # Swap it back
       )    # Wrap all values (including the initial 0) on the stack into a list
            # (which is output implicitly as result)

```

`ÐøU˜nO/тF©X2Føδ*O®}·s-` calculates the inverse of a matrix, which I've done before in this 05AB1E answer of mine.

# Answer
> 1 votes
# Wolfram Mathematica, 22 bytes

Try it online!

```
HarmonicNumber[x,1-#]&

```

---

### How?

`Sum[k^(n - 1), {k, 1, x}] // FullSimplify` reduces to `HarmonicNumber[x, 1 - n]`.

Here `HarmonicNumber[n, r]` means the \\$n\\$-th harmonic number of order \\$r\\$: \\$\ \ \ H\_n^{(r)}=\sum\_{i=1}^n 1 / i^r\\$

# Answer
> 0 votes
# PARI/GP, 21 bytes

```
n->sumformal(x^n--,x)

```

Attempt This Online!

A built-in.

---

# PARI/GP, 36 bytes

```
n->(1/(1-1/matpascal(n))[,^n+1])[n,]

```

Attempt This Online!

Output a list of coefficients in ascending order.

---
Tags: code-golf, math, sequence, polynomials
---


title: Is it an Element?

text:
# Question
Title: Is it an Element?
ello all, I hope this finds you well.

There are 118 elements on the Periodic table at the moment, each one corresponds to the number of protons in an atom's nuclei.

Each element also has a 'symbol'. Hydrogen has 'H', Helium has 'He' and so on. I want to know about these!

### Challenge:

Given 1 string as input, output `true` if the string is present as a symbol on the periodic table. Output `false` if not.

The string is case sensitive. While `He` is a valid symbol, `he` is not.

For reference, here are the elements that are valid symbols for this challenge (from wikipedia):

That is, if the string is any one of the elements in this list, output 'true':

```
Ac,Ag,Al,Am,Ar,As,At,Au,Ba,B,Be,Bh,Bi,Bk,Br,Ca,Cd,C,Ce,Cf,Cl,Cn,Cm,Co,Cr,Cs,Cu,Ds,Db,Dy,Er,Es,Eu,Fm,Fl,F,Fe,Fr,Ga,Gd,Ge,H,He,Hg,Hf,Ho,Hs,I,In,Ir,K,Kr,La,Li,Lr,Lv,Lu,Md,Mg,Mn,Mt,Mo,Mc,N,Na,Nb,Nd,Ne,Ni,Nh,No,Np,O,Og,Os,Pb,P,Pa,Pd,Po,Pr,Pm,Pt,Pu,Ra,Rb,Re,Rf,Rg,Rh,Rn,Ru,S,Sb,Sc,Sm,Sg,Se,Si,Sn,Sr,Ta,Tb,Tc,Te,Th,Ts,Tl,Ti,Tm,W,U,V,Xe,Y,Yb,Zn,Zr

```

And, Alphabetically indexed:

```
Ac,Ag,Al,Am,Ar,As,At,Au,
B,Be,Ba,Bh,Bi,Bk,Br,
C,Ca,Cd,Ce,Cf,Cl,Cn,Cm,Co,Cr,Cs,Cu,
Db,Ds,Dy,
Er,Es,Eu,
F,Fe,Fm,Fl,Fr,
Ga,Gd,Ge,
H,He,Hg,Hf,Ho,Hs,
I,In,Ir,
K,Kr,
La,Li,Lr,Lu,Lv,
Mc,Md,Mg,Mn,Mo,Mt,
N,Na,Nb,Nd,Ne,Ni,Nh,No,Np,
O,Og,Os,
P,Pa,Pb,Pd,Pm,Po,Pr,Pt,Pu,
Ra,Rb,Re,Rf,Rg,Rh,Rn,Ru,
S,Sb,Sc,Se,Sg,Si,Sn,Sm,Sr,
Ta,Tb,Tc,Te,Th,Ti,Tm,Tl,Ts,
U,
V,
W,
Xe,
Y,Yb,
Zn,Zr

```

This is a classic code golf, so be sure to reduce the number of bytes you use in any way possible.

Good luck~!

# Answer
> 16 votes
# Factor \+ `periodic-table`, ~~22~~ 17 bytes

```
[ elements key? ]

```

Attempt This Online!

Factor has a built in periodic table (with all 118 elements and no typos; I checked :D).

# Answer
> 14 votes
# Retina 0.8.2, ~~197~~ 195 bytes

```
^([HNOUVWY]|[CGLP]a|[DNPRSTY]b|[AMST]c|[CMNP][do]|Gd|[BCFGHNRSTX]e|[CHR]f|[AHMORS]g|[BNRT][ah]|[BLNST]i|Bk|[ACFT][lm]|Pm|Sm|[CIMRSZ]n|Ho|Np|[AELZ]r|[BCFIKPS]r?|[ACDEHOT]s|[AMP]t|[ACELPR]u|Lv|Dy)$

```

Try it online! Link includes test cases. Explanation: Grouping by last letter is slightly shorter than grouping by first letter. I also saved three bytes by handling Cd, Co, Md, Mo, Nd, No, Pd and Po together, Ba, Bh, Na, Nh, Ra, Rh, Ta and Th together, and Al, Am, Cl, Cm, Fl, Fm, Tl and Tm together. (Grouping by last letter didn't seem to offer the same opportunities.) Edit: Saved 2 bytes thanks to @DidierL by grouping B, Br, C, Cr, F, Fr, I, Ir, K, Kr, P, Pr, S and Sr together.

Edit: Added Be, which @JonathanAllen pointed out was missing from the table in the question.

# Answer
> 11 votes
# JavaScript (Node.js), 186 bytes

Returns `0` or `1`.

```
s=>parseInt("2cjns/5ogz/1r4hf/kafb8/1pszk/5vs1/1e/by01/5ywx//5m9t/3wh6q/nj4o/24hj/b8n5/21x5j//19b6u/65rh/bini/1/1/1/w/5/5yww".split`/`[([a,b,c]=Buffer(s),a-65)]||0,36)>>b&!(c|b<97|b>122)

```

Try it online!

All truthy inputs / Random falsy inputs

### Commented

```
s =>                    // s = input string
parseInt(               // parse as base-36:
  "2cjns/5ogz/.../5yww" //   lookup string
  .split`/`             //   turned into an array
  [(                    //
    [a, b, c] =         //   a, b, c = ASCII codes of the first
      Buffer(s),        //             three characters in s
    a - 65              //   use a - 65 as the lookup index
  )] || 0,              //   force to 0 if there's no entry
  36                    //
) >> b &                // right-shift by b positions (mod 32)
!(                      // test the least significant bit
  c |                   // make sure that s has either 1 or 2 chars.
  b < 97 | b > 122      // and that the 2nd one (if present) is a
)                       // lowercase letter

```

# Answer
> 8 votes
# Wolfram Language (Mathematica), 50 bytes

```
#~ElementData~"Abbreviation"&~Array~118~MemberQ~#&

```

Uses the inevitable builtin. Don't try it online, since it requires access to Mathematica's data repository that TIO doesn't have :( On the plus side, all of the nested argument precedences worked out so that the `~` syntax could be used without brackets.

# Answer
> 7 votes
# Nibbles, ~~98.5~~ 97.5 bytes (195 nibbles)

*Edit: -2 nibbles by changing the encoding*

```
?+! |_\$u .`/~`=`D-28\$N |+$\$! ~.@:@\$a $ 1e0ffdd0810caa7a28e383c93c330770433251ee362b67eb4b57b2c6f2899d4742d379353a3791767afb7dd86bbf684e52506db285eb7e59af343e632802eec0bde3135659c1618936c003d96bbca

```

Attempt This Online!

Similar 'build the element symbols using the lists of second letters for each first letter' approach to Neil's Charcoal answer.

**How?** (original 98.5-byte version):

```
?++! `%`D-26"j" |@\$u ~.$%:_$~ $
   !                                # zip together
       `D-26                        #  the hex data 243d...
                                    #  decoded using base 26 to " abc...y"
     `%     "j"                     #  and split on the letter "j"
                                    # with
                |@\$u               #  uppercase letters
                                    #  (printable ASCII filtered for uppercase)
                      ~             # by
                       .$           #  mapping over each group of lowercase letters
                          :_$       #  appending each to the uppercase letter
                         %   ~      #  and removing spaces
 ++                                 # flatten to a list of element-strings
?                              $    # and find the index of the input
                                    # (or zero if not found)

```

# Answer
> 6 votes
# \>=4.1, ~~235 232 224 221~~ 220 bytes

We build all valid element names by "overloading" the `/` operator with the function `strsplit`, then unpacking the string of single-character names. We unpack another string with all capital letters except J and Q, then paste them to the unpacked second characters of the two-character names.

I am sure it's very golfable because I am bad at this.

*edit: realized I can remove `UVW` from singletons.*
*edit2: -8 bytes due to Giuseppe tricks*
*edit3: `mapply` can be drop-in replaced with its simplified wrapper `Map`, thanks again Giuseppe* *edit4: another -1 byte from Giuseppe indexing trick*

```
\(x,`/`=strsplit)x%in%unlist(c('BCFHIKNOPSY'/'',Map(paste0,LETTERS[-17][-10],el('cglmrstu,eahikr,adeflnmorsu,bsy,rsu,emlr,ade,egfos,nr,r,airuv,cdgnot,abdeihop,gs,abdmortu,abefghnu,bceginmr,abcehimls,,,,e,b,nr'/',')/'')))

```

Attempt this Online

# Answer
> 5 votes
# Python, 210 bytes

*-10 bytes, thanks to Jonathan Allan*
*-11 bytes, thanks to xnor*

```
lambda s:s in{*"BCFHIKNOPSUVWY"}or"A"<s<"["<s[1:]in[*"cglmrstu,aehikr,adeflnmorsu,bsy,rsu,emlr,ade,egfos,nr,,r,airuv,cdgnot,abdeihop,gs,badormtu,,abefghnu,bcmgeinr,abcehslim,,,,e,b,nr".split(",")[ord(s[0])-65]]

```

Attempt This Online!

## Explanation

First check for one character element names.

If the name has two characters check if the first is between `A` and `[` (one after `Z`) in lexicographical order. Then check if the second character is a second character of an element name starting with the first character

# Python, 362 bytes

the naive approach

```
lambda s:s in"Ac,Ag,Al,Am,Ar,As,At,Au,Ba,B,Bh,Bi,Bk,Br,Ca,Cd,C,Ce,Cf,Cl,Cn,Cm,Co,Cr,Cs,Cu,Ds,Db,Dy,Er,Es,Eu,Fm,Fl,F,Fe,Fr,Ga,Gd,Ge,H,He,Hg,Hf,Ho,Hs,I,In,Ir,K,Kr,La,Li,Lr,Lv,Lu,Md,Mg,Mn,Mt,Mo,Mc,N,Na,Nb,Nd,Ne,Ni,Nh,No,Np,O,Og,Os,Pb,P,Pa,Pd,Po,Pr,Pm,Pt,Pu,Ra,Rb,Re,Rf,Rg,Rh,Rn,Ru,S,Sb,Sc,Sm,Sg,Se,Si,Sn,Sr,Ta,Tb,Tc,Te,Th,Ts,Tl,Ti,Tm,W,U,V,Xe,Y,Yb,Zn,Zr".split(",")

```

Attempt This Online!

# Answer
> 5 votes
# Python 3,  ~~222 219~~  212 bytes

-3 thanks to bsoelch! (Avoiding `enumerate`.)
-7 thanks to xnor! (Use the direct functional reference `[...].count`.)

```
[chr(i+65)+r[r>'y':]for i in range(26)for r in'cglmrstu,zaehikr,zadeflnmorsu,bsy,rsu,zelmr,ade,zefgos,znr,,zr,airuv,cdgnot,zabdehiop,zgs,zabdmortu,,abefghnu,zbcegimnr,abcehilms,z,z,z,e,zb,nr'.split(',')[i]].count

```

(Beryllium is included at a cost of 1 byte)

**Try it online!** Or see the test-suite.

Beatable with a hashing approach or even regex? (Edit or golfing bsoelch's ...until they golfed mine! ;p)

# Answer
> 5 votes
# Ruby, 158 bytes

```
->s{i=[*?B..?Z,*'Aa'..'Zr'].index(s)||2;",:wyp;S_F&?{}?z_o?sqo}]}wo?sg~<?2>~w}SZ|CooOj9Q_o?;"[i/7].ord[i%7]<1}

```

Attempt This Online!

# Answer
> 5 votes
# Thunno 2, 99 bytes

```
»ṘẋḄæØoṖßYp’ɲ»13BkAd×J“UẹÐċḷṘtƁMƓẠÇ|huṗ½ñ{ɓ[ṇẊ§ ?bx€Żcb0ḳßƝḄƤİỵṁ×cj"D³¿Œ_ɼỴıR9?ñ’Þ@YX§1OçG¦ʂŻ“Z€JwƇ

```

Try it online!

Inspired by Neil's Charcoal answer.

#### Explanation

The idea is to construct the first and second letter strings separately, and then zip them together. We can sort the first letters in alphabetical order, and then multiply the alphabet with a list of numbers to get the whole string. There are 8 `A`s, 7 `B`s, 12 `C`s, etc. So, we use the list `[8, 7, 12, ...]`. Then, we use base-255 compression to get the string of second letters, replacing it with a space where the symbol is only one letter, then after zipping we can remove the whitespace. Finally, after we've constructed the list, we can check if it contains the input.

```
»...»13BkAd×J“...“Z€JwƇ  # Implicit input
»...»13B                 # Compressed list [8,7,12,3,3,5,3,6,3,0,2,5,6,9,3,9,0,8,9,9,1,1,1,1,2,2]
        kAd×J            # Multiply elementwise with the uppercase alphabet - the first letters
             “...“       # Compressed string of second letters, or spaces where N/A
                  Z€J    # Zip with the first letters and join each pair into a string
                     w   # Remove whitespace (the space fillers in the second letters)
                      Ƈ  # Is the input in this list?
                         # Implicit output

```

# Answer
> 5 votes
# 05AB1E, 100 bytes

```
•ÍøλMI;ÌL₂<ý¤•13вAuS×J.•∊×FéÛÍ@ƶ
“¬E|*[óAR{œ₄ÝÑâWʒ$^CÓ%$mÚL—λ˜ÇåðH%,YεƒBJ!§½PΣvʒRþKα₂₁ânΔNθ5¨Ó•ø€áIå

```

Try it online!

Same as my Thunno 2 answer.

*-1 thanks to @KevinCruijssen*

#### Explanation

```
•...•13вAuS×J.•...•ø€áIå  # Implicit input
•...•13в                  # Compressed list [8,7,12,3,3,5,3,6,3,0,2,5,6,9,3,9,0,8,9,9,1,1,1,1,2,2]
        AuS×J             # Multiply elementwise with the uppercase alphabet - the first letters
             .•...•       # Compressed string of second letters, or spaces where N/A
                   ø      # Zip with the first letters and join each pair into a string
                    €á    # Remove whitespace (the space fillers in the second letters)
                      Iå  # Is the input in this list?
                          # Implicit output

```

# Answer
> 4 votes
# Ruby, ~~207 190~~  192 bytes

```
->n{k=!j=8
"&$&%$%&$$&%$$%	'($($$$3'&$%*6&$$)$$$&$%44)@$%7*$(6&$G$$+'B'k6+,&$4$&*$(4$%$&$)$>/5$%,%&%$W$&$$$)*4$%%%'$'6$$%&$&$)\xA5DS'".bytes{|i|k||=n==(j+=i>9?i-35:338).to_s(36).capitalize}
k}

```

Try it online!

For some reason, `TIO.run` pastes the `&` characters as `&` in the output formatted for this website, but the code at `TIO.run` shows them as a single character.

Produces all valid elements by incrementing `j` according to each term in the magic string and converting the result to a base 36 number. The increment of `j` is based on `ASCII CODE - 35` to avoid having `"` or `#` in the string.

Single-letter elements are first in this order, and there is a big jump of 338 from `Y` to `Ac` which requires special handling as it won't fit in a single byte. The jump is encoded as a `TAB=ASCII 9`.

2 bytes added to make it work with `Be` and `S`

# Answer
> 4 votes
# Charcoal, 120 bytes

```
№⁻Ｅ”|«↓‹℅Zy⊗⌈↗⁷◧⟦π@0\`‽◧～Ｈ≕' t？¹6´↗T？ⅉς6σ”⁺ι§”&⌊↧\`rfV～⍘ＲＯＢ;ü⌈ê↙⌕Ｘhk~& №Ｅ⪪ＤＴN¿Ｏ-·⁶‹6n×⊟3✳∧Ａp｜λＸⅉω⪫¦⁻⊟»lC↓×；!"B⊘ⅈêα⊗◨·²”κjＳ

```

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

```
№                   Count of
                  Ｓ Input string in
   ”...”            Compressed string of first characters
  Ｅ                 Map over characters
         ι          Current character
        ⁺           Concatenated with
           ”...”    Compressed string of second characters
          §         Indexed by
                κ   Current index
 ⁻               j  Remove all `j`s from all strings
                    Implicitly print

```

The string of two-characters elements is 151 bytes compressed. I tried uppercasing the string which reduces it to only 127 bytes, with the decoding logic resulting in a 155 byte solution, but then I hit on the idea of compressing the first and last characters separately. I then saved a final two bytes by compressing the single-element names with a trailing `j` which I then remove afterwards.

# Answer
> 3 votes
# Python, 271 bytes

```
import re
re.findall("[A-Z][a-z]?","AcAgAlAmArAsAtAuBaBBhBiBkBrCaCdCCeCfClCnCmCoCrCsCuDsDbDyErEsEuFmFlFFeFrGaGdGeHHeHgHfHoHsIInIrKKrLaLiLrLvLuMdMgMnMtMoMcNNaNbNdNeNiNhNoNpOOgOsPbPPaPdPoPrPmPtPuRaRbReRfRgRhRnRuSSbScSmSgSeSiSnSrTaTbTcTeThTsTlTiTmWUVXeYYbZnZr").__contains__

```

ATO

# Answer
> 2 votes
# PowerShell Core, 257 bytes

```
$args-cin("AcAgAlAmArAsAtAuBBaBeBhBiBkBrCCaCdCeCfClCnCmCoCrCsCuDbDsDyErEsEuFFeFmFlFrGaGdGeHHeHgHfHoHsIInIrKKrLaLiLrLuLvMcMdMgMnMoMtNNaNbNdNeNiNhNoNpOOgOsPbPPaPdPoPrPmPtPuRaRbReRfRgRhRnRuSSbScSmSgSeSiSnSrTaTbTcTeThTsTlTiTmUVWXeYYbZnZr"-csplit'([A-Z][a-z]?)')

```

Try it online!

A naive approach, `cin` stands for `case sensitive in` and `csplit` for `case sensitive split`.

+2 bytes for Beryllium

# Answer
> 2 votes
# Python, 210 bytes

```
lambda s:1/(s in{*"BCFHIKNOPSUVWY"}or"A"<s*(s[1]in"cglmrstu,aehikr,adeflnmorsu,bsy,rsu,emlr,ade,egfos,nr,,r,airuv,cdgnot,abdeihop,gs,badormtu,,abefghnu,bcmgeinr,abcehslim,,,,e,b,nr".split(",")[ord(s[::2])-65]))

```

Many thanks to bsoelch's python answer!

I refactored it so it returns `1.0` if the input is an element and raises an Exception if it isn't.

Interesting notes:

1. The `*` is used as a boolean AND.
2. `s[::2]` produces every second element, and `ord` raises an Exception if its argument is longer than one character. So, this expression filters out anything 3 chars or longer

Attempt This Online!

# Answer
> 2 votes
# C (GCC), ~~276~~ 274 bytes

*-2 bytes thanks to @ceilingcat*

```
f(x,s,i,j)char*x,*s;{s="-cglmrstu-@aehikr-@adeflmnorsu-bsy-rsu-@elmr-ade-@efgos-@nr--@r-airuv-cdgnot-@abdehiop-@gs-@abdmortu--abefghnu-@bcegimnr-abcehilms-@-@-@-e-@b-nr";i=*x++-64;j=*x?:64;*x=i&&i<27&63<j&j<123&*x*x[1]<1;for(;*x=*x*i>0;)i-=*s++==45;for(;*s-45;)*x|=j==*s++;}

```

Attempt This Online!

# Answer
> 1 votes
## Pascal, 352 bytes

This `function` requires a processor supporting features of ISO standard 10206 “Extended Pascal”, in particular the `string` schema data type and `index` string search function.

```
type t=string(3);function f(s:t):Boolean;begin case length(s)of 1:f:=index('BCFHIKNOPSUVWY',s)>0;2:f:=odd(index('AcAgAlAmArAsAtAuBaBeBhBiBkBrCaCdCeCfClCmCnCoCrCsCuDbDsDyErEsEuFeFlFmFrGaGdGeHeHfHgHoHsInIrKrLaLiLrLuLvMcMdMgMnMoMtNaNbNdNeNhNiNoNpOgOsPaPbPdPmPoPrPtPuRaRbReRfRgRhRnRuSbScSeSgSiSmSnSrTaTbTcTeThTiTlTmTsXeYbZnZr',s));otherwise f:=6=9 end end;

```

Ungolfed:

```
type
    { A schema data type `string` is an Extended Pascal extension.
      Here we discriminate `string` to have (at least) a capacity
      exceeding one character than the longest abbreviation. }
    tripleCharacter = string(3);

{ NB: When calling with a string literal longer than three characters,
      the extra character are silently clipped. }
function isElementAbbreviation(protected sample: tripleCharacter): Boolean;
    const
        single = 'BCFHIKNOPSUVWY';
        double = 'AcAgAlAmArAsAtAuBaBeBhBiBkBrCaCdCeCfClCmCnCoCrCsCu' +
                 'DbDsDyErEsEuFeFlFmFrGaGdGeHeHfHgHoHsInIrKrLaLi' +
                 'LrLuLvMcMdMgMnMoMtNaNbNdNeNhNiNoNpOgOs' +
                 'PaPbPdPmPoPrPtPuRaRbReRfRgRhRnRuSbScSeSgSiSmSnSr' +
                 'TaTbTcTeThTiTlTmTsXeYbZnZr';
    begin
        case length(sample) of
            1:
            begin
                { In Pascal `string`s indices are 1-based.
                  `index` returns `0` if nothing was found. }
                isElementAbbreviation := index(single, sample) > 0;
            end;
            2:
            begin
                { Do not match, for example, `'cA'`. }
                isElementAbbreviation := odd(index(double, sample));
            end;
            otherwise
            begin
                isElementAbbreviation := false;
            end;
        end;
    end

```

# Answer
> 1 votes
# Python, 229 bytes

Thanks to @Neil for the regex - :)

```
import re;bool(re.match("([HNOUVWY]|[CGLP]a|[DNPRSTY]b|[AMST]c|[CMNP][do]|Gd|[BCFGHNRSTX]e|[CHR]f|[AHMORS]g|[BNRT][ah]|[BLNST]i|Bk|[ACFT][lm]|Pm|Sm|[CIMRSZ]n|Ho|Np|[AELZ]r|[BCFIKPS]r?|[ACDEHOT]s|[AMP]t|[ACELPR]u|Lv|Dy)",input()))

```

...go brr

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