# Question
Title: Given a list of strings, find all elements which are still in the list when any character is deleted
Write a program using the fewest bytes of source code which given a list of strings finds all elements which are still in the list when any character is deleted.

For example, given a list of all English words `boats` would be output because `oats`, `bats`, `bots`, `boas`, `boat` are all English words and thus would be in the list.

Simple Pyhon code example, assuming `words` is the input list:

```
for w in words:
    has_all = True
    for i in range(len(w)):
        test = w[:i] + w[i+1:]
        if test not in words:
            has_all = False
            break
    if has_all
        print(w)

```

Example input list with some strings:

```
aorn (+)
aor (+)
arn
aon
orn (+)
ao
ar
or
rn
on

```

The strings marked with `(+)` are the ones that should be the output.

`arn` and `aon` shouldn't be output because we can delete the middle character to get `an`, which is not in the input list.

You should test that aba is not present on the output of this list:

```
aba
ba
aa
b

```

# Answer
# , 11 bytes

```
*/@e.~1<\.]

```

Try it online!

J's "outfix" adverb `\.` does exactly what we need here.

Take the dictionary as the left arg (implicitly, via the overall dyadic hook), and the string to test as the right arg.

* `1<\.]` Returns the box of every length 1 outfix of our right arg, that is, every copy with exactly 1 char deleted.
* `e.~` Asks if each of those is an element of the dictionary given as the left arg. Returns a list of boolean zeros and ones.
* `*/@` Multiplies them all together, that is, are they all one?
> 5 votes

# Answer
# Python 3, 69 bytes

```
lambda L:[w for w in L if{w[:i]+w[i+1:]for i in range(len(w))}<={*L}]

```

Try it online!

# Python 2, 71 bytes

```
lambda L:[w for w in L if{w[:i]+w[i+1:]for i in range(len(w))}<=set(L)]

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 74 bytes

```
a=>a.filter(w=>[...w].every((_,i)=>a.includes(w.slice(0,i)+w.slice(i+1))))

```

Try it online!

---

### 75 bytes

A bit more fun, but 1 byte longer:

```
a=>a.filter(w=>w.replace(/./g,"$`$',").split`,`.every(w=>!w|a.includes(w)))

```

Try it online!

or:

```
a=>a.filter(w=>!+w.replace(/./g,_=>+!a.includes(r["$`"]+r["$'"])),r=RegExp)

```

Try it online! (SpiderMonkey)
> 4 votes

# Answer
# Jelly, ~~7~~ 6 bytes

```
e-ƤẠ¥Ƈ

```

Try it online!

A monadic link taking a list of words and returning a list of words.

Thanks to @JonathanAllan for saving a byte!

## Explanation

```
    ¥Ƈ | Keep only those where the following is true:
e-Ƥ    | - Check whether each outfix with sublists length 1 removed is in the original list
   Ạ   | - All

```
> 4 votes

# Answer
# Ruby, ~~51~~ ~~48~~ 45 bytes

```
->a{a.reject{|i|i.gsub(/./m){[$`+$']-a}[?"]}}

```

Try it online!

For each character in a string, generate the string with it deleted, then replace the character with either that string, if it's not in `a`, or an empty array, using `-` for the set complement operation. Then check whether the result contains any string representations.

Edit: -3 bytes from Value Ink by not converting arrays to booleans.
> 4 votes

# Answer
# GolfScript, 34 bytes

```
~:a{.,,{1$.2$<\@)>+a?)}%{and}*\;},

```

Try it online!

# Explanation

```
~   # Evaluate the inplicit list input
 :a # Assign to the variable a w/o popping
    # (To be golfed)
{                           }, # Huge filter block
 .   # Copy the current string
  ,, # Generate a length list
    {                 }% # Map the length list:
     1$.2$<\@)>+      # Remove the character at the index
                a?)   # Is this string still in the list?
    {and}*               # logical AND all of the results
    \;                # Discard the extra operand

```
> 3 votes

# Answer
# Charcoal, 11 bytes

```
Φθ⬤ι№θΦι⁻ξμ

```

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

```
 θ          Input array
Φ           Filter where
   ι        Current word
  ⬤         All characters satisfy
    №       (Non-zero) Count of
       ι    Current word
      Φ     Filtered where
         ξ  Character index
          μ Inner index
        ⁻   Differ (i.e. filter out that character index)
     θ      In input array
            Implicitly output each matching word on its own line

```
> 3 votes

# Answer
# Ruby, 64 bytes

```
->l{l.select{|w|(1..w.size).all?{|a|l&[w[0,a-1]+w[a..-1]]!=[]}}}

```

Try it online!
> 3 votes

# Answer
# PHP, 112 bytes

```
for(;$s=$argv[++$i];$j=0){for($t=1;$s[$j];)$t&=in_array(substr($s,0,$j).substr($s,++$j),$argv);if($t)echo"$s,";}

```

Try it online!

That's still pretty ugly and throws a lot of notices, but it works..

Pretty straightforward:

```
for(;$s=$argv[++$i];$j=0){ //loops on arguments skipping the first (script name) and resetting $j each turn
  for($t=1;$s[$j];)        //loops on all chars indexes initializing $t to true
    $t&=in_array(substr($s,0,$j).substr($s,++$j),$argv); //checks if in arguments array, with deleted char -> bitwise AND the result to $t
  if($t)echo"$s,";         //if $t still true, displays argument with a coma
}

```

caveat: can lead to false positive if the name of the script is a word that can be a match in the list (".code.tio" in TIO, so OK here)

Try it online! for the added second test case `[aba, ba, aa, b]`

EDIT: saved 3 bytes using bitwise assign operator `&=in_array` instead of logical operator `=$t&&in_array`

EDIT2: saved another 3 by initializing `$j` to zero and moving `++` inside `substr`

EDIT3: saved another one by resetting `$j` to zero in first loop declaration, saving the `,` (it is undefined on first iteration, causing a bunch of new notices, but PHP is a smart guy)
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), 67 bytes

```
a=>a.Where(x=>x.Select((y,_)=>x.Remove(_,1)).All(y=>a.Contains(y)))

```

Try it online!
> 2 votes

# Answer
# Java 10, ~~137~~ ~~130~~ 121 bytes

```
L->L.stream().filter(w->{var b=1>0;for(int i=0;i<w.length();)b&=L.contains(w.substring(0,i)+w.substring(++i));return b;})

```

-7 bytes thanks to *@ExpiredData*.

Try it online.

**Explanation:**

```
L->                      // Method with String-List parameter & String-Stream return-type
  L.stream().filter(w->  //  Filter the words in the input-Stream by:
    var b=1>0;           //   Create a boolean, starting at true
    for(int i=0;i<w.length();)
                         //   Loop `i` in the range [0, word-length)
      b&=                //    Check if all are truthy for:
         L.contains(w.substring(0,i)+w.substring(++i)
                         //     Remove the `i`th character from the word
                      ); //     and check if this is in the input-list
    return b;})          //   And return the resulting boolean

```
> 2 votes

# Answer
# C++ (clang), ~~216~~ \\$\cdots\\$ ~~164~~ 160 bytes

```
#import<string>
#import<set>
void f(std::set<std::string>d){for(auto w:d){int h=1,i=0;for(;w[i]*h;){auto t=w;h=d.find(t.erase(i++,1))!=end(d);}h&&puts(&w[0]);}}

```

Try it online!

Saved 10 bytes thanks to ceilingcat!!!

**Ungolfed:**

```
#include <iostream>
#include <set>
#include <string>

void f(const std::set<std::string>& words) {
    for (auto word : words) {
        bool hit = true;
        for (size_t i = 0; i < word.size(); ++i) {
            auto temp = word;
            temp.erase(i, 1);
            if (words.find(temp) == end(words)) {
                hit = false;
                break;
            }
        }
        if (hit) {
            std::cout << word << "\n";
        }
    }
}

```
> 2 votes

# Answer
# AWK, ~~101~~ 94 bytes

```
{a[$0]++}END{for(w in a){e=split(w,x,"");for(i in x){t=w;sub(x[i],"",t);e*=a[t]}if(e)print w}}

```

Try it online!
> 2 votes

# Answer
# Haskell 42 bytes

```
f l=[e|e<-l,all(\c->filter(/=c)e`elem`l)e]

```

In `f` I'm just literally asking for all elementes `e` in the list `l`, such that, for all characters `c` in that element, if I filter `c` from `e` (`filter(/=c)e`), the result is still in the list (`filter(/=c)e`elem`l`).
> 2 votes

# Answer
# Japt `-f`, ~~11~~ ~~10~~ 9 bytes

I am *horribly* out of practice; (now slightly less) convinced this can be shorter!

```
¬e@NÎøUjY

```

Try it
> 2 votes

# Answer
# Perl 6, ~~44~~ 42 bytes

*crossed out 44 is still 44*

```
{@^a.grep:{m:ex/^(.*).(.*)$/>>.join⊂@a}}

```

Try it online!

Filter from the input list elements where the possible regex matches excluding one letter are a subset of the input.
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
ʒæ¤g<ùåP

```

Try it online!

```
ʒ            # filter the list of words by:
 æ           #  powerset of the word
  ¤g<        #  length of the word - 1
     ù       #  elements of the powerset that have this length
      åP     #  are they all in the list of words?

```
> 1 votes

# Answer
# Zsh, 58 bytes

```
for x;(repeat $#x (($@[(I)$x[0,i]${x: ++i}]))||exit;<<<$x)

```

Try it online!

I abuse a `(subshell)` to remove the need to reset `i` on each iteration, and to use `exit` instead of `continue 2`.

```
for x;(repeat $#x (($@[(I)$x[0,i]${x: ++i}]))||exit;<<<$x)
for x;                                                      # for each element
      (repeat $#x                                  ;     )  # repeat for the length
      (                   $x[0,i]${x: ++i}               )  # 1-indexed substring, zero-indexed substring
      (             $@[(I)                ]              )  # get smallest index of match
      (           ((                       ))||exit;     )  # if zero, exit the subshell
      (                                             <<<$x)  # if we didn't exit, print the string
      (                                                  )  # exit subshell, which unsets i.

```
> 1 votes

---
Tags: code-golf, combinatorics
---


title: 99 ways to say "I love you"

text:
# Question
Title: 99 ways to say "I love you"
Inspired by this blog post.

Write a program that outputs 99 distinct programs (in the same language) that output the string `I love you`.

How the programs are separated from one another in the output will be defined by you. However, Each byte of output can only belong to at most 1 of the 99 programs.

**Constraints for Output Programs**

1. If **any string** of characters is removed, then the program must not output `I love you`.
e.g. `console.log('I love you');;;` is invalid because `;;;` can be removed
2. If **any two strings** of characters are both removed, then the program must not output `I love you`. This is to prevent inconsequential application of pairs of characters, that pass rule 1 because removing any *single* string will break the program.
e.g. `print((('I love you')))` is invalid, because `((` and `))` can be removed

**There will be two categories of scoring to participate in.**

1. Standard code golf—smallest source code wins
2. Combined code golf—smallest source code + output wins

## Leaderboard

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

```
/* Configuration */

var QUESTION_ID = 198052; // 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 = 48934; // 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
# JavaScript (JavaScript shell), 65 bytes

total: (64 + 3366 = 3450) bytes

```
for(i=99;i++<198;)print(`\\u0${i}="I love you";print(\\u{${i}})`)

```

```
\u0100="I love you";print(\u{100})
\u0101="I love you";print(\u{101})
\u0102="I love you";print(\u{102})
\u0103="I love you";print(\u{103})
\u0104="I love you";print(\u{104})
\u0105="I love you";print(\u{105})

```

It is trivial.

JavaScript allow escape sequence in variable name. `console.lo\u0067('Hello world')` is prefect valid. I don't think this feature is useful anyway. But...

No TIO link, since the TIO version is out-of-date. You may download JavaScript Shell from https://archive.mozilla.org/pub/firefox/releases/72.0.1/jsshell/ .

---

# JavaScript (SpiderMonkey), 76 bytes

total: (76 + 2475 = 2551) bytes

```
for(i=99;i++<198;print(v+'="I love you";print('+v+')'))v=eval('"\\u0'+i+'"')

```

Try it online!

Output:

```
Ā="I love you";print(Ā)
ā="I love you";print(ā)
Ă="I love you";print(Ă)
ă="I love you";print(ă)
Ą="I love you";print(Ą)
ą="I love you";print(ą)

```

This one is shorter when counting total length. And it is much more trivial.

---

# JavaScript (SpiderMonkey), 85 bytes

total: (86 + 36927 = 37013) bytes

```
for(n=99,p="(L='I love you')=>",q="print(L)";n--;p+='x=>')p='('+p,q+=')()',print(p+q)

```

Try it online!

Output:

```
((L='I love you')=>print(L))()
(((L='I love you')=>x=>print(L))())()
((((L='I love you')=>x=>x=>print(L))())())()
(((((L='I love you')=>x=>x=>x=>print(L))())())())()
((((((L='I love you')=>x=>x=>x=>x=>print(L))())())())())()

```

This is my original solution.
> 19 votes

# Answer
# Whitespace, 718 bytes, score: 34180 (33462+718)

```
[S S S T    N
_Push_1][S S S N
_Push_n=0][T    T   S _Store_1:n][N
S S S N
_Create_Label_LOOP][S S S T N
_Push_1][S N
S _Dupe_1][T    T   T   _Retrieve_1:n][T    S S S _Add][S N
S _Dupe_n+1][S S S T    T   S S T   S S N
_Push_100][T    S S T   _Subtract][N
T   S T T   N
_If_0_Jump_to_Label_EXIT_WITH_PRINT][S S S T    N
_Push_1][S N
T   _Swap][T    T   S _Store_1:n+1][S S S T N
_Push_1_newline][S N
S _Dupe_1_newline][S S S T  S T T   T   N
_Push_23_space][S S S T N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S S S N
_Push_0_tab][S T    S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][N
S T N
_Call_Subroutine_PUSH_INTEGER][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][N
S T N
_Call_Subroutine_PUSH_INTEGER][S S S T  N
_Push_1_newline][S S S T    S T T   T   N
_Push_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S N
S _Dupe_1_newline][S T  S S T   S N
_Copy_0-based_2nd_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T  S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T  S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S T    S S T   N
_Copy_0-based_1st_23_space][S S S T N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T  S S T   S S N
_Copy_0-based_4th_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T  S S T   S S N
_Copy_0-based_4th_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S T    S S T   N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T  S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T  S S T   S T N
_Copy_0-based_5th_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T  S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S T    S S T   N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S T   N
_Push_1_newline][S T    S S T   N
_Copy_0-based_1st_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T  S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S T  S S T   T   N
_Copy_0-based_3rd_23_space][S N
S _Dupe_23_space][S S S N
_Push_0_tab][N
S T N
_Call_Subroutine_PUSH_INTEGER][S S S T  N
_Push_1_newline][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S N
S _Dupe_0_tab][S S S T  S T T   T   N
_Push_23_space][S S S N
_Push_0_tab][S N
S _Dupe_0_tab][S T  S S T   S N
_Copy_0-based_2nd_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][N
S T N
_Call_Subroutine_PUSH_INTEGER][N
S N
S N
_Jump_to_Label_LOOP][N
S S T   T   N
_Create_Label_EXIT_WITH_PRINT][S N
N
_Discard_n][N
S S T   N
_Create_Label_PRINT_LOOP][S S S T   S S T   N
_Push_9][T  S S S _Add][T   N
S S _Print_as_character][N
S N
T   N
_Jump_to_Label_PRINT_LOOP][N
S S N
_Create_Subroutine_PUSH_INTEGER][S S S T    N
_Push_1_newline][S S S N
_Push_0][S S S T    N
_Push_1][T  T   T   _Retrieve_1:n][T    T   S _Store_0:m][N
S S S S N
_Create_Label_TAB_LOOP][S S S N
_Push_0_tab][S N
S _Dupe_0][S N
S _Dupe_0][T    T   T   _Retrieve_0:m][S S S T  N
_Push_1][T  S S T   _Subtract][S N
S _Dupe_m-1][N
T   S S T   N
_If_0_Jump_to_Label_DONE_WITH_TAB_LOOP][T   T   S _Store_0:m-1][N
S N
S S N
_Jump_to_Label_TAB_LOOP][N
S S S T N
_Create_Label_DONE_WITH_TAB_LOOP][S S S T   S T T   T   N
_Push_23_space][S N
S _Dupe_23_space][S N
S _Dupe_23_space][N
T   N
_Return_from_Subroutine_PUSH_INTEGER]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

The output Whitespace programs are output without delimiter. Each program will be as follows, where the `x` is variable in the range `[3,102]`.

```
[S S S (x_amount_of_T   )N
_Push_n][S S S T    T   S T T   T   T   N
_Push_constant_111][S S S (x_amount_of_T    )N
_Push_n][T  S S T   ][T T   S _store][S S S T   T   S N
_Push_6_u][S S S N
_Push_0_o][S S S T  S T S N
_Push_10_y][S S T   T   S S T   T   T   T   N
_Push_-79_space][S S T  T   S T S N
_Push_-10_e][S S S T    T   T   N
_Push_7_v][S S S N
_Push_0_o][S S T    T   T   N
_Push_-3_l][S T S S T   S S N
_Copy_0-based_4th_-79_space][S S T  T   S S T   T   S N
_Push_-38_I][N
S S N
_Create_Label_LOOP][S S S (x_amount_of_T    )N
_Push_n][T  T   T   _Retrieve][S S S (x_amount_of_T )N
_Push_n][T  S S S _Add][T   S S S _Add][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_LOOP]

```

In the 1st program, `x` will be 3, so the four `Push n` parts will push the integer `7` (binary `111`; three 1-bits); in the 15th program, `x` will be 18, so the four `Push n` parts will push the integer `262143` (binary `111111111111111111`; eighteen 1-bits); etc. up to `5070602400912917605986812821503` (binary with 102 1-bits).

Try it online for the 15th program (with raw spaces, tabs and new-lines only).

I've used this Whitespace tip of mine to print the output `I love you`. The optimal constant `111` is generated by this Java program. In addition, I use one copy for the space to save bytes.

I've also used this same tip with a constant `9` in the generator program to output the Whitespace sub-programs. After that I've used loads of duplicates, as well as copies for the spaces where possible.

### Explanation in pseudo-code:

**Generator program:**

```
Store n=0 at heap-address 1
Start LOOP:
  Retrieve n from heap-address 1
  n = n + 1
  If(n == 100):
    Call function EXIT_WITH_PRINT
  Store the updated n+1 at heap-address 1
  Push the codepoints of "NNSNSSNTSSSTSSST" minus 9 for the output program
  Call subroutine PUSH_INTEGER
  Push the codepoints of "TTT" minus 9 for the output program
  Call subroutine PUSH_INTEGER
  Push the codepoints of "NSSNNSTTSSTTSSNSSTSSTSNTTTSSNSSSNTTTSSSNSTSTTSSNTTTTSSTTSSNSTSTSSSNSSSNSTTSSSSTTTSST" minus 9 for the output program
  Call subroutine PUSH_INTEGER
  Push the codepoints of "NTTTTSTTSSS" minus 9 for the output program
  Call subroutine PUSH_INTEGER
  Go to the next iteration of LOOP

Function EXIT_WITH_PRINT:
  Discard n that was still on the top of the stack
  Start PRINT_LOOP:
    Add 9 to the value at the top of the stack
    Pop and print it as character
    (this will fail with an error since there is nothing more to pop, when we're done with
     the final character to stop the program)
    Go to the next iteration of PRINT_LOOP

Subroutine PUSH_INTEGER:
  Push the codepoint of "N" minus 9 for the output program
  Retrieve n from heap-address 1
  Integer m = n
  Store m at heap-address 0
  Start TAB_LOOP:
    Push the codepoint of "T" minus 9 for the output program
    Retrieve m from heap-address 0
    m = m - 1
    If(m == 0):
      Call function DONE_WITH_TAB_LOOP
    Store m-1 at heap-address 0
    Go to next iteration of TAB_LOOP

  Function DONE_WITH_TAB_LOOP:
    Push the codepoints of "SSS" minus 9 for the output program
    Return to the caller of the PUSH_INTEGER subroutine, and continue from there

```

**Sub-program:**

Variable as explained before is integer `n` (which has `x` amount of binary 1-bits).

```
Integer t = 111 - n
Store t at heap-address n
Push the codepoints of "uoy evol I" minus 111
Start LOOP:
  Retrieve t from heap-address n
  t = t + n
  Add t (which is 111 again) to the value at the top of the stack
    Pop and print it as character
    (this will fail with an error since there is nothing more to pop, when we're done with
     the final character to stop the program)
    Go to the next iteration of LOOP

```

Since we use the variable `n` four times (`t = 111-n`; `store t at heap-address n`; `retrieve t from heap-address n`; `t = t+n`) with other pieces of relevant code in between the pushes, we need to remove four string-sequences in order to still have a valid `I love you` output, complying to the rule stating you can't remove one or two string-sequences.
> 10 votes

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

### Output: 4275 bytes

```
for(n=100;--n;)console.log(`console.log('I lo'+Buffer([${n}^${118^n}])+'e you')`)

```

Try it online!
> 7 votes

# Answer
## Batch, 131 + 3564 bytes

```
@for %%a in (a b c d e f g h i j k)do @for %%b in (. / \ "," ";" [ ] + "=")do @echo @for %%%%%%a in (love)do @echo%%~bI %%%%%%a you

```

This produces 99 variants of the same code:

```
@for %%k in (love)do @echo=I %%k you

```

The `for` variable (here `k`) loops over the 11 values `a` to `k`, while the other character that changes is the separator after `echo`, which can usually (as here) be any of 11 characters, but five of them need quoting to use in a `for` command, so I've omitted space and `(`. The programs are all irreducible because they need to get the word `love` to appear in the output.
> 6 votes

# Answer
# Python 3, 86 bytes

86 code + 10289 output = 10375 total

```
x=0
while x<99:print(f"print(chr(len('{(bin(x)[2:8]).zfill(73)}'))+' love you')");x+=1

```

sample segment of output: `print(chr(len('0000000000000000000000000000000000000000000000000000000000000000000110000'))+' Love you')`
> 5 votes

# Answer
# C (clang), <sup>~~87~~ \\$\cdots\\$ ~~160~~</sup> 120 bytes

### Output: 3822 bytes (Total: 3942 bytes)

```
i;main(j){for(;i<99;printf("main(){printf(\"%%c Love You\",%d^%d);}\n",j,j^73))j=3+i++*4,j=strchr("$,2MOPW]_",i)?6*j:j;}

```

Try it online!

Fixed pristine-errors kindly pointed out by Expired Data.
Fixed pristine-errors kindly pointed out by Kaddath.
Saved 50 bytes thanks to gastropner!!!

Prints 99 unique lines like:

```
main(){printf("%c Love You",3^74);}

```
> 5 votes

# Answer
# PHP, 96 bytes

# Output: 2516 bytes (total 2612)

```
<?php for(;($i+=2)<773;)if($i<99||--$i%100>67&&$i>299)echo"I<?=chr(".(33+$i++)."-$i)?>love you";

```

Try it online!

Example program:

```
I<?=chr(35-3)?>love you

```

Still quite new at code golf, hope I get this right. Wanted to encode the space as 32 is the lowest number and wanted to do something else than port an existing answer. Got me into troubles with the 2 strings removing part, but I think this time it passes

(Edit: one line was missing, programs count was 98) (Edit2: separator is now `:`, as `-` was in the code, and total count was wrong)

**Edit3: This time I think it's OK** (got much more complicated than planned):

* I had to remove all the intervals of the form `x99-x67` that can be reduced by removing the `x`'s
* Had also to remove all the interval of the form `3xx-2xx` that can be reduced by removing the `xx-` and `xx`
* Tried to keep only `--$i%100>67&&$i>299` as a condition but unfortunately it goes to `1003-971` and a bit beyond that all can be reduced to the form `103-71`
* new code is manupulating `$i` with -- and ++ to avoid to add prenthesis and do `($i-1)%100>67` in test and `"-".($i-1).")` in display
* no separator anymore, as per a question's comment
* removed the space after `echo` (thanks to @Ismael Miguel answer)
> 4 votes

# Answer
# 05AB1E, 23 bytes (combined score 1688 bytes)

```
тGN"•«À¢ÒÙΓʒγ•"тN-…O₃BJ

```

Try it online! or try one of the output programs.

```
тG                       # for N from 1 to 99:
  N                      #  N
   "•«À¢ÒÙΓʒγ•"          #  string "•«À¢ÒÙΓʒγ•"
               тN-       #  100 - N
                  …O₃B   #  "O₃B"
                      J  #  join the entire stack

```

Each subprogram looks like:

```
1                       # 1 (N)
 •«À¢ÒÙΓʒγ•             # compressed integer 11971423964735158206
           99           # 99 (100 - N)
             O          # sum the entire stack
              ₃B        # convert to base 95

```
> 4 votes

# Answer
# Keg, 33 bytes

Programs separated by `:`

Output is 1385 bytes

```
в&(c|&:&I+,&:&,`- love you:`,⑹

```

Try it online!

Programs:

```
ѻв- love you:Ѽг- love you:ѽд- love you:Ѿе- love you:ѿж- love you:Ҁз- love you:ҁи- love you:҂й- love you:҃к- love you:҄л- love you:҅м- love you:҆н- love you:҇о- love you:҈п- love you:҉р- love you:Ҋс- love you:ҋт- love you:Ҍу- love you:ҍф- love you:Ҏх- love you:ҏц- love you:Ґч- love you:ґш- love you:Ғщ- love you:ғъ- love you:Ҕы- love you:ҕь- love you:Җэ- love you:җю- love you:Ҙя- love you:ҙѐ- love you:Қё- love you:қђ- love you:Ҝѓ- love you:ҝє- love you:Ҟѕ- love you:ҟі- love you:Ҡї- love you:ҡј- love you:Ңљ- love you:ңњ- love you:Ҥћ- love you:ҥќ- love you:Ҧѝ- love you:ҧў- love you:Ҩџ- love you:ҩѠ- love you:Ҫѡ- love you:ҫѢ- love you:Ҭѣ- love you:ҭѤ- love you:Үѥ- love you:үѦ- love you:Ұѧ- love you:ұѨ- love you:Ҳѩ- love you:ҳѪ- love you:Ҵѫ- love you:ҵѬ- love you:Ҷѭ- love you:ҷѮ- love you:Ҹѯ- love you:ҹѰ- love you:Һѱ- love you:һѲ- love you:Ҽѳ- love you:ҽѴ- love you:Ҿѵ- love you:ҿѶ- love you:Ӏѷ- love you:ӁѸ- love you:ӂѹ- love you:ӃѺ- love you:ӄѻ- love you:ӅѼ- love you:ӆѽ- love you:ӇѾ- love you:ӈѿ- love you:ӉҀ- love you:ӊҁ- love you:Ӌ҂- love you:ӌ҃- love you:Ӎ҄- love you:ӎ҅- love you:ӏ҆- love you:Ӑ҇- love you:ӑ҈- love you:Ӓ҉- love you:ӓҊ- love you:Ӕҋ- love you:ӕҌ- love you:Ӗҍ- love you:ӗҎ- love you:Әҏ- love you:әҐ- love you:Ӛґ- love you:ӛҒ- love you:Ӝғ- love you:ӝҔ- love you:
```
> 3 votes

# Answer
# 05AB1E, ~~34~~ ~~31~~ ~~30~~ ~~28~~ 25 bytes

*Combined Score*: very very big `(25 + no. permutations of "I love you"*20)`

*-3 bytes thanks to @KevinCruijssen*

```
…I„Î€îœ¦v'"y'""œ{•B‹<•è"J

```

Try it online!

---

# Optimised for Combined Score

# 05AB1E, ~~32~~ ~~30~~ 27 bytes

*Combined Score:* `27 + 1980 = 2007`

```
…I„Î€îœт£¦v'"y'""œ{•B‹<•è"J

```

Try it online!

This may take a while to run...

---

### Explanation

```
…I„Î€î                       # Compressed string "I love you"
      œ                      # Get the permutations of this string
       ¦                     # Remove the first one ("I love you")
        v                    # loop over these and do...
         '"y'"               # the string with the value in (e.g. "I love yuo"
              "œ{•B‹<•è"     # string literal with œ{•B‹<•è value
                        J    # join these and print e.g. "I love yuo"œ{•B‹<•è

```

### Explanation of the output programs:

```
"I love yuo"                   # a string which is a permutation of "I love you"
            œ{                 # get the sorted permutations of this string
              •B‹<•è           # get the value at index 750832 which is "I love you"

```
> 3 votes

# Answer
# Ruby, ~~200~~ ~~181~~ ~~172~~ 165 + ~~3992~~ ~~3828~~ 3540 bytes

```
m="I love you";q=?",?';%w[print $><< puts].map{|e|q.product(q){|c,d|8.times{|i|puts e+c+"#{m.chars.rotate(~i)*""}#{c}.chars.rotate(#{i+1})*#{d*2}"}};puts e+"'#{m}'"}

```

This combines different ways of printing (`print`, `$stdout <<`, `puts`), different ways of quoting the string (`''`, `""`), and different rotations of the string `"I love you"` to make `(((8 * 4) + 1) * 3) =` 99 irreducible programs.

## Golfy Tricks

* Uses `%w[]` as a whitespace-separated string array
* Use `*""` and `*''` instead of `.join`
* Use different combinations of quotation marks (`""`, `''`) instead of different combination of splitting a string (`chars`, `split(//)`), and just use the shorter (`chars`)
* Use `puts` instead of `$stdout<<` as the third way of printing (I didn't think it would be allowed because it also appends a newline where the others don't, but maybe this is fine?)

Try it online! for the initial generator code.

Try it online! for the generated code.

This now has some `"I love you"`s appended with a newline, and some not. I hope this is okay.

EDIT: Saved ~~lots of~~ *even more* bytes thanks to Value Ink!

---

# Ruby, 53 + 2375 bytes

This is the cheap way of using a unicode range as variable names.

```
(?ÿ..?š).each{|v|puts"#{v}='I love you';puts #{v}"}

```

Try it online! for the generator code.

Try it online! for the generated code.
> 3 votes

# Answer
# PowerShell, 63 <sup>\+ 3167 = 3230</sup>

```
1..99|%{$z=$_%10;"''+(echo you $($_-$z)/10) love $z I)[4,2,0]"}

```

Try it online!

Sample output:

```
''+(echo you 0 love 1 I)[4,2,0]
''+(echo you 0 love 2 I)[4,2,0]
...
''+(echo you 1 love 0 I)[4,2,0]
''+(echo you 1 love 1 I)[4,2,0]
''+(echo you 1 love 2 I)[4,2,0]
...
''+(echo you 9 love 8 I)[4,2,0]
''+(echo you 9 love 9 I)[4,2,0]

```

# PowerShell, 2575 <sup>= 101 + 2474</sup>

Inspired by Jo King's answer for Perl.

Minimal total output for Powershell (84+2153) was written by Andrei Odegov

So make sure to upvote them both as well!

```
1..99|%{$n=$_
'"I "+("'+-join(0..6|%{[char](($n-shr$_)%2*32+'LOVEYOU'[$_])
' '*!($_-3)})+'"|% *wer)'}

```

Try it online!

Sample output:

```
"I "+("lOVE YOU"|% *wer)
"I "+("LoVE YOU"|% *wer)
"I "+("loVE YOU"|% *wer)
"I "+("LOvE YOU"|% *wer)
...
"I "+("loVE You"|% *wer)

```

# PowerShell, 2672 <sup>= 99 + 2573</sup>, bonus track

```
1..99|%{$p,$d="0$_"[-2,-1]
$e,$l,$c,$r='I love you'-split"^(.{$p})(.)"
"'$l$d$r'-replace$d,`"$c`""}

```

Try it online!

It generates 10 distinct programs for each char of the input string. The length of string `I love you` is 10 chars. This is enough for 99 iterations

Sample output:

```
'1 love you'-replace1,"I"
'2 love you'-replace2,"I"
'3 love you'-replace3,"I"
...
'8 love you'-replace8,"I"
'9 love you'-replace9,"I"
'I0love you'-replace0," "
'I1love you'-replace1," "
...
'I love yo8'-replace8,"u"
'I love yo9'-replace9,"u"

```

# PowerShell, 94 + 2890, bonus track 2

```
1..99|%{$n=$_;$i=0
'"=I='+-join(' love you'|% t*y|%{$_+'='[1-($n-shr$i++)%2]})+'"-replace"="'}

```

Try it online!

Sample output:

```
"=I= =love you"-replace"="
"=I= l=ove you"-replace"="
"=I= =l=ove you"-replace"="
"=I= lo=ve you"-replace"="
"=I= =lo=ve you"-replace"="
...

```

# PowerShell, 96 + 3094

Specially for those who love to turn `99` into `9`. ٩(^‿^)۶

```
2..100|%{"-join('"+-join(('I love you '*$_)[($_+10)..$_])+"'*$(2+($_-$_%10)/10))[$($_+10)..$_]"}

```

Try it online!

Sample output:

```
-join(' I uoy evol'*2)[12..2]
-join('l I uoy evo'*2)[13..3]
-join('ol I uoy ev'*2)[14..4]
-join('vol I uoy e'*2)[15..5]
-join('evol I uoy '*2)[16..6]
-join(' evol I uoy'*2)[17..7]
-join('y evol I uo'*2)[18..8]
-join('oy evol I u'*2)[19..9]
-join('uoy evol I '*3)[20..10]
-join(' uoy evol I'*3)[21..11]
-join('I uoy evol '*3)[22..12]
-join(' I uoy evol'*3)[23..13]
...
-join(' uoy evol I'*10)[98..88]
-join('I uoy evol '*10)[99..89]
-join(' I uoy evol'*11)[100..90]
-join('l I uoy evo'*11)[101..91]
-join('ol I uoy ev'*11)[102..92]
-join('vol I uoy e'*11)[103..93]
-join('evol I uoy '*11)[104..94]
-join(' evol I uoy'*11)[105..95]
-join('y evol I uo'*11)[106..96]
-join('oy evol I u'*11)[107..97]
-join('uoy evol I '*11)[108..98]
-join(' uoy evol I'*11)[109..99]
-join('I uoy evol '*12)[110..100]

```

# PowerShell, 123 + 3141

...and in a normal order. https://coub.com/view/27d6eh

```
$s='I love you';(2..122|%{"-join('"+-join(("$s "*$_)[-($_+10)..-$_])+"'*$(2+($_-$_%10)/10))[$($_-1)..$($_+9)]"})-notmatch$s

```

Try it online!

Sample output:

```
-join('u I love yo'*2)[2..12]
-join('ou I love y'*2)[3..13]
-join('you I love '*2)[4..14]
-join(' you I love'*2)[5..15]
-join('e you I lov'*2)[6..16]
-join('ve you I lo'*2)[7..17]
-join('ove you I l'*2)[8..18]
-join('love you I '*3)[9..19]
-join(' love you I'*3)[10..20]
-join('u I love yo'*3)[13..23]
-join('ou I love y'*3)[14..24]
-join('you I love '*3)[15..25]
...

```
> 2 votes

# Answer
# Perl 6, 75 bytes, 2178 + 75 = 2253

```
unique("'I love you'.tclc.say",{S:x(8)[\w]~^=' 'x 2.rand}...*)[^99+1]>>.say

```

Try it online!

Outputs variants of:

```
'I love you'.tclc.say

```

string part has a randomised unique case. `tclc` is short for "title case, lowercase", which capitalises the first letter and lowercases the rest.

```
"..."         # Starting from the base program
     ,{                        }...*  # Generate an infinite series of
       S:x(8)[\w]~^=             # String xor the first 8 letters
                    ' 'x 2.rand  # Randomly space or nothing,
                                 # Essentially flipping the case

unique( ... )                 # From the unique elements
             [^99+1]          # Take 99, skipping the first
                    >>.say    # And print each

```

The reason I don't include the first unique element is so that a variant with correct casing isn't produced, since that would be reducible.
> 2 votes

# Answer
R, 84 Bytes

```
for(x in 1:99){cat("assign(intToUtf8(",x,"),'I love you');get(intToUtf8(",x,"))\n")}

```
> 1 votes

# Answer
# `n` `d`, 34 bytes

Different programs are separated as different list items. The `n` flag joins the input with newlines.

```
•u≡`â!=Ç¡l╪G⌠±×èe↔/.╫ù{¶c×█)←╢k0ôF

```

# Uncompressed

```
99''a146+C"C'"a73+C"C-C@ love you@+"++++M

```

# Explanation

```
99                                      M % Map in the range from 1 to 99
  ''                                      % A single quote '
    a146+                                 % Add the current item by 146
         C                                % Convert the current item to a character
          "C'"                            % Add a string C'
              a73+C                       % Add the current item by 73 (creating a difference of 73)
                   "C-C@ love you@+"++++  % Prepend the string and join the whole stack

```

# Program explanation

```
'ⁿC'JC-              # Create the number 73
       C" love you"+ # Convert to character and append "love you"

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 70 bytes

```
for(char i='ÿ';i++<355;Write($"var {i}=\"I love you\";Write({i});"));

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~85 + 2647 = 2732~~ ~~83 + 2251 = 2334~~ 79 + 1818 = 1897

```
0..226|?{[char]::isletterordigit($_)}|%{"`$$([char]$_)"}|%{"($_='I love you')"}

```

-398 thanks to mazzy

Try it online!

Sample output:

```
($0='I love you')
...
($â='I love you')

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~123 + 4247~~ ~~94~~ 90 + 2124 bytes

Heredoc abuse. Takes 49 different alphanumerics (A-Z, \_, a-v) and constructs 2 programs that print the text using the appropriate heredoc. That's only 98 programs, though, so it adds one more print at the end. Each program is 3 lines long, except the last one.

This beats IMP1's Ruby solution in the combined code golf score, but falls behind in standard scoring.

```
l="I love you"
(?A..?v).grep(/\w/){|i|puts"$><<<<"+i,l,i,"puts <<"+i,l,i}
puts"puts'#{l}'"

```

Try it online!

Generated code

### Old solution, 123 + 4247 bytes

Beats out IMP1's (non-Unicode) Ruby solution in the standard code golf department, but falls behind in combined code golf scoring. Unlike their use of multiple output solutions and rotation, I chose to shuffle the string after setting a seed with `srand`.

```
99.times{|i|srand i;puts"srand #{i};puts'#{[*0..9].shuffle.zip('I love you'.chars).sort.map(&:last)*''}'.chars.shuffle*''"}

```

Try it online!

Generated code
> 1 votes

# Answer
# Zsh, 74 bytes

**Output: 2178** (after removing newline delimiters) for a category 2 score of **2252 bytes**

```
for p (echo print '<<<');for v ({1..7} {a..z})<<<"$v='I love you';$p \$$v"

```

Try it online!

Uses method from this Ruby answer, setting a unique variable before printing. In zsh, variables must be alphanumeric, so we limit to 33 names and then print out programs using `echo`, `print`, and `<<<` to get our 99.

There is optimization to be done for category 2, this tweak scores 77 + 2145 = **2222 bytes**, and more can probably be found.
> 0 votes

---
Tags: code-golf, metagolf, pristine-programming
---


# Question
Title: How many countries are in the European Union?
Tonight, 31 January 2020, Brexit will happen and the United Kingdom will leave the European Union, the first time that the number of EU member states will decrease.

Your job is to take a date and output the number of EU1 members on that date, according to the following table:

```
| Start      | End        | Number of members
| 0          | 1957-12-31 | 0
| 1958-01-01 | 1972-12-31 | 6
| 1973-01-01 | 1980-12-31 | 9
| 1981-01-01 | 1985-12-31 | 10
| 1986-01-01 | 1994-12-31 | 12
| 1995-01-01 | 2004-04-30 | 15
| 2004-05-01 | 2006-12-31 | 25
| 2007-01-01 | 2013-06-30 | 27
| 2013-07-01 | 2020-01-31 | 28
| 2020-02-01 | Inf        | 27

```

Input may take one of the following forms:

* your language's date format
* any ordering of integers for year, month and day with any separator (e.g. YYYYMMDD or DD/MM/YYYY)
* number of days lapsed since some epoch.

This is , so shortest code wins!

1. or EEC before 1993

# Answer
# Javascript, ~~85~~ 83 Bytes

```
a=d=>d<0?0:d<180?6:d<276?9:d<336?10:d<444?12:d<556?15:d<588?25:d<666?27:d<745?28:27

```

It takes an input as a float as the *months / fractions of months passed* since `1958-01-01`
(`0` for `1958-01-01T00:00:00` and a negative number for any previous date)

(Since number of days from some epoch is allowed, I assume that also a number of months is valid, as well)

Try it Online

---

# 80 Bytes

(credits: Arnauld)

```
a=d=>d<0?0:d<180?6:d<276?9:d<336?10:d<444?12:d<556?15:d<588?25:27+(d>=666&d<745)

```

---

Sad to see you go, UK
> 12 votes

# Answer
# 05AB1E, ~~29~~ ~~27~~ ~~26~~ ~~25~~ 33 bytes

```
¨12βŽ₅b-‘´`<lp€¸‘Ç.¥@•¿“0p•12в<*O

```

Try it online!

Input is in the form `[yyyy, mm, dd]`.
> 9 votes

# Answer
# Python 2, ~~110~~ 97 bytes

```
lambda d:ord('069:<?IKLK'[sum(d>i for i in(0,5479,8401,10227,13514,16922,17897,20270,22676))])-48

```

Try it online!

-13 bytes, thanks to Jonathan Allan

Takes input as number of days since `1957-12-31` (so `1958-01-01` is day `1`)

---

# Python 3, 93 bytes

```
lambda d:b'069:<?IKLK'[sum(d>i for i in(0,5479,8401,10227,13514,16922,17897,20270,22676))]-48

```

Try it online!

-4 bytes, thanks to mypetlion
> 7 votes

# Answer
# 05AB1E, ~~42~~ 36 bytes

```
•AÂʒë.š¡ε%ž·7í•ŽL}в.¥›O•=γ1sæΔ•₆вsè<

```

Input as number of days since 1957-12-31 (so 1957-12-30 is day `-1`; 1957-12-31 is day `0`; 1958-01-01 is day `1`; etc.)

Try it online or verify some more test cases.

**Old 42 bytes answer taking input in the format `yyyyMMdd`:**

```
¨¨•a3|}\§λ’Iœg½þ•ŽOΩв•32Ø•+@O•=γ1sæΔ•₆вsè<

```

Try it online or verify some more test cases.

`•a3|}\§λ’Iœg½þ•ŽOΩв•32Ø•+` can alternatively be `•Me1εä~.=ΔΩ»•Ž5ãв.¥•32Ù•+` for the same byte-count: Try it online or verify some more test cases.

**Explanation:**

```
•AÂʒë.š¡ε%ž·7í•    # Push compressed integer 813218926689775697373196902446
  ŽL}              # Push compressed integer 5480
     в             # Convert the larger integer to base-5480 as list:
                   #  [5479,2922,1826,3287,3408,975,2373,2406]
      .¥           # Undelta it with leading 0:
                   #  [0,5479,8401,10227,13514,16922,17897,20270,22676]
        ›          # Check for each if it's larger than the (implicit) input-integer
         O         # Take the sum to get the amount of truthy values
•=γ1sæΔ•           # Push compressed integer 122116126451824
 ₆в                # Convert it to base-36 as list:
                   #  [1,7,10,11,13,16,26,28,29,28]
   sè              # Swap to get the sum, and use it to index into this list
     <             # And decrease it by 1
                   # (since a compressed integer/list cannot contain a leading 0)
                   # (after which the result is output implicitly)

¨¨                 # Remove the last two digits from the (implicit) input (the "dd")
  •a3|}\§λ’Iœg½þ•  # Push compressed integer 2722385715080006519908031109868
   ŽOΩ             # Push compressed integer 6203
      в            # Convert the larger integer to base-6203 as list:
                   #  [1,1501,2301,2801,3701,4605,4901,5507,6202]
       •32Ø•       # Push compressed integer 195800
            +      # Add it to each value in the list:
                   #  [195801,197301,198101,198601,199501,200405,200701,201307,202002]
             @     # Check for each if it's larger than or equal to the input minus "dd"
O•=γ1sæΔ•₆вsè<     # Same as above

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand how the compression works.
> 6 votes

# Answer
# Turing Machine Code, ~~972~~ 1009 bytes

My input is the date in the format specified in the test cases `YYYY-MM-DD`.

```
0 0 0 * halt
* 1 _ r €
€ 9 _ r %
* 2 _ r $
$ 0 _ r £
* I 2 r ¢
% 5 _ r ^
% 6 6 r c
% 7 _ r x
% 8 _ r B
% 9 _ r i
% * _ r c
^ * 0 r c
^ 8 6 r c
^ 9 6 r c
B 0 9 r c
B 1 1 r r
B 2 1 r r
B 3 1 r r
B 4 1 r r
B 5 1 r r
B * 1 r e
r * 0 r c
e * 2 r c
x 0 6 r c
x 1 6 r c
x 2 6 r c
x * 9 r c
i 0 1 r
i 1 1 r
i 2 1 r
i 3 1 r
i 4 1 r
i * 1 r t
t * 5 r c
 * 2 r c
£ 0 _ r
£ 1 _ r ★
£ 2 _ r
 0 _ r !
 * 2 r ¢
! - _ r ~
~ 0 _ r 1
1 1 2 r ☆
1 * 2 r ¢
★ 0 2 r ¢
★ 1 2 r ¢
★ 2 2 r ¢
★ 3 _ r &
★ * 2 r ☆
& - _ r @
@ 0 _ r 6
6 0 2 r ¢
6 1 2 r ¢
6 2 2 r ¢
6 3 2 r ¢
6 4 2 r ¢
6 5 2 r ¢
6 6 2 r ¢
6 * 2 r ☆
☆ * 8 r c
 * 5 r c
 1 1 r
 2 1 r
 3 1 r
 4 _ r +
 5 2 r t
 6 2 r t
 * 2 r ¢
¢ * 7 r c
+ - _ r ¬
¬ 0 _ r 4
¬ * 2 r t
4 0 1 r t
4 1 1 r t
4 2 1 r t
4 3 1 r t
4 4 1 r t
4 * 2 r t
6 _ 6 l c
c * _ r c
c _ _ * halt

```

Try it online!

*Added a few bytes thanks to Grimmy being a bit more thorough in testing my code than I was.*
> 6 votes

# Answer
# Charcoal, 48 bytes

```
Ｉ⌕γ§ &)*,/9;<;ＬΦ⪪”)¶↶⌕βγ⦄J≦σν{:Xδp⁴E⊙≕⍘Ｈ⊙βg”⁶‹ιθ

```

Try it online! Link is to verbose version of code. Takes input as YYYYMMDD. Explanation:

```
                 ”...”      Compressed string of YYYYMM values
                ⪪     ⁶     Split into substrings of length 6
              ＬΦ       ‹ιθ  Count those that appear before the input
   § &)*,/9;<;              Look the count up in a translation table
Ｉ⌕γ                         Subtract 32 from the ASCII code

```
> 4 votes

# Answer
# Python 2, ~~158~~ 150 bytes

```
i=int(input()[:6]);print((((((((27,28)[202002>i>201306],25)[i<200701],15)[i<200405],12)[i<199501],10)[i<198601],9)[i<198101],6)[i<197301],0)[i<195801]

```

Try it online!

Takes input as a string in `YYYYMMDD` format

Alternative Python 2 approach without imports. Simply uses nested list indexing to create the equivalent of a big `if/elif` structure.

**NB:** Posted by a British guy who is sorry to see us leave. I'm still all for the Community and working together (whether EU or here).
> 4 votes

# Answer
# Jelly, ~~38~~ 37 bytes

```
“€ɓ⁴5O/ṖṪOṁṪḋg’ḃ⁽×ỵÄŻ>⁸Sị“÷ñıÐ€½µ©¡ñ‘

```

Try it online!

A monadic link taking the zero-indexed count of days since 1958-01-01 as a integer argument and returning an integer.

Thanks to @JonathanAllan for saving a byte!
> 3 votes

# Answer
# AWK, 98 bytes

```
{m=$1*12+$2-23496}1,$0=m<1?0:m<181?6:m<277?9:m<337?10:m<445?12:m<557?15:m<589?25:27+(m>666&&m<746)

```

Try it online!

Input format: `YYYY MM DD`
> 1 votes

# Answer
# JavaScript (ES6), 95 bytes

Expects a number of days since `1957-12-31`.

```
n=>[x=0,5479,2922,1826,3287,3408,975,2373,2406].map((d,i)=>x-=(n-=d)>0&&~('52012910'[i]||~1))|x

```

Try it online!

This is however a bit longer than @FabrizioCalderan's answer, even if it is fixed to use days instead of months.
> 1 votes

# Answer
# x86 (32-bit) assembly, 43 bytes (13 bytes code + 30 bytes data)

This routine expects input in `ax` as a signed short giving number of days since 1950-01-01, and returns output in `al` (clobbering `edi` along the way).

```
    .text
    .globl eu_members
eu_members:
    mov $.Ltbl-1, %edi
.Lloop:
    inc %edi
    scas (%edi), %ax
    jg .Lloop
    mov (%edi), %al
    ret
    .section .rodata
.Ltbl:
    .short 2921
    .byte 0
    .short 8400
    .byte 6
    .short 11322
    .byte 9
    .short 13148
    .byte 10
    .short 16435
    .byte 12
    .short 19843
    .byte 15
    .short 20818
    .byte 25
    .short 23191
    .byte 27
    .short 25597
    .byte 28
    .short 32767
    .byte 27

```

Exact opcodes of the code part (in a linked context so that the relocation of .Ltbl doesn't confuse things):

```
0804930b <eu_members>:
 804930b:       bf 49 a0 04 08          mov    $0x804a049,%edi
 8049310:       47                      inc    %edi
 8049311:       66 af                   scas   %es:(%edi),%ax
 8049313:       7f fb                   jg     8049310 <eu_members+0x5>
 8049315:       8a 07                   mov    (%edi),%al
 8049317:       c3                      ret

```

And here's the test harness I used (note that the assembly code is not PIC safe, so on Debian or Ubuntu systems you will need to pass `-no-pie` to gcc):

```
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>

unsigned char eu_members_wrap(short days_since_1950_01_01) {
    unsigned char res;
    __asm__("call eu_members" : "=a"(res) : "0"(days_since_1950_01_01) : "edi", "cc");
    return res;
}

int main(int argc, char* argv[]) {
  struct tm tm;
  time_t epoch, req;
  short days_since_epoch;
  memset(&tm, 0, sizeof(tm));
  tm.tm_year = 50;
  tm.tm_mon = 0;
  tm.tm_mday = 1;
  epoch = mktime(&tm);
  memset(&tm, 0, sizeof(tm));
  tm.tm_year = atoi(argv[1]) - 1900;
  tm.tm_mon = atoi(argv[2]) - 1;
  tm.tm_mday = atoi(argv[3]);
  req = mktime(&tm);
  days_since_epoch = (((unsigned int) (req - epoch)) / (24 * 60 * 60));
  /* printf("epoch = %ld, req = %ld\n", epoch, req);
  printf("Raw number of days: %hd\n", days_since_epoch); */
  printf("EU members: %hhu\n", eu_members_wrap(days_since_epoch));
  return 0;
}

```
> 1 votes

# Answer
# Perl 5, 46 bytes

```
($q,%d)=split;$q--while!exists$d{$q};say$d{$q}

```

Try it online!

...or try like this on some decent command line:

```
query=19730101
data="0 0 19580101 6 19730101 9 19810101 10 19860101 12 19950101 15 20040501 25 20070101 27 20130701 28 20200201 27"
echo "$query $data" | perl -nE '($q,%d)=split;$q--while!exists$d{$q};say$d{$q}'

```
> -3 votes

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


title: Bucket and Minimize

text:
# Question
Title: Bucket and Minimize
The challenge - given a numeric list L and an integer N as inputs, write a function that:

1. finds the bucket sizes for L such that it is split into N *whole* buckets of equal or near-equal size, and
2. returns for each element in L the minimum of that element's bucket.

Example -

```
L=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
N=5

```

Compute the bucket sizes with the following:

\\$\left \lfloor \frac{| L |}{N} \right \rfloor + 1\\$ elements go into \\$|L| \bmod N\\$ buckets, and

\\$\left \lfloor \frac{| L |}{N} \right \rfloor \\$ go into the rest,

where |L| is the length of L. For the above, we get

`floor(12/5)+1` into `12 mod 5` buckets, and `floor(12/5)` in the rest:

```
[[0, 1, 2], [3, 4, 5], [6, 7], [8, 9], [10, 11]]

```

Finally, we output a list where each element is the minimum of its bucket:

```
[0, 0, 0, 3, 3, 3, 6, 6, 8, 8, 10, 10]

```

Some test cases:

```
In -> Out

[1, 2, 3, 4], 1 -> [1, 1, 1, 1]

[1, 2, 3, 4], 2 -> [1, 1, 3, 3]

[0, 2, 4, 6, 8], 3 -> [0, 0, 4, 4, 8]

[9, 3, 0, 1, 5, 7, 4, 6, 8, 10, 12, 11, 2, 13], 5 -> [0, 0, 0, 1, 1, 1, 4, 4, 4, 10, 10, 10, 2, 2]

[3, 0, -2, 0, -1], 2 -> [-2, -2, -2, -1, -1]

```

This is a code golf challenge. Shortest answer in bytes wins. Standard loopholes apply and such.

Edit:

1. you may assume L is not empty
2. you do not have to handle the case where N\>|L|
3. your answer should return a flat list

Sandbox

# Answer
> 6 votes
# APL (Dyalog Unicode), 40 bytesSBCS

Anonymous infix lambda. Takes \\$N\\$ as left argument and \\$L\\$ as right argument.

```
{p/⌊/¨(-p)↑¨↑∘⍵¨+\p←1+@(⍳⍺|l)⌊⍺⍴⍺÷⍨l←≢⍵}

```

Try it online!

`{``}`\\$⍺:=N,\ ⍵:=L\\$

`l←≢⍵`\\$l:=|L|\\$

`⍺÷⍨`\\$l\over N\\$

`⍺⍴`\\$(\underbrace{\frac{l}N,\frac{l}N,\frac{l}N,\cdots,\frac{l}N}\_{N\text{ elements}})\\$

\\$(\underbrace{\left\lfloor\frac{l}N\right\rfloor,\left\lfloor\frac{l}N\right\rfloor,\left\lfloor\frac{l}N\right\rfloor,\cdots,\left\lfloor\frac{l}N\right\rfloor}\_{N\text{ elements}})\\$

`1+@(``)` increment **at** the following indices:

`⍺|l`\\$|L|\bmod N\\$

\\$(1,2,3,…,|L|\bmod N)\\$

`p←`\\$p:=(\underbrace{\overbrace{1+\left\lfloor\frac{l}N\right\rfloor,1+\left\lfloor\frac{l}N\right\rfloor,\cdots,1+\left\lfloor\frac{l}N\right\rfloor}^{|L|\bmod N\text{ elements}},\left\lfloor\frac{l}N\right\rfloor,\left\lfloor\frac{l}N\right\rfloor,\cdots,\left\lfloor\frac{l}N\right\rfloor}\_{|n|\bmod N\text{ elements}})\\$

`+\` cumulative sum of that list

`↑∘⍵¨` for each element, take that many elements from \\$L\\$

`(-p)↑¨` for each list, take as many trailing elements as the corresponding number in \\$p\\$

`⌊/¨` minimum of each list

`p/` replicate each minimum by the the corresponding number in \\$p\\$

# Answer
> 6 votes
# Jelly, 7 bytes

```
œsṂṁ$€F

```

A dyadic Link accepting `L` on the left and `N` on the right which yields a list as specified.

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

(Also `œsµṂṁ)F` is the same.)

### How?

```
œsṂṁ$€F - Link: list of order-able items, L; positive integer, N
œs      - split L into N chucks, longer ones to the left
     €  - for each chunk:
    $   -   last two links as a monad - i.e. f(chunk):
  Ṃ     -     minimum of chunk
   ṁ    -     mould like chunk
      F - flatten

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~101~~  87 bytes

Takes input as `(array)(n)`.

```
a=>n=>a.map(w=_=>--w?m:m=Math.min(...a.slice(p,p+=w=L/n+(i++<L%n)|0)),L=a.length,i=p=0)

```

Try it online!

## How?

### Variables

* \\$L\\$ is the length of the input array
* \\$i\\$ is the ID of the current bucket
* \\$w\\$ is the width of the current bucket
* \\$m\\$ is the minimum value in the current bucket
* \\$p\\$ is a pointer to the starting point of the next bucket

### Commented

```
a => n =>                     // given the input array a[] and the integer n
  a.map(w =                   // initialize w to a non-numeric value
  _ =>                        // for each value in a[]:
    --w ?                     //   decrement w; if it's not equal to 0:
      m                       //     append the current minimum
    :                         //   else:
      m =                     //     append the updated value of m
        Math.min(             //       which is the minimum value found in
          ...a.slice(         //         the slice of a[]
            p,                //           starting at p
            p +=              //           and ending at the updated value of p (-1):
              w =             //             update w:
                L / n +       //               floor(L / n) is the base width
                (i++ < L % n) //               add 1 if i is less than L mod n
                              //               (then increment i)
                | 0           //               apply the floor()
          )                   //         end of slice()
        ),                    //       end of Math.min()
    L = a.length,             //   initialize L
    i = p = 0                 //   start with i = p = 0
  )                           // end of map()

```

# Answer
> 4 votes
# , ~~52~~ ~~50~~ ~~47~~ ~~42~~ ~~39~~ ~~37~~ ~~35~~ ~~32~~ 27 bytes

```
](]#(<.//.~I.))[:+/-@[]\]=]

```

Try it online!

This solution doesn't use any of the arithmetic formulas. Instead it relies on geometric transformations.

We'll use the example

```
5 f 0 1 2 3 4 5 6 7 8 9 10 11

```

to see how the transformations work:

* `]=]` Does the input equal itself, elementwise? This converts the input to ones:

```
1 1 1 1 1 1 1 1 1 1 1 1

```
* `-@[]\` Split it into rows whose size is `5` (the left arg), filling the final partial row with zeros:

```
1 1 1 1 1
1 1 1 1 1
1 1 0 0 0

```
* `[:+/` Sum the rows:

```
3 3 2 2 2

```
* `] (...(...)) <above result>` Execute the verb in parens with that result (`3 3 2 2 2`) as the right arg, and the original list `]` as the left arg. Now we'll break down the verb in inner parens first...
* `<.//.~I.` This is a dyadic hook which first transforms the right arg `3 3 2 2 2` using `I.`, which duplicates the indexes in place according to the multiplier at each index. Thus `I. 3 3 2 2 2` gives:

```
0 0 0 1 1 1 2 2 3 3 4 4

```
* `<.//.~` Use this mask to group `/.~` the implicit left arg (the original list):

```
0 0 0  1 1 1  2 2  3 3  4  4  <-- Mask
0 1 2  3 4 5  6 7  8 9  10 11 <-- Original List

```
* `<./` Returning the min of each group:

```
0 3 6 8 10

```
* `]#( ... )` Returning to the verb in outer parens: Make right arg `]` (ie, `3 3 2 2 2`) copies of `#` the result of the verb in the inner parens. Thus: make 3 copies of the min of the first group, 3 copies of the min of the 2nd group, 2 copies of the min of the third group, etc:

```
0 0 0 3 3 3 6 6 8 8 10 10

```

# Answer
> 3 votes
# Pyth, 8 bytes

```
smLhSdcF

```

Try it online!

This answer is mostly straightforward in that `c` provides the appropriate splitting behaviour. After that, we map twice to each element of the inner list the element of that list which is minimal. The interesting part is performing this double map: `mLhSd` expands into `mmhSdd`.

# Answer
> 3 votes
# , ~~52~~ 47 bytes

```
function(L,n)ave(L,sort(seq(0,a=L)%%n),FUN=min)

```

Try it online!

`ave` replaces each member of a group with the value provided by `FUN` applied to that group; the rest is just figuring out the groups.

Thanks to Robin Ryder for -5 bytes.

# Answer
> 2 votes
# Python 3.8, 90 bytes

```
lambda L,N,x=0:sum([(w:=len(L)//N+(v<len(L)%N))*[min(L[x:(x:=x+w)])]for v in range(N)],[])

```

**Try it online!**

# Answer
> 2 votes
# CJam, 25 bytes

```
q~\_,@d/m]/{_,\[:e<]*}%e_

```

Try it online!

## Explanation

```
q~                         "Read whole input & eval";
  \                        "Swap the splitted-items down";
   _                       "Copy the list";
    ,                      "Find its length";
     @                     "Roll the 3rd-to-top on top";
      d                    "Convert the number to double";
       /                   "Divide them (resulting in a float)";
        m]                 "Find the ceiling of that number";
          /                "Divide the list into that many chunks";
           {         }%    "Map every item in that list";
            _,\            "Preserve the length of the list";
                :e<        "e< doesn't take a single list, so";
                           "we have to reduce by minimum";
               [   ]       "Turn this result into a list";
                    *      "Repeat the list that many times";
                       ]   "Put the result into a list";
                        e_ "Flatten the list";

```

# Answer
> 1 votes
# Python, 118 bytes

```
def f(L,N):l=len(L);s=l//N;m=l%N;return sum([[min(L[s*i+i*(m>0):s*i+s+i*(m>0)+(i<m)])]*(s+(i<m))for i in range(N)],[])

```

Try it online!

# Answer
> 1 votes
# Charcoal, 21 bytes

```
Ｆη⊞υＥ÷Ｌθ⁻ηι⊟θＦ⮌υＩＥι⌊ι

```

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

```
Ｆη

```

Loop from `N` down to `1`.

```
⊞υＥ÷Ｌθ⁻ηι⊟θ

```

Remove the last `|L|/N` elements of `L` and add them to a separate list.

```
Ｆ⮌υＩＥι⌊ι

```

Reverse the secondary list to restore the elements to their original order, but map each to their minimum before implicitly printing them on separate lines.

# Answer
> 1 votes
# ~~Perl 6~~ Raku, ~~66 65 63~~ 59 bytes

-4 bytes thanks to Jo King.

```
{flat map {.min xx$_},@^m.rotor((1,0 X+@m/$^n)Zxx@m%$n,$n)}

```

Try it online!

This function causes an exception when first executed, but subsequently works. In previous versions of Rakudo, it always worked, and I have filed a Rakudo bug. Thanks for helping me find it.

## Explanation

```
{                                                         } # anonymous function with parameters @m (array) and $n (bucket size)
                                       @m/$^n               # calculate bucket size: length(@m) / $n
                                (1,0 X+      )              # make a list consisting of 1 + bucket-size, bucket-size
                                                            # using the cross-product metaoperator X with operator +
                                              Zxx@m%$n,$n   # repeat (1 + bucket-size) length(@m) % $n times
                                                            # and repeat bucket-size $n times (* didn't work)
                                                            # using the zip metaoperator Z with operator xx
                      @^m.rotor(                         )  # take batches of those sizes from the list @m
      map {.min xx$_},  # replace each bucket with its minimum repeated by its length
 flat                   # flatten the list

```

# Previous version, ~~65~~ 61 bytes

```
{$/=$^m/$^n;flat map {.min xx$_},$m.rotor(1+$/xx$m%$n,$/xx*)}

```

Try it online!

## Explanation

```
{                                                           } # anonymous function with params $m (array) and $n (bucket size)
 $/=$^m/$^n;                                                  # calculate minimum bucket size $/
                                          1+$/xx$m%$n         # take (length of m)%n batches of size 1+$/
                                                     ,$/xx*   # and then as many batches of size $/ as possible
                                 $m.rotor(                 )  # from the list $m
                 map {.min xx$_},                             # replace each bucket with its minimum repeated by its length
            flat                                              # flatten the list

```

# Answer
> 1 votes
# C (clang), ~~107~~ 105 bytes

```
Z,x,y,i,m;f(*a,z,n){for(x=z%n,Z=z/n;m=*a,y=Z,z;a+=y)for(z-=i=y+=x-->0;i--;)wmemset(a,m=a[i]<m?a[i]:m,y);}

```

Try it online!

Thanks to @ceilingcat for saving 2

# Answer
> 1 votes
# 05AB1E, ~~7~~ 5 bytes

```
äεWδ,

```

-2 bytes thanks to *@Grimmy*.

Prints each of the integers on a separated line.

Try it online or verify all test cases.

Outputting as a list would be **6 bytes** instead:

```
äεWδ]˜

```

Try it online or verify all test cases.

**Explanation:**

```
ä       # Split the (implicit) input-list into the (implicit) input-integer
        # amount of pieces, with smaller pieces at the left side if not all are equal
 ε      # Map each inner integer-list to:
  W     #  Push the minimum (without popping the list itself)
   δ    #  Using this minimum, apply to each value in the list:
    ,   #   Print (this minimum) with trailing newline

ä       # Split the (implicit) input-list into the (implicit) input-integer
        # amount of pieces, with smaller pieces at the left side if not all are equal
 ε      # Map each inner integer-list to:
  W     #  Push the minimum (without popping the list itself)
   δ    #  Using this minimum, apply to each value in the list:
    ]   #   Close both this double-vectorized apply-each, as well as the map itself,
        #   leaving the minimums in the inner lists after the apply-each is finished
     ˜  # Flatten this list of integer-lists
        # (after which the resulting list is output implicitly as result)

```

# Answer
> 1 votes
# Haskell, ~~158~~ 145 bytes

*Thank you @SirBogman and @PostRockGarfHunter for saving 13 bytes and for the great tip*

Please feel free to improve it.

```
l%n=map(minimum.o)[0..t-1]where(t,w,v,g,a)=(length l,t`div`n,w+1,t`mod`n*v,map(l!!));n&b=div n b*b;o i|i<g=a[i&v..i&v+w]|b<-g+(i-g)&w=a[b..b+w-1]

```

## Explanation

```
list % n=
  map
  (minimum . sublist)
  [0..listSize - 1]
  where
    (listSize, widthLastBlocks, widthFirstBlocks, lengthFirstBlocks, indecesToElem)=
      (length l                        -- t
      ,listSize`div`n                  -- w
      ,widthLastBlocks+1               -- v
      ,listSize`mod`n*widthFirstBlocks -- g
      ,map(list!!))                    -- a

    n & b = div n b * b -- bigest multiple of b smaller than n

    sublist i           -- o
      |i < lengthFirstBlocks =
        indecesToElem [i & widthFirstBlocks
                       ..
                       i&widthFirstBlocks + widthFirstBlocks - 1]
      |b <- lenghtFirstBlocks + (i - lengthFirstBlocks) & widthLastBlocks =
        indecesToElem [b..b + widthLastBlocks - 1]

```

# Answer
> 1 votes
# Ruby, ~~91~~ 77 bytes

```
->l,n{(0..z=l.size).flat_map{|x|(k=l.slice!(0,z/n+(z%n>x ?1:0))).map{k.min}}}

```

Try it online!

# Answer
> 1 votes
# Haskell, 116 bytes

```
p=replicate
[]&_=[]
f&(x:xs)=(p x$minimum$take x f)++(drop x f)&xs
f%n|(q,r)<-divMod(length f)n=f&((p r$q+1)++p n q)

```

Try it online!

The `%` operator is the bucket and minimize function, where `f` is the list and `n` is the bucket size. The `&` operator is a helper that repeats `x` times the minimum of the first `x` elements of the list `f`, where `x` is the head of the right parameter list. The sum of the right parameter list may be greater than the length of the left parameter list, but the left parameter list must be divided evenly.

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


# Question
Title: Choose 3 strings and output the exact minimum Hamming distance between any pair
Consider \\$3\\$ binary strings of length \\$n\\$ chosen independently and uniformly at random. We are interested in computing the exact expected minimum Hamming distance between any pair. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.

# Task

Given an input n between 2 and 10, inclusive, consider \\$3\\$ binary strings of length \\$n\\$ chosen independently and uniformly at random. Output the exact expected minimum Hamming distance between any pair.

Output should be given as a fraction.

Your code should run in TIO without timing out.

# Answer
> 8 votes
# Pari/GP, ~~92~~ 90 bytes

2 bytes saved thanks to @Nicolas!

```
n->sum(a=0,n,sum(b=0,n-a,sum(c=0,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*min(a+b,min(a+c,b+c)))))/4^n

```

Try it online!

$$ f(n) = \frac{1}{4^n} \sum\_{\substack{a+b+c+d=n\\a,b,c,d\geq 0}} \binom{n}{a,b,c,d}\min(a+b,a+c,b+c)$$

A more direct brute force approach may be shorter in some languages, but I'm not sure if that's true for Pari. Anyway, it's a shame that Pari's `min` only accepts two arguments.

I can avoid the `min` and be about 6 times faster, but the compensating additional code makes it longer. Maybe in another language this is the shorter way. And maybe it is possible to simplify further and get rid of the innermost sum.

```
n->sum(a=0,n,sum(b=a,n-a,sum(c=b,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*(a+b)*6/(1+(a==b)+(b==c))!)))/4^n

```

Try it online!

# Answer
> 2 votes
# Jelly, 31 bytes

```
Ḷṗ4S⁼¥Ƈɓ!×Ṗṁ4SƝṂƲ}:!P$}ð€S,4*$}

```

A monadic Link accepting an integer which yields a pair of integers, `[numerator, denominator]` (not reduced to simplest form).

**Try it online!** Or see all of n=2 to 10 reduced to simplest form.

### How?

Uses the same approach as Christian Sievers' Pari/GP answer

```
Ḷṗ4S⁼¥Ƈɓ!×Ṗṁ4SƝṂƲ}:!P$}ð€S,4*$} - Link: integer, n
Ḷ                               - lowered range -> [0..n-1]
 ṗ4                             - Cartesian power 4 (all length 4 tuples using alphabet [0..n-1]
      Ƈ                         - filter keep those for which:
     ¥                          -   last two links as a dyad:
   S                            -     sum
    ⁼                           -     equals n?
       ɓ               ð€       - for each tuple do f(n, tuple):
        !                       -   factorial = n*(n-1)*...*1
                 }              -   use right argument:
                Ʋ               -     last four links as a monad:
          Ṗ                     -       pop i.e. (a,b,c,d)->(a,b,c)
           ṁ4                   -       mould like 4 -> (a,b,c,a)
              Ɲ                 -       for neighbours:
             S                  -         sum -> (a+b,b+c,c+a)
               Ṃ                -       minimum
         ×                      -   multiply
                      }         -   use right argument:
                     $          -     last two links as a monad:
                   !            -       factorial -> (a!,b!,c!,d!)
                    P           -       product -> a!×b!×c!×d!
                  :             -   integer division
                         S      - sum
                              } - use right argument:
                             $  -   last two links as a monad:
                           4    -     four
                            *   -     exponentiate -> 4^n
                          ,     - pair

```

# Answer
> 2 votes
# 05AB1E, 26 bytes

```
Ý4ãʒOQ}ε¨Ćü+ßI!*y!P÷}O4Im‚

```

Port of *@JonathanAllan*'s Jelly answer, which uses the same formula as @ChristianSievers's Pari/GP answer.
Just like his answer, the output is not reduced to its simplest form.

Try it online or verify all test cases.

**Explanation:**

```
Ý                 # Push a list in the range [0, (implicit) input-integer]
                  # (NOTE: Jonathan's Jelly answer uses the range [0,input) instead of
                  #  [0,input], but that doesn't pose an issue, since the mapped value will
                  #  result in 0, not affecting the total sum)
 4ã               # Create all possible quartets by using the cartesian product with 4
   ʒ              # Filter these quartets by:
    O             #  Take the sum
     Q            #  And check if it's equal to the (implicit) input-integer
   }ε             # After the filter: map each remaining quartet [a,b,c,d] to:
     ¨            #  Remove the last item d: [a,b,c]
      Ć           #  Enclose the list, appending its own head: [a,b,c,a]
       ü+         #  Sum each consecutive pair: [a+b,b+c,c+a]
         ß        #  Pop and push the minimum of this
          I!      #  Push the input, and take its factorial
            *     #  Multiply both by each other
             y!   #  Take the factorial of each value in the quartet: [a!,b!,c!,d!]
               P  #  Take the product of this: a!*b!*c!*d!
                ÷ #  Integer-divide the two: (min(a+b,b+c,c+a)*n!) // (a!*b!*c!*d!)
    }O            # After the map: take the sum of all values in the list
       I          # Push the input-integer again
      4 m         # And take 4 to the power this
         ‚        # And finally pair both together
                  # (after which this pair is output implicitly as result)

```

---
Tags: code-golf, restricted-time
---


title: Super permutations

text:
# Question
Title: Super permutations
# Super permutations

Input: A string
The program should loop through all lengths of the input (decrementing one each time), generate all combinations with replacement of the string, then make permutations out of the generated combinations, and display all of the strings. They can be separated with anything (doesn't need to be a comma)

Example for the string 'abc':

```
a, b, c, aa, ab, ac, ba, bb, bc, ca, cb, cc
aaa, aab, aac, aba, abb, abc, aca, acb, acc
baa, bab, bac, bba, bbb, bbc, bca, bcb, bcc
caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc

```

The values don't necessarily have to be sorted.
Avoid any standard loop holes.

# Answer
> 16 votes
# Scratch 3.0, 65 blocks / ~~637~~ 632 bytes

Look at y'all, having fun with your fancy shmancy permutation functions/map tools. Well, not I! ***No***, not I! When using Scratch, one has to do things themselves! You won't find any built-ins around these parts! *I'm just glad there still ain't any `goto`s ;)*

But more seriously, the image is split into 4 parts because *it's just soooo long* Press space to clear the lists before each run

And finally,

Try it on~~line~~ Scratch!

As SB Syntax:

```
when gf clicked
set[c v]to(0
ask()and wait
set[L v]to(length of(answer
add(1)to[b v
repeat((L)-(1
add(0)to[b v
end
repeat until<(c)=(1
set[s v]to(0
set[l v]to(1
repeat(length of[b v
change[s v]by(item(l)of[b v
change[l v]by(1
end
if<(s)=((L)*(L))>then
set[c v]to(1
end
set[r v]to(
set[l v]to(1
repeat(length of[b v
set[r v]to(join(r)(letter(item(i)of[b v])of(answer
change[i v]by(1
end
add(r)to[o v
replace item(1)of[b v]with((item(1)of[b v])+(1
set[j v]to(1
repeat(length of[b v
if<(item(j)of[b v])>(length of(answer))>then
replace item(j)of[b v]with(1
replace item((j)+(1))of[b v]with((item((j)+(1))of[b v])+(1
end
change[j v]by(1

```

*-5 bytes due to not being a silly billy and removing extranous spaces*

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

*-1 byte thanks to a'\_'*

```
ā€ã

```

Try it online!

# Answer
> 7 votes
# Jelly, 2 bytes

```
ṗJ

```

A monadic Link which accepts a list of characters and returns a list of lists of lists of characters.

**Try it online!** (footer formats as a grid)

### How?

```
ṗJ - list, S
 J - range of length of S
ṗ  - Cartesian power (vectorises)

```

If we must output a flat list of "strings" (lists of characters) we can add (tighten) for the cost of a byte.

# Answer
> 6 votes
# Haskell, 34 bytes

```
f s=init$mapM(\_->s)=<<scanr(:)[]s

```

Try it online!

Here's how it works, using input `s="abc"`:

```
                       scanr(:)[]s

```

Produces the suffixes of `s`, `["abc","bc","c",""]`, by prepending each character in turn to the front and tracking the intermediate results.

```
         mapM(\_->s)

```

Uses the list monad to map each element to `s`, that is, `'xy'-> ["abc","abc"]`, and take multiply them as a Cartesian product, here giving `["aa","ab","ac","ba","bb","bc","ca","cb","cc"]`.

```
         mapM(\_->s)=<<scanr(:)[]s

```

Uses `=<<` as `concatMap` to take the function above that uses `mapM` and apply it to each of the suffixes, thereby producing the Cartesian products of copies of `s` numbering from 0 to its length, in a single list.

```
    init$

```

Removes the empty string, produces from the suffix of length `0`.

```
f s=

```

Declares the function.

# Answer
> 5 votes
# 05AB1E, 6 bytes

```
gENIã)

```

Try it online!

# Explanation

```
gENIã)
 E     # foreach in...
g      # the input
    ã  # find the cartesian product of...
   I   # the input...
  N    # repeat N
     ) # wrap the final stack to an array
       # implicit output of the top element

```

# Answer
> 3 votes
# , 16 bytes

```
a:-.~[:,#\{@#"{<

```

Try it online!

* `a:-.~` Remove empty boxes from...
* `[:,` The flatten of...
* `{@#"{` The Catalog (cross prod) of `{@`...
* `#\{@#"{<`
    + `<` The boxed input...
    + `#"{` Copied this many times...
    + `#\` 1, 2, ... N, where N is the input length. That is, we copy the input once, then twice, ... then N times, taking the Catalog of each of those.

# Answer
> 3 votes
# PHP, ~~176~~ ~~174~~ ~~173~~ ~~171~~ ~~170~~ 166 bytes

```
$c=$t=count($u=array_values(array_unique(str_split($argn))));for($s=1;$i<$t**$t;){$i-$c?:[$s++,$c*=$t,$i=0];for($k=$i++,$j=0;$j<$s;$j++,$k/=$t)echo$u[$k%$t];echo',';}

```

Try it online!

-4 bytes thanks to @Ismael Miguel.

Method: simply count in base N, where N is the number of unique characters in the input string.

# Answer
> 3 votes
# PowerShell, 42 bytes

```
($a=$args)|%{($p=$p|%{$t=$_;$a|%{$t+$_}})}

```

Try it online.

Expects input via splatting.

# Answer
> 2 votes
# Python 3, 95 bytes

```
import itertools as i;lambda s:[''.join(p)for l in range(len(s))for p in i.product(s,repeat=l)]

```

Try it online

# Answer
> 2 votes
# Burlesque,  ~~5~~  4 bytes

```
sacb

```

Try it online!

-1 thanks to DeathIncarnate!

```
sa    # Duplicate the input and get it's length
  cb  # Get all combinations of the input characters up to the length of the input

```

# Answer
> 2 votes
# Python 2, ~~69~~ 68 bytes

```
f=lambda s,A={''}:s in A and A or f(s,A|{a+c for a in A for c in s})

```

Try it online!

Outputs a set; includes the empty string.

# Python 2, 71 bytes

```
f=lambda s,A=[]:s in A and A or f(s,set(s)|{a+c for a in A for c in s})

```

Try it online!

If empty string is not allowed...

# Answer
> 2 votes
# JavaScript (ES7), 90 bytes

Returns a Set.

```
s=>new Set([...Array(n=(L=-~s.length)**~-L)].map(_=>(g=n=>n?[s[n%L-1]]+g(n/L|0):'')(n--)))

```

Try it online!

### Commented

```
s => new Set(            // build a set from
  [...Array(             //   an array of
    n =                  //   n entries, with:
      (L = -~s.length)   //     n = L ** (L - 1)
      ** ~-L             //     where L is the length of s + 1
  )]                     //
  .map(_ =>              //   for each entry:
    ( g = n =>           //     g is a recursive function taking n
        n ?              //       if n is not equal to 0:
          [s[n % L - 1]] //         output s[(n mod L) - 1]
                         //         or an empty string if it's undefined
          + g(n / L | 0) //         recursive call with floor(n / L)
        :                //       else:
          ''             //         stop recursion
    )(n--)               //     initial call to g; decrement n afterwards
  )                      //   end of map()
)                        // end of Set()

```

# Answer
> 2 votes
# Charcoal, 17 bytes

```
ＦＥθＸＬθ⊕κＥι✂⍘⁺ικθ¹

```

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

```
ＦＥθＸＬθ⊕κ

```

Loop over the substring lengths and raise the length to each power in turn.

```
Ｅι✂⍘⁺ικθ¹

```

Loop from each power to double its value and perform base conversion using the input string as the alphabet, then slice off the first character.

# Answer
> 2 votes
# Husk, 4 bytes

Total Husk novice, there may be better ways to golf this.

```
Mπŀ¹

```

Try it online!

# Explanation

```
  ŀ¹ Find the range [1, ..., len(input)]
Mπ   Map with cartesian power of input

```

# Answer
> 2 votes
# Ruby, 60 bytes

```
->s{a,*z=s.chars,'';z.product(*a.map{a+z}).map(&:join)-z|[]}

```

Try it online!

# Answer
> 1 votes
# Perl 6, 32 bytes

```
{flat [\X~] '',|[xx] .comb xx 2}

```

Try it online!

Anonymous code block that takes a string and returns a list of string including the length zero permutation.

# Answer
> 1 votes
# Pyth, 5 bytes

```
^LQSl

```

Try it here!

# Answer
> 1 votes
# , 112 bytes

```
function(S,s=sapply)cat(unlist(s(1:nchar(S),function(X)do.call('paste0',expand.grid(s(rep(S,X),strsplit,''))))))

```

Try it online!

Things that make you go Argh, strings in R.

Expands out to the following

```
cat(                                           # output the results
  unlist(                                      # collapse the list
    sapply(1:nchar(S),                         # for 1 to character length of S
      function(X)do.call('paste0',             # for each row from the grid paste characters together
         expand.grid(                          # create permutations
           sapply(rep(S,X),strsplit,''))))))   # replicate the string X times and split.

```

So we produce a lists of `[['a','b','c']]`, `[['a','b','c'],['a','b','c']]`, `[['a','b','c'],['a','b','c'],['a','b','c']]`. These are feed into `expand.grid` to produce the permutations.

Each row of the grid is pasted together with no gaps in the `do.call`.

As it is still in a list we apply `unlist` so that cat will be able to output it.

# Answer
> 0 votes
# Perl 5 `-lF`, 48 bytes

```
$"=',';map$k{$_}++||say,glob"{@F}"."{@F,''}"x$#F

```

Try it online!

---
Tags: code-golf, string, combinatorics, permutations
---