title: Stack Exchange Answerer

text:
# Question
Title: Stack Exchange Answerer
Oof! You've been coding the whole day and you even had no time for Stack Exchange!

Now, you just want to rest and answer some questions. You have ***T*** minutes of free time. You enter the site and see ***N*** new questions. To write an answer for each you'll need ***ti*** minutes. Of course, as a dedicated reputation gatherer, you want to answer as many questions as you can.

Can you write a program to calculate which questions do you have to answer to write maximum posts in ***T*** minutes?

## Input

First line of input consists `T` minutes you have for answering, and `N`, how many new questions are on the site.
The second line has N numbers: time you need to answer **qi** question.

## Output

Write either an array or numbers split with space: indexes of questions(counting from 0 or 1 - what is better for you) you should answer in order to write as many answers as you can. If you can't answer any questions, write nothing or anything to express that it's impossible. If there are several variants, write any.

## Examples

### Inputs Possible outputs

`60 5`
`30 5 10 20 3` `0 1 2 4`, `0 1 3 4` or `1 2 3 4`

`10 5`
`1 9 5 7 2` `0 2 4` or `0 3 4`

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

`60 5`
`48 15 20 40 3` `1 2 4` or `1 3 4`

`5 1`
`10`

`1 0`

And of course it's , so the shortest code in bytes wins.

# Answer
# Python 3.8, ~~81~~, ~~79~~, 75 bytes

Using the walrus operator `:=`:

```
lambda k,l:[i for j,i in sorted((v,k)for k,v in enumerate(l))if(k:=k-j)>=0]

```

Try it online!

-2 bytes thanks to @JoKing

-4 bytes thanks to @justhalf

# Python 3, ~~158~~, ~~137~~, ~~136~~, ~~130~~, ~~127~~, ~~117~~, ~~103~~, 95 bytes

```
def f(k,l):
 q=[]
 for j,i in sorted((v,k)for k,v in enumerate(l)):k-=j;q+=[i]*(k>=0)
 print(q)

```

Try it online!

-21 bytes thanks to @79037662 by limiting indentation to 1-space.

-14 bytes thanks to @ mypetlion

-8 bytes thanks to @justhalf

Both solutions ignore `N` parameter.
> 14 votes

# Answer
# 05AB1E, ~~9~~ ~~13~~ 12 bytes

```
ā<æʒ¹sèO@}éθ

```

Takes the inputs in the order: \\$q\_i\\$, \\$N\\$ (which is mostly ignored, see explanation below), \\$T\\$.
Uses 0-based indexing.

+4 bytes as bug-fix for test case `[1,1,1,1,1]` resulting in `[0,0,0,0,0]` instead of `[0,1,2,3,4]` (and now switched from 0-based to 1-based indexing).
-1 byte thanks to *@Grimmy* (and back to 0-based indexing again).

Try it online or verify all test cases or get all possible outputs for the test cases instead of just one.

**Explanation:**

```
             # Take the (implicit) input-list qi
ā            # and push a list in the range [1, list-length] without popping the input itself
 <           # Decrease each by 1 to make it 0-based: [0, list-length)
  æ          # Get the powerset of this list of indices
             #  i.e. [0,1,2] → [[],[0],[1],[0,1],[2],[0,2],[1,2],[0,1,2]]
   ʒ         # Filter this list of lists by:
    ¹        #  Push the first input-list qi again
     s       #  Swap to put the current list of the filter at the top of the stack
      è      #  Index each into the list qi
       O     #  Sum these values
        @    #  Check if the (implicit) input-integer is >= this sum
             #  (The very first iteration it will use the second input, which is the length N;
             #   every other iteration it will use the third input, which is the total time T.
             #   Since the very first inner list of the powerset will be the empty list,
             #   this causes no problems; which is how we ignore the mandatory length N input)
         }é  # After the filter: sort all remaining inner lists by length
           θ # Pop and leave the last one, which is (one of) the list(s) with the most items
             # (after which the result is output implicitly)

```
> 7 votes

# Answer
# Japt, ~~22~~ ~~21~~ ~~16~~ 15 bytes

```
ð à ñÊÔæÈxgU <V

```

Try it

```
ð à                 combinations of indexes of 1st input
    ñÊÔ             sorted by length and reversed
       æ            get first element returning true when passed throug...
        ÈxgU        elements of input at X indexes reduced by addition
               <V   less than 2nd input

```

Takes input as \[times...\], time , amount

Saved 1 stealing from @Shaggy ÈxgU
> 6 votes

# Answer
# JavaScript (V8), ~~117~~ ~~113~~ ~~110~~ ~~105~~ ~~85~~ ~~71~~ 63 bytes

*(-3 thanks to Ver Nick says Reinstate Monica)*

*(-20 thanks to Arnauld)*

*(-14 thanks to Shaggy)*

*(-8 thanks to tsh)*

```
a=>g=t=>(a[y=a.indexOf(i=Math.min(...a))]=t)<i?[]:[y,...g(t-i)]

```

Try it online!

Could probably be golfed some more...a function which takes input in three arguments: time, number of questions (not actually used), and an array of question times.

It will repeatedly find the smallest element in the array, and set it to the time available, removing it from the possibilities for the next iteration. It puts the index of the value into the output array.

Thanks to everyone who's contributed to golfing this answer...54 bytes shorter than the original!
> 5 votes

# Answer
# dzaima/APL, ~~15~~ ~~14~~ 13 bytes

```
+\∘<⍛≤+/⍛↑⍋⍤⊣

```

Try it online!

```
+\∘<⍛≤+/⍛↑⍋⍤⊣  train; left arg = ⍺ = t, right arg = ⍵ = T
     ≤         ⍺ <= ⍵
    ⍛          with ⍺ modified to
   <             sorted
+\∘              and then, cumulative sum
               so, cumulativeSum(sort(q)) ≤ T

          ⍋    the indices required for sorting
           ⍤⊣  applied on ⍺
               so, the output, sorted by question time, if T=∞

         ↑     take first ⍺ elements from ⍵ (⍺ is `+\∘<⍛≤`, ⍵ is `⍋⍤⊣`)
      +/⍛        but summing ⍺ first

```
> 5 votes

# Answer
# Jelly, 8 bytes

```
ṢÄ>¬TịỤ{

```

A dyadic Link accepting the question times on the left and the total time on the right which yields the 1-indexed indices.

**Try it online!** (footer calls the Link and prints a formatted version of its output.)

(If we *must* take the number of questions, this works as full program accepting: question times; total time; number of questions.)

### How?

```
ṢÄ>¬TịỤ{ - Link: ts; T        e.g. [1, 9, 5, 7, 2]; 10
Ṣ        - sort ts                 [1, 2, 5, 7, 9]
 Ä       - cumulative sums         [1, 3, 8,15,24]
  >      - greater than (T)?       [0, 0, 0, 1, 1]
   ¬     - logical NOT             [1, 1, 1, 0, 0]
    T    - truthy indices          [1, 2, 3]
       { - use left argument:
      Ụ  -   indices by value      [1, 5, 3, 4, 2]   (i.e index 4 has 2nd largest value)
     ị   - index into              [1, 5, 3]

```

---

Alternative 8:

```
ỤṁṢÄ>Ðḟɗ - indices-by-value moulded-like (cumulative-sums of sorted(ts) if not greater than T)

```

Try it online!
> 5 votes

# Answer
# , 44 41 bytes

```
function(m,t)order(t)[cumsum(sort(t))<=m]

```

Try it online!

Takes input as Time, times. Returns numeric() for empty output.

Order the times, take cumulative sum and then select the times where the cumulative sum is less than or equal to total time.

-1 in the end to get 0-index

-1 byte thanks to Giuseppe
-2 bytes since 0-index is no longer needed
> 4 votes

# Answer
# Japt `-h`, 14 bytes

Assumes `0` is not a valid unit of time.

```
ð à ñÊfÈxgU §V

```

Try it

```
ð à ñÊfÈxgU §V     :Implicit input of array U=q and integer V=T
ð                  :0-based indices of U
  à                :Combinations, which, fortunately, includes the empty array, covering the last test case.
    ñ              :Sort by
     Ê             :  Length
      f            :Filter
       È           :By passing each throughout a function
        x          :  Reduce by addition
         gU        :    After indexing each back in to U
            §V     :  Less than or equal to V?
                   :Implicit output of last element

```

---

Or, if we *have* to take `N` as input (or `0` *is* a valid unit of time).

```
o à ñÊfÈxgV §W

```

Try it

Where `U=N`, `V=q`, `W=T`, `o` creates the range `[0,U)` and everything else is as above.
> 4 votes

# Answer
# Ruby, ~~68 64 60 59~~ 58 bytes

```
->t,q{q.map.with_index.sort.reject{|x,|0>t-=x}.map &:last}

```

Try it online!
> 4 votes

# Answer
# Red, 133 bytes

```
func[t b][s: 0 sort collect[foreach n sort collect[repeat i length? b[keep/only
reduce[b/:i i]]][if(u: s + n/1)<= t[s: u keep n/2]]]]

```

Try it online!

1-indexed. Ignores `N`
> 4 votes

# Answer
# JavaScript (ES10),  ~~78~~  75 bytes

*Saved 3 bytes thanks to @Neil*

Takes input as `(T)(list)`. Ignores `N`.

```
t=>a=>a.map((...x)=>x).sort(([a],[b])=>a-b).flatMap(([v,i])=>(t-=v)<0?[]:i)

```

Try it online!
> 3 votes

# Answer
# Charcoal, 44 bytes

```
Ｎθ≔ＥＮ⟦Ｎι⟧ηＷ∧η¬‹θ§⌊η⁰«≔⌊ηι≧⁻§ι⁰θ≔Φη⁻⌕ηιλη⟦Ｉ⊟ι

```

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

```
Ｎθ

```

Input `T`.

```
ＥＮ⟦Ｎι⟧η

```

Input `N` and make a list of `N` questions with their original index.

```
Ｗ∧η¬‹θ§⌊η⁰«

```

Loop until there are no more questions that can be answered in the remaining time.

```
≔⌊ηι

```

Get the shortest question and its original index.

```
≧⁻§ι⁰θ

```

Subtract the question's time from the time remaining.

```
≔Φη⁻⌕ηιλη

```

Remove the question from the list of questions.

```
⟦Ｉ⊟ι

```

Print the question's original index.
> 2 votes

# Answer
# Python 3, 72 bytes

recursive solution, generating line separated console output

```
def f(T,L):
 if L:M=min(L);I=L.index(M);L[I]=T;T<M or(print(I),f(T-M,L))

```

Try it online!

```
def f(T,L):
 if L:            # do nothing if input is empty
  M=min(L)
  I=L.index(M)
  L[I]=T          # set found list item to remaining time (item will be ignored next iteration)
  T<M or(print(I),f(T-M,L))   # if the found question can be answered in the given time output and find next

```
> 2 votes

# Answer
# , 16 bytes

```
(>:+/\@/:~)#/:@]

```

Try it online!

Attempt at an explanation:

```
>:                create mask of left arg greater than or equal to...
  +/\@/:~         cummulative sum of sorted right arg
         #        copy where true
          /:@]    from permutation that sorts right arg

```
> 2 votes

# Answer
# **C++11, ~~293~~ ~~221~~ 219 bytes**

Here to decimate the competition I am not.

Notes :

1. g++ allows for variable-sized arrays. It saves bytes, so that what I did.
2. the range-based for loops needs a reference to write correctly?!

```
#include<iostream>
void f(int t,int c,int*a){int m,i;int y[c];for(int&b:y)b=0;for(;;){for(m=-1;y[++m]&m<c;);for(i=-1;++i<c;)if(a[m]>=a[i]&!y[i])m=i;if(t>=a[m]&!y[m]){y[m]=1;t-=a[m];}else break;}for(i=-1;++i<c;)if(y[i])std::cout<<i<<' ';}

```

Expanded version :

```
#include <iostream>

void AnswerMostOfTheQuestions(int time_left, int question_count, int answer_times[]) {
  int minimum_term;
  bool is_answered[question_count];
  for(bool& b : is_answered)
    b = 0 ; // No questions have been answered
  while (1) {
    // Find the first unanswered question
    for (minimum_term = 0; is_answered[minimum_term] and minimum_term < question_count; ++minimum_term);
    // Find unanswered question which takes least time to answer
    for (int i = 0; i < question_count; ++i)
      if(answer_times[minimum_term] >= answer_times[i] && ! is_answered[i])
        minimum_term = i;
    if (time_left >= answer_times[minimum_term] &&  not is_answered[minimum_term]) {
      // Answer question (which consumes time)
      is_answered[minimum_term] = true;
      time_left -= answer_times[minimum_term];
     }
    else break;
  }
  // Print index of every answered question
  // 'cause returning them is a waste of bytes to implement
  // Just echo it to a file or something
  for (int i = 0; i < question_count; ++i)
    if(is_answered[i])
      std::cout<<i<<' ';
}

int main(int c, char** v) {
  int question_count = atoi(v[2]), free_time = atoi(v[1]);
  int answer_times[question_count];
  for (int i = 0; i < question_count; ++i)
    answer_times[i] = atoi(v[i+3]);
  // Run solution
  AnswerMostOfTheQuestions(free_time, question_count, answer_times);
}

```

Try it online!
> 2 votes

# Answer
# Husk, 9 bytes

```
↑#≤²∫O¹ηÖ

```

Try it online! Outputs an empty list if no solution is possible.
> 1 votes

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


title: Greatest common substring

text:
# Question
Title: Greatest common substring
Create a program or function which takes a list of strings as input, and outputs the longest string that is a substring of *all* input strings. If there are several substrings of equal length, and no longer substring, output any one of them.

* This may mean outputting the empty string.
* If there are several valid outputs, you may output any one of them. You are not required to give consistent output for a given input so long as the output is always valid.
* There will always be at least one string in the input, but there might not be a non-empty string.
* All printable ASCII characters may appear in the input. You may assume those are the only characters that appear.
* You may take input or produce output by any of the default methods.
* Standard loopholes aren't allowed.
* This is - the fewer bytes of code, the better.

## Test cases:

`[Inputs] -> [Valid outputs (choose one)]`

```
["hello", "'ello"] -> ["ello"]
["very", "much", "different"] -> [""]
["empty", "", "STRING"] -> [""]
["identical", "identical"] -> ["identical"]
["string", "stRIng"] -> ["st", "ng"]
["this one", "is a substring of this one"] -> ["this one"]
["just one"] -> ["just one"]
["", "", ""] -> [""]
["many outputs", "stuptuo ynam"] -> ["m", "a", "n", "y", " ", "o", "u", "t", "p", "s"]
["many inputs", "any inputs", "ny iii", "yanny"] -> ["ny"]
["%%not&", "ju&#st", "[&]alpha_numeric"] -> ["&"]

```

# Answer
# Brachylog (v2), ~~3~~ 9 bytes

```
{sᵛ}ᶠlᵒtw

```

Try it online!

Full program. Input from standard input (as a JSON-style list of strings), output to standard output.

## Explanation

```
{sᵛ}ᶠlᵒtw
 s         Find a substring
  ᵛ          of every element {of the input}; the same one for each
{  }ᶠ      Convert generator to list
     lᵒt   Take list element with maximum length
        w  Output it

```

Apparently, the tiebreak order on `s` is not what it is in nearly everything else in Brachylog, so we need to manually override it to produce the longest output. (That's a bit frustrating: four extra characters for the override, plus two grouping characters because Brachylog doesn't parse two metapredicates in a row.)

Brachylog's `s` doesn't return empty substrings, so we need a bit of a trick to get around that: instead of making a function submission (which is what's normally done), we write a full program, outputting to standard output. That way, if there's a common substring, we just output it, and we're done. If there isn't a common substring, the program errors out – but it *still* prints nothing to standard output, thus it outputs the null string as intended.
> 10 votes

# Answer
# Python 2, 82 bytes

```
f=lambda h,*t:h and max(h*all(h in s for s in t),f(h[1:],*t),f(h[:-1],*t),key=len)

```

Try it online!

Takes input splatted. Will time out for inputs where the first string is long.

The idea is to take substrings of the first strings `h` to find the longest one that appears in all the remaining strings `t`. To do so, we recursively branch on removing the first or last character of `h`.

---

**Python 2, 94 bytes**

```
lambda l:max(set.intersection(*map(g,l)),key=len)
g=lambda s:s and{s}|g(s[1:])|g(s[:-1])or{''}

```

Try it online!

A more direct method. The auxiliary function `g` generates the set all substrings of `s`, and the main function takes the longest one in their intersection.
> 9 votes

# Answer
# Jelly, ~~12~~ 6 bytes

```
Ẇ€f/ṫ0

```

Try it online!

Thanks to @JonathanAllan for saving 6 bytes!
> 7 votes

# Answer
# Ruby 2.6, ~~76 59~~ 54 bytes

```
->a{*w=a;w.find{|r|w<<r.chop<<r[1..];a.all?{|s|s[r]}}}

```

Try it online! \- Ruby 2.5 version (56 bytes)

### How?

Create a list of potential matches, initially set to the original array. Iterate on the list, and if a string does not match, add 2 new strings to the tail of the list, chopping off the first or the last character. At the end a match (eventually an empty string) will be found.

Thanks Kirill L for -2 bytes and histocrat for another -2
> 7 votes

# Answer
# Zsh, ~~126 ...~~ 96 bytes

*-3 bytes from arithmetic for, -6 bytes from implicit `"$@"` (thanks roblogic), -5 bytes from removing unneeded `{` `}`, -1 byte from short form of `for`, -1 byte by using `repeat`, -1 byte by concatenating `for s ($b)` with its body, -13 bytes by changing the repeat loop out for some eval jank.*

```
for l
eval a=\( \$l\[{1..$#l},{1..$#l}\] \)&&b=(${${b-$a}:*a})
for s ($b)(($#x<$#s))&&x=$s
<<<$x

```

~~Try it online! Try it online!~~ Try it online!

We read all possible substrings into the array`a`, and then set `b` to the intersection of the arrays `a` and `b`. The construct `${b-$a}` will only substitue `$a` on the first iteration: Unlike its sibling expansion `${b:-$a}`, it will not substitute when `b` is set but empty.

```
for l;                              # implicit "$@"

# === OLD ===
{
    a= i=                           # empty a and i
    repeat $[$#l**2]                # compound double loop using div/mod
        a+=($l[++i/$#l+1,i%$#l+1])  # append to a all possible substrings of the given line
#               1+i/$#l             # 1,1,1...,  1,1,2,2,2,... ...,  n,n
#                       1+i%$#l     # 1,2,3...,n-1,n,1,2,3,... ...,n-1,n
#       a+=( $l[       ,     ] )    # append that substring to the array
# === NEW ===
    eval a=\( \
        \$l\[{1..$#l},{1..$#l}\] \  # The {bracket..expansions} are not escaped
    \) &&
# ===     ===
    b=( ${${b-$a}:*a} )
#         ${b-$a}                   # if b is unset substitute $a
#       ${       :*a}               # take common elements of ${b-$a} and $a
#   b=(               )             # set b to those elements
}
for s ($b)                          # for every common substring
    (( $#x < $#s )) && x=$s         # if the current word is longer, use it
<<<$x                               # print to stdout

```
> 5 votes

# Answer
# , ~~119~~ ~~116~~ ~~108~~ 106 bytes

```
function(S,`?`=nchar,K=max(?S),s=Reduce(intersect,lapply(S,substring,0:K,rep(0:K,e=K+1))))s[which.max(?s)]

```

Try it online!

Find all substrings of each string, find the intersection of each list of substrings, then finally return (one of) the longest.

*-3 bytes thanks to Kirill L.*

*-8 bytes using* `lapply` *instead of* `Map`

*-2 bytes thanks to Kirill L. again, removing braces*
> 5 votes

# Answer
# 05AB1E, ~~14~~ ~~9~~ 8 bytes

```
€Œ.«ÃéθJ

```

-6 bytes thanks to *@Adnan*.

Try it online or verify all test cases.

**Explanation:**

```
€Œ       # Get the substring of each string in the (implicit) input-list
  .«     # Right-reduce this list of list of strings by:
    Ã    #  Only keep all the strings that are present in both list of strings
     é   # Sort by length
      θ  # And pop and push its last item
         # The substrings exclude empty items, so if after the reduce an empty list remains,
         # the last item will also be an empty list,
       J # which will become an empty string after a join
         # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Perl 6, ~~62~~ 60 bytes

```
{~sort(-*.comb,keys [∩] .map(*.comb[^*X.. ^*]>>.join))[0]}

```

Try it online!

I'm a little annoyed the Perl 6 can't do set operations on lists of lists, which is why there's an extra `.comb` and `>>` in there.

~~Another annoying thing is that `max` can't take an function for how to compare items, meaning I have to use `sort` instead.~~ As pointed out in the comments, `max` *can* take an argument, however it ends up longer since I have to take into account `max` returning negative infinity when there are common substrings (Try it online!).
> 3 votes

# Answer
# Haskell, 80 bytes

```
import Data.List
f(x:r)=last$sortOn(0<$)[s|s<-inits=<<tails x,all(isInfixOf s)r]

```

Try it online!

Get all suffixes (`tails`) of the first word `x` in the list and take all prefixes (`inits`) of those suffixes to get all substrings `s` of `x`. Keep each `s` that `isInfixOf` `all` strings in the remaining list `r`. Sort those substrings by length (using the `(0<$)` trick) and return the last.
> 3 votes

# Answer
# TSQL query, 154 bytes

```
USE master
DECLARE @ table(a varchar(999)collate Latin1_General_CS_AI,i int identity)
INSERT @ values('string'),('stRIng');

SELECT top 1x FROM(SELECT
distinct substring(a,f.number,g.number)x,i
FROM spt_values f,spt_values g,@ WHERE'L'=g.type)D
GROUP BY x ORDER BY-sum(i),-len(x)

```

**Try it online**

Made case sensitive by declaring the column 'a' with collation containing CS (case sensitive).

Splitting all strings from 2540 starting positions(many identical) but the useful values range between 1 and 2070 and ending 0 to 22 characters after starting position, the end position could be longer by changing the type to 'P' instead of 'L', but would cripple performance.

These distinct strings within each rownumber are counted. The highest count will always be equal to the number of rows in the table variable '@'. Reversing the order on the same count will leave the substring with most matches on top of the results followed by reversed length of the substring will leave longest match with most matches on top. The query only select the top 1 row.

In order to get all answers, change the first part of the query to

> SELECT top 1with ties x FROM
> 3 votes

# Answer
## C# (Visual C# Interactive Compiler), ~~320~~ 257 bytes

```
l=>(string.Join(",",l.Select(s=>new int[s.Length*s.Length*2].Select((i,j)=>string.Concat(s.Skip(j/-~s.Length).Take(j%-~s.Length))))
.Aggregate((a,b)=>a.Intersect(b)).GroupBy(x=>x.Length).OrderBy(x =>x.Key).LastOrDefault()?.Select(y=>y)??new List<string>()));

```

Try it online!

Props to @Expired Data and @dana
> 3 votes

# Answer
# Retina 0.8.2, 48 bytes

```
M&!`(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)
O#$^`
$.&
1G`

```

Try it online! Explanation:

```
M&!`(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)

```

For each suffix of the first string, find the longest prefix that's also a substring of all of the other strings. List all of those suffix prefixes (i.e. substrings). If there are no matching substrings, we just end up with the empty string, which is what we want anyway.

```
O#$^`
$.&

```

Sort the substrings in reverse order of length.

```
1G`

```

Keep only the first, i.e. the longest substring.
> 3 votes

# Answer
# Japt v2.0a0 `-hF`, 8 bytes

```
Îã f@eøX

```

Thanks to Shaggy for saving 3 bytes

Try it

```
Îã              //Generate all substrings of the first string
 f@             //Filter; keep the substrings that satisfy the following predicate:
   e            //    If all strings of the input...
    øX          //    Contain this substring, then keep it
-h              //Take last element
-F              //If last element is undefined, default to empty string

```
> 2 votes

# Answer
# Japt `-h`, 8 bytes

(I could knock off the last 3 bytes and use the `-Fh` flag instead but I'm not a fan of using `-F`)

```
mã rf iP

```

Try it or run all test cases

```
mã rf iP     :Implicit input of array
m            :Map
 ã           :  Substrings
   r         :Reduce by
    f        :  Filter, keeping only elements that appear in both arrays
      i      :Prepend
       P     :  An empty string
             :Implicit output of last element

```
> 2 votes

# Answer
# Husk, 6 bytes

```
►LFnmQ

```

Try it online!
> 2 votes

# Answer
# Python 3, 137 bytes

```
def a(b):c=[[d[f:e]for e in range(len(d)+1)for f in range(e+1)]for d in b];return max([i for i in c[0]if all(i in j for j in c)],key=len)

```

Try it online!
> 1 votes

# Answer
# Python 2, 103 bytes

```
lambda b:max(reduce(set.__and__,[{d[f:e]for e in range(len(d)+2)for f in range(e)}for d in b]),key=len)

```

Try it online!

This is an anonymous lambda that transforms each element into the set of all substrings, then `reduce`s it by set intersection (`set.__and__`) and then returns the `max` element by `len`gth.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~147~~ 145 bytes

```
a=>{int i=0,j,m=0,k=a[0].Length;string s="",d=s;for(;i<k;i++)for(j=m;j++<k-i;)if(a.All(y=>y.Contains(s=a[0].Substring(i,j)))){m=j;d=s;}return d;}

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6),  ~~98~~  92 bytes

```
a=>(g=b=s=>a.every(x=>~x.indexOf(s))?b=b[s.length]?b:s:g(s.slice(0,-1,g(s.slice(1)))))(a[0])

```

Try it online!
> 1 votes

# Answer
# Perl 5 (`-aln0777F/\n/` `-M5.01` `-MList::util=max`), 99 bytes

may be golfed more certainly

```
map/(.+)(?!.*\1)(?{$h{$&}++})(?!)/,@F;say for grep{y///c==max map y///c,@b}@b=grep@F==$h{$_},keys%h

```

TIO
> 1 votes

# Answer
# Bash, ~~295~~ ~~166~~ 145

```
for l;{((f++));d=${#l};i=;for((;i++<d**2;)){ echo "${l:i/d:1+i%d}">>$f;};}
for j in *;{((f++));grep -xf$j $[j+1]>$f;};egrep "^.{$(wc -L<$f)}$" $f

```

Try it Online!

Not pretty but at least it works. We write the substrings to files `$f`, then `(e)grep` for longest common line.
. (Old) 166b with arrays
. Prototype script with comments
> 1 votes

# Answer
# Charcoal, 30 bytes

```
≔⊟θη≔⁰ζＦＬη«≔✂ηζ⊕ι¹ε¿⬤θ№κεＰε≦⊕ζ

```

Try it online! Link is to verbose version of code. This algorithm is more efficient as well as shorter than generating all substrings. Explanation:

```
≔⊟θη

```

Pop the last string from the input list into a variable.

```
≔⁰ζ

```

Zero out the substring start index.

```
ＦＬη«

```

Loop over all possible substring end indices. (Actually this loops from 0 excluding the length, so the value is adjusted later.)

```
≔✂ηζ⊕ι¹ε

```

Obtain the current substring.

```
¿⬤θ№κε

```

Check whether this substring is contained in all of the other input strings.

```
Ｐε

```

If it is then overprint any previously output substring.

```
≦⊕ζ

```

Otherwise try incrementing the substring start index.
> 1 votes

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

```
a=>(F=(l,n,w=a[0].substr(n,l))=>l?n<0?F(--l,L-l):a.some(y=>y.indexOf(w)<0)?F(l,n-1):w:"")(L=a[0].length,0)

```

Try it online!

```
a=>(                      // Main function
 F=(                      //  Helper function to run through all substrings in a[0]
  l,                      //   Length
  n,                      //   Start position
  w=a[0].substr(n,l)      //   The substring
 )=>
 l?                       //   If l > 0:
  n<0?                    //    If n < 0:
   F(--l,L-l)             //     Check another length
  :a.some(                //    If n >= 0:
   y=>y.indexOf(w)<0      //     Check whether there is any string not containing the substring
                          //     (indexOf used because of presence of regex special characters)
  )?                      //     If so:
   F(l,n-1)               //      Check another substring
  :w                      //     If not, return this substring and terminate
                          //     (This function checks from the longest substring possible, so
                          //      it is safe to return right here)
 :""                      //   If l <= 0: Return empty string (no common substring)
)(
 L=a[0].length,           //  Starts from length = the whole length of a[0]
 0                        //  And start position = 0
)

```
> 0 votes

# Answer
# Java (JDK), 158 bytes

```
a->{for(int l=a.get(0).length(),i=l,j;i>=0;i--)for(j=0;j<l-i;){var s=a.get(0).substring(j++,j+i);if(a.stream().allMatch(x->x.contains(s)))return s;}return"";}

```

Try it online!

## Credits
> 0 votes

# Answer
# Red, ~~266~~ 174 bytes

```
func[b][l: length? s: b/1 n: 1 until[i: 1 loop n[t: copy/part at s i l r: on foreach u
next b[r: r and(none <> find/case u t)]if r[return t]i: i + 1]n: n + 1 1 > l: l - 1]""]

```

Try it online!

Changed the recursion to iteration and got rid of the sorting.
> 0 votes

# Answer
# Perl 5, 87 bytes

```
my$r;"$&@_"=~/(.{@{[$r=~y,,,c]},}).*(\n.*\1.*){@{[@_-1]}}/ and$r=$1while$_[0]=~s,.,,;$r

```

Try it online!
> 0 votes

# Answer
# Gaia, 15 bytes

```
eḋ¦&⊢⟨:l¦:⌉=¦⟩∇

```

Try it online!

```
e		| eval as code
 ḋ¦		| find all non-empty substrings
   &⊢		| Reduce by set intersection
              ∇	| and return the first element where
      ⟨:l¦:⌉=¦⟩	| the length is equal to the max length
```
> 0 votes

# Answer
# PowerShell, ~~165~~ ~~163~~ 87 bytes

*-76 bytes thanks to Nail for the awesome regexp.*

```
"$($args-join'
'|sls "(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)"-a -ca|% m*|sort Le*|select -l 1)"

```

Try it online!

Less golfed:

```
$multilineArgs = $args-join"`n"
$matches = $multilineArgs|sls "(?<=^.*)(.+)(?=(.*\n.*\1)*.*$)" -AllMatches -CaseSensitive|% matches
$longestOrNull = $matches|sort Length|select -Last 1
"$longestOrNull"

```
> 0 votes

# Answer
# JavaScript (Node.js), ~~90~~ 88 bytes

```
f=(a,s=e=0,w='')=>a[0][e++]?f(a,s+(r=a.some(x=>!x.includes(t=a[0].slice(s,e)))),r?w:t):w

```

Try it online! Test cases shamelessly stolen from @Arnauld. Port of my Charcoal answer. Edit: Saved 2 bytes thanks to @l4m2.
> 0 votes

# Answer
# Perl 5, 86 bytes

```
$_=join"\x1",<>;$p=".*\x1.*\\1"x($.-1);say+(sort{length$b-length$a}/(.+)(?=$p)/msg)[0]

```

Try it online!
> 0 votes

# Answer
# Pyth, 16 bytes

```
eolN.U@bZm{s./dQ

```

Try it online!

```
       m     Q    # Map Q (parsed input) over the following function (lambda d:
          ./d     # Partitions of d (all substrings)
         s        # Reduce on + (make one list)
        {         # deduplicate
    .U            # reduce the result on the following lambda, with starting value result[0]
      @bZ         # lambda b,Z: Intersection between b and Z
                  # Result so far: all common substrings in random order
 o                # sort the resulting sets by the following lambda function:
  lN              # lambda N: len(N)
e                 # last element of that list

```
> 0 votes

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


title: Is my Rep in Stack-Exchange Form?

text:
# Question
Title: Is my Rep in Stack-Exchange Form?
## Premise:

Your reputation is in Stack-Exchange Form if it can be represented by decomposing your medal counts (gold, silver, and bronze counted separately) into their base-10 digits and joining them in any given order, with a few caveats.

While decomposing, each

* Gold medal digit is worth three digits.
* Silver is worth two digits.
* Bronze is one digit.
* Additionally, since SE does not display a medal type if you do not have any, a count of 0 medals for a type will **not** yield a `[0]`.

**Example:**

* `[1 Gold, 2 Silvers, 3 Bronzes]` will decompose into `[1,1,1,2,2,3]`. 321112 and 213121 are two examples of an SE-form number for these medals.
* `[20 Golds, 0 Silvers, 20 Bronzes]` will decompose into `[2,2,2,0,0,0,2,0]`. 20002022 is an SE-form number.
* `[11 Golds, 0 Silvers, 0 Bronzes]` will decompose into `[1,1,1,1,1,1]`. 111111 is the only SE-form number for this.

There will be no leading 0's when considering a SE number. E.g., in the 2nd example above, `00002222 -> 2222` would not be considered a SE-form number for `[20,0,20]`.

## Input/Output:

Input is a list/tuple/array/whatever of `[reputation, gold_medals, silver_medals, bronze_medals]` which are all non-negative integers. This is the assumed order but can be changed. Just make a note in your answer if you do.

Output is any two consistent values for true and false.

## Rules:

* Input will always be valid
* You will always have at least 1 Rep
* You can have no medals at all, which should always return false then.
* The medal counts have no bearing on reality. Having several hundred golds and no bronzes is fine.
* This is so shortest answer in bytes wins.

## Test Cases:

```
#[Rep, Gold, Silver, Bronze] -> Output
[4, 0, 0, 4]       -> True
[1447, 0, 4, 17]   -> True
[74414, 4, 0, 17]  -> True
[4444, 4, 0, 4]    -> True
[4455, 0, 54, 0]   -> True
[5355, 5, 0, 3]    -> True
[53535, 5, 3, 0]   -> True
[4444, 0, 0, 4444] -> True
[444, 4, 0, 0]     -> True
[1234, 0, 0, 1234] -> True
[1234, 0, 0, 4321] -> True

[4444, 1, 0, 1]      -> False
[5555, 5, 0, 55]     -> False
[1234, 1, 23, 4]     -> False
[1, 0, 0, 0]         -> False
[1001001, 0, 10, 10] -> False

```

# Answer
# 05AB1E, ~~16~~ ~~14~~ ~~13~~ ~~11~~ 10 bytes

```
∞×0KJ‚€{íË

```

Takes the medals input in the order `[bronze, silver, gold]` as first input, and `reputation` as second input.

-1 byte thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

```
∞           # Push an infinite positive list: [1,2,3,...]
 ×          # Repeat the values in the (implicit) input-list that many times as string
            # (since the input-list contains just 3 values, the rest of the infinite
            #  list is ignored)
  0K        # Remove all 0s (so all "0", "00" and "000")
    J       # Join the strings in the list together
     ‚      # Pair this string with the (implicit) second input
      €{í   # Sort the digits in both strings in descending order
         Ë  # And check if both are now equal
            # (after which the result is output implicitly as result)

```
> 12 votes

# Answer
# JavaScript (ES6),  ~~92~~  74 bytes

Takes input as `(['gold','silver','bronze'])('rep')`. Returns a Boolean value.

```
b=>r=>[...b.map((n,i)=>n.repeat(+n&&3-i)).join``].sort()+''==[...r].sort()

```

Try it online!

---

# JavaScript (ES6), 74 bytes

Takes input as `(gold, silver, bronze, 'rep')`. Returns a Boolean value.

```
(g,s,b,r)=>(F=s=>[...s].sort()+0)(r)==F([g,g,g,s,s,b].filter(x=>x).join``)

```

Try it online!
> 7 votes

# Answer
# MATL, ~~28 bytes~~ ~~20 bytes~~ ~~16 bytes~~ 13 bytes

Returns 0 for false and 1 for true. This can definitely be golfed down.

~~```
[1,3,2,1]Y"t2:7)XzVXzY@Ums0>

```~~

Down to 16 bytes if the reputation score can be taken in separately, and the order is \[bronze, silver, gold\], reputation
Down to 13 bytes thanks to Luis Mendo

```
3:Y"XzVXzY@Um

```

Try it online!
> 7 votes

# Answer
# , ~~38~~ ~~34~~ ~~31~~ 20 bytes

```
-:&(\:~&.":)]#~#\.**

```

Try it online!

*-11 bytes thanks to FrownyFrog!*
> 7 votes

# Answer
# Ruby, 69 bytes

```
->r,g,s,b{([g,g,g,s,s,b]-[0]).flat_map(&:digits).sort==r.digits.sort}

```

Try it online!
> 6 votes

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

```
íp fn ¬á øUg

```

Takes input as `[rep, bronze, silver, gold]`

Try it or Verify all test cases

```
Sample input: U = [1447, 17, 4, 0]
íp            Repeats each value of U by it's index amount e.g. ["","17","44","000"]
  fn          Remove all falsy values when converted to a number e.g. ["17","44"]
    ¬         Concatenate e.g. "1744"
     á        All permutations e.g. ["1744","1744","1474","1447","1474","1447","7144","7144","7414","7441","7414","7441","4174","4147","4714","4741","4417","4471","4174","4147","4714","4741","4417","4471"]
      øUg     Does it contain the first item of the input?

```
> 5 votes

# Answer
# Retina 0.8.2, 45 bytes

```
,0
,
,(\d*),(\d*),
¶$1$1$1$2$2
%O`.
^(.+)¶\1$

```

Try it online! Link includes test suite. Explanation:

```
,0
,

```

Delete zero scores.

```
,(\d*),(\d*),
¶$1$1$1$2$2

```

Expand the gold and silver scores, and convert the separator to a newline.

```
%O`.

```

Sort the reputation and the expanded scores separately.

```
^(.+)¶\1$

```

Compare the sorted digits.
> 5 votes

# Answer
## Racket, ~~149~~ ~~107~~ 98 bytes

```
(λ(r b s g[h(λ x(sort(string->list(apply ~a(remq*'(0)x)))char<?))])(equal?(h r)(h b s s g g g)))

```

Try it online!

First time golfing in Racket, so still looking for improvements...

Explanation (of the original longer version, but same idea):

```
(λ(r b                              ; take rep and badges as arguments
     [g(λ(x)                        ; helper function g which takes a string
         (sort                      ; and returns the sorted
           (string->list x)         ; list of characters
           char<?))])               ; (sort by ascii code)
  (equal?                           ; compare...
    (g(~a r))                       ; g called on the rep converted to string
    (g                              ; and g called on...
      (string-join                  ; the concatenation of
        (map ~a                     ; the stringified elements of
             (append*               ; the flattened list given by
               (filter              ; the elements of the following list where
                 (λ(x)(>(car x)0))  ; the badge count is nonzero:
                 (map make-list     ; repeat the badge counts
                      '(1 2 3)b)))) ; 1, 2, and 3 times respectively
        ""))))

```
> 5 votes

# Answer
# Jelly, 10 bytes

```
xJ$¹ƇV,Ṣ€E

```

Try it online!

Argument 1: `[Bronze, Silver, Gold]`
Argument 2: `Rep`
> 4 votes

# Answer
# Charcoal, 24 bytes

```
1Ｆ⁴Ｆ↨ＮχＦι⊞υκＦχ¿⁻№υι№θＩι⎚

```

Try it online! Link is to verbose version of code. Takes input in the order rep, bronze, silver, gold and outputs `1` if the rep is valid. Explanation:

```
1

```

Assume the rep is valid.

```
Ｆ⁴Ｆ↨ＮχＦι⊞υκ

```

Loop over the four input values. Push each digit of each value `i` times where `i` is the 0-indexed index of the value. Numeric base conversion is used here as that converts `0` to an empty array.

```
Ｆχ¿⁻№υι№θＩι⎚

```

Check the count of each digit in the array matches that in the first input. If any differ, clear the canvas.
> 2 votes

# Answer
# Jelly, 18 bytes

```
DẋṠƊ€ẋ"3RU¤FṢ⁼⁴DṢ¤

```

Try it online!

this is a *bit* bad
> 2 votes

# Answer
# Python 2, ~~80~~ ~~79~~ ~~77~~ 68 bytes

```
lambda r,g,s,b:S((g>0)*3*`g`+(s>0)*2*`s`+(b>0)*`b`)==S(`r`)
S=sorted

```

Try it online!

Takes input as `rep, gold, silver, bronze`.
> 2 votes

# Answer
# Perl 5 `-lF`, 62 bytes

```
map{@r=sort/./g,@r if($_=<>x$_)>0}1..3;@F=sort@F;say"@r"eq"@F"

```

Try it online!

Takes input on separate lines as

```
reputation
bronze
silver
gold

```
> 2 votes

# Answer
# Husk, 10 bytes

```
€mdPfIṁdṘN

```

Try it online!

Similar to the Japt answer.

Takes `[bronze,silver,gold]` as first argument, `rep` as second argument.

## Explanation

```
€mdPfIṁdṘN
         N natural numbers
        Ṙ  repeat medals that many times
      ṁd   get all their digits as a single array
    fI     filter out zeroes
   P       permutations
 md        mapped to their base-10 numbers
€          is rep in the list?

```
> 2 votes

# Answer
# PowerShell, 66 ~~69~~ bytes

-3 bytes thanks to mazzy

```
''+($args|%{"$_"*$i++*!!$_}|% t*y|sort)-eq(''+$args[0]|% t*y|sort)

```

Try it online!

Takes input at (Rep, Bronze, Silver, Gold)

Figure I'll take a crack at my own question. Converts the numbers `toCharArray`s and sorts them. Appends an empty string so the sorted arrays are converted back to space-separated strings which can then be compared.

We handle 0 medal counts with `!!$_` which doubly negates the number, making it go `non-zero number-> 0 -> 1` or `0 -> 1 -> 0` which is used to blank the repeat counter.
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~69~~ 68 bytes

```
i=IntegerDigits
Sort@i@#==Sort[Join@@i/@Select[{##2,##3,#4},#!=0&]]&

```

Defines an anonymous function; takes inputs to function as \[reputation, bronze, silver, gold\].

I think this method for repeating silver and gold is interesting (and unique among these answers): in an anonymous function, `#n` represents argument n and `##n` represents a sequence of arguments from argument n to the end, so if one were to expand `{##2,##3,#4}`, it would become `{#2,#3,#4,#3,#4,#4}`, which repeats each the necessary number of times while being 7 bytes less than the expanded form.
> 1 votes

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


title: Counting valid Binary Sudoku rows

text:
# Question
Title: Counting valid Binary Sudoku rows
## Background

Binary Sudoku, also known as Takuzu, Binario, and Tic-Tac-Logic, is a puzzle where the objective is to fill a rectangular grid with two symbols (0s and 1s for this challenge) under the following constraints:

1. **Each row/column cannot have a substring of `000` or `111`, i.e. one symbol cannot appear three times in a row, horizontally or vertically.**

* A row/column of `1 0 0 0 1 1` violates this rule since it contains three copies of `0` in a row.
2. **Each row/column should contain exactly as many 0s as 1s, i.e. the counts of two symbols must be the same.**

* A row/column of `1 0 1 1 0 1` violates this rule since it has four 1s but only two 0s.
    * Some examples of rows that meet the first two requirements include:

    ```
    [1 0 0 1]
    [1 1 0 0]
    [1 1 0 1 0 0]
    [1 1 0 0 1 0 0 1]

    ```
3. (Not relevant to this challenge) The entire grid cannot have two identical rows or columns.

Note that the constraint 2 enforces the grid size to be even in both dimensions.

Here are some examples of completed Binary Sudoku:

```
(4x4, using 0s and 1s)
1 1 0 0
0 1 1 0
1 0 0 1
0 0 1 1

(6x8, using Os and Xs)
O O X O X O X X
X X O X O X O O
X O X O X X O O
O O X X O O X X
X X O X O O X O
O X O O X X O X

```

## Challenge

Given a positive integer `n`, calculate the number of distinct valid Binary Sudoku rows of length `2n`; that is, the number of permutations of `n` 0s and `n` 1s which do not have `000` and `111` as a substring.

The sequence is A177790, leading 1 removed and 1-based.

## Test cases

Here are the first 20 terms of this sequence (1-based):

```
2, 6, 14, 34, 84,
208, 518, 1296, 3254, 8196,
20700, 52404, 132942, 337878, 860142,
2192902, 5598144, 14308378, 36610970, 93770358

```

## Scoring and winning criterion

Standard rules apply. The shortest submission in bytes wins.

# Answer
> 10 votes
# Jelly,  ~~13 12~~  9 bytes

```
ŻcṚ$+Ḋ$²S

```

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

### How?

This code is calculating

$$\sum\_{k=\lceil\frac{n}{2}\rceil}^{n}\big(\binom{k}{n-k}+\binom{k+1}{n-(k+1)}\big)^2$$

(where \\$k\\$ starts at \\$0\\$ rather than \\$\lceil\frac{n}{2}\rceil\\$ ...the additional terms are \\$0\\$ but allows a reversal trick)

```
ŻcṚ$+Ḋ$²S - Link: integer, n       e.g. 7
Ż         - zero range                  [0,  1,  2,  3,  4,  5,  6,  7]
   $      - last two links as a monad:
  Ṛ       -   reverse                   [7,  6,  5,  4,  3,  2,  1,  0]
 c        -   n-choose-k                [0,  0,  0,  0,  4, 10,  6,  1]
      $   - last two links as a monad:
     Ḋ    -   dequeue                   [0,  0,  0,  4, 10,  6,  1]
    +     -   add                       [0,  0,  0,  4, 14, 16,  7,  1]
       ²  - square                      [0,  0,  0, 16,196,256, 49,  1]
        S - sum                         518

```

# Answer
> 6 votes
# Pari/GP, 77 bytes

```
n->polcoeff([x,0,1,0]*[0,x,1,0;0,0,1,0;x,0,0,1;x,0,0,0]^(2*n-1)*[1,1,1,1]~,n)

```

Try it online!

This uses a nice method involving automata and is quite efficient.

Consider the automaton that checks if a string satisfies condition one. Besides the initial state and a sink state, it has four interesting states. They signify that everything is still okay, what the last letter was and whether it was the same as the one before. When we replace the `x` with `1` in the matrix that occurs in the program, it describes the possibilities to get from one of these states to another.

Usually we should not ignore the initial state, but since it will not be entered again, we can handle it by starting with the vector `[1,0,1,0]` that describes all the states that can be reached after one step. Multiplying this vector with the matrix raised to the `(m-1)`th power gives a vector that tells us how many words of length `m` lead to each state. To get their sum, we multiply with the transpose of the all-one vector. There doesn't seem to be a shorter way to get the sum of the entries of a vector.

However, we still have condition two. It could be handled by the automaton, but that would need more states, depend on `n` and be complicated to create. Instead, we change the matrix (and starting vector) to have an `x` for each transition that corresponds to reading a `1`. This way, the computation will not compuite a number, but a polynomial where each term `a*x^k` means that there are `a` words accepted by the automaton (i.e. satisfying condition one) that contain `k` `1`s. For example, for `n=3` (words of length 6) that polynomial is `6*x^4+14*x^3+6*x^2`. So we just have to take the coefficient of `x^n`.

# Answer
> 5 votes
# Bash \+ GNU utilities, ~~123~~ ~~121~~ 119 bytes

```
dc<<<[sD1q]so[sD0q]szz`seq -f"%0.fdsK$1lK-[dsk0>zdsndlk>z[d2>od1-d2<F*]dsFxlklFxlnlk-lFx*/]dsCx1lK+d$1r-lCx+d*+" 0 $1`p

```

Try the test suite online!

---

I've added an explanation of this obscure-looking code at the end of the answer!

---

*Shaved off 2 bytes by moving the definitions of macros F and C to the first place they're used, and then another 2 bytes by eliminating two single-quotes that were no longer required after the macros were moved.*

This is another, completely different bash solution. Unlike my other (shorter) solution, this one is very fast -- TIO can compute the value for 1800 in just under its 60-second limit. Because it uses `dc`, it can handle arbitrarily large integers.

The program is based on the binomial coefficient formula from OEIS, which is computed using `dc`. Since loops are such a pain to write in `dc`, I use `seq` instead to unroll the loop into a giant `dc` script to compute the specific number requested, and the `dc` script is then executed.

If you're curious (and don't want to wait the 60 seconds at TIO), here's the 1800th term in the sequence:

`105480721405474718567404887164925416724980133926539712143845881075284\
901677297738964136155557073029386229070488343605298871231397783837622\
530014641802254048917232853438125993571007137377212907244683700588015\
444444467026455576839621404814982031106756318549435412359204504183866\
493764320992226326910391777276272125030010740526937030702909019208912\
640538519829602971756125307274565635138616156817423412863412177199151\
055856207069714084657310495058759139542900519171388443547871558507573\
948937524889911140590562675224573515451638678334944353358816689952838\
021105461897807233248789972151274044554176393928054238190520484054350\
689148029614875765339478833688339093323537661478061731620258929292671\
03260220166411748225093782409130224917917686956257637269268564`

---

**How it works:**

Overall, the structure of the program is: `dc<<<...`, so bash calls dc with a script to run.

But the dc script part isn't written out fully; it's actually generated itself by a program (the dc script is customized for the specific argument `n` that was passed in $1 to bash).

The dc script starts with a prologue string that's taken verbatim, then a call to `seq` to generate the bulk of the `dc` code, and then a final command to print the result.

***PROLOGUE***

The prologue is: `[sD1q]so [sD0q]sz z` (spaces added for clarity -- they don't affect the code).

1. `[sD1q]so` This defines a macro o which replaces the item at the top of the stack with `1`. It's intended to be called from another macro.

In more detail:

```
[    Start a string (to be used as a macro definition).
sD   Pops an item from the stack and stores it in register D.
     (I only do this because dc doesn't provide a way to just pop an item from the stack without doing something with it, and storing it an otherwise unused register is innocuous.)
1    Push `1` onto the stack.
q    Return from this macro and the macro which called it.
]    End the string.
so   Save the macro in register o.

```
2. `[sD0q]sz` This defines a macro z which replaces the top of the stack with `0`. It works the same way as macro `o` above.
3. `z`

This pushes the current stack depth onto the stack. But the stack is currently empty, so it just pushes `0` onto the stack. This initializes the running total for the binomial coefficient sum that we're going to be computing. (The reason for using `z` instead of `0` for pushing a `0` is that a number is coming next; so if I used a `0` to push the 0 here, I'd need to put an extra space after it to separate it from the number coming up. So using `z` saves a byte.)

***CALL TO seq***

The `seq` command is of the form `seq -f %0.f... 0 $1`, where the ... is dc code. This takes each number k from 0 to n (the bash argument $1), replaces %0.f (in the first argument to seq) with k, and writes each of those strings on a line:

```
0...
1...
2...
.
.
.
n...

```

where the `...` at the end of each line is the dc code in the argument to seq.

So the loop that one would imagine for computing $$\sum\_{k=0}^n \big( \binom{k}{n-k}+\binom{k+1}{n-k-1}\big)^2$$ is actually unrolled into a simple but long computation for the specific \\$n\\$ that we have.

There are actually two macro definitions embedded in the dc code. (You can often a save a byte in dc by waiting to define a macro until the first time you use it.)

I'm going to describe those macros first, because I think it's clearer that way.

**The first** of the two embedded macros, `[d2>od1-d2<F*]` computes the factorial of the number at the top of the stack. The macro is saved in register F, so it calls itself recursively:

Assumption: The argument x is on the stack when the macro is called.

```
[    Start macro definition
d    Duplicate the item at the top of the stack, so x is there twice.
2>o  Pop that number. If it's < 2, call macro o to pop the extra copy of the argument, and return from F with 1 on the stack.  (This is the right answer for x! when x<2.)
If it's >= 2:
d    Pop the argument.
1-   Subtract 1.
d    Duplicate the top of the stack, so x-1 is there twice.
2<F  If it's > 2, call F recursively to compute (x-1)!.
*    Multiply the top of stack, which is (x-1)!, by the 2nd item on the stack, which is x, yielding x! as desired.
]    End macro definition

```

The above macro will be saved in register F.

**The second** of the two embedded macros computes the binomial coefficient $$\binom{n}{k} = \frac{n!}{k! (n-k)!},$$ where \\$k\\$ is the number on the top of the stack and \\$n\\$ is the second number on the stack.

The binomial coefficient macro is: `[dsk0>zdsndlk>z[d2>od1-d2<F*]dsFxlklFxlnlk-lFx*/]`, which is saved in register C. (Note that the definition of macro F is actually embedded inside the definition of C.)

Here's how C works (when it's called, `k` is at the top of the stack, and `n` is second):

```
[    start of macro
d    Duplicate k at the top of the stack.
sk   Pop one k and save it in register k.
0>z  Pop the other k, and if it's < 0, call macro z to return 0 from C (which is the right value for the binomial coefficient when k<0).
If k >= 0:
d    Duplicate n (so there are now two n's at the top of the stack).
sn   Pop one n and save it in register n.
d    Duplicate n (so there are now two n's again at the top of the stack).
lk>z If n<k, call macro z to return 0 from C (which is the right value for the binomial coefficient when k>n).
[d2>od1-d2<F*]  This is the definition of macro F, as described earlier, embedded in C.
d    Duplicate the F macro string on the stack.
sF   Pop one copy of the macro F string, and save it in register F.
x    Pop the stack to get a copy of the macro string F and call it.  So now the n at the top of the stack has been replaced by n!
lk   Load k.
lFx  Compute k!.
lnlk- Compute n-k.
lFx   Compute (n-k)!
*     Multiply k! (n-k)!.
/     Compute n!/(k! (n-k)!).
]     End of macro C.

```

So now let's go back to see what the dc code does with each value k from 0 to n. (Below I've written C(n,k) for \\$\binom{n}{k}\\$ since TeX doesn't seem to work inside code-sample formatting.)

```
%0.f seq replaces this with k, so k is pushed on the stack.
d    Duplicate the top of the stack, so k is now on the stack twice.
sK   Pop one of the k's off the stack and store it in register K.
$1   Push n on the stack.  ($1 has already been replaced by n due to bash's parameter expansion.)
lK   Push k back on the stack (load it from register K).
-    Pop n and k, and push n-k onto the stack.
[dsk0>zdsndlk>z[d2>od1-d2<F*]dsFxlklFxlnlk-lFx*/]   This is the embedded defintion of C, with the definition of F embedded in it.
d     Duplicate the string defining C, so it's there twice.
sC    Save the macro for C in register C.
x     Call the macro C.  This pops k and n-k, and replaces them with C(k,n-k).
1     Push 1.
lK    Push k.
+     Compute k+1.
d     Duplicate k+1 on the stack.
$1    Push n.
r     Swap n and the k+1 that comes next.  (So the stack now has k+1 at the top, then n, then k+1 again.)
-     Replace k+1 and n at the top of the stack with n-k-1.
lCx   Replace n-k-1 and k+1 with C(k+1,n-k-1).
+     Add the two binomial coefficients.
d*    Square the sum of the two binomial coefficients.
+     Add it onto the running total.

```

The above is done for each k, so after they're all done, the top of the stack contains the value we want.

***EPILOGUE***

The epilogue is fixed code that's hit last. It just consists of the single dc command `p` which prints the result, with a newline after it.

It may be worth mentioning that the macro F is redefined every time C is called (because the definition of F is embedded in C), but that's OK -- it's defined the same way every time.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 46 bytes

*a(n) = Sum\_{k=0..n} (C(k, n-k) + C(k+1, n-k-1))^2*

```
Sum[Tr@Binomial[{k,k+1},{#,#-1}-k]^2,{k,0,#}]&

```

Try it online!

# Answer
> 3 votes
# Perl 5 `-p`, ~~50~~ 48 bytes

*@Grimmy saved 2 bytes*

```
$_=grep!/000|111/&&y/1//==y/0//,glob"{0,1}"x2x$_

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~114~~ \\$\cdots\\$ ~~93~~ 89 bytes

Saved 15 bytes thanks to Bubbler!!!
Saved 4 bytes thanks to Jitse!!!

```
lambda n:sum([*map(bin(i).count,('000','111','1'))]==[0,0,n]for i in range(4**n//8,4**n))

```

Try it online!

Brute force!

# Answer
> 2 votes
# 05AB1E, ~~13~~ 8 bytes

*Port of Jonathan Allan's Jelly answer*

```
ÝÂcDÀ+nO

```

Try it online!

Old 13-byter:

```
xLÉœêʒü3€ËË}g

```

Try it online!

# Answer
> 2 votes
# Charcoal, 35 bytes

```
ＮθＩＬΦＥＸ⁴θ⭆◧⍘ι²⊗θΣλ›⁼№ι0№ι1ΣＥ²№ι×³Ｉλ

```

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

```
ＮθＩＬΦＥＸ⁴θ

```

Loop from `0` to `2²ⁿ`.

```
⭆◧⍘ι²⊗θΣλ

```

Generate all binary strings of length `2n`.

```
›⁼№ι0№ι1

```

Check that the number of `0`s and `1`s is the same.

```
ΣＥ²№ι×³Ｉλ

```

Check that the string does not contain 3 repeated digits.

# Answer
> 2 votes
# Bash \+ GNU utilities, ~~86~~ 75 bytes

```
n=$1;e()(egrep "(21*){$n}"|grep -v 111);seq $[10**(2*n)]|e|tr 12 21|e|wc -l

```

Try it online!

The input is passed as argument, and the output is written to stdout.

It's very slow -- TIO times out at \\$n=5\\$.

---

**How it works:**

The function e is a filter; it only allows a line through if:

(a) it doesn't have 3 `1`s in a row,

and (b) it has a substring consisting of just `1`s and `2`s, with exactly `n` `2`s.

The seq command counts from \\$1\\$ to \\$10^{2n}\\$. These are all numbers of at most \\$2n\\$ digits (except for the \\$10^{2n}\\$ at the end).

We'll count numbers consisting of just `1`s and `2`s, not `1`s and `0`s, since otherwise we wouldn't get numbers starting with `0`s.

The filter e is applied, and then it's applied to the same string with the `1`s and `2`s switched around. So a number is allowed through if:

(a) it doesn't have 3 `1`s in a row;

(b) it doesn't have 3 `2`s in a row;

(c) it has a substring consisting of just `1`s and `2`s, with exactly `n` `2`s;

and (d) it has a substring consisting of just `1`s and `2`s, with exactly `n` `1`s.

Since the numbers being produced are decimal numbers with at most \\$2n\\$ digits, it follows that we're only letting through numbers with exactly \\$n\\$ `1`s and exactly \\$n\\$ `2`s. (The \\$10^{2n}\\$ at the end is an exception with \\$2n+1\\$ digits, but it won't have passed through the filter anyway.)

Finally, `wc -l` counts the lines remaining.

---

The earlier 86-byte version used dc instead of seq, so it can handle arbitrarily large numbers, not limited by bash's maximum integer size. But that's more or less moot because it's too slow anyway.

Here's the old version:

`n=$1;e()(egrep "(21*){$n}"|grep -v 111);dc<<<"O$1d+^[d1-pd0<f]dsfx"|e|tr 12 21|e|wc -l`

You can see more about that one (including a faster version that's 2 bytes longer, counting in base 3 instead of base 10) in the edit history.

# Answer
> 2 votes
# APL (Dyalog Unicode), 18 bytes

```
+.×⍨1,2+/⊢(-!⊢)⍳,⊢

```

Try it online!

Bubbler's port of the Jelly solution(-14 bytes!).

# APL (Dyalog Unicode), ~~35~~ 32 bytes

```
{+/(×⍨((⍵-1+⊢)!1+⊢)+⊢!⍨⍵-⊢)⍳1+⍵}

```

Try it online! or Verify all test cases

Uses the formula from the Bash answer(which is very, very cool, go upvote it!).

Requires `⎕IO←0` for 0-indexing.

-3 bytes from ovs (Converted inner dfn to train, removing assignment to n).

## Explanation

```
{+/{×⍨((n-⍵+1)!⍵+1)+(n-⍵)!⍵}⍳1+n←⍵}
                               n←⍵  store input in n
                            ⍳1+     range 0..n
   {                       }        apply the following to it's elements k:
                    (n-⍵)!⍵         k C (n-k)
                   +                plus
      ((n-⍵+1)!⍵+1)                 (k+1) C (n-(k+1))
    ×⍨                              squared
 +/                                 sum the resulting array

```

# APL (Dyalog Extended), 42 bytes

```
{+/(≢=2×+/)¨{⍵/⍨{⍱/0 3∊⍵}¨3+/¨⍵}↓⍉⊤⍳2*2×⍵}

```

Try it online!

Brute force method, which is much slower and longer.

# Answer
> 1 votes
# JavaScript (ES6),  ~~80 76~~  70 bytes

A port of the Maple solution presented on OEIS.

```
f=(i,j=i,k=2)=>i*j<0?0:i|j?(k<4&&f(i-1,j,k<3?3:4))+(k&&f(i,j-1,k>1)):1

```

Try it online!

# Answer
> 1 votes
# Japt `-x`, 15 bytes

Far too long and *extremely* inefficient! :\

```
çA á â Ë«ø56¤ò3

```

Try it

# Answer
> 0 votes
# Ruby, 75 bytes

```
->n{([0,1]*n).permutation.uniq.count{|r|r.chunk{|n|n}.all?{|k,v|v.size<3}}}

```

Try it online!

## Explanation

This is a naive solution that generates the permutations and counts the valid ones.

```
->n{([0,1]*n).permutation.uniq.count{|r|r.chunk{|n|n}.all?{|k,v|v.size<3}}}

# This gets all the unique permutations of `0`s and `1`s of size `2n`.
    ([0,1]*n).permutation.uniq

# This counts all instances where the inner block evaluates to true
                               count{                                     }

# This chunks together consecutive `0`s and `1`s.
                                     |r|r.chunk{|n|n}

# This checks that all consecutive `0`s and `1`s are shorter than 3
                                                      all?{|k,v|v.size<3}

```

# Answer
> 0 votes
# C (gcc), 79 bytes

```
f(i,j,k){i=i*j<0?0:i|j?(k<4)*f(i-1,j,3+k/3)+!!k*f(i,j-1,k>1):1;}a(x){f(x,x,2);}

```

A port of Arnauld's solution, and, by extension, the Maple solution on the OEIS page.

I spent way too much time working on an alternate solution. Here's what I came up with that didn't work:

* The number of numbers that don't meet the requirements of rule 1 is `2(x-1)`, or `4(x-1)` in this challenge's input scheme.
* The number of numbers that do meet the requirements of rule 2 is `(n)!/(floor(n/2)!)^2`, or `(2n)!/(n!)^2`.
* These cannot be combined because some numbers meet both the requirements, some meet neither, and the rest meet only one.

*-6 bytes thanks to ceilingcat!*

Try it online!

---
Tags: code-golf, sequence, binary, sudoku
---


title: Don't get your head in a spin!

text:
# Question
Title: Don't get your head in a spin!
# Guidelines

### Task

Write a function that takes in a sentence (a string, or list of characters) and reverses all the words that are greater than or equal to 5 in length.

---

### Examples

`"Hey fellow code golfers" -> "Hey wollef code sreflog"`

`"I aM noT a cAr" -> "I aM noT a cAr"`

`"I Am a tRaiN" -> "I Am a NiaRt"`

---

### Rules

* Since this is code golf, the person with the least amount of bytes as their answer wins.
* The input will have only one space between two adjacent words and there will be no trailing or leading spaces.
* The output must also only have one space between two adjacent words and no trailing or leading spaces.
* You can assume that the input will either be a string, or an array of characters. It WILL NOT be an array of words.
* You must output either a string, or an array of characters. You MUST NOT output an array of words.
* Words with punctuation marks can be seen as 5 or 4 letters, whichever you want
* Capitalisation should stay the same for the same letters

# Answer
# Jelly,  ~~12 10 8~~  7 bytes

-1 thanks to dylnan (use of repeat, `¡`, as a replacement of if, `?`, saving the need for identity, `¹`.)

```
ḲṚṫ¡€5K

```

A monadic link taking and returning lists of characters.

**Try it online!**

### How?

```
ḲṚṫ¡€5K - Link: list of characters
Ḳ       - split at spaces (gets words)
     5  - literal five
    €   - for €ach word:
   ¡    -   repeat:
  ṫ     -   ...number of times: tail (5th character on, if empty falsey->0, else truthy->1)
 Ṛ      -   ...action: reverse
      K - join with spaces

```

---

Previous 8: `ḲṚ¹ṫ?€5K`

Previous 10: `ḲµṚ¹ṫ?5µ€K`

Previous 12s: `ḲµUµL€>4Tµ¦K` and `ḲµṚ¹L>¥?4µ€K`
> 7 votes

# Answer
# Retina, ~~10~~ 8 bytes

*2 bytes saved thanks to @ETHproductions*

```
V`\w{5,}

```

Try it online!

```
  \w{5,}     match 5 or more characters long strings
V`           reverse each match and insert in place

```
> 6 votes

# Answer
# brainfuck, 123 bytes

```
,[[>++++[-<-------->]<[[-<+>]++++[-<++++++++>]>,>]<]<[>]<<<<<[[>]<[.<]>[>]]>>>>[[<]>[.>]]>>>>>,[>++++[->++++++++<]>.[-]]<<]

```

Try it online!

Most of this is just creating the ASCII value for space (32) 3 times, which is 51 bytes, or 41.4% of the total bytecount.

An attempt to only create one cell with 32 at the beginning and use that (124 bytes):

```
++++[->++++++++<],[[>[-<-<+>>>+<]<[[-<+>]>,>>>>]<[[-]>>>>]<<<]>>[-<+>]<<<<<<<<[[>]<[.<]>[[-]>]<<]>>>>[[<]>[.[-]>]]>,[>.>]<<]

```
> 5 votes

# Answer
# JavaScript (ES6), 60 bytes

*-57 bytes, w/ help from @Amorris, @Oliver, @Shaggy*

```
s=>s.split` `.map(w=>w[4]?[...w].reverse().join``:w).join` `

```

My first ever codegolf submission!
> 4 votes

# Answer
# Python 2, ~~56~~ ~~51~~ 49 bytes

-3 bytes thanks to Jonathan Allan
-2 bytes thanks to Mr. Xcoder
-2 bytes thanks to ElPedro

```
for w in input().split():print w[::len(w)<5or-1],

```

Try it online!
> 3 votes

# Answer
# QuadR, 10 bytes

```
\w{5,}
⌽⍵M

```

Try it online!

```
\w{5,}   match 5 or more characters long strings
         and replace
 ⍵M      each match
⌽        with its reverse

```
> 3 votes

# Answer
## Haskell, ~~50~~ 49 bytes

```
f s|s>take 4s=reverse s|1<2=s
unwords.map f.words

```

Try it online!

Edit: -1 byte thanks to @totallyhuman.
> 3 votes

# Answer
# 05AB1E, 12 bytes

```
ð¡εDg4›iR]ðý

```

Try it online!

**Explanation**

```
ð¡             # split on spaces
  ε      ]     # apply to each word
   D           # duplicate
    g          # length
     4›        # greater than 4
       iR      # if true, reverse
          ðý  # join by space

```
> 2 votes

# Answer
# Japt, 11 bytes

*Saved a byte thanks to @Shaggy*

```
®Ê<5?Z:Zw}S

```

Try it online!

### Explanation

```
®        }S    Split on spaces and map each word Z through this function:
 Ê<5             If the length of Z is less than 5,
    ?Z             return Z unchanged.
      :Zw        Otherwise, return Z reversed.
               The words are then re-joined on spaces and sent to output.

```

---

## Japt v2, 11 bytes

```
r/\w{5,}/_w

```

Test it online!

Thought of this just before the Retina answer was posted. Replaces each match of `/\w{5,}/g` with the match reversed.
> 2 votes

# Answer
# C,  ~~105~~  104 bytes

*Thanks to @ceilingcat for saving a byte!*

```
i,k;f(char*s){for(i=0;s[k=i]>32;)++i;for(;i>4&&k--;)putchar(s[k]);~k&&write(1,s,i+=k=!!s[i]);k&&f(s+i);}

```

Try it online!

**Unrolled:**

```
i, k;
f(char*s)
{
    for (i=0; s[k=i]>32;)
        ++i;

    for (; i>4&&k--;)
        putchar(s[k]);

    ~k && write(1, s, i+=k=!!s[i]);
    k && f(s+i);
}

```
> 1 votes

# Answer
# Perl, 22 bytes

Includes `+1` for `p`

```
perl -pe 's/\w{5,}/reverse$&/eg' <<< "Hey fellow code golfers"

```
> 1 votes

# Answer
## \>\<\>, ~~63~~ ~~53~~ 43 bytes

```
i>::48*=$0(+?v
6ov!?lr?(5l~ <.1
*^>i:0(?;48

```

Try it online!

<sub>~~10~~ 20 bytes saved thanks to Jo King!</sub>
> 1 votes

# Answer
# Python, ~~74~~ 69 Bytes

```
def f(a):print' '.join([i if len(i)<5else i[::-1]for i in a.split()])

```

Edit: -5 thanks to @ElPedro
> 1 votes

# Answer
# GolfScript, 24 bytes

```
" "/{.,4>{-1%}{}if}%" "*

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~152~~ ~~125~~ 106 bytes

```
j;f(char*S){for(char*Z;*S;S=Z+!!*Z)for(Z=S+strcspn(S," "),j=0;Z-S>4&&--j*2>S-Z;Z[j]^=S[~j]^=Z[j]^=S[~j]);}

```

Try it online!
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~132~~ 119 bytes

```
 s =input
s s arb . x (' ' | rpos(0)) rem . s
 x =gt(size(x),5) reverse(x)
 o =o x differ(s) ' ' :s(s)
 output =o x
end

```

Try it online!
> 0 votes

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

```
s/\S{5,}/reverse$&/eg

```

Try it online!

Replace (`s///`) all (`/g`) at least 5 (`{5,}`) non-whitespace (`\S`) by the evaluation (`/e`) of `reverse$&`/the reversed match.
> 0 votes

# Answer
# Python 3, ~~67~~ 65 bytes

```
lambda s:' '.join([c[::-1]if len(c)>4 else c for c in s.split()])

```
> 0 votes

# Answer
# JavaScript, ~~69~~ 66 bytes

```
s=>s.split` `.map(i=>i.length>4?[...i].reverse().join``:i).join` `

```

Try it online!
> 0 votes

# Answer
# JavaScript, ~~73~~ 50 bytes

*-23 bytes thanks to Shaggy and ETHproductions*

```
s=>s.replace(/\w{5,}/g,x=>[...x].reverse().join``)

```

### Test cases

```
let f =

s=>s.replace(/\w{5,}/g,x=>[...x].reverse().join``)

console.log(f("Hey fellow code golfers"))
console.log(f("I aM noT a cAr"))
console.log(f("I Am a tRaiN"))
```
> 0 votes

# Answer
# Red, 98 bytes

```
f: func[a][parse a[any[copy n[to{ }| to end](if(length? n)> 4[n: reverse n]prin n)skip(prin{ })]]]

```

Try it online!

## Ungolfed

```
f: func [a] [
    parse a [                            ; parse the argument on
        any [                            ; zero or more
            copy n [                     ; copy the matched substring to n
                to { }                   ; scan to a space
                | to end                 ; or to the end
            ]
            ( if (length? n) > 4 [       ; if the length of the match is bigger than 4
                  n: reverse n           ; reverse the match
              ]
            prin n)                      ; print the match
            skip (prin { })              ; skip the space
        ]
    ]

```
> 0 votes

# Answer
# JavaScript, 53 bytes

An alternative, but slightly longer, method to the straightforward reversing of words of length ≥5, which Oliver beat me to.

```
s=>s.replace(/\S+/g,m=>[...m].sort(_=>!!m[4]).join``)

```

Try it online
> 0 votes

# Answer
# Python 2, 53 bytes

```
for i in input().split():print i[::(-1,1)[len(i)<5]],

```

As far as I can see the , at the end does not leave a trailing space but please correct me if I am wrong.

Try it online!
> 0 votes

# Answer
## Pyth, 20 bytes

```
VcwdI>lN4p+_Nd.?p+Nd

```

Try it online!

```
Vcwd          | for N in input().split(" "):
    I>lN4     |     if len(N)>4:
        p+_Nd |         print(N[::-1]+" ", end="")
    .?        |     else:
        p+Nd  |         print(N+" ", end="")

```
> 0 votes

# Answer
# Java 8, 131 bytes

```
s->s.join(" ",java.util.Arrays.stream(s.split(" ")).map(x->x.length()<5?x:new StringBuffer(x).reverse()+"").toArray(String[]::new))

```

**Explanation:**

Try it online.

```
s->                            // Method with String as both parameter and return-type
  s.join(" ",                  //  Join String-array with spaces:
      java.util.Arrays.stream( //   An Array-stream of:
        s.split(" "))          //    The input-String split by spaces
      .map(w->                 //     Mapped to:
           w.length()<5?       //      If the word is not of length 5:
            w                  //       Leave the word as is
           :                   //      Else:
            new StringBuffer(x).reverse()+"")
                               //       Reverse it
      .toArray(String[]::new)) //   And convert the Stream to a String-array for the join

```
> 0 votes

# Answer
# Japt `-S`, 9 bytes

```
¸®zZÊ¨5©2

```

Try it
> 0 votes

# Answer
# CJam, 18 bytes

Port of my GolfScript answer.

```
lS/{_,4>{-1%}&}%S*

```

Try it online!
> 0 votes

# Answer
# Husk, 10 bytes

```
wm?↔Io>5Lw

```

Try it online!
> 0 votes

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


# Question
Title: Turn an integer n into a list containing it n times
Given an integer `n` as input, return a list containing `n`, repeated `n` times. For example, the program would take `5` and turn it into `[5,5,5,5,5]`. The elements need to be integers, not strings. No built-in functions that accomplish the task are allowed.

This is , so standard rules apply.

# Answer
> 33 votes
# Jelly, 1 byte

```
x

```

Try it online!

Note that this is **not** the “repeat `n` `n` times” built-in — its function is more general than that. For example `4,5,6x1,2,3` equals `[4, 5, 5, 6, 6, 6]`. Given only one argument, Jelly just happens to use it as both the left and right argument for the supplied link, but this functionality is not *inherent* to `x`.

If this doesn’t count, there are various fun 2-byte alternatives:

```
x` ṁ` Ra Rị R» a€ oR oḶ oṬ oẊ Ḷị Ḷ» Ṭị Ṭ» Ẋị Ẋ» ị€ ṛ€ ȧ€ »€

```

etc.

# Answer
> 22 votes
# Python 3, 14 bytes

```
lambda k:[k]*k

```

Try it online!

# Answer
> 19 votes
# Operation Flashpoint scripting language,  ~~50~~  46 bytes

```
f={a=[];t=_this;while{count a<t}do{a=a+[t]};a}

```

**Call with:**

```
hint format["%1", 5 call f]

```

**Output:**

# Answer
> 13 votes
# APL (Dyalog), 2 bytes

Five equally short solutions. Last two are courtesy of Zacharý.

---

```
⍴⍨

```

Try it online!

cyclically **r**eshape

self

---

```
/⍨

```

Try it online!

`/` replicate

self

---

```
\⍨

```

Try it online!

`\` expand

self

---

```
⌿⍨

```

Try it online!

replicate along first (and only) axis

self

---

```
⍀⍨

```

expand along first (and only) axis

self

Try it online!

# Answer
> 12 votes
# Mathematica, 10 bytes

```
#~Table~#&

```

# Answer
> 11 votes
# Proton, 8 bytes

```
n=>[n]*n

```

Try it online!

# Answer
> 9 votes
# JavaScript (ES6), 19 bytes

```
n=>Array(n).fill(n)

```

---

## Try it

```
o.innerText=(f=
n=>Array(n).fill(n)
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 9 votes
# Octave, 12 bytes

```
@(n)~(1:n)+n

```

Try it online!

# Answer
> 7 votes
# Pyth, 2 bytes

```
*]

```

**Test suite.**

---

```
*]QQ - Full program with implicit input

 ]   - Turn the input into a list.
*    - Repeat it a number of times equal to the input.

```

# Answer
> 7 votes
# Haskell, 13 bytes

```
f n=n<$[1..n]

```

Try it online! Usage: `f 5` yields `[5,5,5,5,5]`. For `n=5`, `[1..n]` yields the list `[1,2,3,4,5]`. `n<$` replaces each element of this list with `n`.

# Answer
> 6 votes
# , 18 bytes

```
array(n<-scan(),n)

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 2 bytes

Try it online!

# Answer
> 5 votes
# Dodos, 76 bytes

```
	f f r 2
2

r
	r d
	f s t f
d
	dip f s t
	f
t
	dot f
	dot
s
	s dip
f
	dab

```

Try it online!

# Explanation:

`f` is an alias for `dab` (tail).

`s` is subtraction, as explained on the wiki: **(x, y) → (0, y−x)** when **x ≤ y**.

`t` maps **(a, b, c…)** to **(b+c+…, a+b+c+…)**.

`f s t` maps **(a, b, c…)** to **a**. This is our “head” function.

`d` dips only the head of its argument: **(a, b, c…) → (|a−1|, b, c…)**

`r` is the main repetition logic. We map **(a, b)** to **(\*r(|a−1|, b), b)**.

For example, **r(4, 7)** will evaluate as

```
  r(4, 7)
= r(3, 7), 7
= r(2, 7), 7, 7
= r(1, 7), 7, 7, 7
= r(0, 7), 7, 7, 7, 7
  → This would call r(1, 7), but (1, 7) ≥ (0, 7), so surrender!
= 0, 7, 7, 7, 7, 7.

```

Finally, we define `2`, which maps **n → (n, n)**, and define `main` as `f f r 2`, computing **r(n, n)** and chopping off the first two elements.

# Answer
> 4 votes
# Japt, 2 bytes

```
ÆU

```

Test it

---

## Explanation

Implicit input of integer `U`. Generate an array of integers from `0` to `U-1`. Fill it with `U`. Implicit output of resulting array.

# Answer
> 4 votes
# Perl 5, ~~18~~ 14 bytes

-4 bytes thanks to @DomHastings

```
sub{(@_)x"@_"}

```

Try it online!

Is `x` a builtin that does the entire task? Sort of? Not really? Rules unclear?

Edit: Yeah, probably it's fine.

# Answer
> 4 votes
# Java (OpenJDK 8), ~~50~~ 48 bytes

```
n->java.util.Arrays.stream(new int[n]).map(i->n)

```

Try it online!

*-2 bytes thanks to @Jakob*

Inspired by the comments in @OlivierGrégoire's post, and optimized a little further. Takes an integer input, creates an IntStream of `n` elements, then maps each element to `n` and returns it.

# Answer
> 4 votes
# Haskell (14 bytes)

```
replicate>>=id

```

Thanks to @nimi, I don't need any import anymore. Yay!

It's a function that takes an integer argument; for example, the following returns `[5,5,5,5,5]`:

```
(replicate>>=id) 5

```

# Answer
> 4 votes
# TeX, 81 bytes

```
\newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat}

```

## Usage

```
\documentclass[12pt,a4paper]{article}
\begin{document}
\newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat}

\f{5}

\f{10}
\end{document}

```

# Answer
> 4 votes
# Husk, 2 bytes

```
´R

```

Try it online!

```
´    -- Apply next function twice to same argument
 R   -- given an integer n and some element, replicate the element n-times

```

---

### Polite alternative (3 bytes)

```
ṠIR

```

Try it online!

# Answer
> 3 votes
# J, 2 bytes

```
$~

```

Same as the APL answer: reflexively shape the input. In other words:

```
$~ y
y $ y
NB. y copies of y

```

# Answer
> 3 votes
# Brainbash, 39 bytes

```
>-[-[-<]>>+<]>->#[->+>+<<]>>[-<;<<.>>>]

```

Try it online!

Prints `N` `N` times. Works by generating 32, taking input, then duplicating the input twice, then output the first for each 1 in the second.

# Answer
> 3 votes
# C (gcc), 55 bytes

```
int*f(k){int*r=malloc(k*4),a=k;for(;a-->0;)r[a]=k;k=r;}

```

Try it online!

Returns a list of `k` integers.

# Answer
> 3 votes
# Röda, 10 bytes

```
{[[_]*_1]}

```

Try it online!

Explanation:

```
{[[_]*_1]}
{        } /* Anonymous function   */
   _       /* The input (_1)       */
  [ ]      /* As a list            */
     *_1   /* Repeated _1 times    */
 [      ]  /* Pushed to the stream */

```

# Answer
> 3 votes
# Coreutils, sed, 14 bytes

```
yes $1|sed $1q

```

As a zsh function, 20 19 bytes:

```
f(){yes $1|sed $1q}

```

Try it online!

# Answer
> 3 votes
# MATL, ~~4~~ 3 bytes

```
tY"

```

Try it online!

**Explanation:**

```
t       % duplicate elements
Y"      % replicate elements of array
        % (implicit) convert to string and display

```

# Answer
> 3 votes
# Groovy, 9 bytes

```
{[it]*it}

```

Try it online!

---

Perhaps the most competitive groovy answer I've done to date.

# Answer
> 3 votes
# brainfuck, 16 bytes

```
[->+>+<<]>[->.<]

```

Try it online!

## The breakdown:

```
[->+>+<<]          Duplicate 'n' into the next 2 cells to the right
         >         Move to the first duplicate
          [->.<]   Print 'n', 'n' times

```

As I'm sure you're aware, brainfuck takes input and output values as ASCII characters. So a `!` is represented as the value 33.

# Answer
> 2 votes
# Java (OpenJDK 8), ~~58~~ 56 bytes

```
n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;}

```

Try it online!

-2 bytes thanks to @KevinCruijssen

# Answer
> 2 votes
# Swift 3, 29 bytes

```
{n in(0..<n).map{_ in n}}

```

**Try it here!**

# Swift 3, 30 bytes

```
{Array(repeating:$0,count:$0)}

```

**Try it here!**

# Answer
> 2 votes
# C# (Mono), ~~38~~ 37 bytes

```
n=>System.Linq.Enumerable.Repeat(n,n)

```

Old version for 38 bytes:

```
n=>"".PadLeft(n,(char)n).ToCharArray()

```

Try it online!

A `char` in C# is an `int` underneath so this appears to be valid.

---

# C# (Mono), 44 bytes

```
using System.Linq;n=>new int[n].Select(_=>n)

```

If the above is invalid this is for an extra 6 bytes.

Try it online!

# Answer
> 2 votes
# Tampio, ~~109~~ 85 bytes

```
a:n uni on a a:na
nolla a:na on tyhjyys
a:n seuraaja o:na on o lisättynä a:han o:na

```

Explanation:

```
a:n uni on   a a:na
uni(a)  =  f(a,a)

  nolla a:na on tyhjyys
f(0,    a)   =  []

  a:n seuraaja o:na on o lisättynä a:han o:na
f(a   +1,      o)   =  o :       f(a,    o)

uni(a)   = f(a,a)
f(0  ,a) = []
f(a+1,o) = o : f(a,o)

```

# Answer
> 2 votes
**PHP**, **19 Bytes**

I'm new here can anyone tell if this is ok ?

```
for(;$b--;)$a[]=$n;

```

try it online!

EDIT:

looks to not be a valid form so :

**32 Bytes** (by Titus)

(+1 Byte for `R` flag)

```
for($b=$argn;$b--;)echo$argn,_;

```

try it online!

# Answer
> 2 votes
# cQuents v0, 3 bytes

```
::n

```

Try it online!

## Explanation

```
::    Mode: sequence 2. Given input n, output the sequence n times
  n   Each item in the sequence is n

```

# Answer
> 2 votes
# Common Lisp, 31 bytes

```
(lambda(x)(fill(make-list x)x))

```

Try it online!

# Answer
> 2 votes
# Perl 6, 9 bytes

```
{$_ xx$_}

```

Try it online

Uses the built-in list/statement repeat operator `xx`

# Answer
> 2 votes
# Kotlin, 22 bytes

```
{n:Int->(1..n).map{n}}

```

Try it online!

# Answer
> 2 votes
# Element, 9 bytes

```
_2:'[2:`]

```

Try it online!

```
_        input
2:       double the input
'        push one to control stack
[2:`]    for (number), double it, output one of them

```

# Answer
> 2 votes
# Ruby, 10 characters

```
->n{[n]*n}

```

Sample run:

```
irb(main):001:0> ->n{[n]*n}[5]
=> [5, 5, 5, 5, 5]

```

Try it online!

### Ruby, 18 characters

```
->n{Array.new n,n}

```

Sample run:

```
irb(main):001:0> ->n{Array.new n,n}[5]
=> [5, 5, 5, 5, 5]

```

Try it online!

# Answer
> 2 votes
# PowerShell, ~~13~~ 10 bytes

```
{@($_)*$_}

```

## Usage

```
PS C:\> 2 | % {@($_)*$_}
2
2

```

And:

```
PS C:\> 5 | % {@($_)*$_}
5
5
5
5
5

```

By default, PowerShell shows array content one element per line. Running it through the `ConvertTo-Json` cmdlet shows it in a more familiar form:

```
PS C:\> 5 | % {@($_)*$_} | ConvertTo-Json -Compress
[5,5,5,5,5]

```

# Answer
> 2 votes
# TI Basic, 10 bytes

This assumes an empty list

```
Ans→dim(L₁:L₁+Ans

```

Here's the hex, along with the code to explain the byte count:

```
72  04 B5   5D 00 3E 5D 00 70 71
Ans →  dim( L₁    :  L₁    +  Ans

```

## How?

```
Ans→dim(L₁:L₁+Ans
Ans→dim(L₁        Since the list is empty, this makes L₁ a list on Ans 0's
          :       Separator
           L₁+Ans Since TI-Basic vectorizes some commands,
                  this adds Ans (basically the input here) to each element in L₁,
                  which results in Ans for each element.

```

# Answer
> 2 votes
# TI Basic, 6 bytes

```
Ans+0rand(Ans

```

Thanks to @Oki for this solution!

# Answer
> 2 votes
# Flurry, 12 bytes

```
({}){({})}{}

```

### Run example

```
$ ./flurry -inn -c "({}){({})}{}" 3
3 3 3
$ ./flurry -inn -c "({}){({})}{}" 6
6 6 6 6 6 6

```

This uses the "push x y times" construct `y {({})} x`, just that in this case both are the input number `n`.

```
({})  Pop and push n; evaluates to n
{({})}  A lambda that returns its argument unchanged,
        pushing its argument once onto the stack
{}    Pop n

```

# Answer
> 1 votes
# Recursiva, 4 bytes

```
*aAa

```

Try it online!

# Explanation:

```
*a  : Multiply a times(Here, 8) [8,8,8,8,8,8,8,8]
  A : List-ify a [8]
   a: All a's will be assigned with the first input argument) 8

```

# Answer
> 1 votes
# Charcoal, ~~9~~ ~~5~~ ~~4~~ 3 bytes

```
Ｅθθ

```

Try it online!

-4 bytes thanks to Neil, -1 byte thanks to Erik the Outgolfer

## Explanation

```
Ｅ  Ｉθ Map with lambda returning first input cast to integer
  Ｎ    Implicit range over next (first) input

```

# Answer
> 1 votes
# Ohm, 4 bytes

```
DÄWî

```

Try it online!

```
DÄWî

D     duplicate
 Ä    push n onto the stack n times
  W   wrap the stack in a list
   î  cast to integer

```

# Answer
> 1 votes
# Pyke, 3 bytes

```
]1*

```

**Try it here!**

```
]1  - Wrap the input into a list.
  * - Repeat the list.

```

# Answer
> 1 votes
# , 2 bytes

```
#~

```

Try it online!

`#` copy

`~` self

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

```
n->[n|x<-[1..n]]

```

Try it online!

Or:

```
n->vector(n,x,n)

```

Try it online!

Or:

```
n->powers(1,n,n)

```

Try it online!

# Answer
> 1 votes
# Stacked, 6 bytes

```
[:rep]

```

Try it online!

This is an anonymous function that takes input on the stack and leaves output on the stack. This simply takes the input, duplicates it, then repeats the input by the input.

# Answer
> 1 votes
# QBasic 4.5, 48 bytes

```
INPUT a
DIM t(a)
FOR x=1TO a
t(x)=a
NEXT

```

# Answer
> 1 votes
# Aceto, 3 bytes

Assumes the integer is on the stack already.

This just duplicates the top stack element and then performs stack multiplication (i.e. Python's `[x]*y`).

# Answer
> 1 votes
# SOGL V0.12, 2 bytes

```
∙r

```

Try it Here!
Outputs to the stack.
Explanation:

```
∙   multiply POP (string, defaults to input) by POP (number, defaults to the same input)
     vertically - so to an array of strings
 r  swap types - convert the strings to numbers

```

# Answer
> 1 votes
# Brain-Flak, ~~28~~, 22 bytes

```
{(({}[()])<>[]())<>}<>

```

Try it online!

Normally, the version that uses one stack would be shorter. However, in this case it's 6 bytes longer:

```
(({})){({}<(({}))>[()])}{}{}

```

# Answer
> 1 votes
# Gaia, 2 bytes

Try it online!

```
w   Wrap input into list
 ×  Repeat (input) times

```

# Answer
> 1 votes
# MY, 6 bytes

```
ωi×ω+↵

```

Try it online!

## How?

* `ω`, push the first command line argument evaluated
* `i`, pop `n`; push `[1...n]`
* `×`, pop `a`; pop `b`; push `b*a`. `0` is popped when there is nothing on the stack. Since commands vectorize ("vecify" in MY), it ends up being an array of `n` 0's.
* `ω`, push the first command line argument evaluated
* `+`, pop `a`; pop `b`; push `b+a`. Adds the command line argument to every item in the array of `0` repeated `n` times, giving us `n` repeated `n` times
* , pop `n`; print `n` with a newline.

# Answer
> 1 votes
# Prolog (SWI), 33 bytes

```
X*L:-maplist(=(X),L),length(L,X).

```

Try it online!

# Answer
> 1 votes
# Tcl, 22 bytes

```
time {lappend L $n} $n

```

Try it online!

---

With built-ins:

# Tcl, 13 bytes

```
lrepeat $n $n

```

Try it online!

# Answer
> 1 votes
# MacOS bash, 12

```
jot $1 $1 $1

```

This also works on Linux if the `jot` package is installed, e.g. `sudo apt install athena-jot`.

Try it online.

# Answer
> 1 votes
# Actually, 2 bytes

Explanation:

```
;α
;   duplicate the input
 α  push a list containing n copies of n

```

`α` is not a builtin for this challenge by the usual definition, because it does not solve this challenge by itself. `α` takes the top stack element (call it `a`) and repeats the next stack element (`b`) `a` times. It's roughly equivalent to iterable multiplication in Python (`[5, 1]*2 == [5, 5, 1, 1]`), but also works on non-iterables (`52α` yields `[5, 5]`).

Try it online!

# Answer
> 1 votes
# 4, 32 bytes

```
3.700001000260201801500101010294

```

Try it online!

If you have concerns regarding the input format, please read this first.

**Transpiles roughly as**

```
grid[1] = grid[0] = input()
while grid[1] != 0:
  print(grid[0])
  grid[1] -= 1

```

# Answer
> 1 votes
# Braingolf, 6 bytes

```
!A.$_=

```

Try it online!

## Explanation

```
!A.$_=  Implicit input from commandline args
!A      Read top of stack without popping, run next operator that many times
  .     Duplicate top of stack
   $_   Pop top of stack
     =  Print stack

```

We have to pop the top of the stack because otherwise we'll have 1 too many copies of `n`. If we remove the `!` and let `A` pop the top of the stack, duplicate will have nothing to duplicate.

# Answer
> 1 votes
# Clojure, 13 bytes

```
#(repeat % %)

```

# Answer
> 1 votes
# Coq, 68 bytes

```
fun n=>(fix f k n:=match n with|0=>nil|S n=>(k::f k n)%list end) n n

```

Of course there's a library function, giving 46 bytes:

```
Require List. Definition f n:=List.repeat n n.

```

# Answer
> 1 votes
Just found this lang and wanted to give it a go.

# LOLCODE, 164 bytes

```
HAI 1.2
I HAS A CHZBRGR
GIMMEH CHZBRGR
CHZBRGR IS NOW A NUMBR
IM IN YR CRIB UPPIN YR HMBRGR TIL BOTH SAEM CHZBRGR AN HMBRGR
VISIBLE CHZBRGR
IM OUTTA YR CRIB
KTHXBYE

```

Try it online!

# Answer
> 1 votes
# Pyt, 3 bytes

```
Đ⑴*

```

Explanation:

```
                Implicit input
Đ               Duplicates input
 ⑴             Pushes an array, [1,1,...,1], with input 1's, onto the stack
   *            Multiply the array element-wise by the input
                Implicit output

```

Try it online!

# Answer
> 1 votes
# **FORTH 21 Bytes**

```
: B 0 DO DUP . LOOP ;

```

OUTPUT:

```
10 B
10 B 10 10 10 10 10 10 10 10 10 10

```

# Answer
> 1 votes
# Gol\>\<\>, 5 bytes

```
:MR:B

```

Try it online!

### Example full program & How it works

```
1AGIE;GDlR~
:MR:B

1AG          Register row 1 as function G
   IE;       Take number input; halt on EOF
      G      Call G
       D     Print the stack contents
        lR~  Empty the stack
             Repeat indefinitely

:M           Duplicate top and decrement
  R:         Duplicate n-1 times
    B        Return

```

# Answer
> 1 votes
# MAWP, 13 bytes

```
%@!1A[1A~!~]%

```

-15 bytes after integer input rework (Dion).

Try it!

# Answer
> 1 votes
# Integral, 6 Bytes

Outputs the list as individual stack elements joined by the newline.

If built-ins weren't banned, it would be possible via (1 bytes).

```
◙v◙♦▼e

```

Try it!

## Explanation

```
◙      Duplicate input, in order to get around the edge case 1
 v◙    "◙": Create a copy of the operand, when evaluated
   ♦   Swap up a copy of the input
    ▼  Decrement
     e Repeat input-1 times: Duplicate stack

```

# Answer
> 1 votes
# Keg, 5 bytes

```
:(|:.

```

Try it online!

# Answer
> 1 votes
# Arn, 7 bytes

```
|ÅF└¾c)

```

# Explanation

Unpacked: `v{_}\1=>`

```
    \ Fold/map (in this case just map) with...
v{ A block with the key of v
  _ Input
}
      1=> Range, [1, in]

```

# Answer
> 0 votes
# \[Swift 3\], ~~55~~ 49 bytes

```
func a(n:Int)->[Int] {return (0..<n).map{_ in n}}

```

# Answer
> 0 votes
# C++, ~~86~~ ~~56~~ 45 bytes

*Thanks to @ceilingcat for saving ~~30~~ 41 bytes!*

```
#import<list>
#define f(n)std::list<int>(n,n)

```

Try it online!

# Answer
> 0 votes
## REXX, 24 bytes

```
arg n
say copies(n' ',n)

```

Uses the built-in function `copies()`, and naturally, this being REXX, the copies are integers just as much as they are strings.

# Answer
> 0 votes
# WendyScript, 10 bytes

```
#:(x)[x]*x

(#:(x)[x]*x)(5) // => [5,5,5,5,5]

```

Try it online!

# Answer
> 0 votes
# , 5 bytes

```
Du@"Ä

```

Try it online!

# Answer
> 0 votes
# Pyth, 5 bytes

Super simple

```
.[QQY

```

Explanation:

```
.[QQY     Pad Y with eval(input) copies of eval(input)

```

Try it online!

# Answer
> 0 votes
# 8th, ~~42~~ 37 bytes

**Code**

```
>r a:new ( r@ a:push ) r@ times rdrop

```

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

**Usage**

```
: f >r a:new ( r@ a:push ) r@ times rdrop ;

ok> 5 f .
[5,5,5,5,5]

```

We could save another 6 bytes if we accept the idea of leaving numbers on `r-stack` after processing.

# Answer
> 0 votes
# , 7 bytes

```
0*1:n+n

```

Try it online!

# Answer
> 0 votes
# VBA, 75 Bytes

Defined `Function` that takes input `n` of expected type `Integer` and returns an array of length `n` filled with `n` to STDOUT

```
Function l(n)
Dim o
ReDim o(1To n)
For i=1To n
o(i)=n
Next
l=o
End Function

```

# Answer
> 0 votes
# Excel VBA, 49 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs a array of range values, `o`, with bounds `(1 To [A1], 1)` to the VBE immediate window.

```
[A1].Resize([A1],1)=[A1]:o=Sheet1.UsedRange.Value

```

# Answer
> 0 votes
# Julia 12

```
~x=fill(x,x)

```

Also it kinda generalizes to tuples making tensors.

```
julia> ~3
3-element Array{Int64,1}:
 3
 3
 3

julia> ~tuple(2,4)
2×4 Array{Tuple{Int64,Int64},2}:
 (2, 4)  (2, 4)  (2, 4)  (2, 4)
 (2, 4)  (2, 4)  (2, 4)  (2, 4)

julia> ~tuple(2,4,3)
2×4×3 Array{Tuple{Int64,Int64,Int64},3}:
[:, :, 1] =
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)

[:, :, 2] =
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)

[:, :, 3] =
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)

```

# Answer
> 0 votes
# TI-BASIC, 12 bytes

```
Ans→dim(L₁:Ans(L₁+1

```

Assumes an empty list.

# Answer
> 0 votes
# Objective-C 107 Bytes

```
#define a NSMutableArray
-(a*)f:(int)n{a*m=[a arrayWithCapacity:n];for(int i=0;i<n;i++)m[i]=@(n);return m;}

```

A little macro abuse and a basic loop, everyone else took the good languages...

## Usage

```
[self f:5];

```

returns an array of number objects of the given value

# Answer
> 0 votes
# Microscript II, 14 bytes

```
$s{o`s`+s}sNv*

```

# Answer
> 0 votes
# Ly, ~~13~~ 10 bytes

```
ns[>l<1-]>

```

Try it online!

Prints space-separated numbers. If outputting without a separator is allowed, `ns[lu1-];` works for 9 bytes.

Explanation:

```
ns[>l<1-]>

ns         # take input and save it
  [        # loop
   >l<     # load save and push it to another stack
      1-   # decrement
        ]  # end loop
         > # go to other stack
           # implicitly print

```

# Answer
> 0 votes
# F#, 32 bytes

```
let m n=List.map(fun x->n)[1..n]

```

Creates a list 1 to n, then mapping a function to each element to replace it with n.

# Answer
> 0 votes
# Axiom, 23 bytes

```
f(x)==[x for i in 1..x]

```

This 15 bytes would be better

```
f(x)⊳[x|i∈1..x]

```

f(x) return the list contains x element x but Axiom is a good approximation to that. Goes under 15 bytes it seems too much golfed

# Answer
> 0 votes
# Ruby, 12 bytes

```
->(n){[n]*n}

```

13 bytes

```
Array.new n,n

```

# Answer
> 0 votes
# QBIC, 17 bytes

```
dim g(:)[a|g(b)=a

```

This is a direct port of my QBasic answer (48 bytes), and QBIC does what it does best: compressing QBasic.

## Explanation

```
dim g(:) Defines an array of x elements, where x is a cmd line param
[a|      FOR b = 1 TO a (the : above creates 'a' and assigns the cmd line param to it)
g(b)=a   Set each array element to 'a'

```

# Answer
> 0 votes
### dc, 21

```
?dsn[lnpr1-d0!=F]dsFx

```

Try it online!

Ungolfed:

```
# Read a number from standard input (?), save it to register n (sn) and leave a copy on the stack (d)
?dsn

# Function F: print register n as many times as the top of the stack shows
[            # start of macro
  lnp        # print register n
  r          # swap the counter to the top
  1-         # decrement counter
  d          # duplicate counter for the comparison
  0 !=F      # if counter is not zero run F again
]dsFx        # end of macro, save it to F (sF) and execute (d x)

```

Run on the command line like this:

```
echo 5 | dc dcscript

```

Output:

```
5
5
5
5
5

```

This shorter script works for `n>1` (15 bytes):

```
? [d d z 1- <F]dsFx f

```

This uses the depth of the stack to determine when to stop.

# Answer
> 0 votes
# Excel VBA, 26 Bytes

Anonymous VBE immediate window function that takes input, `n` from range `[A1]` and returns an array object `X` with `n` stuffed into it `n` times.

```
x=Split([Rept(A1&" ",A1)])

```

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 41 bytes

```
R	R =ARRAY(N,N)	:(RETURN)
	DEFINE('R(N)')

```

Try it online!

`ARRAY` initializes an array with the given indices, in this case, `1:N`. It has an optional argument which it uses to initialize all the values in the array.

# Answer
> 0 votes
# ///, 23 bytes

```
/i///0./.1//1/i,//.//i.

```

Try it online!

Since there is no other way to take input in ///, it is hard coded. Also, since /// is a string-based language, input is in unary.

Example with input 5:

```
/i/00000//0./.1//1/i,//.//i.

```

How it works (with example input 5):

```
/i/00000//0./.1//1/i,//.//i.    Program with input.
/i/00000/                       Replace i with input. This is to make 1 uniform input.
         /0./.1/                Replace "0." with ".1". This turns all the 0s to 1s in the later i without bothering the next piece of code.
                /1/i,/          Replace 1s with input and a comma. This places the input into where the 1s were, essentially replacing each unary char of the input with the input, delimited with commas.
                      /.//      Remove the period.
                          i.    Input with period, main thing being modified by code.

```

# Answer
> 0 votes
# Python 3, ~~63~~ 54 Bytes

Saved 9 bytes thanks to Xcoder

```
a=[];i=input()
for _ in" "*int(i):a+=(i);
print(a)

```

**Same code but will print every iteration of the list, saves 2 bytes**

```
a=[];i=input()
for _ in" "*int(i):a+=(i);print(a)

```

# Answer
> 0 votes
# Fortran (GFortran), 45 bytes

```
SUBROUTINE B(I)
INTEGER A(I)
A=I
PRINT*,A
END

```

Try it online!

This is a simple version, in which the subroutine is used to avoid the allocation stuff, since we have a unknown length array. The TIO link leads to a version with the full program, with 67 bytes in total.

# Answer
> 0 votes
# K (oK), 4 bytes

**Solution:**

```
x#x:

```

Try it online!

**Explanation:**

`5#5` means take from 5, 5 times. But doesn't appear we can do the same trick as APL/J to reduce this one down.

```
x#x: / the solution
  x: / save input as x
x#   / take from it x times

```

# Answer
> 0 votes
# Stax, 3 bytes

```
]x*

```

Run and debug it

Internally it actually converts an integer to the array required but the implicit output changes it to codepoints. By default, output by codepoint is allowed though.

## Explanation

```
]      Convert input to singleton
 x*    Repeat input times

```

# Answer
> 0 votes
# 12-basic, ~~17~~ 14 bytes

```
?[X=INPUT()]*X

```

Try

# Answer
> 0 votes
# Kotlin, ~~20~~ ~~19~~ 15 bytes

Shorter Kotlin answer using the `List` constructor.

```
{n->List(n){n}}

```

Try it online!

Ungolfed:

```
// lambda function
{ n ->
    List(n) { n }  // create a List of n Ints where each item is n
}

```

Because `List` is actually an `interface`, `List()` is actually a function that creates a `List` of the specified type (here figured out through inference) and a fixed size, using the given lambda to initialize the value of each item. `{ n }` means the lambda will always return the value of `n`.

# Answer
> 0 votes
# Japt `-m`, 1 byte

```
N

```

Try it online!

`-m` is a flag that runs the program on each item in the input. Because the input is a number, it gets turned into a range first. `N` is the input.

# Answer
> 0 votes
# Gol\>\<\>, 7 bytes

```
I:R:~D;

```

This uses the convenient 'D' - Debug operator, which outputs the stack!

```
I       //Get integer input
 :R:    //Repeat input, double the number
    ~D; //Delete the last item in the stack(to get the right number) and output the entire stack with debug

```

Try it online!

# Answer
> 0 votes
# Rockstar, 83 bytes

Rockstar only has string I/O so output is a comma delimited string, which may not be allowed by the spec. To conform with the spec, though, the second line ensures the elements in the actual array are integers.

```
listen to N
cast N
X's0
while N-X
let L at X be N
let X be+1

join L with ","
say L

```

Try it here (Code will need to be pasted in)

# Answer
> 0 votes
# Bound, 6 bytes

```
ic1-Rc

```

Explaination:

```
i # Get input (for example 5) [5]
c # Copy the top element [5, 5]
1 # Put 1 onto the stack [5, 5, 1]
- # Subtraction [5, 4]
R # Pop the top element, repeat the next command that many times [5]
c # Copy the top element [5, 5, 5, 5, 5]

```

Try it online!

# Answer
> 0 votes
# GolfScript, 5 bytes

```
~.])*

```

Try it online!

```
~       # Parse the input to an integer     5
 .      # Copy it                           5 5
  ]     # Put everything in an array       [5 5]
   )    # Remove the last element          [5] 5
    *   # Multiply                         [5 5 5 5 5]

```

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