title: What is the most frequent word?

text:
# Question
Title: What is the most frequent word?
# What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

## Rules/Requirements

* Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.
* There must be a free interpreter/compiler available for your language.
* If it is possible, provide a link to a site where your program can be tested.
* Your program must not write anything to `STDERR`.
* Your program should take input from `STDIN` (or the closest alternative in your language).
* Standard loopholes are forbidden.
* Your program must be case-insensitive (`tHe`, `The` and `the` all contribute to the count of `the`).
* If there is no most frequent word (see test case #3), your program should output nothing.

### Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

## Test Cases

```
The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>

```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

## Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called ), will win.

## Submissions

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 79576; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
## Pyke, ~~26~~ 25 bytes

```
l1dcD}jm/D3Sei/1qIi@j@
(;

```

Try it here!

Or ~~23~~ 22 bytes (noncompeting, add node where kills stack if false)

```
l1cD}jm/D3Sei/1q.Ii@j@

```

Try it here!

Or with punctuation, 23 bytes (I think this competes? Commit was before the edit)

```
l1.cD}jm/D3Sei/1q.Ii@j@

```

Try it here!

Or 12 bytes (definitely noncompeting)

```
l1.cj.#jR/)e

```

Try it here!

```
l1           -     input.lower()
  .c         -    punc_split(^)
    j        -   j = ^
     .#   )  -  sort(V(i) for i in ^)
       jR/   -   j.count(i)
           e - ^[-1]

```
> 6 votes

# Answer
# Jelly, 25 bytes

```
ṣ⁶f€ØB;”-¤Œl©Qµ®ċÐ€ĠṪịµẋE

```

Try it online! or verify all test cases.
> 14 votes

# Answer
# Pyth - ~~23~~ 30 bytes

There has to be a better way to include digits and hyphens, but I just want to fix this right now.

```
Kc@s+++GUTd\-rzZ)I!tJ.M/KZ{KhJ

```

Test Suite.
> 11 votes

# Answer
# Octave, ~~115~~ 94 bytes

```
[a,b,c]=unique(regexp(lower(input('')),'[A-z]*','match'));[~,~,d]=mode(c); try disp(a{d{:}})

```

Accounts for the case with no most frequent word by using `try`. In this case it outputs nothing, and "takes a break" until you catch the exception.

Saved 21(!) bytes thanks to Luis Mendo's suggestion (using the third output from `mode` to get the most common word).

---

The rules have changed quite a bit since I posted my original answer. I'll look into the regex later.
> 6 votes

# Answer
# Perl 6, 80 bytes

```
{$_>1&&.[0].value==.[1].value??""!!.[0].key given .lc.words.Bag.sort:{-.value}}

```

Let's split the answer into two parts...

```
given .lc.words.Bag.sort:{-.value}

```

`given` is a control statement (like `if` or `for`). In Perl 6, they're allowed as postfixes. (`a if 1`, or like here, `foo given 3`). `given` puts its topic (right-hand side) into the special variable `$_` for its left-hand side.

The "topic" itself lowercases (`lc`), splits by word (`words`), puts the values into a Bag (set with number of occurences), then sorts by value (DESC). Since `sort` only knows how to operate on lists, the `Bag` is transformed into a `List` of `Pair`s here.

```
$_>1&&.[0].value==.[1].value??""!!.[0].key

```

a simple conditional (`?? !!` are used in Perl 6, instead of `? :`).

```
$_ > 1

```

Just checks that the list has more than one element.

```
.[0].value==.[1].value

```

Accesses to `$_` can be shortened... By not specifying the variable. `.a` is exactly like `$_.a`. So this is effectively "do both top elements have the same number of occurences" – If so, then we print '' (the empty string).

Otherwise, we print the top element's key (the count): `.[0].key`.
> 5 votes

# Answer
# Ruby, ~~94~~ ~~92~~ 102 bytes

Gotta go fast (FGITW answer). Returns the word in all uppercase, or `nil` if there is no most frequent word.

Now updated to new specs, I think. However, I did manage to golf down a little so the byte count is the same!

```
->s{w=s.upcase.tr("_'",'').scan /[-\w]+/;q=->x{w.count x};(w-[d=w.max_by(&q)]).all?{|e|q[e]<q[d]}?d:p}

```
> 4 votes

# Answer
# 05AB1E, 30 bytes

Code:

```
lžj¨„ -«Ãð¡©Ùv®yQOˆ}®¯MQÏDg1Q×

```

Uses **CP-1252** encoding. Try it online!.
> 4 votes

# Answer
## JavaScript (ES6), 155 bytes

```
s=>(m=new Map,s.toLowerCase().replace(/[^- 0-9A-Z]/gi,'').split(/\ +/).map(w=>m.set(w,-~m.get(w))),[[a,b],[c,d]]=[...m].sort(([a,b],[c,d])=>d-b),b==d?'':a)

```

Based on @Blue's Python answer.
> 4 votes

# Answer
# Python 3.5, 142 137 134 112 117 ~~110~~ 127 bytes:

(*+17 bytes, because apparently even if there are words more frequent than the rest, but they have the same frequency, nothing should still be returned.*)

```
def g(u):import re;q=re.findall(r"\b['\-\w]+\b",u.lower());Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]

```

Should now satisfy all conditions. This submission assumes that at least 1 word is input.

Try It Online! (Ideone)

Also, if you want one, here is another version of my function devoid of any regular expressions at the cost of about 43 bytes, though this one is non-competitive anyways, so it does not really matter. I just put it here for the heck of it:

```
def g(u):import re;q=''.join([i for i in u.lower()if i in[*map(chr,range(97,123)),*"'- "]]).split();Q=q.count;D=[*map(Q,{*q})];return['',max(q,key=Q)][1in map(D.count,D)]

```

Try this New Version Online! (Ideone)
> 4 votes

# Answer
# Pyth, 32 bytes

```
p?tlJeM.MhZrS@Ls++\-GUTcrz0d8ksJ

```

Test suite.
> 3 votes

# Answer
# Sqlserver 2008, 250 bytes

```
DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said.';

WITH c as(SELECT
@ p,@ x
UNION ALL
SELECT LEFT(x,k-1),STUFF(x,1,k,'')FROM
c CROSS APPLY(SELECT patindex('%[^a-z''-]%',x+'!')k)k
WHERE''<x)SELECT max(p)FROM(SELECT top 1with ties p
FROM c WHERE p>''GROUP BY p
ORDER BY count(*)DESC
)j HAVING count(*)=1

```

Try it online!

# Sqlserver 2016, 174 bytes

Unable to handle data like this example(counting the equals as 3 words):

```
DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said. = = ='

SELECT max(v)FROM(SELECT TOP 1WITH TIES value v
FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@,'"',''),',',''),'.',''),' ')GROUP
BY value ORDER BY count(*)DESC)x HAVING count(*)=1

```
> 3 votes

# Answer
# PostgreSQL, 246, 245 bytes

```
WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"''',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t

```

Output:

Input if anyone is interested:

```
CREATE TABLE i(t TEXT);

INSERT INTO i(t)
VALUES ('The man walked down the road.'), ('Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.'),
       ('This sentence has no most frequent word.'), ('"That''s... that''s... that is just terrible!" he said. '), ('The old-fashioned man ate an old-fashioned cake.'),
       ('IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.'), ('a   a            a b b b c');

```

---

Normally I would use `MODE() WITHIN GROUP(...)` and it will be much shorter, but it will violate:
> If there is no most frequent word (see test case #3), your program should output nothing.

---

**EDIT:**

Handling `'`:

```
WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"!',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t

```

`**`SqlFiddleDemo`**`

Output:

```
╔═══════════════════════════════════════════════════════════════════════════════════════════════╦═══════════════╗
║                                              t                                                ║      max      ║
╠═══════════════════════════════════════════════════════════════════════════════════════════════╬═══════════════╣
║ a a a b b b c                                                                                ║               ║
║ The old-fashioned man ate an old-fashioned cake.                                              ║ old-fashioned ║
║ IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.  ║ ipv6          ║
║ This sentence has no most frequent word.                                                      ║               ║
║ "That's... that's... that is just terrible!" he said.                                         ║ that's        ║
║ The man walked down the road.                                                                 ║ the           ║
║ Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.        ║ he            ║
╚═══════════════════════════════════════════════════════════════════════════════════════════════╩═══════════════╝

```
> 3 votes

# Answer
# JavaScript (ES6), 99 bytes

```
F=s=>(f={},w=c='',s.toLowerCase().replace(/[\w-']+/g,m=>(f[m]=o=++f[m]||1)-c?o>c?(w=m,c=o):0:w=''),w)
```

```
#input { width: 100%; }
```

```
<textarea id="input" oninput="output.innerHTML=F(this.value)"></textarea>
<div id="output"></div>
```
> 3 votes

# Answer
# Retina, 97 bytes

The rules keep changing...

```
T`L`l
[^-\w ]

O`[-\w]+
([-\w]+)( \1\b)*
$#2;$1
O#`[-\w;]+
.*\b(\d+);[-\w]+ \1;[-\w]+$

!`[-\w]+$

```

Try it online!

Test suite.
> 2 votes

# Answer
# Python, 132 bytes

```
import collections as C,re
def g(s):(a,i),(b,j)=C.Counter(re.sub('[^\w\s-]','',s.lower()).split()).most_common(2);return[a,''][i==j]

```

Above code assumes that input has at least two words.
> 2 votes

# Answer
# R, 115 bytes

```
function(s)if(sum(z<-(y=table(tolower((x=strsplit(s,"[^\\w']",,T)[[1]])[x>""])))==max(y))<2)names(which(z))else NULL

```

This is a function that accepts a string and returns a string if a single word appears more often than others and `NULL` otherwise. To call it, assign it to a variable.

Ungolfed:

```
f <- function(s) {
    # Create a vector of words by splitting the input on characters other
    # than word characters and apostrophes
    v <- (x <- strsplit(s, "[^\\w']", perl = TRUE))[x > ""]

    # Count the occurrences of each lowercased word
    y <- table(tolower(v))

    # Create a logical vector such that elements of `y` which occur most
    # often are `TRUE` and the rest are fase
    z <- y == max(y)

    # If a single word occurs most often, return it, otherwise `NULL`
    if (sum(z) < 2) {
        names(which(z))
    } else {
        NULL
    }
}

```
> 2 votes

# Answer
# Python 2, 218 bytes

Assumes more than 2 words. Getting rid of punctuation destroyed me...

```
import string as z
def m(s):a=[w.lower()for w in s.translate(z.maketrans('',''),z.punctuation).split()];a=sorted({w:a.count(w)for w in set(a)}.items(),key=lambda b:b[1],reverse=1);return a[0][0]if a[0][1]>a[1][1]else''

```
> 1 votes

# Answer
## Matlab (225)

* Rules chaneged :/

.

```
      function c=f(a),t=@(x)feval(@(y)y(y>32),num2str(lower(x)-0));f=@(x)num2str(nnz(x)+1);e=str2num(regexprep(a,'([\w''-]+)',' ${t($1)} ${f($`)} ${f([$`,$1])}'));[u,r,d]=mode(e);try c=find(e==d{:});c=a((e(c(1)+1)):(e(c(1)+2)));end

```
* Toolbox is necessary to run this.
* How does this work, one of the nicest privileges of regex replace in matlab this it field-executes tokens by calling external-environmental functions parameterized by the tokens caught in the inner environment, so any sequence of `"Word_A Word_B .."` is replaced by integers `"A0 A1 A2 B0 B1 B2 ..."` where the first integer is the numerica ascii signature of the word, the second is the starting index, the third is the ending index, these last two integers dont reduplicate in the whole sequence so i took this advantage to transpose it to an array, then mode it then search the result in that array, so the starting/ending indices will consequently follow.
* **Edit:** after changing some details, the program is called function by a string parameter.

---

**20** bytes saved thanks to @StewieGriffin, **30** bytes added reproaches to common-agreed loopholes.
> 1 votes

# Answer
# PHP, 223 bytes

```
$a=array_count_values(array_map(function($s){return preg_replace('/[^A-Za-z0-9]/','',$s);},explode(' ',strtolower($argv[1]))));arsort($a);$c=count($a);$k=array_keys($a);echo($c>0?($c==1?$k[0]:($a[$k[0]]!=$a[$k[1]]?$k[0]:'')):'');

```
> 1 votes

# Answer
# Perl, ~~60~~ ~~56~~ ~~55~~ 54 bytes

Includes +3 for `-p`

```
#!/usr/bin/perl -p
s/[\pL\d'-]+/$;[$a{lc$&}++]++or$\=$&/eg}{$\x=2>pop@

```

If a word cannot be just a number you can also drop the `a` for a score of 53.
> 1 votes

# Answer
# Shell, ~~89~~ ~~86~~ 82 bytes

```
grep -Po "[\w'-]+"|sort -f|uniq -ci|sort -nr|awk 'c>$1{print w}c{exit}{c=$1;w=$2}'

```

This lists all words in the input, then sorts them with counts from most common to least common. The `awk` call merely ensures that the #2 word doesn't have the same count as the #1 word.

Unwrapped:

```
grep -Po "[\w'-]+"      # get a list of the words, one per line
  |sort -f              # sort (case insensitive, "folded")
  |uniq -ci             # count unique entries while still ignoring case
  |sort -nr             # sort counted data in descending order
  |awk '
    count > $1 {        # if count of most common word exceeds that of this line
      print word        # print the word saved from it
    }
    count {             # if we have already saved a count (-> we are on line 2)
      exit              # we always exit on line 2 since we have enough info
    }
    {                   # if true (run on line 1 only due to the above exit)
      count = $1        # save the count of the word on this first line
      word = $2         # save the word itself
    }'

```

`grep -o` is the magic tokenizer here. It takes each word (as defined by a regex accepting word characters (letters, numbers, underscore), apostrophe, or hyphen using PCRE given `-P`) and puts it on its own line. This accepts underscores, as to many other answers here. To disallow underscores, add four characters to turn this portion into `grep -oi "[a-z0-9'-]*"`

`alias cnt='sort -f |uniq -ci |sort -nr'` is an old standby of mine. Without regards to case, it alphabetizes (erm, asciibetizes) the lines of the input counts occurrences of each entry, then reverse-sorts by the numeric occurrences so the most popular is first.

`awk` only looks at the first two lines of that descending ranked list. On line one, `count` is not yet defined, so it is evaluated as zero and therefore the first two stanzas are skipped (zero == false). The third stanza sets `count` and `word`. On the second line, `awk` has a defined and nonzero value for `count`, so it compares that count to the second best count. If it's not tied, the saved `word` is printed. Regardless, the next stanza exits for us.

Test implemented as:

```
for s in "The man walked down the road." "Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy." "This sentence has no most frequent word." "\"That's... that's... that is just terrible\!\" he said." "The old-fashioned man ate an old-fashioned cake." "IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses." "This sentence with words has at most two equal most frequent words."; do printf "%s\n==> " "$s"; echo "$s" |grep -io "[a-z0-9'-]*"|sort -f|uniq -ci|sort -nr|awk 'c>$1{print w}c{exit}{c=$1;w=$2}'; echo; done

```
> 1 votes

# Answer
# 05AB1E, ~~22~~ ~~21~~ 20 bytes

```
žK„- JÃl#{D.MDgiJëõ?

```

Explanation:

```
žK                     # Push [a-zA-Z0-9]
  „-                   # Push 2-char string containing a hyphen and a space
     J                 # Join the stack into a single element
      Ã                # Removes all characters from implicit input except those specified above
       l               # Converts to lowercase
        #              # Split string by spaces
         {             # Sorts array
          D            # Duplicates
           .M          # Finds most common element
             Dg        # Gets length of string without popping
                 iJ    # If length == 1, then convert the array to a string (otherwise the output would be ['example'] instead of example
                   ëõ? # Else push an empty string.

```

Note: If you're fine with trailing newlines in the output for when you're not supposed to output anything, remove the `?` at the end to save a byte.

Note #2: The program will not work with a single word, but I doubt this would be a problem. If you want to fix this, replace `#` with `ð¡` for an extra byte.

05AB1E uses CP-1252 as the charset, not UTF-8.

Try it online!
> 1 votes

# Answer
# Julia 1.0, ~~140~~ 133 bytes

```
~s=(d=Dict();split(replace(lowercase(s),r"[^\' 0-9a-z-]"=>"")).|>w->d[w]=get(d,w,0)+1;(x,y)=findmax(d);sum(x.==values(d))<2 ? y : "")

```

Try it online!

-7 bytes thanks to MarcMush: replace `count(i->d[i]==x,keys(d))` with `sum(x.==values(d))`
> 1 votes

# Answer
# Python, 158 bytes

```
def g(s):import collections as c,re;l=c.Counter(re.sub('[^\w\s-]',"",s.lower()).split());w,f=l.most_common(1)[0];return[w,""][all(f==i[1]for i in l.items())]

```

Takes its input like this:

```
g("Bird is the word")

```

Should match all the requirements, although it does fail on empty strings, is it necessary to check for those? Sorry for the delay.

Advice / feedback / black magic tips for saving bytes are always welcome
> 0 votes

# Answer
# Lua, ~~232~~ ~~199~~ 175 bytes

```
w,m,o={},0;io.read():lower():gsub("[^-%w%s]",""):gsub("[%w-]+",function(x)w[x]=(w[x]or 0)+1 end)for k,v in pairs(w)do if m==v then o=''end if(v>m)then m,o=v,k end end print(o)

```
> 0 votes

# Answer
# Rexx, ~~109~~ ~~128~~ 122 bytes

```
pull s;g.=0;m=0;do i=1 to words(s);w=word(s,i);g.w=g.w+1;if g.w>=m then do;m=g.w;g.m=g.m+1;r=w;end;end;if g.m=1 then say r

```

Pretty printed...

```
pull s
g.=0
m=0
do i=1 to words(s)
  w=word(s,i)
  g.w=g.w+1
  if g.w>=m
  then do
    m=g.w
    g.m=g.m+1
    r=w
  end
end
if g.m=1 then say r

```
> 0 votes

# Answer
# PowerShell (v4), 117 bytes

```
$y,$z=@($input-replace'[^a-z0-9 \n-]'-split'\s'|group|sort Count)[-2,-1]
($y,($z,'')[$y.Count-eq$z.Count])[!!$z].Name

```

The first part is easy enough:

* `$input` is ~= stdin
* Regex replace irrelevant characters with nothing, keep newlines so we don't mash two words from the end of a line and the beginning of the next line into one by mistake. (Nobody else has discussed multiple lines, could golf -2 if the input is always a single line).
* Regex split, `Group` by frequency (~= Python's collections.Counter), `Sort` to put most frequent words at the end.
* PowerShell is case insensitive by default for everything.

Handling if there isn't a most frequent word:

* Take the last two items \[-2,-1\] into $y and $z;
* an N-item list, where N\>=2, makes $y and $z the last two items
* a 1-item list makes $y the last item and $z null
* an Empty list makes them both null

Use the bool-as-array-index fake-ternary-operator golf `(0,1)[truthyvalue]`, nested, to choose "", $z or $y as output, then take .Name.

```
PS D:\> "The man walked down the road."|.\test.ps1
The

PS D:\> "Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy."|.\test.ps1
he

PS D:\> "`"That's... that's... that is just terrible!`" he said."|.\test.ps1
Thats

PS D:\> "The old-fashioned man ate an old-fashioned cake."|.\test.ps1
old-fashioned

PS D:\> "IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses."|.\test.ps1
IPv6

```
> 0 votes

# Answer
# Perl 5, ~~96~~ ~~92~~ 84 + 2 (`-p` flag) = 86 bytes

```
++$h{+lc}for/\w(?:\S*\w)?/g}{$m>$e[1]||$e[1]>$m&&(($_,$m)=@e)||($_="")while@e=each%h

```

Using:

```
> echo "The man walked down the road." | perl -p script.pl

```
> 0 votes

# Answer
bash, ~~153~~ ~~146~~ ~~131~~ ~~154~~ ~~149~~ ~~137~~ bytes

```
declare -iA F
f(){ (((T=++F[$1])==M))&&I=;((T>M))&&M=$T&&I=$1;}
read L
L=${L,,}
L=${L//[^- a-z0-9]}
printf -vA "f %s;" $L
eval $A;echo $I

```

Operation:

declare an associative array F of integers (declare -iA F)

f is a function that, given a word parameter $1, increments frequency count for this word (T=++F\[$1\]) and compares to max count so far (M).

If equal, the we have a tie so we will not consider this word to be most frequent (I=)

If greater than max count so far (M), then set max count so far to frequency count of this word so far (M=$T) and remember this word (I=$1)

End function f

Read a line (read L) Make lowercase (L=${L,,}) Remove any character except a-z, 0-9, dash(-) and space (L=${L//\[^- a-z0-9\]}) Make a sequence of bash statements that calls f for each word (printf -vA "f %s;" $L). This is saved to variable A. eval A and print result (eval $a;echo$I)

Output:

```
This quick brown fox jumps over this lazy dog.
-->this
This sentence with the words has at most two equal most frequent the words.
-->
The man walked down the road.
-->the
This sentence has no most frequent word.
-->
Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
-->he
"That's... that's... that is just terrible!" he said.
-->thats
The old-fashioned man ate an old-fashioned cake.
-->old-fashioned
IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
-->ipv6

```

Bug: FIXED I have a bug that is not revealed in these test cases. If input is

```
This sentence with words has at most two equal most frequent words.

```

then my code should output nothing.

~~I have a fix but I seem to have hit a bash bug... I get very odd behaviour is M is not declared an integer: ++F\[$1\]==M (after a few repeated words) increments both F\[$1\] and M!!~~ \- my mistake.
> 0 votes

# Answer
# Tcl 8.6, 196 bytes

```
lmap s [join [read stdin] \ ] {dict incr d [regsub -all {[^\w-]} [string tol $s] {}]}
set y [dict fi $d v [lindex [lsort [dict v $d]] end]]
if {[llength $y]!=2} {set y {}}
puts "==> [lindex $y 0]"

```

(Alas, I can't figure out how to get it any smaller than that...)

**Explanation**

It uses several obscure Tcl idioms to do stuff.

* `[join [read stdin] " "]` — input string→list of whitespace-separated words
* `lmap ...` — iterate over every element of that list. (Shorter than `foreach` and effectually identical since the result is discarded.)
* `[regsub ... [string tolower ...]]` — Convert the string to lowercase and strip all characters except for word characters and the hyphen.
* `[dict incr d ...]` — Create/modify a dictionary/word→count histogram.
* `set y ...` — Sort the dictionary values, take the largest one, and return all (key,value) pairs corresponding to it.
* `if...` — There must be exactly two elements: a single (key,value) pair, else there is nothing to print.
* `puts...` — Print the key in the key value pair, if any. (No word has spaces.)

You can play with it using CodeChef.
> 0 votes

# Answer
# Python 3, 106 bytes

```
def f(s):s=s.split();z=sorted([s.count(i)for i in set(s)]);return("",max(set(s),key=s.count))[z[-2]<z[-1]]

```
> 0 votes

# Answer
# Python 3, ~~76~~ ~~98~~ 100 bytes

```
import re,statistics as S
try:print(S.mode(re.split("([a-z0-9-]+)",input().lower())[1::2]))
except:1

```

**Try it online**

Outputs the most common word as lowercase. Does not include apostrophes because "apostrophes are not required to be included."

`statistics.mode` requires Python 3.4

Unfortunately, no output to `stderr` is allowed, or it'd be much shorter.
> 0 votes

# Answer
# R, 96 bytes

19 bytes shorter than the existing R answer, with a somewhat different approach.

```
t=table(gsub("[^a-z0-9'-]","",tolower(scan(,''))))
`if`(sum(t==max(t))-1,'',names(which.max(t)))

```

Reads from stdin, so the input is automatically separated by spaces. We convert to lowercase and use `gsub` to remove all non-alphanumerics (plus `-` and `'`). We count the instances of each word with `table` and save the result to `t`. Next, we check if there is more than 1 maximum in `t` (by seeing if there is more than one element which is equal to `max(t)`. If so, we return the empty string `''`. If not, we return the word corresponding to the maximum in `t`.
> 0 votes

# Answer
# Java 7, 291 bytes

```
import java.util.*;Object c(String s){List w=Arrays.asList(s.toLowerCase().split("[^\\w'-]+"));Object r=w;int p=0,x=0;for(Object a:w){p=Collections.frequency(w,r);if(Collections.frequency(w,a)>p)r=a;if(p>x)x=p;}for(Object b:w)if(!b.equals(r)&Collections.frequency(w,b)==p)return"";return r;}

```

The rule where it should output nothing when there are multiple words with the same occurrence took quite a bit of extra code..

**Ungolfed:**

```
import java.util.*;
Object c(String s){
  List w = Arrays.asList(s.toLowerCase().split("[^\\w'-]+"));
  Object r = w;
  int p = 0,
      x = 0;
  for(Object a : w){
    p = Collections.frequency(w, r);
    if(Collections.frequency(w, a) > p){
      r = a;
    }
    if(p > x){
      x = p;
    }
  }
  for(Object b : w){
    if(!b.equals(r) & Collections.frequency(w, b) == p){
      return "";
    }
  }
  return r;
}

```

**Test code:**

Try it here.

```
import java.util.*;
class M{
  static Object c(String s){List w=Arrays.asList(s.toLowerCase().split("[^\\w'-]+"));Object r=w;int p=0,x=0;for(Object a:w){p=Collections.frequency(w,r);if(Collections.frequency(w,a)>p)r=a;if(p>x)x=p;}for(Object b:w)if(!b.equals(r)&Collections.frequency(w,b)==p)return"";return r;}

  public static void main(String[] a){
    System.out.println(c("The man walked down the road."));
    System.out.println(c("Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy."));
    System.out.println(c("This sentence has no most frequent word."));
    System.out.println(c("\"That's... that's... that is just terrible!\" he said."));
    System.out.println(c("The old-fashioned man ate an old-fashioned cake."));
    System.out
        .println(c("IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses."));
    System.out.println(c("This sentence with words has at most two equal most frequent words."));
  }
}

```

**Output:**

```
the
he
     (nothing)
that's
old-fashioned
ipv6
     (nothing)

```
> 0 votes

---
Tags: code-golf, string, natural-language
---


title: Bad factorial joke

text:
# Question
Title: Bad factorial joke
Sometimes I make bad jokes... And a bad joke I like to make involves interpreting exclamation marks in sentences as the factorial sign.

# Task

Your task is to write a program that receives a sentence and applies the factorial joke to the sentence.

The "factorial joke" consists of looking for exclamation marks "!" and doing the factorial of whatever is to the left of it. If the thing to the left is an integer, then the usual factorial is used. If the thing to the left is a word (a sequence of characters in `[a-zA-Z]`, delimited by spaces), then we want to concatenate all of the subsequent prefixes of the word.

E.g. if the word was `abcd` then `abcd! = abcdabcaba`.

**However**, there is an exception, which is when the sentence contains a "1!" or "2!", because `1! = 1` and `2! = 2` and the joke doesn't really work. In these cases, your program can do whatever it wants EXCEPT applying the factorial joke or returning the same sentence.

# Input

A sentence with characters in the range `[a-zA-Z0-9 !]` with the restriction that only one exclamation mark "!" is present and to the right of an integer or a "word". This means you don't have to worry with things as `"abc4!"` as a word here is defined as a sequence of *alphabetical* characters delimited by spaces.

# Output

The same sentence, but with the factorial joke applied to the word or integer on the left of the exclamation mark.

# Test cases

You can find a Python reference implementation here

```
We lost the match 3 to 0! -> We lost the match 3 to 1
ora bolas! -> ora bolasbolabolbob
give me 4! -> give me 24
I wanted 2! give me 2 -> undefined
Let us build a snowman! -> Let us build a snowmansnowmasnowmsnowsnosns
We are late because it is past 17! -> We are late because it is past 355687428096000
I only have one! -> I only have oneono
I only have 1! -> undefined
Incredible! I have never seen anything like it -> IncredibleIncrediblIncredibIncrediIncredIncreIncrIncInI I have never seen anything like it
What an amazing code golf challenge this is! -> What an amazing code golf challenge this isi
So many test cases! -> So many test casescasecascac
These are actually just 11! -> These are actually just 39916800
No wait! there are 13 -> No waitwaiwaw there are 13

```

---

This is so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

# Answer
> 10 votes
# 05AB1E, ~~23~~ ~~22~~ ~~26~~ ~~25~~ 20 bytes

```
ð¡εD'!åi¨ÐaiηRJë2Lså+!]ðý

```

+4 bytes for two bug-fixes (+1 in case the input is without spaces; +3 for `0!`)
-5 bytes thanks to *@Grimmy*.

Outputs `2`/`3` for `1!`/`2!` respectively.

Try it online or verify all test cases.

**Explanation:**

```
ð¡                  # Split the (implicit) input-string on spaces
                    # (NOTE: `#` cannot be used here if the input doesn't contain spaces)
  ε                 # Map each part to:
   D                #  Duplicate it
    '!åi           '#  If it contains a "!":
        ¨           #   Remove the last character (the "!")
         D          #   Duplicate it
          !         #   Take the factorial of it (strings remain the same)
           s        #   Swap to get the duplicate value again
            >       #   Increase it by 1 (strings remain the same)
             η      #   Get the prefixes of this string/integer
              R     #   Reverse it
               J    #   And join them together to a single string
                M   #   And then push the largest value on the stack
                    #   (which is either the factorial-integer;
                    #    or the integer+1 if it was 0, 1, or 2;
                    #    otherwise it's the longest string, which is the joined prefixes)
  ]                 # Close both the map and if-statement
   ðý               # And join everything with space delimiter again
                    # (after which the result is output implicitly)

```

# Answer
> 10 votes
# Python 3.8, <sup>~~222~~ \\$\cdots\\$ ~~178~~</sup> 176 bytes

Saved 2 bytes thanks to Kevin Cruijssen!!!
Added ~~2~~ 3 bytes to fix bugs.
Saved 5 bytes thanks to ovs!!!

```
lambda j:(g:=re.match(r"(.*)\b(\w+)!(.*)",j).group)(1)+(str(math.perm(int(f)))*-~(f in'1 2')if(f:=g(2))[0]<':'else''.join(f[:i]for i in range(len(f),0,-1)))+g(3)
import math,re

```

Try it online!

Replaces `1!` with `11` and `2!` with `22`.

### Ungolfed:

```
import math,re
def f(j):
 m=re.match(r"(.*)\b(\w+)!(.*)" ,j)
 f=m.group(2)
 if f in ('1','2'):f=''
 if re.match(r"\d+",f):
     f=str(math.factorial(int(f)))
 else:
     f=''.join(f[:i] for i in range(len(f),0,-1))
 return m.group(1)+f+m.group(3)

```

# Answer
> 8 votes
# JavaScript (ES6),  ~~86 85~~  80 bytes

Replaces `1!` and `2!` with `0` ... ¯\\\_(ツ)\_/¯

```
s=>s.replace(/\w+!/,g=s=>(s=s.slice(0,-1))?1/s?'1006'[s]||s*g(s-1+'#'):s+g(s):s)

```

Try it online!

### How?

Because the callback function of `replace()` is recursive, it's better to feed it with a single variable \\$s\\$ to keep the recursive calls short. That's why the `!` is captured along with the word preceding it.

The same `slice(0,-1)` is used to remove the `!` on the first iteration and to build the prefixes in case of a string. In order to make the factorial computation compatible with that method, we just have to pad the recursive argument with a random character which is immediately removed by the next iteration.

To deal with the weird edge cases \\$1!\\$ and \\$2!\\$, we use the small lookup string `'1006'` to stop the recursion whenever the value is less than or equal to \\$3\\$. This way, we have \\$0!=1\\$, \\$3!=6\\$ and \\$n! = 6\cdot\prod\_{k=4}^{n}k\\$ for \\$n\>3\\$, but \\$1!=2!=0\\$ (sic).

### Commented

*NB: alternate slash symbols used in the regular expression to prevent the syntax highlighting from being broken*

```
s =>                        // s = input string
  s.replace(                // find in s
    ⁄\w+!⁄,                 // a word followed by a '!'
    g = s =>                // g is a recursive function computing the replacement
      (s = s.slice(0, -1))  //   remove the last character from s
                            //   (for the 1st iteration, it removes the '!')
      ?                     //   if the resulting string is not empty:
        1 / s ?             //     if this is a numeric value:
          '1006'[s]         //       0 -> 1, 1 -> 0, 2 -> 0, 3 -> 6
          || s *            //       for all other values, multiply s by
             g(s - 1 + '#') //       the result of a recursive call with s - 1,
                            //       padded with a '#' for the next slice()
        :                   //     else (s is a string):
          s +               //       append s
          g(s)              //       append the result of a recursive call
      :                     //   else (s is empty):
        s                   //     stop recursion
  )                         // end of replace()

```

# Answer
> 7 votes
# Python 3, ~~157~~ 155 bytes

Thanks to Noodle9 for -2 bytes.

```
(*s,w),b=map(str.split,input().split('!'))
w*=1+(w in'1 2')
if'A'>w:
 i=int(w);w=1
 while i:w*=i;i-=1
else:
 d=w[:-1]
 while d:w+=d;d=d[:-1]
print(*s,w,*b)

```

Try it online!

# Answer
> 5 votes
# Wolfram Language (Mathematica), 173 bytes

```
StringRiffle[""<>If[Last@#=="!",If[NumberQ[n=ToExpression[""<>#]],If[n>0&&n<3&&First@#!="0","",ToString@n],Rest@NestList[Most,#,Length@#-1]],#]&/@Characters/@StringSplit@#]&

```

Try it online!

*-2 bytes from @Kevin Cruijssen*

# Answer
> 5 votes
# Perl 5 `-p -MList::Util=product`, 93 bytes

```
s/(\d+)!/$1?$1>2?product 1..$1:'':1/e;s%(\w+)!%join'',map{substr$1,0,$_}reverse 1..length$1%e

```

Try it online!

# Answer
> 5 votes
# Jelly, ~~22~~ 21 bytes

```
;”ḟV$¹ƤṖṚƊfØD$?ċ¡€”!K

```

Try it online!

A full program taking a list of words and printing a string. For the 1 and 2 cases the 1 and 2 are dropped from the output. Saved a byte now that a list of words is permitted input.

## Explanation

```
Ḳ                      | Split at spaces
                ċ¡€”!  | For each word, if it contains a ! then do the following:
           fØD$?       | - If any characters are left after restricting to digits:
     $                 | - Then:
 ;”ḟ                   |   - Append ḟ (which will filter out 1 and 2 at the next step because x! == x)
    V                  |   - Evaluate (i.e. calculate the factorial and then filter out the input number)
          Ɗ            | - Else:
      ¹Ƥ               |   - Prefixes
        Ṗ              |   - Remove last
         Ṛ             |   - Reverse
                     K | Finally, join with spaces

```

# Answer
> 4 votes
# Ruby, ~~88 85~~ 83 bytes

```
->s{s.sub(/\S+!/){|z|z<?1?1:z>?9?z.chars.map{z=z.chop}*'':eval([6,*4..z.to_i]*?*)}}

```

Try it online!

# Answer
> 4 votes
# Retina, 70 bytes

```
' %/!$/&/^[012]!$/(`..
$.(*__
/\D./(^`.
$`
.+
*
_
$.>`$*
~`^
^.$*¶$$.(

```

Try it online! Link includes test cases. Explanation:

```
' %

```

Split the input into words.

```
/!$/&

```

Only process words that end in `!`.

```
/^[012]!$/(`

```

If this is `0!`, `1!` or `2!`...

```
..
$.(*__

```

... then return the incremented digit. (Approach shamelessly stolen from @Arnauld.)

```
/\D./(

```

If the word contains a non-digit (excluding the trailing `!`)...

```
^`.
$`

```

... then replace it with all of its prefixes in reverse order. (Note that these are exclusive prefixes so that the empty prefix is included but the string including the `!` is excluded.)

```
.+
*
_
$.>`$*
~`^
^.$*$n$$.(

```

Otherwise compute the factorial.

# Answer
> 4 votes
# Red, ~~242~~ ~~225~~ 204 bytes

```
func[s][c: charset[#"0"-#"z"]parse s[any[change[copy t any c"!"](
case[find"12"t[0]t <"A"[t: to 1 t p: 1 while[t > 1][p: p * t
t: t - 1]p]t >":"[p: copy t until[take/last p append t p p =""]t]])| skip]]s]

```

Try it online!

# Answer
> 4 votes
# SNOBOL4 (CSNOBOL4), 206 bytes

```
	D =84 ** 9
	INPUT ARB . L SPAN(&UCASE &LCASE D) . W '!' REM . R
	W SPAN(D) 	:F(S)
	N =W + 1	LT(W,3)	:S(O)
	N =W
F	W =W - 1	GT(W,1)	:F(O)
	N =N * W	:(F)
S	N =N W
	W ARB . W RPOS(1)	:S(S)
O	OUTPUT =L N R
END

```

Try it online!

`84 ** 9 = 208215748530929664` which has all the digits from 0-9.

```
	D =84 ** 9						;* D contains every decimal digit.
	INPUT ARB . L SPAN(&UCASE &LCASE D) . W '!' REM . R
	;* split the input into an ARBitrary Left part, the Word followed by a '!' and the REMainder to the Right part.
	W SPAN(D) 	:F(S)					;* if W has digits, goto S
	N =W + 1	LT(W,3)	:S(O)				;* if W < 3, then N = W + 1 and goto O
	N =W							;* set N = W
F	W =W - 1	GT(W,1)	:F(O)				;* decrement W, and goto O if W == 0
	N =N * W	:(F)					;* N = N * W, goto F
S	N =N W							;* W is a string, so set N = N W
	W ARB . W RPOS(1)	:S(S)				;* set W to W excluding its final character and if W had any characters, goto S
O	OUTPUT =L N R						;* output Left, the New middle, and the Right string.
END

```

# Answer
> 4 votes
# , ~~205~~ ~~201~~ ~~194~~ 189 bytes

```
s=scan(,'');l=grepl('\\w!',s);w=s[l];n=nchar;k=function(m,x)substr(x,1,n(x)-m);w=k(1,w);b=as.numeric(w);o=`if`(is.na(b),Reduce(paste0,sapply(0:n(w)-1,k,w)),gamma(b+1));s[l]=o;if(o!=w)cat(s)

```

Try it online!

# Answer
> 2 votes
# Jelly, 26 bytes

```
ḲṖVN!Ƒ¡!ƲṖƤṚ$<”AẠ$?¹ċ?€”!K

```

A full program accepting a string which prints the result.

**Try it online!**

Kind of a tough one for Jelly.

### How?

```
ḲṖVN!Ƒ¡!ƲṖƤṚ$<”AẠ$?¹ċ?€”!K - Link: list of characters, s
Ḳ                          - split at space characters -> words
                       ”!  - literal '!' character
                      €    - for each word:
                     ?     -   if...
                    ċ      -   ...condition: count (i.e. contains?)
                  ?        -   ...then: if...
                 $         -            ...condition: last two links as a monad:
             <             -              less than:
              ”A           -                literal 'A' character
                Ạ          -              all?
        Ʋ                  -            ...then: last four links as a monad:
 Ṗ                         -              pop (remove the '!')
  V                        -              evaluate as Jelly code (get an integer)
      ¡                    -              repeat...
     Ƒ                     -              ...number of times: is invariant under?:
    !                      -                factorial
   N                       -              ...action: negate (i.e. 1;2;X -> -1;-2;X)
       !                   -              factorial (-1! = -2! = inf)
            $              -            ...else: last two links as a monad:
          Ƥ                -              for prefixes:
         Ṗ                 -                pop (remove the `!` from each prefix)
           Ṛ               -              reverse
                   ¹       -   ...else: no-op
                         K - join with spaces
                           - implicit, smashing print

```

# Answer
> 2 votes
# Husk, 23 bytes

```
wm??öΣ↔ḣhȯs§Y→ΠiV√I€'!w

```

Try it online!

Maps 1 to 2 and 2 to 3.

On my phone, so writing an explanation is not too easy, but I'll try.

Code with parentheses for "clarity":

```
wm(?(?(Σ↔ḣh)(s§Y→Πi)(V√))(I)(€'!))w

```

The main part of the code is built by conditionals, they may be a bit easier to read once you know that in Husk `?abc` means `if c then a else b`. Also, most of the time `fg` is the composition of functions `f` and `g`, so we are actually applying `g` before `f` (to oversimplify it, you should read the code backwards)

A pseudocode for this could be:

```
Split input into words, map the following function to each word and then join them again.
  If word contains '!':
    if any character of the word is a letter:
      get the head of the word (drop final '!')
      get the list of prefixes (heads)
      reverse it
      join prefixes in a single word
    else:
      convert word to integer
      get the maximum between:
        successor
        factorial
      convert it back to string
  else apply Identity function (do nothing)

```

# Answer
> 2 votes
# Charcoal, 57 bytes

```
≔⌕θ!η≔⊟⌕Ａ⁺ …θη ζ…θζ≔✂θζη¹ε≡ε2¹1¹0¦1¿ΣεＩΠ…·¹Ｉε⭆ε…ε⁻Ｌεκ✂θ⊕η

```

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

```
≔⌕θ!η

```

Find the position of the `!`.

```
≔⊟⌕Ａ⁺ …θη ζ

```

Find the position of the start of the word ending in `!`.

```
…θζ

```

Print the prefix of the input before the word.

```
≔✂θζη¹ε≡ε

```

Extract the word and switch on it.

```
2¹1¹0¦1

```

If it's `2` or `1` then output a `-`, otherwise if it's a `0` then outputs `1`, otherwise...

```
¿ΣεＩΠ…·¹Ｉε

```

... if it's an integer then output its factorial, otherwise...

```
⭆ε…ε⁻Ｌεκ

```

... output its prefixes in reverse order. (These are inclusive prefixes, so they include the word itself but not the empty string.)

```
✂θ⊕η

```

Print the suffix of the input after the `!`.

# Answer
> 2 votes
# Japt, 27 bytes

Well, this is just god-awful but I've spent far too long on it to *not* post it. Kids, let this be a warning against trying to golf without your full faculties about you!

```
r"(%w+)!"Ï<3?°Y:Yn ÊªYå+ Ôq

```

Try it

# Answer
> 1 votes
# 05AB1E, ~~26~~ ~~22~~ 26 bytes

```
ð¡εD'!¢i¨D.ïiÐ!Ês!*ëηRJ]ðý

```

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 227 bytes

```
s=>{var w=s.Split("!")[0].Split(" ").Last();if(!int.TryParse(w,out int n))for(;(w=w.Substring(1)).Length!=0;)s=s.Replace("!",w+"!");else{for(int i=n;--i>0;n=n*i);s=s.Replace(w+"!",""+(n<1?1:n>4?n:0));}return s.Replace("!","");}

```

Try it online!

# Answer
> 1 votes
# C (GCC), 236 bytes

```
i,j;char*a,*b,*c,*d;f(char*s){a=strchr(s,33);for(b=a;b>s&!isspace(b[-1]);--b);for(d=s;d-b;)putchar(*d++);*a=0;if(*b&64)for(c=a;*b;*--c=0)printf("%s",b);else{for(i=j=1;j-atoi(b);)i*=++j;printf("%d",i);}printf("%s",a+1);j>0&j<3&&puts(b);}

```

Try It Online!

Explanation:

```
i,j;
char*a,*b,*c,*d;

f(char*s)
{
    // a is the first '!' in s
    a=strchr(s,33);
    // b is the first character after the first whitespace before a, or s if there is no whitespace there
    for(b=a;b>s&!isspace(b[-1]);--b);
    // Print each character from s to b
    for(d=s;d-b;)putchar(*d++);
    // Null-terminate s at a
    *a=0;
    // If b is alphabetic
    if(*b&64)
        // While there's anything left of b, print b and shorten it by adding an earlier null terminator
        for(c=a;*b;*--c=0)
            printf("%s",b);
    else {
        // If b is not alphabetic, it's assumed to be a number.
        // i is the product of all j-s between 1, and b as a number
        for(i=j=1;j-atoi(b);)i*=++j;
        printf("%d",i);
    }
    // Print everything after the exclamation mark
    printf("%s",a+1);
    // Print the number twice if it's 1 or 2
    j>0&j<3&&puts(b);
}

```

ceilingcat's 226 byte version:

```
i,j;char*a,*b,*c,*d;f(char*s){for(b=a=index(s,33);b>s&!isspace(b[-1]);--b);for(d=s;*a=d-b;)putchar(*d++);if(*b&64)for(c=a;*b;*--c=0)printf(b);else{for(i=j=1;j-atoi(b);)i*=++j;printf("%d",i);}printf("%s",a+1);j>0&j<3&&puts(b);}

```

Try It Online

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


title: Help Me Type on My New Keyboard

text:
# Question
Title: Help Me Type on My New Keyboard
## Overview

As most of y'all who visit chat know, I am Russian by ethnicity<sup>\[citation not needed\]</sup>. Recently, I switched from a keyboard that maps the letters 1-to-1 (mnemonic) to Windows' default mnemonic keyboard. Here are the letter mappings:

```
"`" -> "ъ"
"q" -> "я"
"w" -> "ш"
"e" -> "е"
"r" -> "р"
"t" -> "т"
"u" -> "у"
"i" -> "и"
"o" -> "о"
"p" -> "п"
"a" -> "а"
"d" -> "д"
"f" -> "ф"
"g" -> "г"
"h" -> "х"
"k" -> "к"
"l" -> "л"
"'" -> "ь"
"z" -> "з"
"x" -> "ж"
"v" -> "в"
"b" -> "б"
"n" -> "н"
"m" -> "м"

```

You may have notcied that s, c, y, and j are missing. This keyboard, unlike the first one I used, has several combining keys (the aforementioned ones) These keys, while also having their own letters mapped to them, can be combined with other keys in sequence to write even more letters. The combinations for those keys are as follows:

```
"sc" -> "щ"
"ch" -> "ч"
"ya" -> "я"
"ye" -> "э"
"yo" -> "ё"
"yu" -> "ю"
"ja" -> "я"
"je" -> "э"
"jo" -> "ё"
"ju" -> "ю"

```

Note that there are 3 ways to write `я`: `q`, `ya`, and `ja`.

To type the single letters mapped to them, either press that key and then press space, or type an unrecognised key combination. Here are the single letter mappings for those keys:

```
"s" -> "с"
"c" -> "ц"
"y" -> "ы"
"j" -> "й"

```

For example, if I type in `c`  (note the space), it will give me `ц`, while typing in `cy` gives me `цы`. Typing in `yosc` is `ёщ`, and `yq` is `ыя`.

## The task

Your input will be given as all lowercase Russian + ASCII space, and you task is to convert that to a sequence of letters in the US keyboard I'd have to type.

## Testcases

```
"один" (one) -> "odin"
"стапятидесятитрёхтысячный" (one hundered fifty three thousandth) ->  "stapqtidesqtitryohtysqchnyj" or "stapyatidesyatitryohtysjachnyj" or any variation on the typing of "я" or "ё"
"код гольф" (code golf) -> "kod gol'f"
"иван рубит дрова вова топит печь" (Ivan is splitting wood, Vova is stoking the stove; a common mnemonic for the six noun cases) -> "ivan rubit drova vova topit pech'"
"разъяренный чтец эгоистично бьёт пятью жердями шустрого фехтовальщика" (An enraged narrator selfishly beats with five poles a nimble fencer; a sentence that uses all 33 Russian letters) -> "raz`yarennyj chtec  jegoistichno b'yot pqt'yu xerdyami wustrogo fehtoval'scika" (note the double space after "chtec". I used a mixture of "q" and "ya" for "я" here)

```

## Scoring

As this is , shortest answer in bytes wins.

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

```
s=>s.replace(/\S/g,c=>"rs tufhc chwsc`y 'yeyuq_yoabvgdexzij klmnop".match(/[scyj]?./g)[c.charCodeAt()%34])

```

Try it online!

# Answer
> 5 votes
# Retina 0.8.2, 159 bytes

```
щ
sc
ч
ch
ё
yo
ю
yu
э
je
ю
ju
T`сцыы`scyj`с[^ scyjц]|ц[^ scyjх]|[йы][^ scyjаеоу]
[сцыы]
$&
T`а-цшъ-ья`abvg\dexzi-pr-uf\hc\w\`y'q

```

Try it online! Link includes test cases. Explanation:

```
щ
sc
ч
ch
ё
yo
ю
yu
э
je
ю
ju

```

Translate the digraphs.

```
T`сцыы`scyj`с[^ scyjц]|ц[^ scyjх]|[йы][^ scyjаеоу]

```

Transliterate any unrecognised pairs starting with `s`, `c`, `y` or `j`.

```
[сцыы]
$&

```

Insert spaces after any other letter that maps to `s`, `c`, `y` or `j`.

```
T`а-цшъ-ья`abvg\dexzi-pr-uf\hc\w\`y'q

```

Transliterate the rest of the Russian letters.

# Answer
> 2 votes
# Python, 125 bytes

```
lambda s:re.sub('\S',lambda c:re.findall("[scyj]?.","rs tufhc chwsc`y 'yeyuq_yoabvgdexzij klmnop")[ord(c[0])%34],s)
import re

```

Attempt This Online!

Port of Arnauld's JS answer.

---
Tags: code-golf, natural-language, keyboard
---


title: Non-Hamming numbers

text:
# Question
Title: Non-Hamming numbers
Hamming number (also known as regular number) is a number that evenly divides powers of 60. We already have a task to do something with it. This time we are going to do the opposite.

I define non-Hamming number as in: \\$n\\$ is non-Hamming number if and only if it satisfies following two conditions:

* \\$n\\$ is positive integer, and
* \\$n\\$ does not divide powers of 60 evenly; i.e. \\$60^m\mod n\neq0\\$ for all positive integer \\$m\\$.

Make a program, a function, or a subroutine that does one of these:

1. takes no input to print/return/generate a list of non-Hamming numbers infinitely, or
2. takes a positive integer \\$n\\$ as input to print/return/generate \\$n\\$th non-Hamming number (can be either 0-indexed or 1-indexed), or
3. takes a positive integer \\$n\\$ as input to print/return/generate a list of first \\$n\\$ non-Hamming numbers.

4. ~~takes a positive integer \\$n\\$ to print/return/generate non-Hamming number until \\$n\\$ (suggested by @Wasif, can be inclusive or not; i.e. non-Hamming numbers that are either \\$\<n\\$ or \\$\leq n\\$).~~ abolished by @rak1507.

# Example

This example shows how program/function/subroutine that does 3rd task should work:

* Input: `5`
* Output: `7, 11, 13, 14, 17`

# Rules

* I/O method is done by your desired format.
* If you are answering one of 2nd or 3rd task, you can assume that input is a non-negative integer.
* No external resources.
* Standard loopholes apply.
* If your program/function/subroutine fails to output huge non-Hamming numbers because of overflow (or similar boundary) but is theotically valid, it is acceptable.
* Shortest code in bytes wins. However, if someone have won entire of this post, you can still try to win among languages and tasks.

# P.S.

It's actually A279622.

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

*-1 thanks to ovs.*

```
∞ʒÓg3›

```

Try it online!

```
∞ʒÓg3›  # full program
 ʒ      # all elements of...
∞       # [1, 2, 3, ...]...
 ʒ      # where...
   g    # the length of...
  Ó     # the exponents of the prime factorization of...
        # (implicit) current element in list...
     ›  # is greater than...
    3   # literal
        # implicit output

```

# Answer
> 6 votes
# Jelly, 6 bytes

```
30*%µƇ

```

Try it online!

Takes \\$n\\$ and outputs all non-Hamming numbers \\$\le n\\$, as allowed by the OP.

Thanks to Delfad0r for suggesting this method in chat!

---

# Jelly, 7 bytes

```
ÆfṀ>5Ʋ#

```

Try it online!

-2 bytes thanks to xnor, who noted that \\$k\\$ is a non-Hamming number if it's ~~smallest~~ largest (thanks ovs, for catching that) prime factor is greater than \\$5\\$!

Returns the first \\$n\\$ non-Hamming numbers

---

## How they work

```
30*%µƇ - Main link. Takes n on the left
    µƇ - Filter the range i ∈ [1, 2, ..., n] on the following:
30*    -   Raise 30 to the power i
   %   -   That is not divisible by i?

ÆfṂ>5Ʋ# - Main link. Takes no arguments
     Ʋ  - Group the previous 4 links into a monad f(k):
Æf      -   Prime factors of k
  Ṁ     -   Maximum
   >5   -   Greater than 5?
      # - Read n from STDIN and count up k = 1, 2, 3, ... until n such k return True under f(k)

```

# Answer
> 6 votes
# JavaScript (V8), 61 bytes

A full program that prints the sequence forever.

```
for(k=6;x=++k;)[2,3,5].some(g=d=>x%d?x<2:g(d,x/=d))||print(k)

```

Try it online!

### Commented

```
for(               // infinite loop:
  k = 6;           //   start with k = 6
  x = ++k;         //   increment k and copy it to x
)                  //
  [2, 3, 5]        // list of primes less than 7
  .some(g = d =>   // for each of them:
    x % d ?        //   if d is not a divisor of x:
      x < 2        //     return true if x = 1
    :              //   else:
      g(d, x /= d) //     divide x by d and do a recursive call
  )                // end of some()
  ||               // if true, k is 5-smooth (aka regular, aka Hamming number)
  print(k)         // otherwise, print it

```

---

# JavaScript (ES6), 65 bytes

Returns the \\$n\\$th term of the sequence, 1-indexed.

```
f=(n,k=6)=>n?f(n-[2,3,5].every(g=d=>x%d?x>1:g(d,x/=d),x=++k),k):k

```

Try it online!

# Answer
> 3 votes
# , 25 bytes

```
(>:[]echo~5<{:@q:)@]^:_&7

```

Try it online!

YAIOXI

> Yet Another Implementation Of xnor's Idea.

* `^:_&7` Loop forever, starting with 7:
* `]echo~...` Echo the current count if...
* `5<{:@q:` 5 is less than the last `{:` prime factor `q:` (they're listed in ascending order). This step is merely a side effect.
* `>:[` Return the increment of the counter and keep looping.

# Answer
> 3 votes
# Vyxal, 8 5 bytes

**Huge thanks to @Lyxal for -3 bytes using a filter lambda, so I could beat all!**

```
'ǐG5>

```

Takes an integer input \\$n\\$, and outputs all non-hamming numbers \\$\le{n}\\$ (According to new rule)

**Explanation**

```
'         # Filter lambda
 ǐ        # Prime factors of each number
  G       # Maximum
   5>     # Greater than 5?
          # Implicitly output

```

Try it!

# Answer
> 2 votes
# Husk, 7 bytes

Uses xnor's idea.

```
foV>5pN

```

Try it online!

Outputs an infinite list.

```
foV>5pN
      N  From the infinite list of natural numbers,
f        keep the ones that satisfy the following predicate
  V      There exists
     p   a prime factors
   >5    that is greater than 5

```

# Answer
> 2 votes
# Factor \+ `lists.lazy math.primes.factors math.unicode`, 51 bytes

```
1 lfrom [ factors [ 5 > ] ∃ ] lfilter [ . ] leach

```

Try it online!

## Explanation:

It's a full program that prints non-Hamming numbers forever, using @xnor's tip about prime factors greater than 5.

* `1 lfrom` An infinite lazy list of the natural numbers.
* `[ factors [ 5 > ] ∃ ] lfilter` Select numbers with a prime factor greater than 5.  is shorthand for `any?` and this turns out to be 1 byte shorter than `supremum 5 >`.
* `[ . ] leach` Print every item in the list.

# Answer
> 2 votes
# Haskell, 25 bytes

```
[n|n<-[1..],mod(30^n)n>0]

```

Try it online!

The infinite list of non-Hamming numbers.

## How?

A positive integer \\$n\\$ is Hamming if and only if \\$n\\$ divides \\$30^n\\$.

# Answer
> 2 votes
# , ~~69~~ ~~70~~ ~~69~~ 67 bytes

```
while(T<-T+1)for(i in 1:T+6)if(sum(!i%%2:i)<2&!T%%i){show(T);break}

```

Try it online!

xnor's idea in base R.

*+1 thanks to @Dominic spotting an error and then -1 golfing `print` to `show`.*

# Answer
> 2 votes
# JavaScript (Browser), 31 bytes

```
for(k=1n;;)30n**++k%k&&alert(k)

```

Try it online!

# Answer
> 2 votes
# Ruby, 26 bytes

```
1.step{|x|30**x%x>0&&p(x)}

```

Try it online!

# Answer
> 1 votes
# Retina, 44 bytes

```
K`
"$+"{`$
_
)+`^((_+)(?=\2{1,4}$))*_$
$&_
_

```

Try it online! Outputs the `n`th number. No test suite because of the way the program uses history. Explanation:

```
K`

```

Delete the input, replacing it with unary 0.

```
"$+"{`
)`

```

Repeat the input number of times.

```
$
_

```

Increment the current value.

```
+`^((_+)(?=\2{1,4}$))*_$

```

While the current value is a product of powers of 2, 3, 4 or 5...

```
$&_

```

... increment it.

```
_

```

Convert the result to decimal.

To convert the script into one that outputs the first `n` numbers:

* Remove the `)` at the beginning of the 4th line
* Prefix `.*\`` to the last line.

# Answer
> 1 votes
# PowerShell Core, ~~137~~ 89 bytes

```
filter d{param($b)if($_%$b){$_}else{$_/$b|d $b}}1.."$args"|d 3|d 5|d 2|?{++$t;$_-1}|%{$t}

```

Try it online!

Thanks mazzy!

# Answer
> 1 votes
# Pyth, ~~14~~ 12 bytes

```
7W=hTI<5ePTT

```

Try it online!

Prints the infinite sequence.

```
7     # First print 7 separately.
W     # While
T     # Initialized to 10 by default
=hT   # Increment T by 1
PT    # Lists prime factors of T in increasing order.
>ePT5 # If the highest prime factor is greater than 5, then
T     # Print T

```

*-2 bytes thanks to kops*

# Answer
> 1 votes
# Japt, 9 bytes

Outputs the first `n` terms.

```
Èk d¨7}jU

```

Try it

```
Èk d¨7}jU     :Implicit input of integer U
È             :Function taking an integer as input
 k            :  Prime factors
   d          :  Any?
    ¨7        :    Greater than equal to 7
      }       :End function
       jU     :Get the first U integers that return true

```

# Answer
> 1 votes
# \+ gmp, ~~37~~ 51 bytes

*Edit: +14 bytes after the rules were changed to disallow outputting all non-Hamming numbers up to `n`: now outputs the infinite list*

```
n=gmp::as.bigz(1);repeat if(60^(n=n+1)%%n>0)show(n)

```

Try it online!

Outputs infinite list of non-Hamming numbers.

Uses arbitrary-precision calculations to simply check whether `n` divides the `n`th power of 60 (this is sufficient to be certain that it also can't divide any higher power of 60). We could have stopped at the `floor(log2(n))`th power of 60, but it would have made an annoyingly long program.

Of course, the mathematics itself is correct even without the `gmp` library to handle the actual abritrary-precision calculations... so we could have an even shorter version in base- if we don't mind going out-of-range for "huge" non-Hamming numbers:

---

# , ~~35~~ 44 bytes

*Edit: +9 bytes to comply with the changed rules*

```
repeat if(30^(log2(T<-T+1)%/%1)%%T>0)show(T)

```

Try it online!

Same approach as above, but goes out-of-range for "huge" non-Hamming numbers, defined as any number greater than 16383.

If we are somewhat more timid and define a "huge" to be any number greater than 12 (and accept that above this the program will output junk or crash), then we can have an even shorter ~~23-byte~~ 34-byte solution of just `repeat if(30^(T<-T+1)%%T>0)show(T)` Try it!.

# Answer
> 1 votes
# Stax, 7 bytes

```
üu§└ÿà♦

```

Run and debug it

~~TIL that `|M` returns infinity for empty lists~~. Found a method without `|M`.

# Answer
> 1 votes
# PowerShell Core, 56 bytes

inspired by Julian's answer (loop instead recursion)

```
1.."$args"|?{$a=$_;2,3,5|%{for(;!($a%$_)){$a/=$_}};$a-1}

```

Try it online!

# Answer
> 1 votes
# Charcoal, 23 bytes

```
≔⁰θＦＮ«≦⊕θＷ¬﹪Ｘ³⁰θθ≦⊕θ⟦Ｉθ

```

Try it online! Link is to verbose version of code. Outputs the first `n` numbers. Explanation: Uses @Delfad0r's approach.

```
≔⁰θ

```

Start at zero.

```
ＦＮ«

```

Repeat `n` times.

```
≦⊕θ

```

Increment the accumulator.

```
Ｗ¬﹪Ｘ³⁰θθ

```

While it divides its power of `30`...

```
≦⊕θ

```

... increment it.

```
⟦Ｉθ

```

Output the found value on its own line.

# Answer
> 1 votes
# Zsh, ~~44~~ 43 bytes

```
seq inf|factor|grep ' 7
 .[^ ]'|cut -d: -f1

```

Try it online!

-1 thanks to @tail spark rabbit ear

* `seq inf`: count up infinitely
* `factor`ise each number in the form `52: 2 2 13`
* `grep`: keep only lines matching the `r`egular `e`xpression  `7\n .[^ ]`
    + The newline acts like "or"
    + Essentially matches either a factor that starts with 7, or a factor with more than one digit. This will match any prime \> 5, so as long as there's at least one matching factor, the whole line will be printed
* `cut -d: -f1`: take the first field (where fields are separated by colons) of each line. This gets only the number itself

# Zsh, 45 bytes

```
for ((;++a;)){>`factor $a`;><7->&&<<<$a;rm *}

```

Try it online!

* `for ((;++a;)){}`: for each integer up to infinity:
    + `factor $a`: factorise the number in the form `52: 2 2 13`
    + `>```: create the files according to the words in the factorisation (e.g. `52:`, `2` (duplicates are just ignored), and `13`)
    + `<7->`: look for a file which is a number greater than or equal to 7
        - If the number has a prime factor greater than 5, it is not a Hamming number and will be matched
        - The number itself always has a trailing colon, so it can never be matched by this
    + `>`: and try to output to it
    + `&&`: if that works, then:
        - `<<<$a`: print the number
    + `rm *`: remove all the files (so we're fresh for the next iteration)

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

It was easier to generate many (seven) times as many numbers as needed, then trim the excess:

```
h(n)=select(x->factor(x)[,1][-1..-1][1]>5,vector(7*n,i,i+1))[1..n]

```

Try it online!

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

Generates an infinite sequence of non-Hamming numbers

```
i=7;while(1,if(factor(i)[,1][-1..-1][1]>5,print(i));i++)

```

Try it online!

# Answer
> 0 votes
# PowerShell, 235 bytes

```
param($k)$s='$f;$n/=$f';function F($n){$m=[math]::sqrt($n);$f=2;while(!($n%$f)){iex $s};$f=3;while($f-le$m-and$n-ge$m){while(!($n%$f)){iex $s};$f+=2};$n};$a=@();$a=@();$g=1;while($a.length-lt$k){$j=(F($g)[-1])-gt5;if($j){$a+=$g}$g++}$a

```

Try it online!

# Answer
> 0 votes
# Julia 0.4, 52 bytes

```
x=1;while x>0 keys(factor(x+=1))⊆1:5||print(-x)end

```

Try it online!

I'm using Julia 0.4 for `factor`, which was then moved in the package `Primes.jl`

also works with recent versions of Julia + Primes.jl

`factor(x)` returns a `Dict` with the keys been the prime factors and the values the exponent of each factor

in more recent version with `Primes.jl`, `factor(Set,x)` can be called instead for the same result

# Answer
> 0 votes
# AWK, 92 bytes

Previously 93 bytes that outputs intfinite list.

Given a line of an integer \\$n\\$, outputs first \\$n\\$ nunbers.

Pretty naïve.

```
{for(k=j=7;$0--;k=++j){for(;k%2-1;k/=2);for(;!(k%3);k/=3);for(;!(k%5);k/=5);if(k>1)print j}}

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~38~~ ~~37~~ 35 bytes

```
x=1
while[30**x%x>0==print(x)]:x+=1

```

Try it online!

Where'd the python answers go???

Port of G.B.'s answer.

-2 thx to @Steffan

# Answer
> 0 votes
# Pyt, 16 bytes

```
7`Đϼ6<Π?ŕ:ŕĐƥ;⁺ł

```

Try it online!

Prints the list of Hamming numbers without end.

```
7                     push 7 (the first Hamming number)
 `             ł      do... while the top of stack is truthy
  Đ                   Đuplicate
   ϼ                  get unique ϼrime factors
    6<Π?              are they all less than 6?
        ŕ             if so, ŕemove top of stack
         :ŕĐƥ         otherwise; ŕemove top of stack, Đuplicate top of stack,
                      and ƥrint top of stack
             ;⁺       either way, increment top of stack

```

---
Tags: code-golf, sequence, number-theory
---


# Question
Title: Convert superscript numbers to normal numbers
# Introduction

My gnome friends are writing a programming language and have asked for my help. Due to their size, the gnomes can only handle small superscript numbers instead of big numbers. However, the language they're writing the interpreter in only accepts big numbers!

# Your Challenge

Given an input of a superscript number (a series of characters that can be any of ⁰¹²³⁴⁵⁶⁷⁸⁹), convert it to normal ASCII numbers and print the result. This is code golf, so shortest answer wins!

## Test Cases

```
¹ -> 1
⁵ -> 5
¹²³ -> 123
⁶⁵⁵³⁵ -> 65535
⁰¹²³ -> 123

```

# Answer
> 16 votes
# JavaScript, 20 bytes

```
s=>s.normalize`NFKD`

```

Try it online!

# Answer
> 14 votes
# JavaScript (ES6), 43 bytes

Edit: +1 to support `0123` -\> `123` ...

```
s=>+s.replace(/./g,c=>c.charCodeAt()%92%12)

```

Try it online!

### Conversion table

```
 char. | code | mod 92 | mod 12
-------+------+--------+--------
  '⁰'  | 8304 |   24   |   0
  '¹'  |  185 |    1   |   1
  '²'  |  178 |   86   |   2
  '³'  |  179 |   87   |   3
  '⁴'  | 8308 |   28   |   4
  '⁵'  | 8309 |   29   |   5
  '⁶'  | 8310 |   30   |   6
  '⁷'  | 8311 |   31   |   7
  '⁸'  | 8312 |   32   |   8
  '⁹'  | 8313 |   33   |   9

```

# Answer
> 10 votes
# Hexagony, side length 4, 37 bytes

```
92},/%=\_@=..}{<.{\<.>".2//{%.1!}>'/_

```

## Unwrapped code:

```
    9 2 } ,
   / % = \ _
  @ = . . } {
 < . { \ < . >
  " . 2 / / {
   % . 1 ! }
    > ' / _

```

Try it on hexagony.net

This is my first post on Code Golf, and first time using Hexagony. It's as painful as the name implies, but so satisfying to get a result! I ended up with more mirrors than I expected, but I'm pretty proud of what I achieved.

Credit to the previous users who worked out the modulo trick. My hexagon would have been a lot bigger without `%92%12`!

# Answer
> 8 votes
# , ~~45~~ ~~53~~ 51 bytes

*Edit +8 bytes to comply with the updated rules (`0123` -\> `123`), but then -2 bytes thanks to pajonk*

```
function(s)el(chartr("⁰¹²³⁴-⁹","0-9",s):1)

```

Try it online!

---

# , ~~53~~ ~~51~~ 57 bytes / ~~25 bytes with IO as character codes~~

*Edit: -4 bytes thanks to pajonk, but then +6 bytes (again thanks to pajonk) to comply with the updated rules*

```
function(s,x=utf8ToInt(s))el(intToUtf8(x%%64-8*!x-185):1)

```

Try it online!

Function without multi-byte character codes, but sadly the verbose `utf8ToInt` and `intToUtf8` function names make it quite long if we want to accept input directly as a string...

The new rule that `⁰¹²³` should output `123` invalidates the second version with IO as character codes. It could be fixed for +17 bytes, but it's shorter to completely change approach (below), porting Arnauld's charcode-to-digit method.

---

# , 40 bytes with IO as character codes

```
function(c)c%%92%%12%*%10^rev(seq(!c)-1)

```

Try it online!

# Answer
> 8 votes
# Jelly, 7 bytes

```
O%12&ƊḌ

```

Try it online!

```
O         Get ordinal values
 %12&Ɗ    Apply x ↦ x%12&x
      Ḍ   Digits to number

```

I found the `x%12&x` formula by computer search. If I/O were super duper lenient, I guess `%12&` would be a valid 4-byte answer.

# Answer
> 7 votes
# Python 3.8 (pre-release), ~~46~~ 50 bytes

-1 thanks to ovs!

```
lambda x:int(x.translate('%7d   45678923'%10*999))

```

Try it online!

Helper program to generate this: helper

# Answer
> 7 votes
# Charcoal, 2 bytes

```
ＩＶ

```

Try it online! Explanation:

```
 Ｖ  Eval as a Charcoal integer literal
Ｉ   Cast to string
    Implicitly print

```

# Answer
> 6 votes
# Raku, ~~14~~ ~~10~~ ~~11~~ 8 bytes

+1 and +4 to remove leading 0's.

-3 bytes thanks to Moonchild!

```
+~*.NFKD

```

Try it online!

---

# Raku `-p`, ~~15~~ ~~19~~ bytes

-1 byte and -1 flag thanks to Jo King!

```
$_=+S:g{.}=$/.EVAL

```

Try it online!

Raku uses superscript digits as exponents, but single digits on their own evaluate to their numeric value.

# Answer
> 6 votes
# C (gcc), ~~83~~ \\$\cdots\\$ ~~60~~ 46 bytes

```
n;f(int*s){for(n=0;*s;)n+=9*n+*s++%92%12;n=n;}

```

Try it online!

Inputs a pointer to a `wchar_t` string of superscript numbers.
Returns the normal number.

Discovered the `n % 92 % 12` formula independently.

# Answer
> 5 votes
# Vyxal, 7 bytes

```
C:12%⋏ṅ

```

Try it Online!

Port of Lynn's answer thanks to steffan.

# Answer
> 4 votes
# Python 3, 53 bytes

```
from unicodedata import*
lambda s:normalize("NFKC",s)

```

Try it online!

# Answer
> 4 votes
# JavaScript, ~~65~~ ~~62~~ ~~61~~ 60 bytes

```
s=>s.replace(/./g,x=>-~'¹²³⁴⁵⁶⁷⁸⁹'.search(x))

```

*Saved 3 bytes thanks to Neil.*

*Saved 1 byte thanks to Shaggy.*

*Saved 1 byte thanks to Arnauld.*

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~11~~ 8 bytes

```
Ç92%12%J

```

-3 bytes porting *@Arnauld*'s JavaScript method (thanks *@Neil* for the heads up).

Add a trailing `ï` (+1 byte) if you want to remove leading 0s..

Try it online or verify all test cases.

**Explanation:**

```
Ç         # Convert the (implicit) input to a list of its codepoint-integers
          #  e.g. "⁰¹²³⁴⁵⁶⁷⁸⁹" → [8304,185,178,179,8308,8309,8310,8311,8312,8313]
 92%      # Modulo-92
          #  → [24,1,86,87,28,29,30,31,32,33]
    12%   # Modulo-12
          #  → [0,1,2,3,4,5,6,7,8,9]
       J  # Join the list together
          #  → 0123456789
        ï # (Optionally) Remove leading 0s by casting to an integer
          #  → 123456789
          # (after which the result is output implicitly)

```

# Answer
> 4 votes
# Pip, ~~9~~ 12 bytes

*+3 bytes to handle more stringent rules*

```
+:A_%E#A_MJa

```

Replit! (Note: the Unicode input seems not to play well with Pip's interactive mode, or maybe it's a Replit issue. For best results, Ctrl-C out of the default interactive mode and enter `./pip.py -e A_%E#A_Ma ⁶⁵⁵³⁵` at the command prompt.)

Or, here's a 14-byte equivalent in Pip Classic: Try it online!

### Explanation

After some trial and error, I found a really nice property of these numbers' codepoints:

* ¹, ², and ³ have codepoints 185, 178, and 179. Mod 8 (or 4), these become 1, 2, and 3.
* The other superscript numbers have codepoints equal to the corresponding digit plus 8304. Mod 16 (or 12, or many other options), these become their respective digits.

So all we need to do is take the codepoint of each digit mod 8 if it's 3 digits and mod 16 if it's 4 digits...

```
          a  First command-line argument
        MJ   Map this function to each character, joining the results together:
  A_          Codepoint of the character
    %         Mod
     E        2 to the power of
      #       Length of
       A_     Codepoint of the character
+:           Treat the resulting string as a number (removing leading 0s)

```

# Answer
> 3 votes
# APOL, ~~46~~ 27 bytes

`I(j(ƒ(i %(%(↶(∋) 92) 12))))`

Uses Arnauld's 92/12 solution.

*Note: 3 bytes can be saved by removing the `I` instruction, however this version is not case 5-compliant.*

## Explanation

```
I(               Cast to integer
  j(             Join string (default is no seperator)
    ƒ(           List-builder for loop (returns a list of every returned value of the passed instruction)
      i          Get input
      %(         Modulo 2 (12)
        %(       Modulo 1 (92)
          ↶(     Get codepoint
            ∋    The current item in the for loop
          )
        92
        )
      12
      )
    )
  )
)
Implicit print

```

Old code (uses lookup table instead):

`v(0 []);f(i a(0 t(⌕("⁰¹²³⁴⁵⁶⁷⁸⁹" ∋))));I(j(⁰))`

# Answer
> 3 votes
# APL (dzaima/APL), ~~16~~ 15 bytes

−1 byte thanks to rak1509

Anonymous tacit prefix function. Requires 0-based indexing.

```
10⊥'⁰¹²³⁴⁵⁶⁷⁸'⍳

```

Try it online!

`10⊥` evaluate in base 10

`'⁰¹²³⁴⁵⁶⁷⁸'⍳` the respective *i*ndices of the argument characters in this string (any character not in the string gets the first index beyond the end, i.e. 9)

# Answer
> 3 votes
# Retina 0.8.2, 19 bytes

```
T`⁰-⁹_¹²³`dd

```

Try it online! Link includes test cases. Explanation: `d` is a shorthand for `0123456789`. As `⁰-⁹` expands to `⁰ⁱ⁲⁳⁴⁵⁶⁷⁸⁹`, and assuming none of `ⁱ⁲⁳` will appear in the input, those supserscript digits will get mapped to ASCII digits, while the `_¹²³` gets mapped to `0123` (the remaining digits in `d` get ignored). `_` is actually a placeholder on the LHS and does nothing except to skip `0` on the RHS (on the RHS it causes the character on the LHS to be deleted).

# Answer
> 3 votes
# Japt `-m`, 7 bytes

Use Arnauld's formula so be sure to upvote him.

```
c %#\%C

```

Try it

# Answer
> 3 votes
# C (gcc) with `-funsigned-char`, 63 bytes

This version takes a string of UTF-8 characters. If the leading byte is `E2` then I mask the third byte with 15; otherwise I mask the second byte with 3. It's useful that `B9` (the trailing byte of ¹) is odd!

```
i;f(char*s){for(i=0;*s;s++)i=(*s++-226?*s&3:*++s&15)+i*10;i=i;}

```

Try it online!

# Answer
> 3 votes
# Nibbles, ~~6.5~~ 6 bytes (12 nibbles)

```
`@~.$`&%$12

```

A port of Lynn's Jelly answer comes out ~~half-a-byte~~ a byte shorter in Nibbles.

```
   .            # Map over
    $           # the input string:
     `&         #  bitwise-and of
        $       #  each element
       %        #  modulo
         12     #  twelve
                #  and itself
`@~             # Finally, convert from base-10 digits

```

# Answer
> 2 votes
# Python 3, ~~63~~ 62 bytes

`lambda n: int("".join([str("⁰¹²³⁴⁵⁶⁷⁸⁹".index(c))for c in n]))`

Thanks @Fmbalbuena!

# Answer
> 2 votes
# Husk, ~~10~~ 9 bytes

```
dm(Sn%12c

```

Try it online!

Port of ~~Arnauld's Javascript answer~~ Lynn's Jelly answer.

The 'charcode-to-charcode' modulo-except-when-it's-185 approach is discouragingly long in Husk, but Lynn's 'charcode-to-digit' modulo-AND approach is very well-suited to Husk's `d` (digits to decimal number) function.

# Answer
> 2 votes
# PHP, 35 bytes

```
<?=+iconv('','US//TRANSLIT',$argn);

```

Try it online!

Some nice PHP builtin

# Answer
> 2 votes
# Nim, 63 bytes

```
import strutils,unidecode
stdin.readAll.unidecode.parseInt.echo

```

Try it online!

If removing leading zeros is not required:

## Nim, 45 bytes

```
import unidecode
stdin.readAll.unidecode.echo

```

Try it online!

# Answer
> 2 votes
# Turing Machine Code, 99 bytes

```
* ⁰ 0 r *
* ¹ 1 r *
* ² 2 r *
* ³ 3 r *
* ⁴ 4 r *
* ⁵ 5 r *
* ⁶ 6 r *
* ⁷ 7 r *
* ⁸ 8 r *
* ⁹ 9 r *

```

Try it online!

# Answer
> 2 votes
# Ruby, 40 bytes

```
->s{s.tr("⁰-⁹¹²³","0-9123").to_i}

```

Try it online!

# Answer
> 2 votes
# Excel, ~~72~~ 63 bytes

Saved 9 bytes thanks to JvdV

```
=--CONCAT(MOD(MOD(UNICODE(MID(A1,SEQUENCE(LEN(A1)),1)),92),12))

```

Not very exciting, really. It's the Excel version of Arnauld's answer.

* `MID(A1,SEQUENCE(LEN(A1)),1)` pulls each character from the input one at a time.
* `MOD(MOD(UNICODE(MID(~)),92),12))` converts that character to unicode and then takes the mod 92 and mod 12.
* `--CONCAT(MOD(~))` combines all those code values into a string and then coerces that string into a number by making it negative twice (so back to positive again) which also will drop any leading zeros.

# Answer
> 2 votes
# Factor, 13 bytes

```
[ nfkd dec> ]

```

`nfkd` postdates the build TIO uses, so have a screenshot:

# Answer
> 2 votes
# Lua, 94 bytes

```
r=0 t={[185]=1,[178]=2,[179]=3}for _,c in utf8.codes(...)do r=r*10+(t[c]or c-8304)end print(r)

```

Try it online!

# Answer
> 2 votes
# Prolog (SWI), 40 bytes

```
A+O:-unicode_nfkd(A,C),atom_number(C,O).

```

Try it online!

Builtins

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

```
_O%12%92C

```

Try it online!

```
_O%12%92C
        C # Convert to charcodes
     %92  # Mod 92
  %12     # Mod 12
 O        # Join the list of digits
_         # Cast to number to get rid of leading 0s

```

# Answer
> 2 votes
# Julia 1.0, ~~78~~ 71 bytes

```
~x=parse(Int,join(Dict(["⁰¹²³"...;'⁴':'⁹'].=>0:9)[i] for i=x))

```

Try it online!

* -3 bytes thanks to MarcMush: use range directly, no need to vectorize with `[0:9;]`
* -4 bytes thanks to MarcMush: use array comprehension instead of an anonymous function, removing one occurrence of the splat operator `...`

# Answer
> 1 votes
# Java, 67 bytes

```
s->java.text.Normalizer.normalize(s,java.text.Normalizer.Form.NFKD)

```

Try it online!

# Answer
> 1 votes
# Haskell, 75 bytes

```
f=mapM(\x->[putStr$show k|k<-[0..],x=="⁰¹²³⁴⁵⁶⁷⁸⁹"!!k]!!0)

```

Try it online!

# Answer
> 1 votes
# Pyt, 10 bytes

```
ą2Ĩ4+1ᴇ%ǰƖ

```

Try it online!

```
ą                 implicit input; convert to ąrray of characters
 2Ĩ               due to oversight in implementing arbitrary-base integer
                  Ĩnterpretation, this returns the position for each character
                  in the list of potential base characters (which is a contiguous
                  stretch)
   4+             add 4 to each
     1ᴇ%          modulo 10
        ǰ         ǰoin without delimiters
         Ɩ        cast to Ɩnteger; implicit print

```

# Answer
> 1 votes
# Thunno, \\$ 11 \log\_{256}(96) \approx \\$ 9.05 bytes

```
OD12%z.A&ZD

```

Attempt This Online!

Port of Lynn's Jelly answer.

#### Explanation

```
OD12%z.A&ZD  # Implicit input
OD           # Get ordinals and duplicate
  12%        # Mod 12 of each
     z.      # Zip and apply to each pair:
       A&    #  Bitwise AND
         ZD  # Convert to integer
             # Implicit output

```

# Answer
> 1 votes
# Python, 53 bytes

```
lambda s:int(''.join(str(x%12&x)for x in map(ord,s)))

```

Attempt This Online!

Port of Lynn's Jelly answer. Not the best Python answer (by 3 bytes), but uses a different method to the others.

# Answer
> -2 votes
# Python 3, 89 bytes

```
lambda a:int(a.translate(dict(zip(map(ord,"⁰¹²³⁴⁵⁶⁷⁸⁹"),"0123456789"))))

```

Try it online!

-77 Bytes thanks to @grandBagel

-31 Bytes thanks to @ovs

---
Tags: code-golf, unicode, conversion
---


title: Count Up, Replace, Repeat!

text:
# Question
Title: Count Up, Replace, Repeat!
### Definition

Define the **n**th array of the CURR sequence as follows.

1. Begin with the singleton array **A = \[n\]**.
2. For each integer **k** in **A**, replace the entry **k** with **k** natural numbers, counting up from **1** to **k**.
3. Repeat the previous step **n - 1** more times.

For example, if **n = 3**, we start with the array **\[3\]**.

We replace **3** with **1, 2, 3**, yielding **\[1, 2, 3\]**.

We now replace **1**, **2**, and **3** with **1**; **1, 2** and **1, 2, 3** (resp.), yielding **\[1, 1, 2, 1, 2, 3\]**.

Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding **\[1, 1, 1, 2, 1, 1, 2, 1, 2, 3\]**. This is the third CURR array.

### Task

Write a program of a function that, given a strictly positive integer **n** as input, computes the **n**th CURR array.

The output has to be a *flat* list of some kind (and array returned from a function, a string representation of your language's array syntax, whitespace-separated, etc.).

This is . May the shortest code in bytes win!

### Test cases

```
 1 -> [1]
 2 -> [1, 1, 2]
 3 -> [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]
 4 -> [1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4]
 5 -> [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
 6 -> [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]

```

# Answer
## Jelly, 3 bytes

```
R¡F

```

Try it online

## Explanation

```
R¡F    Argument n

R      Yield range [1..n]
 ¡     Repeat n times
  F    Flatten the result

```
> 25 votes

# Answer
## Python, 50 bytes

```
lambda i:eval("[i "+"for i in range(1,i+1)"*i+"]")

```

Scope abuse! For example, for `i=3`, the string to be evaluated expands to.

```
[i for i in range(1,i+1)for i in range(1,i+1)for i in range(1,i+1)]

```

Somehow, despite using the function input variable `i` for everything, Python distinguishes each iteration index as belonging to a separate scope as if the expression were

```
[l for j in range(1,i+1)for k in range(1,j+1)for l in range(1,k+1)]

```

with `i` the input to the function.
> 17 votes

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

```
DFL

```

**Explained**

```
D     # duplicate input
 F    # input times do
  L   # range(1,N)

```

Try it online

Saved 3 bytes thanks to @Adnan
> 12 votes

# Answer
## Retina, 33 bytes

```
$
$.`$*0
+%(M!&`1.*(?=0)|^.+
O`.+

```

Input and output in unary.

Try it online!

Even though I didn't use the closed form for the related challenge, adapting this answer was surprisingly tricky.
> 6 votes

# Answer
## Python 2, 82 bytes

```
lambda n:[1+bin(i)[::-1].find('1')for i in range(1<<2*n-1)if bin(i).count('1')==n]

```

This isn't the shortest solution, but it illustrates an interesting method:

* Write down the first `2^(2*n-1)` numbers in binary
* Keep those with exactly `n` ones
* For each number, count the number of trailing zeroes, and add 1.
> 6 votes

# Answer
## Actually, 9 bytes

```
;#@`♂RΣ`n

```

Try it online!

Explanation:

```
;#@`♂RΣ`n
;#@        dupe n, make a singleton list, swap with n
   `♂RΣ`n  call the following function n times:
    ♂R       range(1, k+1) for k in list
      Σ      concatenate the ranges

```

Thanks to Leaky Nun for a byte, and inspiration for another 2 bytes.
> 4 votes

# Answer
## C#, 128 Bytes

```
List<int>j(int n){var l=new List<int>(){n};for(;n>0;n--)l=l.Select(p=>Enumerable.Range(1,p)).SelectMany(m=>m).ToList();return l;

```
> 4 votes

# Answer
# APL, 11 bytes

```
{∊⍳¨∘∊⍣⍵+⍵}

```

Test:

```
      {∊⍳¨∘∊⍣⍵+⍵} 3
1 1 1 2 1 1 2 1 2 3

```

Explanation:

* `+⍵`: starting with ,
* `⍣⍵`: do the following  times:
    + `⍳¨∘∊`: flatten the input, and then generate a list \[1..N\] for each N in the input
* : flatten the result of that
> 4 votes

# Answer
# J, 18 bytes

```
([:;<@(1+i.)"0)^:]

```

Straight-forward approach based on the process described in the challenge.

## Usage

```
   f =: ([:;<@(1+i.)"0)^:]
   f 1
1
   f 2
1 1 2
   f 3
1 1 1 2 1 1 2 1 2 3
   f 4
1 1 1 1 2 1 1 1 2 1 1 2 1 2 3 1 1 1 2 1 1 2 1 2 3 1 1 2 1 2 3 1 2 3 4

```

## Explanation

```
([:;<@(1+i.)"0)^:]  Input: n
                 ]  Identity function, gets the value n
(     ...     )^:   Repeat the following n times with an initial value [n]
      (    )"0        Means rank 0, or to operate on each atom in the list
         i.           Create a range from 0 to that value, exclusive
       1+             Add 1 to each to make the range from 1 to that value
    <@                Box the value
 [:;                  Combine the boxes and unbox them to make a list and return
                    Return the final result after n iterations

```
> 2 votes

# Answer
## CJam, 14 bytes

```
{_a\{:,:~:)}*}

```

Test it here.

### Explanation

```
_a   e# Duplicate N and wrap it in an array.
\    e# Swap with other copy of N.
{    e# Do this N times...
  :, e#   Turn each x into [0 1 ... x-1].
  :~ e#   Unwrap each of those arrays.
  :) e#   Increment each element.
}*

```
> 2 votes

# Answer
## Haskell, 33 bytes

```
f n=iterate(>>= \a->[1..a])[n]!!n

```

Thanks to nimi for saving a byte.

A pointfree version is longer (35 bytes):

```
(!!)=<<iterate(>>= \a->[1..a]).pure

```
> 2 votes

# Answer
## Mathematica, ~~27~~ 26 bytes

*1 byte saved with some inspiration from Essari's answer.*

```
Flatten@Nest[Range,{#},#]&

```

Fairly straightforward: for input `x` we start with `{x}` and then apply the `Range` to it `x` times (`Range` is `Listable` which means that it automatically applies to the integers inside arbitrarily nested lists). At the end `Flatten` the result.
> 2 votes

# Answer
# Python 3, ~~75~~ 74 bytes

```
def f(k):N=[k];exec('A=N;N=[]\nfor i in A:N+=range(1,i+1)\n'*k+'print(N)')

```

This is just a straightforward translation of the problem description to code.

Edit: Saved one byte thanks to @Dennis.
> 2 votes

# Answer
## JavaScript (Firefox 30-57), ~~63~~ 60 bytes

```
f=n=>eval(`[${`for(n of Array(n+1).keys())`.repeat(n--)}n+1]`)

```

Port of @xnor's Python answer.
> 2 votes

# Answer
## R, ~~60~~ 49 bytes

Pretty straightforward use of `unlist` and `sapply`.

```
y=x=scan();for(i in 1:x)y=unlist(sapply(y,seq));y

```

Thanks to @MickyT for saving 11 bytes
> 2 votes

# Answer
## Clojure, 59 bytes

```
(fn[n](nth(iterate #(mapcat(fn[x](range 1(inc x)))%)[n])n))

```

Explanation:

Really straight forward way to solve the problem. Working from the inside out:

```
(1) (fn[x](range 1(inc x))) ;; return a list from 1 to x
(2) #(mapcat (1) %)         ;; map (1) over each item in list and flatten result
(3) (iterate (2) [n])       ;; call (2) repeatedly e.g. (f (f (f [n])))
(4) (nth (3) n))            ;; return the nth value of the iteration

```
> 2 votes

# Answer
## php 121

Not really very much in the way of tricks behind this one. Flattening an array in php isn't short so it's necessary to build it flat in the first place

```
<?php for($a=[$b=$argv[1]];$b--;)$a=array_reduce($a,function($r,$v){return array_merge($r,range(1,$v));},[]);print_r($a);

```
> 2 votes

# Answer
# Pyth, 8 bytes

```
usSMGQ]Q

```

Try it online!

```
usSMGQ]Q   input as Q

u    Q     repeat for Q times,
      ]Q   starting as [Q]:

  SMG          convert each number in the array to its range
 s             flatten

           then implicitly prints the result.

```
> 1 votes

# Answer
# Jelly, 7 bytes

Quick, before Dennis answers (jk)

```
WR€F$³¡

```

Try it online!

```
WR€F$³¡  Main monadic chain. Argument: z

W        Yield [z].
     ³¡  Repeat the following z times:
 R€          Convert each number in the array to the corresponding range.
   F         Flatten the array.

```
> 1 votes

# Answer
## Python 2, ~~69~~ ~~68~~ 66 bytes

```
def f(n):a=[n];exec'a=sum([range(1,i+1)for i in a],[]);'*n;print a

```

Edit: Saved 1 byte thanks to @xnor. Saved 2 bytes thanks to @Dennis♦.
> 1 votes

# Answer
## F# , 63 bytes

```
fun n->Seq.fold(fun A _->List.collect(fun k->[1..k])A)[n]{1..n}

```

Returns an anonymous function taking n as input.

Replaces every entry k in A with \[1..k\], repeats the process n times, starting with A = \[n\].
> 1 votes

# Answer
# Swift 3, 58 Bytes

Meant to run directly in the a playground, with n set to the input:

```
var x=[n];for i in 0..<n{x=x.reduce([]){$0+[Int](1...$1)}}

```

Ungolfed, with most short hand notation reverted:

```
let n = 3 //input

var x: Array<Int> = [n]
for i in 0..<n {
    x = x.reduce(Array<Int>[], combine: { accumulator, element in
        accumulator + Array<Int>(1...element)
    })
}

```
> 1 votes

# Answer
# Java, 159 Bytes

**Procedure**

```
int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;}

```

**Usage**

```
public static void main(String[] args){String out = "["; int [] b = q(6);for(int c:b)out+=c+", ";System.out.println(out+"]");}

public static int[] q(int y){int z[]=new int[]{y};for(int i=0;i<y;i++){int d=0,a=0;for(int c:z)d+=c;int[]r=new int[d];for(int c:z)for(int j=0;j<c;)r[a++]=++j;z=r;}return z;}

```

*Sample output:*

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

```
> 1 votes

# Answer
# Bash + GNU utilities, 49

* 1 byte saved thanks to @Dennis.

Piped recursive functions FTW!

```
f()((($1))&&xargs -l seq|f $[$1-1]||dd)
f $1<<<$1

```

`n` is passed on the command-line. Output is newline-separated.

The use of `dd` causes statistics to be sent to STDERR. I think this is OK, but if not, `dd` can be replaced with `cat` at a cost of 1 extra byte.
> 1 votes

# Answer
# Ruby, 44 bytes

A simple recursive approach.

```
->n,a=[n]{n>0?F[n-1,a.flat_map{[*1.._1]}]:a}

```

Attempt This Online!
> 1 votes

# Answer
# Perl 5, 53 bytes

A subroutine:

```
{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}

```

See it in action as

```
perl -e'print "$_ " for sub{($i)=@_;for(1..$i){my@c;push@c,1..$_ for@_;@_=@c}@_}->(3)'

```
> 0 votes

# Answer
## Ruby, 61 bytes

```
def f(n);a=[n];n.times{a=a.map{|i|(1..i).to_a}.flatten};a;end

```
> 0 votes

# Answer
# PHP, ~~100~~ 98 bytes

Run with `php -r '<code>' <n>`.

```
for($a=[$n=$argv[1]];$n--;$a=$b)for($b=[],$k=0;$c=$a[$k++];)for($i=0;$i++<$c;)$b[]=$i;print_r($a);

```

In each iteration create a temporary copy looping from 1..(first value removed) until `$a` is empty.

---

These two are still and will probably remain at 100 bytes:

```
for($a=[$n=$argv[1]];$n--;)for($i=count($a);$i--;)array_splice($a,$i,1,range(1,$a[$i]));print_r($a);

```

In each iteration loop backwards through array replacing each number with a range.

```
for($a=[$n=$argv[1]];$n--;)for($i=$c=0;$c=$a[$i+=$c];)array_splice($a,$i,1,range(1,$c));print_r($a);

```

In each iteration loop through array increasing index by previous number and replacing each indexed element with a range
> 0 votes

# Answer
# Japt `-mh`, 4 bytes

```
N=cõ

```

Try it
> 0 votes

# Answer
# Perl 5 \+ `-p`, 28 bytes

```
eval's/\d+/@{[1..$&]}/g;'x$_
```

Try it online!
> 0 votes

# Answer
# Pyt, 9 bytes

```
Đ`⇹řƑ⇹⁻ł+

```

Try it online!

```
Đ            implicit input; Đuplicate
 `     ł     do... while top of stack is truthy
  ⇹          swap top two items on stack
   ř         řangify (element-wise)
    Ƒ        Ƒlatten array
     ⇹       swap top two items on stack
      ⁻      decrement
       +     add (to get rid of pesky 0); implicit print

```
> 0 votes

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