# Question
Title: I am passive aggressive and want to insult my boss without him finding out
It's been a rough few months at work and I feel like I just want to scream right to my boss' face. I am, however, not one to directly confront people I have a problem with. I also don't want to lose my job.

So here's an idea: I want to be able to insult him, without him ever finding out. And I realized the perfect way: I need some sort of software that encodes an insult inside an otherwise perfectly fine message. And seeing as how he's known to not see forests for trees, I think I know just how:

Write me a program that takes as input a string of unknown length, but containing no line breaks. This will be the raw message I want to send.

If possible, return the string formatted such that the message "DIE IN A GREASE FIRE" makes up the entire left column. With new paragraphs where spaces in between words should go. Now, as I am very angry, it is equally important that every letter is in upper case.

You may not modify the string in any other way, i.e. you may not turn all of the string into upper case characters.

If the string in question cannot be formatted in this way, you are to return the original string. Read input from standard input.

Normal rules apply: No HTTP requests, no consulting Marvin from THGTTG, etc.

Example input:

> Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance level for taking the blame took a serious dent then. From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments. Right where we always seem to end up these days. Every single project. It's becoming unbearable.

Example output:

> Dear Boss, how are things?
> It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.
> Every last bit of it.
>
> Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.
> Not that I think I should stand without blame. Not at all.
>
> All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.
>
> Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.
> Remember the Flakenhauser contract.
> Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.
> All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.
> Still, I - alone - took blame for it.
> Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.
>
> From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again.
> In spite of all my accomplishments.
> Right where we always seem to end up these days.
> Every single project. It's becoming unbearable.

This is code golf. Shortest code wins.

# Answer
# CJam, ~~56~~ 53 bytes

```
q_"DIEIINAAGGREASEFFIRE"{S@:A+S@+#:BA<AB>}%(!B)*\N*@?

```

Try it online!

### How it works

```
q_                     Read all input from STDIN and push a copy.
"DIEIINAAGGREASEFFIRE" Push the characters we're searching for in form of a
                       string. We'll try to prepend a linefeed to all of them.
                       Some characters are duplicated to prepend two linefeeds.
{                      For every character C in that string:
  S@                   Push ' ' and rotate the string on the stack on top of it.
  :A                   Save the string (initially the input) in A.
  +                    Prepend the space to A.
  S@+                  Construct the string " C".
  #                    Compute the index of " C" in the modified A.
  :B                   Save the index in the variable B.
  A<                   Push the substring of A up to the index.
  AB>                  Push the substring of A after the index.
}%
(                      Shift the first element of the resulting array.
!                      Compute the logical NOT. This pushes 1 if and only if the
                       array's first element is an empty string, which is true
                       if and only if the input string started with a D.
B)                     Push the last value of B and increment. If the last match
                       was successful and, therefore, all matches were successful,
                       B != -1, so B + 1 != 0.
*                      Compute the product of the two topmost items on the stack.
\                      Swap the resulting Booleanr with the array of substrings.
N*                     Join the array, separating by linefeeds.
@                      Rotate the input string on top of the stack.
?                      Select the joined array if the Boolean is 1 and the input
                       string otherwise.

```
> 55 votes

# Answer
## Perl - 60 bytes

```
#!perl -p
$_=(join$/,$_=~('DIE\IN\A\GREASE\FIRE'=~s/./($&.*)/gr))||$_

```

Counting the shebang as one.

This solution uses the innermost string to build up the following regex:

```
(D.*)(I.*)(E.*)(\.*)(I.*)(N.*)(\.*)(A.*)(\.*)(G.*)(R.*)(E.*)(A.*)(S.*)(E.*)(\.*)(F.*)(I.*)(R.*)(E.*)

```

which is similar to the regex used in m.buettner's solution. The generated regex is then matched against the input. In a list context, this will return an array containing each of the match groups, which are joined together by a newline (the reason for the 'match nothing' groups `(\.*)`, is to insert an additional newline). If there is no match, the original string is output instead.

---

## Perl - 73 bytes

```
#!perl -pl
$s=$_}for(map$s!~s/.*?(?=$_)//?$\='':$&,'DIEI.NA.G.REASEF.IRE$'=~/./g){

```

Counting the shebang as two.

This splits up the string at the appropriate delimiters, and collects the pieces in an array. If any of them fail to match, the output record separator (which was set to a newline with the `-l` option) is unset, and so the string is output unmodified.
> 26 votes

# Answer
# GolfScript, 53 bytes

Looks like Dennis and I came up with pretty similar things in parallel... But here's my attempt.

Click on the links before each code block to try it online. Unfortunately, the online interpreter won't allow you to run code larger than 1024 characters, so I had to perform some... "compression" of the test input. But it does still work.

Squished version

```
..(\;68=(>"IEIINAAGGREASEFFIRE"{1$.@?:^<n@^>}/](]^0<=

```

Unsquished, commented version

```
.       # (Save input)
.(\;    # Get first character
68=(>   # If 'D', work with input; else, work with one-character string
"IEIINAAGGREASEFFIRE"
{       # For each character
 1$.@   # (Duplicate message twice)
 ?:^    # Find first index of character
 <n     # Extract part before index and add a newline
 @^>    # Extract part including and after index as new "message"
}/      # (Close loop)
](]^0<= # If last line was successfully matched, select result; else, select input

```

A point raised by Dennis: All GolfScript programs print an automatic final newline. Whether or not this should invalidate my solution as-is, I'm not sure. I believe it would cost 4 characters to suppress the final newline by adding `"":n` somewhere near the end.
> 13 votes

# Answer
# JavaScript 116

Javascript implementation of m-buettner's idea

```
console.log((RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z=prompt())||[,z]).slice(1).join('\n'))

```

**Test** snippet

```
z="Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance level for taking the blame took a serious dent then. From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments. Right where we always seem to end up these days. Every single project. It's becoming unbearable.";

T1.textContent = (RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')

z='From that FIFA point on'
T2.textContent = (RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')
```

```
pre { border: 1px solid black }
```

```
T1<pre id=T1></pre>
T2 (the FIFA test)<pre id=T2></pre>
```
> 7 votes

# Answer
### Ruby - 140

```
a="DIEINAGREASEFIRE";n=[4,6,7,13];i=0;o='';s=ARGV[0]
s.chars.each{|c|
if c==a[i]
i+=1;o+="\n";o+="\n"if n-[i]!=n
end
o<<c
}
puts((i<16)?s:o)

```

**No regexes in this one**. It simultaneously walks the characters in the ARGV\[0\] input, and a string containing characters we need to break on to make our left-column message. Was originally going to stick spaces after the letters that need to have a newline, but found that it was a bit shorter to hardcode the indexes at which to insert the line break.

Once all is said and done, it checks to see that the `i` index has incremented enough times to have gone through every letter that needed breaking. If it hasn't, we just print out the original string. If it has, we give 'em the formatted one.

`n-[i]!=n` was a neat trick to save characters when checking whether or not the current index was one that needed an extra line break (as compared to `n.include? i`). Also saved some characters by using `{}`s instead of `do/end` despite being a multiline block, and used a ternary condition on the final puts to save characters when determining which one to output.

Not the shortest, but I thought it would be neat to do without regular expressions.
> 7 votes

# Answer
## Perl, 184 bytes

Not a spectacular score for Perl, but here is a simple regex solution

```
$_=<>;s/^(D.*) (I.*) (E.*) (I.*) (N.*) (A.*) (G.*) (R.*) (E.*) (A.*) (S.*) (E.*) (F.*) (I.*) (R.*) E/$1\n$2\n$3\n\n$4\n$5\n\n$6\n\n$7\n$8\n$9\n$10\n$11\n$12\n\n$13\n$14\n$15\nE/;print;

```
> 6 votes

# Answer
# Python3 (166 138)

Golfed:

```
s='';o=input()
for n in o.split():s+=[n,'\n'+n.title()][n[0]==("DIEINAGREASEFIRE"*len(o))[s.count('\n')]]+' '
print([o,s][s.count('\n')==16])

```

Ungolfed-ish:

```
format_s = ''
unformat_s = input()
for n in unformat_s.split():
    format_s += [n, '\n' + n.title()][n[0] == ("DIEINAGREASEFIRE"*len(unformat_s))[format_s.count('\n')]] + ' '
print([unformat_s, format_s][format_s.count('\n') == 16])

```

Although the use of the lambda pleases me somewhat, that mass number of variables used and the somewhat messy development has the opposite effect. Regex may have been a good idea too. Hay ho, at least it works :).

Edit: replaced lambda variable with `count` builtin, and shortened split statement.
> 5 votes

# Answer
# J - ~~110~~ 103 bytes

Why doesn't J have good functions to handle strings, but only array functions? I'll revise this if I figure out something smart.

Edit: Shortened and fixed output (it had extra spaces before) and checking. I also improved the explanation.

```
f=:[:>,&.>/@('IEIINAAGGREASEFFIRE'&t=:(}.@[t{.@[(}:@],(((0{I.@E.)({.;LF;}.)])>@{:))])`]@.(0=#@[))@< ::]

```

### Explanation:

> I'll denote function usage as `[<left argument>] <function name> <right argument>`, e.g. `f <text>`. I also won't explain every detail because the function is quite long.
>
> `@` applies the right function to the left function, eg. `f@g x == f(g(x))`
>
> `t=:(}.@[t{.@[(}:@],(((0{I.@E.)({.;LF;}.)])>@{:))])']@.(0=#@[)` is a recursive function `<delimiters> t <boxed string>` that splits the string with every delimiter, in order. Fails if some delimiter is not found.
>
> `(((0{I.@E.)({.;LF;}.)])>@{:)` splits the string from the left side of the delimiter, adding a linefeed between them.
>
> `>@{:` gets the last string from a list (the one which hasn't been split yet)
>
> `0{I.@E.` gets the index to split at, failing if the delimiter doesn't exist.
>
> `{.;LF;}.` concatenates left side of the split, linefeed and right side of the split
>
> `}:@],` concatenates results of the earlier splits and the result of the last function (last meaning: look up)
>
> `']@.(0=#@[)` checks if there's any delimiters left, and calls the function described above (5 lines) if there is. Otherwise returns.
>
> `'IEIINAAGGREASEFFIRE'&` sets the left argument of `t` to that string
>
> `[:>,&.>/@` joins the results of splitting
>
> `::]` if something fails (I made the search for the split index the weak point), return the original string.

### Examples (too long?):

```
   f 'Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I''m saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance lev...
Dear Boss, how are things?
It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.
Every last bit of it.

Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.
Not that I think I should stand without blame. Not at all.

All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.

Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.
Remember the Flakenhauser contract?
Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.
All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.
Still, I - alone - took blame for it.
Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.

From that point on,
I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments.
Right where we always seem to end up these days.
Every single project. It's becoming unbearable.
   f 'Die in a grease fire. It''s fun. Every time.'
Die in a grease fire. It's fun. Every time.
   f 'hai'
hai

```
> 1 votes

# Answer
---

# Python3 (165)

```
def c(m,h,l=[]):
 if h:s=m.rindex(h[0]);l=[m[s:]]+l;return c(m[:s],h[1:],l)
 return[m]+l
i=input()
try:print('\n'.join(c(i,"ERIF ESAERG A NI EID")))
except:print(i)

```

### Ungolfed

```
def headings_remaining(headings): return len(headings) > 0
def head(s): return s[0]
def tail(s): return s[1:]
def prepend(l,e): l.insert(0, e)
def reverse(s): return s[::-1]

def chunk(message,headings,output_list=[]):
    if headings_remaining(headings):
        split_index = message.rindex(head(headings))
        message_init = message[:split_index]
        message_last = message[split_index:]

        prepend(output_list, message_last)
        return chunk(message_init, tail(headings), output_list)
    else:
        prepend(output_list, message)
        return output_list

input_message=input()
try:
    headings=reverse("DIE IN A GREASE FIRE")
    print('\n'.join(chunk(input_message,headings)))
except ValueError: # Couldn't keep splitting chunks because didn't find heading
    print(input_message)

```

### Explanation

`chunk` recursively splits off the end of the message containing the last heading and prepends it to a list.

Caveat: this won't work if there are no spaces at all between two proposed headings in your letter for some reason, but that seems unlikely in a letter to your boss.
> 1 votes

# Answer
**Ruby 115**

```
n,a,c,i=[4,6,7,13],gets,'',0;a.chars{|x|x=='DIEINAGREASEFIRE'[i]?(i+=1;c+="\n"if n-[i]!=n;c+="\n#{x}"):c+=x};puts c

```

**Ruby 95**

```
a,c,i=gets,"",0;a.chars{|x|x=="DIEINAGREASEFIRE"[i]?(i+=1;c+="\n#{x}"):(c+=x)};puts c

```
> 1 votes

# Answer
# JavaScript (ES6), ~~93~~ 115 bytes

```
alert(prompt(x=[...'DIEI1NA1G1REASEF1IRE',i=0]).replace(/\b./g,a=>i<20&&a.match(x[i])?(+x[++i]?i++&&`

`:`
`)+a:a))

```

I used `replace` to step through the string, with a match for `/\b./g` so as to only find characters that either followed a space or began the string. Then I checked each character to see if it matched the current index in the array I was looking for, and added a newline before it if it did, and incremented `i`.

EDIT: Missed the need to create newlines between words. I've done that now, which brings it up to 115.
> 1 votes

# Answer
**PHP, 328 bytes**

Given a file named 'G' containing the raw text to "enmessage"

```
<?php
$a=implode(file("G"));$b=str_split('DIEINAGREASEFIRE');foreach(array_unique($b) as $c){foreach(str_split($a) as $h=>$d){if($c==$d)$l[$c][]=$h;}}$e=-1;$n=$a;foreach($b as $f=>$c){foreach($l as $j=>$m){if($c==$j){foreach($m as $k=>$h){if($h>$e){$n=substr($n,0,$h)."\n".$c.substr($a,$h+1);$e=$h+2;break 2;}}}}}echo nl2br($n);

```

Explanation (~ungolfed && commented code) :

```
<?php
$string=implode(file("G"));          // raw text to deal with
$msg=str_split('DIEINAGREASEFIRE');  // hidden message (make it an array)

 // 2D array : [letters of the message][corresponding positions in txt]
foreach(array_unique($msg) as $letter) {
    foreach (str_split($string) as $pos=>$let) {
        if ($letter==$let) $l[$letter][]=$pos; //1 array per seeked letter with its positions in the string
    }
}

$currentPos=-1;
$newString=$string;
foreach ($msg as $key=>$letter) { // deal with each letter of the desired message to pass
    foreach($l as $cap=>$arrPos) {// search in letters list with their positions
        if($letter==$cap) {       // array of the current parsed letter of the message
            foreach($arrPos as $kk=>$pos) { // see every position
                if ($pos>$currentPos) {     // ok, use the letter at that position
                    $newString=substr($newString,0,$pos)."\n".$letter.substr($string,$pos+1); // add line break
                    $currentPos=$pos+2; // take new characters into account (\n)
                    break 2;            // parse next letter of the message
                }
            }
        }
    }
}                    /* (note that I could have added some other (random) line breaks management, so that
                      * the message is not TOO obvious... !*/
echo nl2br($newString);

```
> 1 votes

# Answer
# PHP, 136 bytes

```
for($f=" ".join(file(F));$c=DIEINAGREASEFIRE[$i++];){while(($p=strpos($f,$c,$p))&&$f[$p-1]>" ");$p?$f[$p-1]="\n":$i=20;}echo$i<20?$f:"";

```

if the whole insult can be put; prints the modified string with a leading space or linebreak; empty output if not. Run with `-r`.

**breakdown**

```
for($f=" ".join(file(F));       // read input from file "F"
    $c=DIEINAGREASEFIRE[$i++];) // loop through insult characters:
{
    while(($p=strpos($f,$c,$p))     // find next position of $c
        &&$f[$p-1]>" ");            // ... preceded by a space
    $p?$f[$p-1]="\n"                // if found, replace the space with a newline
    :$i=20;                         // else break the loop
}
echo$i<20?$f                // if modified text has the full insult, print it
    :"";                    // else print nothing

```
> 1 votes

# Answer
# Zsh \+ `sed`, ~~167~~ ... 158 bytes

```
cp a z;b=DIE_IN_A_GREASE_FIRE
for c (${(s::)b}){sed -i "$ s/ $c/ \n$c/" a
((##$b[j++]==95))&&sed -i '$ i\\' a}
$b()<a;`<a|cut -c -1|sed 's/^$/_/g'|rs -g0`||<z

```

Try it Online!

The long email one-liner is stored in file `a`. Using `sed -i '$ <blah>'` always edits the *last line* of `a`. The last line `$` is incrementally reduced as we insert `\n` characters.

Cut out quite a few bytes in the early versions of this solution. Added ~50 bytes for the 'original string' requirement. Ignored the STDIN thing per meta consensus.

Could be a lot shorter (101 bytes) if we ignore the requirement for extra line breaks

```
cp a z;b=DIEINAGREASEFIRE;for c (${(s::)b})sed -i "$ s/ $c/ \n$c/" a
$b()<a;`<a|cut -c -1|rs -g0`||<z

```

<sub>Old versions that don't fully meet the requirements:</sub> <sub>~~106 bytes~~</sub> <sub>~~115 bytes~~</sub> <sub>~~146 bytes~~</sub> <sub>~~153 bytes~~</sub> <sub>~~167 bytes~~</sub>
> 1 votes

# Answer
**Python - 190 Bytes**

```
l,r="IExINxAxGREASExFIRE","\n";k=p=raw_input();y=i=0
for c in l:
    if c!="x":
        h=len(p);x=p[y:h].find(c)
        if x==-1:i+=1
        p=p[0:x+y-1]+r+p[x+y:h];y=x+y;r="\n"
    else:r=r+r
if i!=0:p=k

```

**Ungolfed**

This is my first golf attempt :) Looking to learn some great coding techniques, regardless, I just focused on using find and then some string splicing to find the appropriate characters and format the output.

Variables -

l.r = l is assigned characters we will be using as our guide to create our new formatted paragraph. r is assigned the new line character for us in spacing the new output.

k,p = The input paragraph. K is used to revert to the original as it is not reassigned during execution of the script. I check against x to know when to add a double new line for spacing purposes.

y,i = y is a "cursor" of sorts, keeps track of the last position a character was found so we find through the paragraph correctly for splicing purposes, i is sanity check, if we don't hit all of our characters we revert the paragraph (p variable) to it's original input via the k variable.

h = Input length, which we use in splicing.

x = The position of the current character represented by C, used for splicing as well.

c = Characters in l to iterate and search for.

The following code is reworded and broken out from the original code for readability to as what is happening:

```
letters,return="IExINxAxGREASExFIRE","\n"
input1=input2=raw_input()
lastpos=sanity=0

for char in letters:
    if char != "x":
        inputlength=len(input1)
        charposition=input1[lastpos:inputlength].find(char)
        if charposition==-1:
            sanity+=1
        input1=input1[0:position+lastpos-1]+return+input1[position+lastpos:inputlength]
        lastpos=position+lastpos
        return="\n"
    else:return=return+return
if sanity!=0:
    input1=input2

```

I would appreciate your feedback! I am looking to learn.
> 0 votes

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


title: On The Subject Of Simon Says

text:
# Question
Title: On The Subject Of Simon Says
This challenge is from a game, Keep Talking And Nobody Explodes.

*This is like one of those toys you played with as a kid where you have to match the pattern that appears, except this one is a knockoff that was probably purchased at a dollar store.* – From the manual

# Objective

The **Simon Says** module consists of 4 colored buttons: **R**ed, **B**lue, **G**reen, and **Y**ellow. Given a sequence of button flashes and a sequence of button presses, decide whether it would disarm the module.

In the original game, the module consists of multiple stages, but in this challenge, only one stage will be considered.

# How To Disarm

* The buttons will flash in a sequence. These buttons shall be mapped accordingly to the chart below, and shall be pressed.
* You may press the wrong button in cost of a **strike**. Then the mapping will change. Only up to 2 strikes are tolerable because a 3rd strike will detonate the bomb.
* You must not press buttons anymore after the module is disarmed.

The chart:

```
Strikes\Flash Red    Blue   Green  Yellow
0             Blue   Red    Yellow Green
1             Yellow Green  Blue   Red
2             Green  Red    Yellow Blue

```

(This chart is for a bomb whose serial number has a vowel. It is assumed for the purpose of this code-golf challange.)

# I/O format

The input shall be two strings consisting of `R`, `B`, `G`, and `Y`, indicating the colors. Case sensitive.

Though in the game, a stage consists of up to 5 flashes, in this challenge, there may be an arbitrary nonzero number of flashes.

An input not fitting to this format falls in *don't care* situation.

The output format is flexible.

# Examples

Let's say the button flash sequence is `GRYBB`. The followings are examples of button press sequences:

## Truthy

* `YBGRR`
* `RBYRGG` (in cost of 1 strike)
* `YBGRBG` (in cost of 1 strike)
* `YBGBGRR` (in cost of 2 strikes)

## Falsy

* `YBG` (The module isn't disarmed yet)
* `RRR` (The 3rd strike detonated the bomb)
* `YBGRRB` (You cannot press buttons anymore after the module is disarmed)
* `RRRY` (You cannot press buttons after the bomb detonates)

# Answer
> 2 votes
# 05AB1E, 40 bytes

```
ε.•B¸}îÑu`öVÏ•u4ôćs¾ès‡IN¾-©èÊ½®}ÔèQ¾3‹*

```

Inputs in the order `button-press sequence, flash sequence`, where the `flash sequence` is a list of characters (`button-press sequence` can be either a string or character-list, doesn't matter too much).

Try it online or verify all test cases.

**Explanation:**

```
ε        # Map over the characters of the first (implicit) button-press sequence input:
 .•B¸}îÑu`öVÏ•
         #  Push compressed string "rbgybrygygbrgryb"
   u     #  Uppercase it
    4ô   #  Split it into parts of size 4
 ć       #  Extract head; pop and push remainder-list and first item separately
  s      #  Swap so the remainder-list is at the top
   ¾è    #  Index the strikes-counter `¾` into it,
         #  which is 0 by default
     s   #  Swap so the extracted head "RBGY" is at the top again
      ‡  #  Transliterate the current character according to these two strings
 I       #  Push the second flash sequence input-list
  N      #  Push the current map-index
   ¾-    #  Subtract the strikes-counter `¾` from it
     ©   #  Store this index in variable `®` (without popping)
      è  #  Pop and index it into the flash sequence input
 Ê       #  Check whether the two characters are NOT equal
  ½      #  If they aren't equal: increase the strikes-counter `¾` by 1
 ®       #  Push index `®`
}Ô       # After the map: connected-uniquify the list of indices
  è      # Index each into the second (implicit) input-list
   Q     # Check if it's equal to the second (implicit) input-list
       * # AND
    ¾3‹  # The strike-counter is smaller than 3
         # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•B¸}îÑu`öVÏ•` is `"rbgybrygygbrgryb"`.

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

Expects `(a)(b)`. Returns `0` or `1`.

```
a=>b=>Buffer(a).every(g=c=>"BRGR_GYBY"[c%s%12]==b[i++]||s++%5&&g(c),s=63,i=0)&!b[i]

```

Try it online!

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

Didn't do any more testing beyond the sample test cases.

```
f=(a,b,c=0)=>[...b].every((x,i)=>a[c]&&(c+="BRYGYGBRGRYB"[(i-c)*4+"RBGY".indexOf(a[c])]==x,i-c<2))&&c==a.length

```

Try it online!

Explanation:

* Init counter to 0
* For each character in b, check if counter is less than length of a
* Increment counter if the button is pressed correctly
* Exit early if there are 3 strikes
* Check whether the counter is equal to the length of a

# Answer
> 1 votes
# Retina 0.8.2, 97 bytes

```
T`RGYB`Ro`.+,
^(.+)(.*,)\1
$2
\b,.
,
T`BRGY`Ro`.+,
^(.+)(.*,)\1
$2
\b,.
,
T`Yo`GRBY`.+,
^(.*),\1$

```

Try it online! Link includes test cases. Explanation:

```
T`RGYB`Ro`.+,

```

Translate the flashes according to the first row of the chart. `Ro` here stands for the reverse of the other pattern; the `R` in that pattern is literal because it does not precede a range or special character.

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

```

Remove all correct button presses.

```
\b,.
,

```

Remove a strike, but only if there are still more buttons to press.

```
T`BRGY`Ro`.+,

```

Update the flashes so that they match the second row of the chart. Note that this means translating from the first row to the second row.

```
^(.+)(.*,)\1
$2
\b,.
,

```

Remove any further correct button presses and strike.

```
T`Yo`GRBY`.+,

```

Update the flashes so that they match the third row of the chart. Here `o` has no `R` so it just expands to `YGRBY`, where the final `Y` is ignored because it's a duplicate.

```
^(.*),\1$

```

Check that the exact correct button presses remain.

# Answer
> 1 votes
# Charcoal, 54 bytes

```
≔±Ｌθζ≔⁰εＦη¿ζ¿⁼⌕RBGY§θζ⌕§⪪”$⌊η²<↑ΣG≧”⁴ει≦⊕ζ≦⊕ε≔³ε∧¬ζ‹ε³

```

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

```
≔±Ｌθζ

```

Start at the first button flash, but use the negated length as this makes the win condition easier to test and cyclic indexing means that it doesn't matter.

```
≔⁰ε

```

Start with no strikes.

```
Ｆη

```

Loop over each button press.

```
¿ζ

```

If the bomb has not yet been disarmed, then:

```
¿⁼⌕RBGY§θζ⌕§⪪”$⌊η²<↑ΣG≧”⁴ει

```

If the current flash matches the current button press (according to the number of strikes), then...

```
≦⊕ζ

```

... increment the flash index, otherwise...

```
≦⊕ε

```

... increment the number of strikes.

```
≔³ε

```

Otherwise, set the number of strikes to `3`.

```
∧¬ζ‹ε³

```

Check that the bomb was disarmed without needing three strikes.

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


title: Josephus problem (counting out)

text:
# Question
Title: Josephus problem (counting out)
## The challenge

Write a function that takes two positive integers \\$n\\$ and \\$k\\$ as arguments and returns the number of the last person remaining out of \\$n\\$ after counting out each \\$k\\$-th person.

This is a code-golf challenge, so the shortest code wins.

## The problem

\\$n\\$ people (numbered from \\$1\\$ to \\$n\\$) are standing in a circle and each \\$k\\$-th is counted out until a single person is remaining (see the corresponding wikipedia article). Determine the number of this last person.

E.g. for \\$k=3\\$ two people will be skipped and the third will be counted out. I.e. for \\$n=7\\$ the numbers will be counted out in the order \\$3 \\, 6 \\, 2 \\, 7 \\, 5 \\, 1\\$ (in detail \\$\require{cancel}1 \\, 2 \\, \cancel{3} \\, 4 \\, 5 \\, \cancel{6} \\, 7 \\, 1 \\, \cancel{2} \\, 4 \\, 5 \\, \cancel{7} \\, 1 \\, 4 \\, \cancel{5} \\, 1 \\, 4 \\, \cancel{1} \\, 4\\$) and thus the answer is \\$4\\$.

## Examples

```
J(7,1) = 7      // people are counted out in order 1 2 3 4 5 6 [7]
J(7,2) = 7      // people are counted out in order 2 4 6 1 5 3 [7]
J(7,3) = 4      // see above
J(7,11) = 1
J(77,8) = 1
J(123,12) = 21

```

# Answer
## GolfScript, 17 bytes

```
{{@+\)%}+\,*)}:f;

```

Takes `n k` on the stack, and leaves the result on the stack.

## Dissection

This uses the recurrence `g(n,k) = (g(n-1,k) + k) % n` with `g(1, k) = 0` (as described in the Wikipedia article) with the recursion replaced by a fold.

```
{          # Function declaration
           # Stack: n k
  {        # Stack: g(i-1,k) i-1 k
    @+\)%  # Stack: g(i,k)
  }+       # Add, giving stack: n {k block}
  \,*      # Fold {k block} over [0 1 ... n-1]
  )        # Increment to move from 0-based to 1-based indexing
}:f;

```
> 5 votes

# Answer
## Minsky Register Machine (25 non-halt states)

Not technically a function, but it's in a computing paradigm which doesn't have functions per se...

This is a slight variation on the main test case of my first MRM interpretation challenge:

Input in registers `n` and `k`; output in register `r`; it is assumed that `r=i=t=0` on entry. The first two halt instructions are error cases.
> 14 votes

# Answer
## Python, 36

I also used the formula from wikipedia:

```
J=lambda n,k:n<2or(J(n-1,k)+k-1)%n+1

```

Examples:

```
>>> J(7,3)
4
>>> J(77,8)
1
>>> J(123,12)
21

```
> 7 votes

# Answer
### Mathematica, ~~38~~ 36 bytes

Same Wikipedia formula:

```
1~f~_=1
n_~f~k_:=Mod[f[n-1,k]+k,n,1]

```
> 6 votes

# Answer
## C, 40 chars

This is pretty much just the formula that the above-linked wikipedia article gives:

```
j(n,k){return n>1?(j(n-1,k)+k-1)%n+1:1;}

```

For variety, here's an implementation that actually runs the simulation (99 chars):

```
j(n,k,c,i,r){char o[999];memset(o,1,n);for(c=k,i=0;r;++i)(c-=o[i%=n])||(o[i]=!r--,c=k);
return i;}

```
> 5 votes

# Answer
## dc, 27 bytes

```
[d1-d1<glk+r%1+]dsg?1-skrxp

```

Uses the recurrence from the Wikipedia article. Explanation:

```
# comment shows what is on the stack and any other effect the instructions have
[   # n
d   # n, n
1-  # n-1, n
d   # n-1, n-1, n
1<g # g(n-1), n ; g is executed only if n > 1, conveniently g(1) = 1
lk+ # g(n-1)+(k-1), n; remember, k register holds k-1
r%  # g(n-1)+(k-1) mod n
1+  # (g(n-1)+(k-1) mod n)+1
]
dsg # code for g; code also stored in g
?   # read user input => k, n, code for g
1-  # k-1, n, code for g
sk  # n, code for g; k-1 stored in register k
r   # code for g, n
x   # g(n)
p   # prints g(n)

```
> 5 votes

# Answer
## J, 45 characters

```
j=.[:{.@{:]([:}.]|.~<:@[|~#@])^:(<:@#)>:@i.@[

```

Runs the simulation.

Alternatively, using the formula (31 characters):

```
j=.1:`(1+[|1-~]+<:@[$:])@.(1<[)

```

I hope Howard doesn't mind that I've adjusted the input format slightly to suit a dyadic verb in J.

Usage:

```
   7 j 3
4
   123 j 12
21

```
> 4 votes

# Answer
### GolfScript, ~~32~~ 24 bytes

```
:k;0:^;(,{))^k+\%:^;}/^)

```

*Usage:* Expects the two parameters *n* and *k* to be in the stack and leaves the output value.

(thanks to Peter Taylor for suggesting an iterative approach and many other tips)

The old (recursive) approach of 32 chars:

```
{1$1>{1$(1$^1$(+2$%)}1if@@;;}:^;

```

This is my first GolfScript, so please let me know your criticisms.
> 4 votes

# Answer
### Groovy, 36 bytes

```
def j(n,k){n>1?(j(n-1,k)+k-1)%n+1:1}

```
> 3 votes

# Answer
## R, 48

```
J=function(n,k)ifelse(n<2,1,(J(n-1,k)+k-1)%%n+1)

```

Running Version with examples: http://ideone.com/i7wae
> 3 votes

# Answer
### Scala, 53 bytes

```
def?(n:Int,k:Int):Int=if(n<2)1 else(?(n-1,k)+k-1)%n+1

```
> 2 votes

# Answer
## Haskell, 68

```
j n=q$cycle[0..n]
q l@(i:h:_)k|h/=i=q(drop(k-1)$filter(/=i)l)k|1>0=i

```

Does the actual simulation. Demonstration:

> GHCi\> j 7 1
> 7
> GHCi\> j 7 2
> 7
> GHCi\> j 7 3
> 4
> GHCi\> j 7 11
> 1
> GHCi\> j 77 8
> 1
> GHCi\> j 123 12
> 21
> 2 votes

# Answer
### Ruby, 39 bytes

```
def J(n,k)
n<2?1:(J(n-1,k)+k-1)%n+1
end

```

Running version with test cases: http://ideone.com/pXOUc
> 1 votes

# Answer
## C, 88 chars

Does the simulation, doesn't calculate the formula.
Much longer than the formula, but shorter than the other C simulation.

```
j(n,k){
    int i=0,c=k,r=n,*p=calloc(n,8);
    for(;p[i=i%n+1]||--c?1:--r?p[i]=c=k:0;);
    return i;
}

```

Notes:
1. Allocates memory and never releases.
2. Allocates `n*8` instead of `n*4`, because I use `p[n]`. Could allocate `(n+1)*4`, but it's more characters.
> 1 votes

# Answer
# Q, 34 bytes

```
f:{$[x=1;1;1+mod[;x]f[x-1;y]+y-1]}

```

Usage:

```
q)f .'(7 1;7 2;7 3;7 11;77 8;123 12)
7 7 4 1 1 21

```
> 1 votes

# Answer
## Ruby, 34 bytes

```
J=->n,k{n<2?1:(J(n-1,k)+k-1)%n+1}

```
> 1 votes

# Answer
## C++, 166 bytes

### Golfed:

```
#include<iostream>
#include <list>
int j(int n,int k){if(n>1){return(j(n-1,k)+k-1)%n+1;}else{return 1;}}
int main(){intn,k;std::cin>>n>>k;std::cout<<j(n,k);return 0;}

```

### Ungolfed:

```
#include<iostream>
#include <list>
int j(int n,int k){
    if (n > 1){
        return (j(n-1,k)+k-1)%n+1;
    } else {
        return 1;
    }
}
int main()
{
    int n, k;
    std::cin>>n>>k;
    std::cout<<j(n,k);
    return 0;
}

```
> 1 votes

# Answer
# Powershell, 56 bytes

```
param($n,$k)if($n-lt2){1}else{((.\f($n-1)$k)+$k-1)%$n+1}

```

Important! The script calls itself recursively. So save the script as `f.ps1` file in the current directory. Also you can call a script block variable instead script file (see the test script below). That calls has same length.

Test script:

```
$f = {

param($n,$k)if($n-lt2){1}else{((&$f($n-1)$k)+$k-1)%$n+1}

}

@(
    ,(7, 1, 7)
    ,(7, 2, 7)
    ,(7, 3, 4)
    ,(7, 11, 1)
    ,(77, 8, 1)
    ,(123,12, 21)
) | % {
    $n,$k,$expected = $_
    $result = &$f $n $k
    "$($result-eq$expected): $result"
}

```

Output:

```
True: 7
True: 7
True: 4
True: 1
True: 1
True: 21

```
> 1 votes

# Answer
# Nibbles, 6 bytes

```
+~/\,@0%+_@

```

Attempt This Online!

Uses the formula as described on Wikipedia: \\$J(n,k) = g(n,k) + 1\\$, where

$$\begin{align}g(1,k) &= 0 \\ g(n,k) &= (g(n-1,k)+k) \bmod n\end{align}$$

```
+~/\,@0%+_@
+~          Add 1
  /          fold right
   \          reverse
    ,          range from 1 to
     @          n
      0       with initial value 0
       %      modulo
        +      add
         _      k
          @     accumutalor
               item

```
> 1 votes

# Answer
# Haskell, 29

Using the formula from wikipedia.

```
1#_=1
n#k=mod((n-1)#k+k-1)n+1

```
> 0 votes

# Answer
# JavaScript (ECMAScript 5), 48 bytes

Using ECMAScript 5 since that was the latest version of JavaScript at the time this question was asked.

```
function f(a,b){return a<2?1:(f(a-1,b)+b-1)%a+1}

```

## ES6 version (non-competing), 33 bytes

```
f=(a,b)=>a<2?1:(f(a-1,b)+b-1)%a+1

```

## Explanation

Not much to say here. I'm just implementing the function the Wikipedia article gives me.
> 0 votes

# Answer
# 05AB1E, 11 bytes

```
L[Dg#²<FÀ}¦

```

Try it online!

```
L           # Range 1 .. n
 [Dg#       # Until the array has a length of 1:
     ²<F }  #   k - 1 times do:
        À   #     Rotate the array
          ¦ #   remove the first element

```
> 0 votes

# Answer
# 8th, 82 bytes

**Code**

```
: j >r >r a:new ( a:push ) 1 r> loop ( r@ n:+ swap n:mod ) 0 a:reduce n:1+ rdrop ;

```

**SED** (Stack Effect Diagram) is: `n k -- m`

**Usage and explanation**

The algorithm uses an array of integers like this: if people value is 5 then the array will be \[1,2,3,4,5\]

```
: j \ n k -- m
    >r                               \ save k
    >r a:new ( a:push ) 1 r> loop    \ make array[1:n]
    ( r@ n:+ swap n:mod ) 0 a:reduce \ translation of recursive formula with folding using an array with values ranging from 1 to n
    n:1+                             \ increment to move from 0-based to 1-based indexing
    rdrop                            \ clean r-stack
;

ok> 7 1 j . cr
7
ok> 7 2 j . cr
7
ok> 7 3 j . cr
4
ok> 7 11 j . cr
1
ok> 77 8 j . cr
1
ok> 123 12 j . cr
21

```
> 0 votes

# Answer
# , 24 bytes

```
1+1{1([:|/\+)/@,.1|.!.0#

```

Try it online!

An iterative approach based on the dynamic programming solution.

## Explanation

```
1+1{1([:|/\+)/@,.1|.!.0#  Input: n (LHS), k (RHS)
                       #  Make n copies of k
                 1|.!.0   Shift left by 1 and fill with zero
    1          ,.         Interleave with 1
             /@           Reduce using
           +                Addition
        |/\                 Cumulative reduce using modulo
  1{                      Select value at index 1
1+                        Add 1

```
> 0 votes

# Answer
# , 19 bytes

```
1+(}:@|.^:({:@])i.)

```

Try it online!

### How it works

```
1+(}:@|.^:({:@])i.)   Left: k, Right: n
                i.    Generate [0..n-1]
        ^:            Repeat:
   }:@|.                Rotate left k items, and remove the last item
          ({:@])        n-1 (tail of [0..n-1]) times
1+                    Add one to make the result one-based

```
> 0 votes

# Answer
# Dart, 33 bytes

```
f(n,k)=>n<2?1:(f(n-1,k)+k-1)%n+1;

```

Try it online!
> 0 votes

# Answer
# Japt, 15 bytes

```
_é1-V Å}h[Uõ] Ì

```

Try it online!

A byte could be saved by 0-indexing k, but it isn't actually an index so I decided against that.

Explanation:

```
         [Uõ]      :Starting with the array [1...n]
_      }h          :Repeat n-1 times:
 é1-V              : Rotate the array right 1-k times (i.e. rotate left k-1 times)
      Å            : Remove the new first element
              Ì    :Get the last value remaining

```
> 0 votes

# Answer
# Japt `-h`, 10 bytes

```
õ
£=éVn1¹v

```

Try it
> 0 votes

# Answer
# Husk, <sup>~~11~~</sup> 8 bytes

```
Ωεȯtṙ←⁰ḣ

```

Try it online!

Algorithm from Kamil Drakari's answer.
> 0 votes

# Answer
# APL (Dyalog Unicode), 17 bytes

```
{¯1↓⍺⌽⍵}⍣{1=≢⍺}∘⍳

```

Try it online!

Takes input as `k f n`.

## Explanation

```
{¯1↓⍺⌽⍵}⍣{2=≢⍵}∘⍳
               ∘⍳ list from 1..n
        ⍣         (f⍣g) → apply f repeatedly till g is true
{¯1↓⍺⌽⍵}          f: rotate list through k elements, drop last
         {1=≢⍺}   g: is the length = 1, for the previous iteration?

```

# APL (Dyalog Unicode), 36 bytes

```
1+{⍺>1:⍺|⍵+⍵∇⍨⍺-1⋄0}

```

Try it online!

Recursive function.
> 0 votes

# Answer
# Jelly, 7 bytes

```
RṙṖ¥ƬṖṪ

```

Try it online!

## How it works

```
RṙṖ¥ƬṖṪ - Main link. Takes n on the left and k on the right
R       - Range; Yield [1, 2, ..., n]
   ¥Ƭ   - Do the following to a fixed point and collect intermediate steps:
 ṙ      -   Rotate k steps to the left
  Ṗ     -   Remove the last element
     Ṗ  - Remove the empty list (the fixed point)
      Ṫ - Return the single element left over

```
> 0 votes

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


title: The second even sublime number

text:
# Question
Title: The second even sublime number
*easy mode of my previous challenge*

A perfect number is a positive integer whose sum of divisors (except itself) is equal to itself. E.g. 6 (1 + 2 + 3 = 6) and 28 (1 + 2 + 4 + 7 + 14 = 28) are perfect.

A **sublime number** (OEIS A081357) is a positive integer whose count and sum of divisors (including itself) are both perfect. E.g. 12 is a sublime number because:

* the divisors of 12 are 1, 2, 3, 4, 6, 12
* the count of divisors is 6 (perfect)
* the sum of divisors is 28 (perfect)

The next smallest known sublime number is

```
6086555670238378989670371734243169622657830773351885970528324860512791691264

```

which is a product of a power of 2 and six Mersenne primes

$$ 2^{126}(2^3-1)(2^5-1)(2^7-1)(2^{19}-1)(2^{31}-1)(2^{61}-1) $$

These two numbers are the only known sublime numbers as of 2022. The necessary and sufficient conditions for even sublime numbers have been found in this paper (pdf), but it remains unknown whether odd sublime numbers exist.

It is known that there are no other *even* sublime numbers before the number, but it is not known whether there are any *odd* ones.

## Task

Output the second even sublime number shown above. It is OK to only theoretically output this number in the following ways:

* the program outputs the correct number with probability 1 in finite time
* the program outputs the correct number given enough time and unlimited memory
* the program would output the correct number if the native number type had infinite precision

Standard rules apply. The shortest code in bytes wins.

# Answer
# PARI/GP, 45 bytes

```
print(vecprod([4^i-2^i|i<-[3,5,7,19,31,61]]))
```

Attempt This Online!

The number is \\$\prod\_{i\in\\{3,5,7,19,31,61\\}}(4^i-2^i)\\$. In fact, \\$126=3+5+7+19+31+61\\$.

Another interesting fact is that \\$2^{126}\\$ is just the sum of divisors of \\$\prod\_{i\in\\{3,5,7,19,31,61\\}}(2^i-1)\\$. This might be useful for some golfing language if there is a built-in for divisor sum.
> 8 votes

# Answer
# Python 2, 37 bytes

```
print~-2**31*~-2**61*14448825433<<126

```

Try it online!

Writes out \\$2^{31}-1\\$, \\$2^{61}-1\\$, and the bit-shift \\$2^{126}\\$, and hardcodes the remaining product.
> 7 votes

# Answer
# , ~~33~~ 32 bytes

*Edit -1 byte thanks to @xnor.*

```
prod(8^42,2^c(3,5,7,19,31,61)-1)

```

Try it online!

Spells out the product.

@alephalpha's approach lead to +1 byte for me, but @Dominic van Essen found a 32-byte version (see the footer of the TIO link above).
> 7 votes

# Answer
# Pyth, ~~20~~ ~~19~~ ~~16~~ 15 bytes

```
*FsmtB^2dPC"9

```

Try it online!

```
*FsmtB^2dPC"9
          C"9  # compressed 3772545
         P     # prime factors (3, 5, 7, 19, 31, 61)
   mtB^2d      # map d: [2**d, 2**d - 1]
  s            # flatten
*F             # reduce on multiplication

```

-3 bytes thanks to @CursorCoercer
-1 byte thanks to @isaacg
> 5 votes

# Answer
# 05AB1E, ~~13~~ 11 bytes

```
•w4н•foD<*P

```

-2 bytes thanks to *@alephalpha*.

Try it online.

**Explanation:**

```
•w4н•        # Push compressed integer 3772545
     f       # Get its prime factors: [3,5,7,19,31,61]
      o      # Get 2 to the power for each of these integers
       D     # Duplicate the list
        <    # Decrease each by 1 in the copy
         *   # Multiply the values at the same positions in the two lists
          P  # Get the product of this list
             # (after which the result is output implicitly)

```

See this 05AB1E tips of mine (section *How to compress large integers?*) to understand why `•w4н•` is `3772545`.
> 5 votes

# Answer
# Vyxal, ~~14~~ ~~13~~ 11 bytes

```
»;⟑L»ǐE:‹*Π

```

Try it Online!

-1 byte thanks to alephalpha and -2 bytes thanks to Mukundan314.

# Jelly, ~~17~~ 16 bytes

```
“¤¦¬Œþ=‘2*’æ«21P

```

Try it online!

-1 byte thanks to xnor.
> 4 votes

# Answer
# Factor \+ `math.unicode`,  ~~40~~  38 bytes

```
4 2 [ "=">array n^v ] bi@ v- Π .

```

Try it online!

-2 bytes from porting @alephalpha's PARI/GP answer.

Note `"="` is a literal string that is equivalent to `{ 3 5 7 19 31 61 }`. You can only see the `=` since the rest are non-printable, but you can see the non-printable characters on TIO. This needs to be converted to an array because `n^v` is buggy otherwise. Still 4 bytes shorter than the sequence literal.

* `4 2 [ ... ] bi@` Apply `[ ... ]` to both 4 and 2.
* `{ 3 5 7 19 31 61 } n^v` Input raised to 3, input raised to 5, etc.
* `v-` Subtract two vectors.
* `Π` Take the product.
* `.` Print the result to stdout.
> 4 votes

# Answer
# Bash, 47 Bytes

```
echo "14448825433*(2^31-1)*(2^61-1)*(2^126)"|bc

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 32 bytes

```
8^42##&@@(2^{3,5,7,19,31,61}-1)&

```

Try it online!
> 3 votes

# Answer
# Prolog (SWI), 51 bytes

*Thanks JoKing and Steffan for helping me golf some bytes*

```
?-X is(2^61-1)*14448825433*(2^31-1)*2^126,write(X).

```

Try it online!

My very first Prolog answer :D, probably can be golfed a lot though.
> 3 votes

# Answer
# MATL, ~~21~~ ~~19~~ ~~18~~ 14 bytes

```
3772545YfWtqhp

```

Try it online!

```
3772545YfWtqhp
3772545Yf         # Prime factorize 3772545 (3, 5, 7, 19, 31, 61)
         W        # 2 ** elements
          t       # duplicate list
           q      # decrement elements in copy by 1
            h     # concatenate lists
             p    # product

```

-2 bytes thanks to @Luis Mendo
> 2 votes

# Answer
# Charcoal, 21 bytes

```
ＩΠＥＸ²⁻Ｅ357COm℅ι⁴⁸×ι⊖ι

```

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

```
       357COm           Literal string `357COm`
      Ｅ                 Map over characters
              ι         Current character
             ℅          ASCII code
     ⁻                  Vectorised subtract
               ⁴⁸       Literal integer `48`
   Ｘ                    Vectorised exponentiate with base
    ²                   Literal integer `2`
  Ｅ                     Map over powers of `2`
                    ι   Current power of `2`
                   ⊖    Decremented
                 ×      Multiplied by
                  ι     Current power of `2`
 Π                      Take the product
Ｉ                       Cast to string
                        Implicitly print

```
> 2 votes

# Answer
# MathGolf, 15 bytes

```
357HT╟)]ó_(m*ε*

```

Try it online.

**Explanation:**

```
3        # Push 3
 5       # Push 5
  7      # Push 7
   H     # Push 19
    T    # Push 31
     ╟   # Push 60
      )  # Increase the 60 by 1
       ] # Wrap the stack into a list: [3,5,7,19,31,61]
ó        # Calculate 2 to the power each of these integers
 _       # Duplicate the list
  (      # Decrease each by 1
   m*    # Multiply the values at the same positions in the lists together
     ε*  # Product: reduce by multiplication
         # (after which the entire stack joined together is output implicitly as result)

```
> 2 votes

# Answer
# Nibbles, ~~16 15~~ 12.5 bytes

```
`*.`D62*;^2$-$~ a8532dc3

```

Attempt This Online!

*-2.5 bytes thanks to Dominic van Essen*

Nibbles has no prime-related built-ins, so I had to resort to good old base conversion.

```
`*.`D62*;^2$-$~ a8532dc3
`*                       Product
  .                       for each n in
   `D62                    convert from base 62
                a8532dc3    2824023491
       *                   multiply
         ^2                 2 to the power of
           $                 n
        ;    $              with itself
            - ~              minus 1

```
> 2 votes

# Answer
# Vyxal, ~~16~~ 13 bytes

```
₆¨*≬K₍L∑¨=∆Kc

```

Try it Online!

half-Legitimate calculation ~~is~~ was shorter than hard coding lol. Given enough time and memory, this would eventually output the right number.

## Explained

```
₆¨*≬K₍L∑¨=∆Kc
₆¨*≬        c   # From all multiples of 64 (which contains the target number), get the first where:
    K₍L∑        #   The list [len(factors), sum(factors)]
        ¨=∆K    #   Is invariant under sum of proper divisors

```
> 1 votes

# Answer
# Python, ~~49 46~~ 45 bytes

Did some google calculation.

```
print(2**126*14448825433*(2**31-1)*(2**61-1))

```
> 1 votes

# Answer
# Burlesque, 33 bytes

```
{Jfc~]++==}s1r1f{fcsa%1!j++%1!&&}

```

Try it online!

Given infinite time, should find sublime numbers

```
{    # IsPerfect function
 J   # Duplicate
 fc  # Factors
 ~]  # Without self
 ++  # Sum
 ==  # Equals self
}s1  # Store as "1"
r1   # Range 1..inf
f{   # Filter
 fc  # Factors
 sa  # Non-destructive Length
 %1! # IsPerfect
 j++ # Sum of factors
 %1! # IsPerfect
 &&  # And
}

```
> 1 votes

# Answer
# Jelly, 12 bytes

```
⁹Æs;ÆdÆṣƑƲ1#

```

A full program that will (eventually!) print the result.

Don't Try it online!
The  starts the search at 256, if one replaces it with `1` it'll find `12` \- try that **here**.

---

Faster in 13:

```
“;Y,’Æf2*×’$P

```

Try it here.
> 1 votes

# Answer
# Thunno, \\$ 17 \log\_{256}(96) \approx \\$ 13.99 bytes

```
3772545AF2@D1-z*P

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

```
3772545AF2@D1-z*P
3772545            # Push 3772545                (there's no integer compression in Thunno)
       AF          # Prime factors of that       ([3, 5, 7, 19, 31, 61])
         2@        # 2 ** each one               ([8, 32, 128, 524288, 2147483648, 2305843009213693952])
           D1-     # Duplicate and subtract one  ([7, 31, 127, 524287, 2147483647, 2305843009213693951])
              z*   # Multiply                    ([56, 992, 16256, 274877382656, 4611686016279904256, 5316911983139663489309385231907684352])
                P  # Product of the list         (6086555670238378989670371734243169622657830773351885970528324860512791691264)

```
> 1 votes

# Answer
# Pyt, ~~22~~ ~~17~~ 16 bytes

```
3772545ǰϼ2⇹^Đ⁻*Π

```

Try it online!

```
3772545             push 3, 7, 7, 2, 5, 4, 5
       ǰ            ǰoin elements on stack with no delimiter
         ϼ          get unique ϼrime factors (casts to integer)
          2⇹^       raise 2 to each power
             Đ⁻     Đuplicate; decrement
               *    element-wise multiplication
                Π   product of list; implicit print

```
> 1 votes

# Answer
# Jelly, 30 bytes

My first Jelly answer! Hope I'll get better in the future.

```
2*’
[3,5,7,19,31,61]ç
¢×/æ«126

```

Attempt This Online!
> 1 votes

# Answer
# , 23 bytes

```
echo*/(,<:)2^q:3772545x

```

Same solution as most answers.

Attempt This Online!

```
echo*/(,<:)2^q:3772545x
               3772545x  NB. extended precision literal
             q:          NB. prime factors
           2^            NB. raise 2 to each factor
      (,<:)              NB. monadic hook
        <:               NB. decrement
       ,                 NB. concat with hook input
    */                   NB. product reduce
echo                     NB. print

```
> 1 votes

---
Tags: code-golf, math, kolmogorov-complexity, number-theory
---


title: The tedious array of 7 rules

text:
# Question
Title: The tedious array of 7 rules
# The rundown

Create a program that generates an array of random length with random numbers, then apply a series of rules that alter the array. After the rules have been applied, print the sum of the array unless specified otherwise

# Array setup

The array must be a random length between **5 and 10** inclusive, with random integers between **1 and 20** inclusive. Each array length should have equal probability of happening and each integer should have an equal probability of being picked per element.

# The 7 rules

The rules should act as if they were applied in sequence (eg: rule 1 acts before rule 2) and are only applied once. **For proof of rule application, the array must be printed to console after each rule application and once before any rules are applied.**

1. If the array contains a 7, subtract 1 from every element
2. If rule 1 is applied and the array now contains a 0, add 1 to each element
3. If the array contains a 13, exclude the 13, and all elements that follow, from the array
4. If the array contains a 2, exclude all odd numbers
5. If the array contains a 20, and the third element is even, return 20 as the sum then terminate. If a 20 is present and the third element is odd, return 20 times the length of the array as the sum then terminate.
6. If the sum is greater than 50, remove the last element repeatedly until it is less than or equal to 50
7. If the array contains a 16, print the sum in both decimal and hexadecimal.

# Example

Here is an initial array,

```
[20, 2, 5, 7, 14, 8]

```

Rule 1 can be applied:

```
[19, 1, 4, 6, 13, 7]

```

Rule 3 is applied next:

```
[19, 1, 4, 6]

```

No other rules are needed, so the program returns **30** as the sum.

# Notes

* I'm not an experienced code golfer, although I can say my personal record is in Python 3 with **369 bytes**.
* The rules don't have to actually be applied in order, but have to act as if they did.

# Answer
# Python 3, ~~294~~ ~~301~~ ~~287~~ 356 bytes

```
import random as r
r=r.randint
k=[r(i)+1for i in[20]*r(5,11)]
p=print
if 7in k:k=[i-1for i in k]
p(k)
if 0in k:k=[i+1for i in k]
p(k)
i=k.find(13)
if not~i:k=k[:i]
p(k)
if 2in k:k=[i for i in k if~i%2]
p(k)
a=0
z=len(k)>2and k[2]%2
if 20in k:a=20*len(k)**z
if~z:p(k)
while sum(k)>50:k=k[:-1]
if~z:p(k)
if a:p(a)
else:a=sum(k);p(a,hex(a)*(16in k))
if~z:p(k)

```

I don't know how you're going to prevent people circumventing the rules, but this one uses the procedure specified.

+7 bytes; thanks to @YamB for saving a few bytes; added a lot more to fix a previous error.
-14 bytes thanks to @RootTwo and myself and also corrected the error.
+83 bytes; this is getting horribly long because OP keeps changing the rules. -some number of bytes thanks to @ZacharyT
> 8 votes

# Answer
# 05AB1E, 91 bytes

```
5TŸ.RF20©L.R})=D7åi<=D0åi>=}}D13åiD13k£=}D2åiDÈÏ=}D®åiDgs2èÉ®si*},q}[DO50›_#¨=]D16åiDOH,}O,

```

Try it online! or With input
> 6 votes

# Answer
# JavaScript, ~~344~~ ~~342~~ ~~340~~ ~~342~~ ~~335~~ ~~331~~ ~~333~~ ~~313~~ ~~311~~ ~~305~~ ~~298~~ ~~297~~ ~~290~~ ~~289~~ ~~283~~ ~~279~~ ~~271~~ ~~265~~ 263 bytes

Following this exchange* in the challenge's comments and after much deliberation I opted to use `new Date` as the seed for the random number generator instead of `Math.random()`. Doing so means that all the integers in the array will be of the same value.

Now a full programme, rather than a function

```
D=new Date
P=print
I=n=>~a.indexOf(n)
C=(n,c)=>I(n)&&P(a=+c?a.map(x=>x+c):a.filter(c))
P(a=[...Array(D%6+5)].map(x=>D%20+1))
C(7,-1)
C(s=0,1)
C(13,(_,x)=>x<~I(13))
C(2,x=>x%2)
P(I(t=20)?a[2]%2?t*a.length:t:P(a.filter(x=>s+x<51?s+=x:0))|I(16)?[s,s.toString(16)]:s)

```

Try it online! or with `Math.random`

---

\*Screenshot, in case it's deleted:
> 6 votes

# Answer
# C (gcc), ~~621~~ ~~619~~ ~~593~~ ~~585~~ ~~570~~ ~~562~~ ~~557~~ ~~552~~ ~~529~~ ~~517~~ ~~500~~ ~~482~~ ~~461~~ ~~444~~ ~~442~~ ~~441~~ 438 bytes

There's a whole lot of golfing needed here... Fixed a bug where it would print the hexidecimal once for each 16 in the list...

Special thanks to ZacharyT with the golf help

```
#define R r[i]
#define P printf("%d "
#define L for(d=i=0;i<l;i++)
d,i,j,l,r[11];p(i){L P,R);puts("");}main(){srand(time(0));for(l=5+rand()%5;i<l;R=1+rand()%20,i++);for(p();i--;)if(R==7){L--R;j=i=1;}for(p();j&&i<l;i++)if(!R){L++R;j=i=l;}p();L if(R==13)l=i;p();L if(R==2)for(d=1;d;)L if(R&1)for(d=1,--l;i<=l;i++)R=r[i+1];p();L if(R==20)return P,r[3]&1?20*l:20);for(j=i=0;i<l&&j+R<51;j+=R,i++);l=i;p();P,j);L if(R==16)printf("0x%x",j,i=l);}

```

Try it online!
> 4 votes

# Answer
# K (ngn/k), ~~160~~ ~~147~~ 139 bytes

-13 from consolidating `0N!` prints/other tweaks

-8 by converting to `ngn/k`

```
{0N!'|(a@:&(~2!a)|^a?2;a:(a?13)#a;a+:|/~a;a-:|/a=7;a:1+(*5+1?6)?20);$[^a?20;;:20*(1;#a)2!a 2];0N!a@:&51>+\a;(+/a),$[^a?16;!0;,`hex@`c$+/a]}

```

Try it online!

From the beginning to the end...

* `0N!'|` print each of the following in reverse order (when building lists, `ngn/k` executes the right-most/last list item first, the second-to-last item second, etc. For ease of explanation, the below are listed in the order they are executed)
    + `a:1+(*5+1?6)?20` generate 5-10 random numbers between 1 and 20, storing in `a`
    + `a-:|/a=7;` decrement `a` if it contains a `7`
    + `a+:|/~a;` increment `a` if it contains a `0`
    + `a:(a?13)#a;` take elements occurring before the first `13`
    + `a@:&(~2!a)|^a?2;` if a `2` is present, remove odds from `a`
* `$[^a?20;;:20*(1;#a)2!a 2];` if `20` is present, check the third value `a 2` and early return from the function (otherwise do nothing)
* `0N!a@:&51>+\a;` remove values where the cumulative sum up to that point is \>50
* `$[^a?16;+/a;(+/a;`hex@`c$+/a)]` return either the sum of `a` (if no `16` is present), or return the sum as both an integer and in hexadecimal representation (the latter as a string)
> 4 votes

# Answer
## JavaScript (ES6), ~~296~~ ~~295~~ ~~290~~ 289 bytes

A full program that logs the initial array, the intermediate results and the final sum to the console.

```
f="z=[...Array(5+6j)]Z1+20jw7`-1w0`+1w13_qi+1<-kw2_qn&1^1w20_z[2]&1?a.length*20:20);else{q(s+=n)<51,s=0w16_b.toString(16_;b)}zconsole.log(aw_;if(k=~a.indexOf(v((n,i)=>qz=a.filtervj*Math.random()|0bz.reducevn+i,0)`_z=aZn_))Z.mapv";for(g of "Z_`bjqvwz")e=f.split(g),f=e.join(e.pop());eval(f)
```

### How it works

This was compressed using this JS packer.

Breakdown:

* Packed string: ~~226~~ 225 bytes
* Unpacking code: ~~69~~ 64 bytes

Below is the original source code with some additional whitespace and line feeds for readability. Rather than applying standard golfing tricks, it was written in a way that produces as many repeating strings as possible in order to please the packer. For instance, the syntax `if(k=~a.indexOf(N))` is duplicated everywhere although `k` is only used in the 3rd rule.

```
console.log(a=[...Array(5+6*Math.random()|0)].map((n,i)=>1+20*Math.random()|0));
if(k=~a.indexOf(7))
  console.log(a=a.map((n,i)=>n-1));
if(k=~a.indexOf(0))
  console.log(a=a.map((n,i)=>n+1));
if(k=~a.indexOf(13))
  console.log(a=a.filter((n,i)=>i+1<-k));
if(k=~a.indexOf(2))
  console.log(a=a.filter((n,i)=>n&1^1));
if(k=~a.indexOf(20))
  console.log(a[2]&1?20*a.length:20);
else {
  console.log(a=a.filter((n,i)=>(s+=n)<51,s=0));
  if(k=~a.indexOf(16))
    console.log(a.reduce((n,i)=>n+i,0).toString(16));
  console.log(a.reduce((n,i)=>n+i,0))
}

```

### Unpacking methods

The original unpacking code is:

```
f="packed_string";for(i in g="ABCDEFGHI")e=f.split(g[i]),f=e.join(e.pop());eval(f)

```

All the following ES6 variants have exactly the same size:

```
eval([..."ABCDEFGHI"].reduce((f,g)=>(e=f.split(g)).join(e.pop()),"packed_string"))
[..."ABCDEFGHI"].map(g=>f=(e=f.split(g)).join(e.pop()),f="packed_string")&&eval(f)
eval([..."ABCDEFGHI"].map(g=>f=(e=f.split(g)).join(e.pop()),f="packed_string")[8])

```

The only way I've found so far to shave off a few bytes is to use `for ... of`:

```
f="packed_string";for(g of "ABCDEFGHI")e=f.split(g),f=e.join(e.pop());eval(f)

```
> 3 votes

# Answer
# Java 10, ~~622~~ ~~619~~ ~~618~~ ~~613~~ ~~576~~ 575 bytes

```
v->{var L=new java.util.Stack<Integer>();String r="",N="\n";int c=(int)(Math.random()*6+5),i=c;for(;i-->0;L.add((int)(Math.random()*20+1)));r+=L+N;if(L.contains(7)){for(;++i<c;L.set(i,L.get(i)-1));r+=L+N;}if(L.contains(i=0)){for(;i<c;L.set(i,L.get(i++)+1));r+=L+N;}if((i=L.indexOf(13))>=0){L.subList(i,c).clear();r+=L+N;}if(L.contains(2)){for(i=0;i<L.size();)if(L.get(i)%2>0)L.remove(i);else++i;r+=L+N;}if(L.contains(20))return r+20*(L.get(2)%2<1?1:L.size());i=0;for(var x:L)i+=x;for(;i>50;)i-=L.remove(L.size()-1);return r+L+N+(L.contains(16)?Byte.valueOf(i+"",16)+N:"")+i;}

```

-1 byte thanks to *@Poke*
-6 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
v->{                          // Method with empty unused parameter and String return
  var L=new java.util.Stack<Integer>();
                              //  Integer-list, starting empty
  String r="",                //  Result-String, starting empty
         N="\n";              //  Temp-String `N`, containing a newline
  int c=(int)(Math.random()*6 //  Get a random integer in the range [0,6]
              +5),            //  And add 5
  i=c;for(;i-->0;             //  Loop that amount of times:
    L.add((int)(Math.random()*20+1)));
                              //   Add a random integer in the range [1,20] to the list
  r+=L+N;                     //  Append the current list + newline to the result-String
  if(L.contains(7)){          //  If the list now contains a 7:
    for(;++i<c;L.set(i,L.get(i)-1));
                              //   Decrease each value by 1
    r+=L+N;}                  //   And append the current list + newline again
  if(L.contains(i=0)){        //  If the list now contains 0:
    for(;i<c;L.set(i,L.get(i++)+1));
                              //   Increase each value by 1
    r+=L+N;}                  //   And append the current list + newline again
  if((i=L.indexOf(13))>=0){   //  If the list now contains a 13:
    L.subList(i,c).clear();   //   Remove all values from that 13 onward from the list
    r+=L+N;}                  //   Append the current list + newline again
  if(L.contains(2)){          //  If the list now contains a 2:
    for(i=0;i<L.size();)      //   Loop over the list:
      if(L.get(i)%2>0)        //    If the current value is odd:
        L.remove(i);          //     Remove it
      else                    //    Else:
        ++i;                  //     Skip it, and go to the next value
    r+=L+N;}                  //   Append the current list + newline again
  if(L.contains(20))          //  If the list now contains a 20:
    return r                  //   Return the result-String
           +20*               //   And append 20 multiplied by:
               (L.get(2)%2<1? //    If the third item is even:
                 1            //     Multiply the 20 by 1 so it'll remain 20
                :             //   Else (it's odd instead):
                 L.size());   //    Multiply the 20 by the list-size
  i=0;for(var x:L)i+=x;       //   Set `i` to the sum of the list
  for(;i>50;)                 //  Loop as long as the list-sum is larger than 50:
    i-=L.remove(L.size()-1);  //   Remove the last item of the list
  return r                    //  Return the result-String
         +L+N                 //  Appended with the current list + newline again
         +(L.contains(16)?    //  If the list now contains a 16:
            Byte.valueOf(i+"",16)+N
                              //   Append the sum as hexadecimal
           :                  //  Else:
            "")               //   Append nothing
         +i;}                 //  And append the sum (as regular base-10 integer)

```

**Sample outputs:**
*Comments behind the sample outputs aren't printed, but I added them as clarification.*

```
[17, 5, 3, 1, 16, 17, 11, 7, 13]   // Initial print (size 9)
[16, 4, 2, 0, 15, 16, 10, 6, 12]   // Rule 1 (contains a 7)
[17, 5, 3, 1, 16, 17, 11, 7, 13]   // Rule 2 (contains a 0)
[17, 5, 3, 1, 16, 17, 11, 7]       // Rule 3 (contains a 13)
[17, 5, 3, 1, 16]                  // Rule 6 (sum must be <= 50)
66                                 // Rule 7 (contains a 16 -> print as Hexadecimal)
42                                 // Print sum as integer

[4, 18, 17, 12, 11, 8]             // Initial print (size 6)
[4, 18, 17]                        // Rule 6 (sum must be <= 50)
39                                 // Print sum as integer

[4, 14, 6, 14, 7, 20, 2, 2]        // Initial print (size 8)
[3, 13, 5, 13, 6, 19, 1, 1]        // Rule 1 (contains a 7)
[3]                                // Rule 3 (contains a 13)
[3]                                // Print is always done after rule 6
3                                  // Print sum as integer

```
> 2 votes

# Answer
# PowerShell, 525 413 bytes

```
filter a{"$a"};0..(4..9|random)|%{$a+=@(1..20|random)};a;if(7-in$a){$a=($a|%{$_-1});a;if(0-in$a){$a=($a|%{$_+1});a}}$b=$a;$a=@();foreach($z in $b){if($z-ne13){$a+=@($z)}else{a;break}}if(2-in$a){$a=($a|?{$_%2-eq0});a}if(20-in$a){if($a[2]%2){20*$a.count;exit}else{20;exit}}while(($h=$a-join'+'|iex)-gt50){$a=$a[0..($a.count-2)];a}if(16-in$a){$l=0..9+'a b c d e f'-split' ';$q=[math]::floor($h/16);"$q"+$l[$h%16]};$h

```

Try it online!

I wanted to attempt this one although I figured I wouldn't beat the answers already here :P I have been attempting to golf this down still, I'm sure it's possible with less bytes. Found a better method for hex, but could probably still improve.

Had to cast `$a` to a string so many times it was better to create a filter for it...

There were quite a few easy golfs I missed such as parentheses and spaces. Might still be some out there?

Somewhat easier to read code:

```
filter a{"$a"};0..(4..9|random)|%{$a+=@(1..20|random)};a;
if(7-in$a){$a=($a|%{$_-1});a;if(0-in$a){$a=($a|%{$_+1});a}}
$b=$a;$a=@();foreach($z in $b){if($z-ne13){$a+=@($z)}else{a;break}}
if(2-in$a){$a=($a|?{$_%2-eq0});a}
if(20-in$a){if($a[2]%2){20*$a.count;exit}else{20;exit}}
while(($h=$a-join'+'|iex)-gt50){$a=$a[0..($a.count-2)];a}
if(16-in$a){$l=0..9+'a b c d e f'-split' ';$q=[math]::floor($h/16);"$q"+$l[$h%16]};$h

```
> 2 votes

# Answer
First try at code golf!

Already beat by other javascripters! Dangit! I will improve!!! =)

## **Javascript -\> ~~550~~ 402 bytes**

Could definitely be improved. Compressed Now:

```
f="ba=[];bl;yz5+5`^=0;i<y;i++)a[i]z20+1|~7j-1|~0j+1|}}~13_l=indexOf(13`ql,y-l-Y_^ in a)if(a[i]%2)qi,Y0)&&(!a[3]%2_k'20'`throw new Error(`}do{l=Vreduce((X,num)=>X+num`ifW)qy-1,1`}whileW|kl`~16))kl.toString(16)`~if(Vincludes(|`ka`z=Zound(Zandom()*yVlengthqVsplice(kalert(j_Vmap((i)=>ibvar `);_)){^for(biZMath.rY1|}~2XtotalW(l>50Va.";for(i in g="VWXYZ^_`bjkqyz|~")e=f.split(g[i]),f=e.join(e.pop());eval(f)

```

Originial:

```
var a=[];var l;a.length=Math.round(Math.random()*5+5);for(var i=0;i<a.length;i++)a[i]=Math.round(Math.random()*20+1);alert(a);if(a.includes(7)){a.map((i)=>i-1);alert(a);if(a.includes(0)){a.map((i)=>i+1);alert(a);}}if(a.includes(13)){l=indexOf(13);a.splice(l,a.length-l-1);alert(a);}if(a.includes(2)){for(var i in a)if(a[i]%2)a.splice(i,1);alert(a);}if(a.includes(20)&&(!a[3]%2)){alert('20');throw new Error();}do{l=a.reduce((total,num)=>total+num);if(l>50)a.splice(a.length-1,1);}while(l>50);alert(a);alert(l);if(a.includes(16))alert(l.toString(16));

```
> 2 votes

# Answer
# Ruby 2.4, 260 bytes

Ruby 2.4 is required for `Enumerable#sum`.

```
p a=(1..s=5+rand(5)).map{1+rand(19)}
a.map!{|i|i-1}if a.index 7
p a
a.map!{|i|i+1}if a.index 0
p a
a.pop s-(a.index(13)||s)
p a
a.reject! &:odd?if a.index 2
p a
a.index(20)?p(20*[1,s][(a[2]||1)%2]):((a.pop;p a)while a.sum>50
p m=a.sum;puts"%x"%m if a.index 16)

```

Try it online! (Neither repl.it nor tio.run support Ruby 2.4 yet, so this online version replaces `sum` with `inject(:+)`, which has the same behavior.)
> 2 votes

# Answer
# R (3.3.1), 325 bytes

Pretty naive implementation; I think I can probably make it a bit shorter.

```
s=sample(1:20,sample(5:10,1));print(s);if(7%in%s){s=s-1;print(s);if(0%in%s)s=s+1;print(s)};if(13%in%s){s=s[1:(which(s==13)-1)];print(s)};if(2%in%s){s=s[!(s%%2)];print(s)};if(20%in%s){if(s[3]%%2){20*length(s);print(s)}else{20;print(s)}};while(sum(s)>50){s=s[-length(s)];print(s)};if(16%in%s){print(as.hexmode(sum(s)))};sum(s)

```
> 1 votes

# Answer
## MATLAB, 275 bytes

I originally planned on maybe a one-liner Octave answer, but requiring output of all applied rules thwarted my plans. Instead, a fairly straightforward MATLAB answer with a few interesting optimisations, e.g. the use of `cumsum` instead of the obvious `while` for rule 6. Still, a lot of the byte count is wasted on `if`s to prevent output if a rule is not applied.

```
A=randi(20,1,randi(6)+4)
if any(A==7)
A=A-1
if any(~A)
A=A+1
end;end
q=find(A==13,1);if q
A=A(1:q-1)
end
if any(A==2)
A=A(2:2:end)
end
if any(A==20)
if mod(A(3),2)
20*length(A)
else
20
end;return;end
q=cumsum(A)<51;if any(~q)
A=A(q)
end
q=sum(A)
if(any(A==16))
dec2hex(q)
end

```

Try it online!
> 0 votes

# Answer
# Scala 587 bytes one liner

```
import scala.util.Random;object A{def main(args:Array[String])={val s=5+Random.nextInt(6);var a=new Array[Int](s);for(i<-1 to s){a(i-1)=1+Random.nextInt(20)};p(a);if(a.contains(7)&& !a.contains(1)){a.map(a=>a-1);p(a)};if(a.contains(13)){if(a(0)==13)a=new Array[Int](0)else a=a.slice(0,a.indexOf(13));p(a)};if(a.contains(2)){a=a.filter(pred=>pred%2==0);p(a)};if(a.contains(20)){if(a(2)%2==0)println(20)else println(20*a.length)}else{while(a.sum>50)a=a.dropRight(1);val u=a.sum;if(a.contains(16))println(Integer.toHexString(u));println(u)}};def p[T](a: Array[T])=println(a.mkString(","))}

```

# Scala, 763 bytes as is

```
import scala.util.Random
object TA {
  def main(args:Array[String])={
    val s=5+Random.nextInt(6)
    var a=new Array[Int](s)
    for (i<-1 to s)
      a(i-1)=1+Random.nextInt(20)
    p(a)
    if(a.contains(7) && !a.contains(1)){
      a.map(a=>a-1)
      p(a)
    }
    if(a.contains(13)){
      if (a(0)==13) a=new Array[Int](0) else a=a.slice(0,a.indexOf(13))
      p(a)
    }
   if(a.contains(2)){
      a=a.filter(pred=>pred%2== 0)
      p(a)
    }
    if(a.contains(20)){
      if (a(2)%2==0) println(20) else println(20*a.length)
    }else{
      while(a.sum>50)
        a=a.dropRight(1)
      val u =a.sum
      if (a.contains(16)) println(Integer.toHexString(u))
      println(u)
    }
  }
  def p[T](a: Array[T])={
    println(a.mkString(","))
  }
}

```
> 0 votes

# Answer
# Python 3, ~~297 293 289~~, 278 bytes

As Arnauld spotted, you can't get 0 unless rule 1 was applied, which saved on indenting. Thanks to everyone else who commented with suggestions too.

```
from random import*
p=print
a=b=sample(range(1,20),randint(5,10))
p(a)
if 7in a:a=[i-1for i in a];p(a)
if 0in a:a=b;p(a)
if 13in a:a=a[:a.index(13)];p(a)
if 2in a:a=[i for i in a if~i%2];p(a)
if 20in a and~a[2]%2:a=[20]
while sum(a)>50:a=a[:-1]
b=sum(a)
p(b)
if 16in a:p(hex(b))

```

Try it online
> 0 votes

# Answer
# MATLAB, ~~228~~ 241bytes

```
a=randi(20,1,randi(6)+4)
b=@any;
a=a-b(a==7)
a=a+b(a==0)
a(find(a==13,1):end)=[]
a(and(mod(a,2),b(a==2)))=[]
if b(a==20)
a=[a 0 0 0];
s=20*(1+mod(a(3),1)*(numel(a)-4))
else
a(cumsum(a)>50)=[]
s=sum(a)
if b(a==16)
h=['0x' dec2hex(s)]
end
end

```

This will apply all rules in order, printing the array value after each step.

~~The program will crash on rule 5 if the resulting number of elements is less than three. There is currently nothing to say what should happen if there is no third element, so I am assuming that a crash is acceptable.~~ The program will now print 20 if there are less than 3 elements and one or more is a 20.

Interestingly step 2 can be applied regardless of whether step 1 was. This is because the input array will never have a 0 in it meaning that if there are any 0's in the array it must be as a result of step 1 having occurred.

All rules are applied in turn, up until 5, even if there are no changes made. As a result the array will be printed at the start and then after each step up until 5. After step 5 you will either get the sum if it is applied, or no output until after step 6. An extra line containing `a` could be added after the else statement to ensure that the array value is printed after step 5 at the cost of 2 bytes.

---

I'd also like to mention that I didn't look at the other answers until after I had written this. I see now that there is another MATLAB answer with some similarities - all of which are coincidental.
> 0 votes

# Answer
# Perl 6, 246 bytes

```
my&f={.grep($^a)};my&s=->{.say};$_=[(1..20).pick xx(5..10).pick];s;$_»--
if f 7;s;$_»++ if f 0;s;.splice(.first(13):k//+$_);s;$_=[f*%%2]if f 2;
s;say(20*(.[2]%%2||$_)),exit if $_>2&&f 20;s;.pop while
.sum>49;$/=f 16;$_=.sum;s;.base(16).say if $/

```

Ungolfed:

```
my &f = { .grep($^a) };  # Helper function: search $_ for something
my &s = -> { .say };     # Helper function: print $_
$_ = [ (1..20).pick xx (5..10).pick ];  # Generate the initial array
s;  # Print the array
$_»-- if f 7;  # Decrement all elements if it contains a 7
s;  # Print the array
$_»++ if f 0;  # Increment all elements if a zero is found
s;  # Print the array
.splice(.first(13):k // +$_);  # Splice out everything from the first 13 onward
s;  # Print the array
$_ = [ f *%%2 ] if f 2;  # Remove all odd elements if a 2 is found
s;  # Print the array
say(20*(.[2] %% 2 || $_)), exit if $_ > 2 && f 20;  # Print and exit, maybe
s;  # Print the array
.pop while .sum > 49;  # Remove elements from the end until sum is below 50
$/ = f 16;  # Save in $/ whether $_ contains a 16
$_ = .sum;  # Set $_ to its own sum
s;  # Print the sum
.base(16).say if $/  # Print the sum in hexadecimal if the last array contained a 16

```
> 0 votes

# Answer
# Common Lisp, 490 bytes

Here the array is represented as a Common Lisp list.

```
(let((a(loop for i from 1 to(+ 5(random 5))collect(1+(random 19)))))(flet((p()(format t"~a~%"a))(m(x)(member x a))(h(x)(map-into a x a)))(p)(and(m 7)(h'1-))(p)(and(m 0)(h'1+))(p)(let((p(position 13 a)))(and p(setf a(butlast a (-(length a)p)))))(p)(and(m 2)(setf a(remove-if'oddp a)))(p)(or(and(m 20)(or(and(third a)(oddp(third a))(* 20(length a)))20))(p)(and(setf a(loop for x in a sum x into s while (<= s 50) collect x)) nil)(p)(let((s(reduce'+ a)))(print s)(and(m 16)(format t"~x"s))))))

```

As usual, large use of `and` and `or` as control structures.

```
(let ((a (loop for i from 1 to (+ 5 (random 5))  ; create initial list
            collect (1+ (random 19)))))
  (flet ((p () (format t "~a~%" a))     ; auxiliary functions: print list
         (m (x) (member x a))           ; check membership
         (h (x) (map-into a x a)))      ; operate on elements
    (p)
    (and (m 7) (h '1-))                 ; if 7 is present decrement all values
    (p)
    (and (m 0) (h '1+))                 ; if 0 is now present increment all values
    (p)
    (let ((p (position 13 a)))          ; remove from 13 (if exists)
      (and p (setf a (butlast a (- (length a) p)))))
    (p)
    (and (m 2) (setf a (remove-if 'oddp a)))   ; if 2 is present remove odd values
    (p)
    (or (and (m 20)                            ; if 20 is present
             (or (and (third a)                ;    when third is present
                      (oddp (third a))         ;         and it is odd
                      (* 20 (length a)))       ;         return 20 times the length
                 20))                          ;    otherwise return 20
        (p)                                    ; otherwise (20 is not present)
        (and (setf a (loop for x in a sum x into s ; compute sum of elements
                        while (<= s 50)            ; limited to 50
                        collect x))                ; and return those elements
             nil)                                  ; (to execute the rest of the code)
        (p)
        (let ((s (reduce '+ a)))                   ; compute the final sum
          (print s)                                ; print the result in decimal
          (and (m 16) (format t "~x" s))))))       ; if 16 is present print also in hexadecimal

```
> 0 votes

# Answer
# Perl 5 `-MList::Util=sum`, 256 bytes

```
$,=$";say$_="@{[map{0|1+rand 20}1..5+rand 6]}";/\b7/&&s/\d+/$&-1/ge&&(say)&&/\b0/&&s/\d+/$&+1/ge&say;s/ ?13.*//&&say;@a=/\d+/g;/\b2\b/&&say@a=grep$_%2-1,@a;/20/&&(say$a[2]%2?20*@a:20)&exit;$t=pop@a while($_=sum@a)>50;$t&&say@a;say;"@a"=~/16/&&printf"%x",$_

```

Try it online!
> 0 votes

# Answer
# Vyxal, 82 bytes

```
6℅4+ƛ20℅;…:7c[‹…:A¬[›…}1J:13ḟẎ…:2cß~₂…D20c[2i₂[20|L20*],Q}1J:¦‡50>ǑẎ…:16c[∑₌,H,|∑,

```

Try it Online!

## Explained

```
6℅4+ƛ20℅;…:7c[‹…:A¬[›…}1J:13ḟẎ…:2cß~₂…D20c[2i₂[20|L20*],Q}1J:¦‡50>ǑẎ…:16c[∑₌,H,|∑,
6℅4+ƛ20℅;…  # Generate the original array with randint(1, 6) + 4 items, each being randint(1, 20). Print it without popping.
:7c[‹…      # If the array contains a 7, subtract 1 from everything
:A¬[›…}     # If there's 0s after doing that, add 1 to everything
1J:13ḟẎ…    # Find the first occurance of `13` in the array with a 1 appended, and keep everything up to that index. If `13` is not in the array, this will return -1, and will keep everything except the appended 1. Basically, the appended 1 is always removed.
2cß~₂…      # If the array contains a 2, keep only even numbers
D20c[2i₂[   # If there's 20 in the array and the 3rd item (0 if < 3 items) is even:
20          #   Push 20
|L20*       # else, push len(array) * 20
,Q}         # print and terminate
1J:¦‡50>ǑẎ… # find the first item in the cumulative sums of the array where the sum is > 50 and keep until that index. Same logic as the 13 check.
:16c[       # If 16 is in the array
∑₌,H,       # Print the sum as dec and hex
|∑,         # else, just print the sum

```
> 0 votes

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


# Question
Title: Smallest numbers whose square has even number of digits
```
4, 32, 317, 3163, 31623, 316228, 3162278, 31622777, 316227767, 3162277661, 31622776602, 316227766017, 3162277660169, 31622776601684, 316227766016838, 3162277660168380, 31622776601683794, 316227766016837934, 3162277660168379332, 31622776601683793320, 316227766016837933200, 3162277660168379331999, 31622776601683793319989, 316227766016837933199890, ...

```

Or in other words: given *n* output the *(n * 2)*-th term of OEIS A017936: smallest number whose square has n digits.

Essentially we removed powers of 10 from mentioned OEIS serie.

# Notes

As noted by Neil, there is a correlation with the digits of √(1/10), or even 10, 1 or any power of 10.
He also explained: *the length of integers increases at each power of 10. The length of squares of integers increases at (the ceiling of) each power of √10. Half of these powers are also powers of 10, while the other half are powers of 10 multiplied by √(1/10).*

Additionally a proof was given by jjagmath.
*If *n* is the number where the square change from having *k* digits to \\$k+1\\$ digits then \\$(n-1)^2\<10^k\le n^2\\$. So \\$n-1 \< 10^{k/2}\le n\\$.
If *k* is even we have \\$n = 10^{k/2}\\$.
If \\$k = 2m+1\\$ then \\$n-1 \< 10^{m+1}\sqrt{1/10}\< n\\$ which explains why the first digits of *n* coincide with \\$\sqrt{1/10}\\$.*

**More notes**

* There is a difference between the last digit and the corresponding digit in \\$\sqrt{1/10}\\$, e.g. for the 5th term:

```
5th term     31623
√(1/10)    0.31622776601..
                 ↑

```
* Formal formula from OEIS A017936: *a(n) = ceiling(10^((n-1)/2))* which includes powers of 10 terms.
* The next term of *x* is between *\\$(x-1) * 10\\$* and *\\$x * 10\\$*

# Rules

This is , all usual golfing rules apply.

This is also so you can output:

* *n*-th element
* first *n* terms
* infinite sequence

**Floating point issues are allowed.**
However answers that doesn't fail due to floating point issues are encouraged, you can post both solutions so that we'll see the difference, in that case please post best score as main solution and the other as alternative indicating both scores.

I could fork the challenge in two separate questions but.. I think duplicating is annoying and doesn't make much sense.
At the same time, considering what @Bubbler stated in the FP issues consensus: *"Allowing or disallowing such functions (and intermediate floating point values) has a huge consequence, to the point that I could say it defines the actual challenge"*, I think it may be interesting to have a kind of challenge inside the challenge between FP issues in the same language.

---

Sandbox

# Answer
# Python, 26 bytes

```
lambda n:int(10**(n-.5))+1
```

Attempt This Online!

Has floating-point issues.

# Python, 45 bytes

```
f=lambda n,i=1:10*100**n>i*i and f(n,i+1)or i
```

Attempt This Online!

Suboptimal - this is kind of an intermediary solution that shows another way of proving the formula. (I came up with this before seeing the formula, and once I saw the formula I noticed the connection)

Here is something of a derivation:

1. Convert the loop-based solution (see below) to a recursive version:

```
f=lambda n,i=1:n*2>len(str(i*i))and f(n,i+1)or i

```
2. Replace `len(str())` with a logarithmic computation \\$ \lfloor\log(i^2) + 1 \rfloor \\$:

```
f=lambda n,i=1:n*2>floor(log10(i*i)+1)and f(n,i+1)or i

```
3. It's an integer comparison, so the `floor` can be removed:

```
f=lambda n,i=1:n*2>log10(i*i)+1and f(n,i+1)or i

```
4. Raise both sides of the comparison as a power of `10`:

```
f=lambda n,i=1:10**(n*2)>10**(log10(i*i)+1)and f(n,i+1)or i

```
5. Simplify:

```
f=lambda n,i=1:100**n>i*i*10and f(n,i+1)or i

```
6. Due to an off-by-one error, the answer I arrived at had `10*` on the wrong side of the comparison; this is negated by choosing to use zero-indexed input (which is what I did instead of fixing the off-by-one error, because I'm lazy)

At this point we have my intermdiate answer:

```
f=lambda n,i=1:10*100**n>i*i and f(n,i+1)or i

```
7. Square root both sides of the comparison:

```
f=lambda n,i=1:sqrt(10)*10**n>i and f(n,i+1)or i

```
8. Noting that the recursive wrapper now just searches for the first integral satisfying value of `i`, so it's pointless and can be replaced by `floor` `+1`:

```
lambda n:floor(sqrt(10)*10**n)+1

```
9. Some Python-specific tweaks to get a more optimal final answer:

```
lambda n:int(10**(n-.5))+1

```

This is now just the 26-byter above!

I'm tired, so there are probably a bunch of mistakes in this derivation, but they mirror my tired and mistake-ridden thought process!

# Python 2, 41 bytes

```
n=i=input()
while`i*i`[-n:n]:i+=1
print i
```

Attempt This Online!

Completely non-formulaic solution.

-4 bytes with a cool slicing trick thanks to loopy walt.

-4 thanks to dingledooper
> 5 votes

# Answer
# Jelly, 7 bytes

```
Ḥ’⁵*Æ½‘

```

Try It Online!

```
Ḥ’⁵*Æ½‘  Main Link
Ḥ        Double
 ’       Decrement
  ⁵*     10 ^ that (smallest number with 2n digits)
    Æ½   Floor square root
      ‘  Increment

```

Square root + ceiling is one byte shorter but has floating point issues at n = 17 so Jonathan Allan provided a fix for +1 byte that avoids this issue.
> 5 votes

# Answer
# Vyxal, 5 bytes

```
d‹↵√⌈

```

Try it online or verify the test cases.

```
d‹↵√⌈
d     # Double
 ‹    # Decrement
  ↵   # 10 to the power of that
   √  # Sqrt
    ⌈ # Ceiling

```
> 5 votes

# Answer
# , 19 bytes

```
\(n)10^(n-.5)%/%1+1
```

Attempt This Online!

Uses slight modification of the supplied formula.
> 4 votes

# Answer
# Python 2, 42 bytes

It outputs the sequence infinitely. Notably, this approach goes for efficiency without losing precision as a result of floating-point math.

```
n=3
s=50
while 1:print-~n;n=n*5+s/n;s*=100

```

Try it online!

### Explanation

The sequence can be computed by taking the first \\$ n \\$ digits of \\$ \sqrt{10} \\$, rounded up. To do this efficiently, we can use the Babylonian method. By taking an arbitrary number \\$ x \\$, and repeatedly applying it to the recurrence \\$ x = \frac{1}{2}(x + \frac{10}{x}) \\$, we can obtain an approximation of \\$ \sqrt{10} \\$ that converges extremely quickly (with quadratic convergence).

The above formula can be translated in Python as `n=n/2+5/n`. This works fine to simply compute the square root, but to compute the sequence we must scale \\$ n \\$ by a factor of 10 after each iteration. This can be done by having another variable `s` as the "scale factor", and modifying our original formula to scale by `s`. We end up with the following formula:

```
n=((n/s)/2+5/(n/s))*s*10; s*=10

```

It looks disgusting at first, but we can clean it up a bit:

```
n=((n/s)/2+5/(n/s))*s*10;s*=10  ->
n=(n/s/2+5*s/n)*s*10;s*=10      ->
n=n/s/2*s*10+5*s/n*s*10;s*=10   ->
n=n*5+5*s/n*s*10;s*=10          ->
n=n*5+50*s*s/n;s*=10            ->
n=n*5+s/n;s*=100                (starting with s=50)

```

The only thing left to do now is to modify the formula to round *up*. This turns out to be pretty simple, only changing `n` to `n+1`. I've checked that the first 500 terms of the sequence exactly match the output, though in theory, it is still susceptible to rounding errors.
> 3 votes

# Answer
# Charcoal, 8 bytes

```
Ｉ⌈×₂χＸχＮ

```

Try it online! Link is to verbose version of code. 0-indexed. Uses floating-point arithmetic. Explanation:

```
    χ       Predefined variable `10`
   ₂        Square root
  ×         Multiplied by
      χ     Predefined variable `10`
     Ｘ      Raised to power
       Ｎ    Input as a number
 ⌈          Ceiling
Ｉ           Cast to string
            Implicitly print

```

26 bytes using only integer arithmetic:

```
≔⁰ηＦＮ«≧×χηＷ﹪Ｌ×⊕η⊕η²≦⊕η»Ｉ⊕η

```

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

```
≔⁰η

```

Start with `0` as `⌊√1/10⌋`.

```
ＦＮ«

```

Repeat `n` times.

```
≧×χη

```

Multiply by 10 as our first estimate of `⌊10ⁱ·√1/10⌋`.

```
Ｗ﹪Ｌ×⊕η⊕η²≦⊕η

```

Increment our estimate until the number of digits of its square would become even, at which point it exactly equals `⌊10ⁱ·√1/10⌋`.

```
»Ｉ⊕η

```

Increment the final estimate, resulting in `⌈10ⁿ·√1/10⌉` as required.
> 2 votes

# Answer
# C (gcc), 22 bytes

```
f(n){n=exp10(n-.5)+1;}

```

Try it online!
> 2 votes

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

```
n=>-~(10**(n+.5))

```

Try it online!

Works up to \\$n=8\\$.

---

# JavaScript (Node.js), 23 bytes

```
n=>(p=10**(n+.5)+1)-p%1

```

Try it online!

Works up to \\$n=15\\$.

---

# JavaScript (Node.js), 40 bytes

```
n=>eval("for(i=0n;!('0'+i*i)[2*n];)++i")

```

Try it online!

Don't try it at home.
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
·<°tî

```

Port of *@hyper-neutrino♦*'s Jelly answer, so also outputs \\$a(n)\\$ based on \\$n\\$.

Try it online or verify all test cases.

**Explanation:**

```
·      # Double the (implicit) input-integer
 <     # Decrease it by 1
  °    # Take 10 to the power this input*2-1
   t   # Take the square-root of that
    î  # Ceil it
       # (after which the result is output implicitly)

```
> 2 votes

# Answer
# BQN, 9 bytes

```
⌈10⋆-⟜0.5

```

Try it at BQN online REPL

```
⌈           # ceiling of
 10⋆        # 10 to the power of
    -⟜0.5  # input minus 0.5

```
> 1 votes

# Answer
# Husk, 7 bytes

```
⌈`^10-.

```

Try it online!

Uses formula: floor () of `10` to the power of (`^`) input minus (`-`) a half (`.`).

---

# Husk, 9 bytes

```
€D⁰mȯLd□N

```

Try it online!

Calculates the number of digits (`Ld`) of the square () of each () number (`N`), and selects the index of the first () one that matches the input () doubled (`D`).
> 1 votes

# Answer
# Julia 1.0, 18 bytes

```
~n=ceil(10^(n-.5))

```

Try it online!

Based on the formula provided. By default, `ceil` returns a float, but `Int` can also be specified:

```
julia> f(n)=ceil(Int,10^(n-.5));

julia> map(f,1:10)
10-element Vector{Int64}:
          4
         32
        317
       3163
      31623
     316228
    3162278
   31622777
  316227767
 3162277661

```
> 1 votes

# Answer
# Nibbles, 6.5 bytes

```
+^^~-*$~~-2~
+          ~ Add 1 to
 ^       -2   floor of square root of
  ^~           10 to the power of
    -   ~       subtract 1 from
     * ~         multiply 2 with
      $           input

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, sequence, integer, floating-point
---


# Question
Title: Total Number of o's in all Cardinal Numbers up to \$n\$ in Standard American English
Let n be any integer between 1 and 999,999 inclusive. Your challenge is to write a complete program which using stdin or command-line arguments takes in n and outputs the number of times the letter "o" is needed to write all cardinal numbers in standard American English between 1 and n. You can assume that n will always be an integer within the above given range.

You can just use all lowercase letters as I do below. So we count all "o". No need to worry about uppercase "O".

Here is a quick review of how to write English numerals in American English.

```
one two three four ... nine ten eleven twelve thirteen fourteen ... nineteen twenty
twenty-one twenty-two ... twenty-nine thirty ... forty ... fifty ... sixty ...
seventy ... eighty ... ninety ... one hundred ... two hundred ... three hundred ...
nine hundred ... one thousand ... two thousand ... nine thousand ... ten thousand ...
eleven thousand ... ninety-nine thousand ... one hundred thousand ...
two hundred thousand ... nine hundred ninety-nine thousand nine hundred ninety nine.

```

The hyphen for two digit numbers doesn't matter.

The commas don't matter of course. I excluded them above.

Separation between hundreds and tens doesn't matter because we are only counting the letter "o" so 110 can be written as "one hundred ten", or "one hundred and ten". I excluded the "and" above.

For this challenge "hundred" and "thousand" must be preceded by "one" instead of "a" when being used at the beginning of the number. So 1111 must be "one thousand one hundred eleven" instead of "a thousand one hundred eleven".

Here are some more random numerals to clarify.

```
219873 = two hundred nineteen thousand eight hundred seventy three
615023 = six hundred fifteen thousand twenty three
617610 = six hundred seventeen thousand six hundred ten
423716 = four hundred twenty-three thousand seven hundred sixteen
386031 = three hundred eighty-six thousand thirty one

```

Here are some samples for what your code should return.

```
./mycount 1
1

```

There's only "one" to write so we need only a single "o".

```
./mycount 10
3

```

We only need three o's namely in "one", "two", and "four".

```
./mycount 101
41

```

Your code must be self-contained and must not connect to the internet, download any files, perform any query, etc. I can already see somebody using google or mathematica with wolfram alpha to do this.

True code-golf. The shortest code in any language wins. Please post your code with some test cases. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks. So everyone feel free to upvote any solutions you like.

Happy coding!

# Answer
## R - 54

```
sum(nchar(gsub("[^o]","",english::english(1:scan()))))

```

I get 41 for n=101. I hope someone can confirm.
> 7 votes

# Answer
## JavaScript 1.8 (150)

```
function f(n)n<14?(22>>n)&1:n<100?((n/10|0)==4)+f(n%10):n<1e3?f(n/100|0)+f(n%100):f(n/1e3|0)+f(n%1e3)+1;m=readline();for(s=i=0;i++<m;)s+=f(i);print(s)

```

As written, this will only work in SpiderMonkey `js` (the one used by Anarchy Golf). If running this in Firefox, replace `readline` with `prompt` and `print` with `alert`. Use of Mozilla's nonstandard "expression closures" feature means this will not work in any other interpreter unless you insert `{return` and `}` in the necessary places (at a cost of 7 characters).

Original test cases:

* 1 → 1
* 10 → 3
* 101 → 41

Some additional ones:

* 1020 → 726
* 21667 → 40173
* 120000 → 262002
* 999999 → 2359000
> 3 votes

# Answer
# C - 147 ~~148 157 163 166 172 200~~

C is the right tool for the job

```
s;l(x){s+=(22>>x%10&1)+(x/10%10==4)-!((x+89)/2%50);x&&l(x/100%10);}main(x,v)int**v;{for(x=atoi(v[1]);x;x--)l(x),l(x/1000),s+=x>999;printf("%d",s);}

```

Original tests:

* 1 -\> 1
* 10 -\> 3
* 101 -\> 41

Tests by @PleaseStand :

* 1020 -\> 726
* 21667 -\> 40173
* 120000 -\> 262602
* 999999 -\> 2359000

Plus some of my own random tests: http://qp.mniip.com/p/cy
> 3 votes

# Answer
# Mathematica ~~49 58~~ 50 bytes

Without a library or internet access.

```
StringCount[""<>IntegerName[Range@#,"Words"],"o"]&

```

---

**Note**:

"Words" guarantees that no digits will be left untranscribed into English.

This incorrectly returns one "o". (Emphasis added.)

```
IntegerName[1020]

```

> 1 th**o**usand 20

---

This yields two "o"'s, as required. (Emphasis added.)

```
IntegerName[1020,"Words"]

```

> **o**ne th**o**usand, twenty

---

**Example**

```
StringCount[""<>IntegerName[Range@#,"Words"],"o"]&[1020]

```

> 726
> 2 votes

# Answer
# Vyxal `s`, 6 bytes

```
ƛ∆ċ\oO

```

Try it Online!

Suggested by *@emirps*

## Vyxal, 7 bytes

```
ɾ∆ċṅ\oO

```

Try it Online!

Num-to-words builtins FTW!

#### Explanation

```
ƛ∆ċ\oO  # Implicit input
ƛ       # Map over range:
 ∆ċ     #  Convert to words
   \oO  #  Count "o"
        # s flag sums the list
        # Implicit output

ɾ∆ċṅ\oO # Implicit input
ɾ       # One-range
 ∆ċ     # Convert to words
   ṅ    # Join into a string
    \oO # Count "o"
        # Implicit output

```
> 2 votes

# Answer
# Moo - 137 bytes

```
s=$string_utils;m=player;i=0;for a in[1..toint(read(m))]i=i+length(s:strip_all_but(s:english_number(a),"o"));suspend(0);endfor m:tell(i);

```

The `suspend(0)` is necessary to avoid a `Task ran out of ticks` for high inputs. Also, this code takes quite a long time to run for very high numbers.
> 1 votes

# Answer
# Python \+ num2words, 81 bytes

```
lambda n:sum(num2words(i).count('o')for i in range(1,n+1))
from num2words import*

```
> 1 votes

# Answer
## Perl - 384

```
#!/usr/bin/perl
@b=qw(1 1 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1);
sub b($){my($b,$m)=shift;if(20>$b){$b[$b];}elsif(100>$b){$m=$b%10;
$b[(($b-$m)/10)+18]+($m?b($m):0);}elsif(1000>$b){$m=$b%100;
b(($b-$m)/100)+($m?b($m):0);}elsif(1000000>$b){$m=$b%1000;
b(($b-$m)/1000)+1+($m?b($m):0);}}
sub c($){my$c=shift;my$d=0;$d+=b($c--)while($c);$d;}
print c($_)."\n"while(<>);

```

this would run faster with caching but that would increase my score
> 0 votes

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