# Question
Title: Generate ordered combinations with repetition
Given a string of different characters, and a number n, generate all the ordered combinations with repetition, of length 1 to n, using those characters.

Another way to define it is to see the given characters as "custom" digits in the base (radix) of the number of characters, then the program should generate all the "numbers" with 1 to n digits in that base, however, leading "zeros" are included too.

The combinations should be ordered by their length (1 character first, then 2, etc), but other than that they can be in any order. You can choose the most convenient ways of handling input and output. Shortest code wins.

Examples:

`ab, 3` -\> `a,b,aa,ab,ba,bb,aaa,aab,aba,baa,abb,bab,bba,bbb`
`0123456789, 2` -\> `0,1,2,3,4,5,6,7,8,9,00,01,...,09,10,11,...,99`

# Answer
> 4 votes
# APL (Dyalog Unicode), 13 bytesSBCS

```
⊃,/,¨∘.,\⎕⍴⊂⍞

```

Try it online!

never miss an opportunity to use a scan :)

prompts for a string of "digits" and then for `n`

thanks @Adám for telling me how to enable `]box` on TIO

# Answer
> 5 votes
# Python 2, 56 bytes

`n` is the maximum length and `s` is expected to be a list of characters. It is not clear to me whether *n = 0* or an empty character list are valid inputs, but this function also handles them correctly.

```
f=lambda s,n:n*s and s+[x+c for x in f(s,n-1)for c in s]

```

# Answer
> 4 votes
## J, 41 char

```
   f=.}:@;@({@(,&(<',')@(]#<@[))"1 0>:@i.@])

   'ab' f 3
a,b,aa,ab,ba,bb,aaa,aab,aba,abb,baa,bab,bba,bbb

```

# Answer
> 3 votes
## APL (31)

```
{,/⍺∘{↓⍉⍺[1+(⍵⍴⍴⍺)⊤⍳⍵*⍨⍴⍺]}¨⍳⍵}

```

Usage: the left argument is the string and the right argument is the number, like so:

```
    'ab'{,/⍺∘{↓⍉⍺[1+(⍵⍴⍴⍺)⊤⍳⍵*⍨⍴⍺]}¨⍳⍵}3
b  a  ab  ba  bb  aa  aab  aba  abb  baa  bab  bba  bbb  aaa

```

The output is ordered by length, but within the length groups they are shifted one to the left, this was easiest.

Explanation:

* `,/⍺∘{`...`}¨⍳⍵`: for 1..⍵, apply the function to ⍺ and join the results together.
* `(⍵⍴⍴⍺)⊤⍳⍵*⍨⍴⍺`: for each number from 1 to (⍵=(current length))^(⍴⍺=(amount of chars)), convert to base ⍴⍺ using ⍵ digits.
* `1+`: add one because arrays are 1-indexed.
* `⍺[`...`]`: use these as indexes into the string
* `↓⍉`: rotate the matrix, so the 'numbers' are on the rows instead of in the columns, and then split the matrix up by rows.

# Answer
> 3 votes
# Haskell, 34 characters

```
x%n=do k<-[1..n];mapM(\_->x)[1..k]

```

Straightforward use of the list monad. The only real golfing is the use of `mapM` instead of the more idiomatic (and shorter) `replicateM` which would require importing `Control.Monad`.

**Usage**

```
> "ab" % 3
["a","b","aa","ab","ba","bb","aaa","aab","aba","abb","baa","bab","bba","bbb"]

```

# Answer
> 2 votes
# Python, 97 94

```
from itertools import*
s,n=input()
L=t=[]
exec"t=t+[s];L+=map(''.join,product(*t));"*n
print L

```

`t=t+[s]` can't be shortened to `t+=[s]` because L and t would be pointing to the same list.

Input: `'ab', 3`

Output:

```
['a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bb
a', 'bbb']

```

# Answer
> 2 votes
# Mathematica ~~29 19~~ 28

```
Join@@(i~Tuples~#&/@Range@n)

```

**Usage**

```
i={a, 4, 3.2};n=3;

Join@@(i~Tuples~#&/@Range@n)

```

> {{a}, {4}, {3.2}, {a, a}, {a, 4}, {a, 3.2}, {4, a}, {4, 4}, {4, 3.2}, {3.2, a}, {3.2, 4}, {3.2, 3.2}, {a, a, a}, {a, a, 4}, {a, a, 3.2}, {a, 4, a}, {a, 4, 4}, {a, 4, 3.2}, {a, 3.2, a}, {a, 3.2, 4}, {a, 3.2, 3.2}, {4, a, a}, {4, a, 4}, {4, a, 3.2}, {4, 4, a}, {4, 4, 4}, {4, 4, 3.2}, {4, 3.2, a}, {4, 3.2, 4}, {4, 3.2, 3.2}, {3.2, a, a}, {3.2, a, 4}, {3.2, a, 3.2}, {3.2, 4, a}, {3.2, 4, 4}, {3.2, 4, 3.2}, {3.2, 3.2, a}, {3.2, 3.2, 4}, {3.2, 3.2, 3.2}}

# Answer
> 2 votes
# MATL, ~~9~~ 8 bytes

```
x:"1G@Z^

```

Try it on MATL Online!

(MATL was created after this challenge was posted, but I believe that's ok by meta consensus these days.)

*(-1 bytes thanks to @Luis Mendo.)*

`x` \- delete string input from stack (automatically copies it to clipboard G)

`:"` \- implicit input of number n, loop from 1 to n

`1G` \- paste back the input string from clipboard G on the stack

`@` \- push the current loop iteration index

`Z^` \- cartesian power: cartesian product of input with itself `@` number of times

The cartesian power results (`@`-digit "numbers" in the given base) are accumulated on the stack and implicitly displayed at the end.

# Answer
> 1 votes
# Python - 106

The straightforward, uncreative solution. If you find significant improvements, please post as a separate answer.

```
s,n=input()
l=len(s)
for i in range(1,n+1):
 for j in range(l**i):t='';x=j;exec't+=s[x%l];x/=l;'*i;print t

```

Input: `"ab",3`
Output:

```
a
b
aa
ba
ab
bb
aaa
baa
aba
bba
aab
bab
abb
bbb

```

# Answer
> 1 votes
# Python, 100

Derived from @aditsu's solution.

```
s,n=input()
L=len(s)
i=0
while i<n:i+=1;j=0;exec"x=j=j+1;t='';exec't+=s[x%L];x/=L;'*i;print t;"*L**i

```

Input: `'ab', 3`

Output:

```
b
a
ba
ab
bb
aa
baa
aba
bba
aab
bab
abb
bbb
aaa

```

# Answer
> 1 votes
## Perl 5 \+ `-nlF -M5.010 -MList::Util+(uniq)`, 41 bytes

```
$,=$"=",";say grep/./,uniq glob"{,@F}"x<>

```

Try it online!

-1 byte thanks to @Xcali!

# Answer
> 1 votes
# Pyth, 6 bytes

```
s^LQSE

```

Expects the set of characters as 1st input, number of digits as 2nd. A byte could be saved if there were a single-byte method to repeatedly access the 2nd input, but alas...

Try it online here.

```
s^LQSE   Implicit: Q=input 1, E=evaluate next input
    SE   Range [1,2,...,E]
 ^LQ     Perform repeated cartesian product of Q for each element of the above
s        Flatten

```

# Answer
> 1 votes
# Perl 6, 33 bytes

```
{flat [\X~] '',|[$^a.comb xx$^b]}

```

Try it online!

Anonymous code block that takes a string and a number and returns a list of strings.

# Answer
> 0 votes
# PHP 180

I have no idea... I'm feeling lazy.

```
<?php $f=fgetcsv(STDIN);$l=strlen($f[1]);$s=str_split($f[1]);for($i=1;$i<=$f[0];$i++)for($j=0;$j<pow($l,$i);$j++){$o="";$x=$j;for($q=0;$q<$i;$q++){$o.=$s[$x%$l];$x/=$l;}echo"$o ";}

```

# Answer
> 0 votes
## Erlang 110

The Y combinator version (for shell):

```
fun(X, N)->F=fun(_,_,0)->[[]];(G, X, Y)->[[A|B]||A<-X,B<-G(G,X,Y-1)]end,[V||Y<-lists:seq(1,N),V<-F(F,X,Y)]end.

```

# Answer
> 0 votes
## Erlang 89 (118)

Module version:

```
-module(g).
-export([g/2]).
h(_,0)->[[]];h(X,N)->[[A|B]||A<-X,B<-h(X,N-1)].
g(X,N)->[V||Y<-lists:seq(1,N),V<-h(X,Y)].

```

Chars counted without mandatory bookkeeping (module and export).

# Answer
> 0 votes
# Ruby, ~~73~~ 64 bytes

```
->s,n{c=s.chars;(0...n).flat_map{c.product(*[c]*_1)}.map{_1*''}}

```

### 66 byte version because TIO doesn't support `_1`

```
->s,n{c=s.chars;(0...n).flat_map{|i|c.product(*[c]*i)}.map &:join}

```

Try it online!

# Answer
> 0 votes
# K (ngn/k), 17 bytes

```
{,/(,/,'/:)\x#,y}

```

Try it online!

# Answer
> 0 votes
# Japt, 9 bytes

Explanations to follow.

```
õ!àUçV)mâ

```

Try it

```
õ_çV àZ â

```

Try it

# Answer
> 0 votes
# Jelly, 6 bytes

```
WẋŒpƤẎ

```

Try it online!

Function submission, taking the list of digits as the first argument and the number of digits as the second. The digits themselves can be any of Jelly's data types, but I used integers in the TIO link above because it produces the best-looking output in Jelly's automatic “function → full program” wrapper.

## Explanation

```
WẋŒpƤẎ                      (called with arguments, e.g. [1,2,5], 3)
Wẋ       Make {argument 2} copies of {argument 1}  (e.g. [[1,2,5],[1,2,5],[1,2,5])
    Ƥ    For each prefix:                          (e.g. 1-3 copies of [1,2,5])
  Œp       take Cartesian product of its elements
     Ẏ   Flatten one level

```

The Cartesian product effectively gives us all numbers with a given number of digits (according to which prefix we're working with). So we end up with a list of lists of combinations (grouped by length), and can flatten that one level in order to get a list that isn't grouped (but which is still *sorted* by length, as the question requires, as  doesn't change the relative order of the elements and `Ƥ` tries shorter prefixes first).

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
ã€Œ˜Ùé

```

Try it online or verify all test cases.

**Explanation:**

```
ã         # Cartesian product of the second input repeated the first input amount of times
          #  i.e. 3 and 'ab' → ['aaa','aab','aba','abb','baa','bab','bba','bbb']
 €Œ       # Take all the substrings for each of those results
          #  i.e. 'aba' → ['a','ab','aba','b','ba','a']
   ˜      # Flatten the list of lists
    Ù     # Remove all duplicated values
     é    # Sort the list by length

```

---

**6-bytes alternative:**

NOTE: Flexible output: Outputs a new list for every length, all on the same print-line.
Converting it to a single list would be 2 bytes longer: `Lv²yã`})` (Try it online).

```
Lv²yã?

```

Try it online or verify all test cases.

**Explanation:**

```
Lv        # Loop `y` in the range [1, integer_input]
  ²yã     #  Take the second input and create an `y` times repeated cartesian product of it
          #   i.e. y=2 and 'ab' → ['aa','ab','ba','bb']
     ?    #  Print this list (without new-line)

```

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


title: Rotate-Replace a String

text:
# Question
Title: Rotate-Replace a String
### Task

Write a program or function that, given a string and a list of strings, replaces each occurrence of an element of the string list contained in the string with the next element of the string list.

### Example

The string is `The cat wore a hat on my doormat so I gave it a pat` and the list is `["at","or","oo"]`, we observe that the following bracketed substrings are in the list of strings:

```
The c[at] w[or]e a h[at] on my d[oo]rm[at] so I gave it a p[at]

```

We replace each element simultaneously with the element after it. The element after `"at"` in the list is `"or"`, the element after `"or"` is `"oo"`, and the element after `"oo"` is `"at"`. We get

```
The c[or] w[oo]e a h[or] on my d[at]rm[or] so I gave it a p[or]

```

so the output is

```
The cor wooe a hor a on my datrmor so I gave it a por

```

Note that when we were finding substrings, we selected `d[oo]rm[at]` instead of `do[or]m[at]`. This is because the substrings cannot overlap, so when deciding between overlapping substrings we choose the one(s) which come first in the string. When that has ambiguity, we choose the one(s) which come first in the input list.

### Input

Input can be taken in any reasonable format. The list can be newline-delimited, space-delimited, or delimited by any reasonable character.

### Output

Output the string generated after the replacements

### Rules

* You may assume that the input string and list consist only of printable ASCII (0x20 to 0x7E).
* You may assume that the strings in the input list do not contain your delimiter.
* You may assume that the input list has no repeated elements.
* None of the Standard Loopholes are allowed.
* Since this is , lowest score in bytes wins.

### Testcases

```
String
List of Strings
Output
-----
"My friend John went to the park."
["j","J"," "]
"Myjfriendj ohnjwentjtojthejpark."
-----
"Monkey Tacos!"
["Monkey","Programming Puzzles"," "," & ","Tacos!","Code Golf", "Puzzles", "Dragons"]
"Programming Puzzles & Code Golf"
-----
"No matches this time :("
["Match","Duel","(No"]
"No matches this time :("
-----
"aaaaa"
["aa","b","a","c"]
"bbc"
-----
"aaaaa"
["b","a","c","aa"]
"ccccc"
-----
"pencil"
["enc","pen","nci","cil"]
"ncienc"
-----
"Seriously, a lowercase rot one?"
["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
"Sfsjpvtmz, b mpxfsdbtf spu pof?"

```

# Answer
## JavaScript (ES6), 99 bytes

```
f=(s,a,i=a.findIndex(w=>s.startsWith(w)))=>s?(~i?a[i+1]||a[0]:s[0])+f(s.replace(a[i]||s[0],''),a):s

```
> 3 votes

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

It's early so probably room for improvement.

```
rVq| @VgVbX Ä

```

Try it online

---

## Explanation

```
                  :Implicit input of string U
r                 :Replace in U
 Vq|              :  V joined to a string with "|" (which is RegEx "or")
     @            :  Pass each match X through a function
        VbX       :    Index of X in V
            Ä     :    Add 1
     Vg           :    Get the element at that index in V

```
> 2 votes

# Answer
# Java 8, ~~227~~ 215 bytes

```
q->a->{String s=q,t;for(int i=0,j,l=a.length-1;i<s.length();i++)for(j=0;j<=l;j++)if(i==i+s.substring(i).indexOf(a[j])){s=s.substring(0,i)+(t=a[j<l?j+1:0])+s.substring(i+a[j].length());i+=t.length()-1;j=l;}return s;}

```

Ok, I got to admit: this challenge looks easy on paper, but there are many edge-cases for a verbose programming language like Java.. The first test case was easy, and was responsible for the general approach. The second test case caused a problem where it skipped two characters that both had to be replaced in a row `<space>J` -\> `j<space>`. And then I had to fix another problem where test case `"aaaaa"; ["aa","b","a","c"]` resulted in `bcb` instead of the intended `bbc`. Oh, and the third test case replaced the `Puzzles` part twice at one point as well.. **But**, everything is fixed now, and all test-cases work.

**Explanation:**

Try it here.

```
q->a->{String s=q,                        // Method with String & String-array parameters and String return-type
  ,t                                      //  Temp String
  for(                                    //  Loop (1) over the characters of the input String
      int i=0,j,l=a.length-1,t;           //  Some temp integers
                               i<s.length();i++)
    for(j=0;j<=l;j++)                     //   Loop (2) over the String-array
      if(i==i+s.substring(i).indexOf(a[j])){
                                          //    If we've found a match:
        s=                                //     Replace the input-String with:
          s.substring(0,i)                //      The first part of this input-String
          +(t=a[j<l?j+1:0])               //      + the next item in the String-array (and set `t` to it)
          +s.substring(i+a[j].length());  //      + the last part of this input-String
        i+=t.length()-1;                  //     Raise `i` by the length of this replacement item (`t`) - 1
        j=l;//break;                      //     Break loop (2)
      }                                   //    End of if
                                          //   End of loop (2) (implicit / single-line body)
                                          //  End of loop (1) (implicit / single-line body)
  return s;                               //  Return resulting String
}                                         // End of method

```
> 2 votes

# Answer
# Python 2, 89 bytes

```
import re
s,a=input()
print re.sub('(%s)'%')|('.join(a),lambda m:a[m.lastindex%len(a)],s)

```

`re.sub` can use a replacer function, it just gets a shifted value from the original list.
> 1 votes

# Answer
# APL (Dyalog), 12 bytes

## Main answer

Needs escapeing of things that will clash with PCRE, which is acceptable.

`{⍺⎕R(1⌽⍺)⊢⍵}`

For each non-overlapping, sequential occurrence of each element of the left argument (), **R**eplace (`⎕R`) the occurrence with the corresponding element of the left argument rotated one step left (`1⌽⍺`), applied to () the right argument ().

---

## For general interest

### A version which needs less escaping

Some arguments will clash with PCRE, so to avoid requiring the input to be pre-escaped, we can enclose each search pattern in `\Q` and `\E`:

`{('\Q'∘,¨,∘'\E'¨⍺)⎕R(1⌽⍺)⊢⍵}`

New here are `'\Q'` prepended (`∘,`) to each (`¨`) and append (`,∘`) `'\E'` to each (`¨`).

### A version which needs no escaping

Still, this requires escaping any premature `\E` and also certain characters in the transformation patterns, so we can preprocess the search and transformation patterns to escape all problematic characters:

`{R←⎕R'\\&'⋄('\P{Xan}'R⍺)⎕R(1⌽'\\|%|&'R⍺)⊢⍵}`

`R←⎕R'\\&'` define the monadic operator *R* by currying the transformation pattern `\\&` (prefix a backslash to the matched text) as right operand.

then

`'\\|%|&'R⍺` call *R*, looking for any backslash or percent or ampersand, (i.e. prefix them with a backslash) on the left argument

`1⌽` rotate that one step to the left

`'\P{Xan}'R⍺` call *R*, looking for any non-alphanumeric character, (i.e. prefix them with a backslash) on the left argument

`(``)⎕R(``)⊢⍵`**R**eplace text in the right argument – this time with safe search and transformation patterns
> 1 votes

# Answer
# PHP\>=7.1, 79 Bytes

```
<?[$s,$o]=$_GET;$k=$o;$k[]=array_shift($k);echo strtr($s,array_combine($o,$k));

```

Online Version
> 1 votes

# Answer
# Ruby, 50 bytes

```
->a,b{a.gsub(%r[#{b*?|}]){|z|(b*2)[b.index(z)+1]}}

```

Straight forward as always :)
> 1 votes

# Answer
# C#, 199 bytes

```
s=>a=>{for(int i=0,j,l=a.Count-1,t;i<s.Length;i++)for(j=0;j<=l;j++)if(i==i+s.Substring(i).IndexOf(a[j])){s=s.Substring(0,i)+a[t=j<l?j+1:0]+s.Substring(i+a[j].Length);i+=a[t].Length-1;j=l;}return s;};

```

A straight port of @KevinCruijssen's answer so go give him an upvote!

It's unfortunate that `string.Split` in C# removes the split strings otherwise I'm sure that would have been shorter.
> 0 votes

# Answer
# PHP, 66 bytes

```
while($t=$argv[++$i+2])$p[$argv[$i+1]]=$t;echo strtr($argv[1],$p);

```

takes input from command line arguments; assumes that none of the arguments is `0`.

Run with `php -nr '<code>'`.
> 0 votes

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


title: crossed out 44 is still regular 44 ;(

text:
# Question
Title: crossed out 44 is still regular 44 ;(
## Introduction

On March 24th, 2015 *@isaacg* golfed his Pyth answer from 44 to 42 bytes. Since a crossed out 44 (~~44~~) looks a lot like a regular 44, *@Optimizer* made the following comment:

> striked out 44 is still normal 44 :(

After that, on October 21st, 2015, *@Doorknob♦* golfed his Ruby answer from 44 to 40 (and later 38) bytes and added the following part to his answer, with a link to that original comment of *@Optimizer*:

> crossed out 44 is still regular 44 ;(

This was the start of an answer-chaining meme, where every crossed out 44 (and in some occasions 4 or 444) linked back to the previous one.

Then on April 8th, 2017 (I'm not sure if this was the first answer to do so, but it's the earliest one I could find), *@JonathanAllan* golfed his Python answer from 44 to 39. He however used `<s> 44 </s>` so the 44 would look like this:  ~~44~~ , and added the following to his answer:

> Crossed out  44  is no longer 44 :)

And that was basically the (beginning of the) end of the meme.

## Challenge

As for this challenge: Given a list of positive integers and a date, output the list comma-and-space separated where every number except for the last one is placed between `<s>...</s>` tags.

In addition, if any of the crossed out numbers is in the sequence `[4, 44, 444, 4444, ...]` (A00278 on oeis.org):

* If the date is before April 8th, 2017: Also output the exact (all lowercase and with semicolon emoticon) text `crossed out N is still regular N ;(` (`N` being the crossed out number from the sequence) on a second line.
* If the date is April 8th, 2017 or later: The crossed out number `N` from the sequence should have the leading and trailing ` ` added. No need for any additional lines of output.

**Examples:**

Input: `list = [50, 48, 44, 41]`, `date = January 1st, 2017`
Output:

```
<s>50</s>, <s>48</s>, <s>44</s>, 41
crossed out 44 is still regular 44 ;(

```

Input: `list = [500, 475, 444, 301, 248]`, `date = June 2nd, 2018`
Output:

```
<s>500</s>, <s>475</s>, <s> 444 </s>, <s>301</s>, 248

```

## Challenge rules:

* You can assume the input-list is a sorted list from largest to smallest, only containing positive integers. In reality a byte-count can also go up due to bug-fixes, but for the sake of this challenge we pretend it only goes down.
* You can assume only a single number from the sequence `[4, 44, 444, 4444, ...]` is present in the input-list (if any).
* The output format is either printed to STDOUT, or returned as a string (or character array/list/2D-array if that's preferable). A trailing newline is of course optional.
* The output format is strict. `<s>...</s>` is mandatory; ` ... ` is mandatory; `", "` (comma and space) is mandatory; and `\ncrossed out ... is still regular ... ;(` exactly is mandatory (on a separated line).
* You may take the input-date as date-objects; timestamps; loose integers for year, month, and day; a single number in the format `yyyyMMdd`; integer days since December 31st, 1899 (which would be `42832` for April 8th, 2017); or any other reasonable input-format. The date if-statement isn't the major part of this challenge.
* The input integer-list can also be a list of strings if you want.
* You don't have to add the `<sup>...</sup>` tags to the `crossed out ... is still regular ... ;(` line as is usually done with the actual meme answers.
* You can assume the input-list will never contain byte-counts outside the `[1, 50000]` range (so you'll only have these five `{4, 44, 444, 4444, 44444}` to worry about).

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input: [50, 48, 44, 41] and January 1st, 2017
Output:
<s>50</s>, <s>48</s>, <s>44</s>, 41
crossed out 44 is still regular 44 ;(

Input: [500, 475, 444, 301, 248] and  June 2nd, 2018
Output:
<s>500</s>, <s>475</s>, <s> 444 </s>, <s>301</s>, 248

Input: [8, 6, 4] and December 5th, 2017
Output:
<s>8</s>, <s>6</s>, 4

Input: [8, 6, 4, 3, 2] and September 15th, 2015
Output:
<s>8</s>, <s>6</s>, <s>4</s>, <s>3</s>, 2
crossed out 4 is still regular 4 ;(

Input: [119, 99, 84, 82, 74, 60, 51, 44, 36, 34] and February 29th, 2016
Output:
<s>119</s>, <s>99</s>, <s>84</s>, <s>82</s>, <s>74</s>, <s>60</s>, <s>51</s>, <s>44</s>, <s>36</s>, 34
crossed out 44 is still regular 44 ;(

Input: [404, 123, 44] and March 4th, 2016
Output:
<s>404</s>, <s>123</s>, 44

Input: [4, 3] and April 8th, 2017
Output:
<s> 4 </s>, 3

Input: [44] and October 22nd, 2017
Output:
44

Input: [50000, 44444, 1500] and August 1st, 2018
Output:
<s>50000</s>, <s> 44444 </s>, 1500

Input: 50, 38, 23 and September 8th, 2001
Output:
<s>50</s>, <s>38</s>, 23

```

# Answer
> 8 votes
# Jelly,  ~~444~~ , ~~94~~, 93 bytes

```
Ñȧ$“ ”,¤j$€io.ɗ¦@Ṗj@€“<s>“</s>”oj⁾,
⁴>⁽A€
“¢⁻$gẆẠ⁷Ṭ]ḳṁṛż?=çỊI×V»Ỵjṭ⁷ẋÇ¬ȧẠƲ
ṖḟÐḟ”4Ḣµñ³,Ç

```

A full program. The inputs are a list of strings and a date taken as integer days since January the first 1970 (making 17264 April the eighth 2017)

**Try it online!**

### How?

```
Ñȧ$“ ”,¤j$€io.ɗ¦@Ṗj@€“<s>“</s>”oj⁾,  - Link 1: L = list of characters ("4...4") OR integer (0),
                                          -         R = list of lists of characters (the strings provided to the program)
  $                                       - last 2 links as a monad:
Ñ                                         -   call next Link (2) as a monad
                                          -   ...gets: is date input to program greater than 2017-04-07?
 ȧ                                        -   AND (if so gets the value of L, else 0), say X
                    ¦@                    - sparse application (with swa@pped @rguments)...
                      Ṗ                   - ...with right argument = popped R (without it's rightmost entry)
                   ɗ                      - ...to: last 3 links as a dyad
                i                         -          first index of X in popped R (0 if no found, so 0->0)
                  .                       -          literal 0.5
                 o                        -          OR (change any 0 to 0.5)
                                          -        ...i.e. index of "4...4" if L was one or 0.5, an invalid index
              $€                          - ...do: for €ach... last 2 links as a monad:
            ¤                             -          nilad followed by link(s) as a nilad:
   “ ”                               -            literal list of characters = " "
           ,                              -            pair (with itself) = [" ", " "]
             j                            -            join (with the item) e.g.: " 444 " or [" ", 0, " "]
                          “<s>“</s>”      - literal list of lists of characters = ["<s>", "</s>"]
                       j@€                - for €ach... join (with swa@pped @rguments)
                                    o     - OR with R (vectorises, so adds the popped entry back onto the right-side)
                                      ⁾,  - literal list of characters = ", "
                                     j    - join

⁴>⁽A€ - Link 2: greater than 2017-04-07?
⁴     - program's 4th argument (2nd input)
  ⁽A€ - literal 17263 (days(2017-04-07 - 1970-01-01))
 >    - greater than?

“¢⁻$gẆẠ⁷Ṭ]ḳṁṛż?=çỊI×V»Ỵjṭ⁷ẋÇ¬ȧẠƲ - Link 3: L = list of characters ("4...4") OR integer (0)
“¢⁻$gẆẠ⁷Ṭ]ḳṁṛż?=çỊI×V»           - compressed list of characters = "crossed out \n is still regular \n ;("
                     Ỵ           - split at newlines = ["crossed out ", " is still regular ", " ;("]
                      j          - join with L
                        ⁷        - literal newline character
                       ṭ         - tack (add to the front)
                              Ʋ  - last 4 links as a monad:
                          Ç      -   call last Link (2) as a monad
                           ¬     -   NOT
                             Ạ   -   All (1 if L is "4...4", 0 if L is 0)
                            ȧ    -   AND
                         ẋ       - repeat (i.e. get the list of characters to print or an empty list)

ṖḟÐḟ”4Ḣµñ³,Ç - Main Link: list of strings, integer (days since 1970-01-01)
Ṗ            - pop (list of strings without it's rightmost entry)
  Ðḟ         - filter discard if:
 ḟ           -   filter discard any which are in...
    ”4       -   ...literal character '4'
      Ḣ      - head (yields 0 if list is now empty)
       µ     - new monadic chain, call that X
         ³   - program's 3rd argument (1st input) - call that Y)
        ñ    - call next Link (1) as a dyad (i.e. f1(X, Y))
           Ç - call last Link (3) as a monad (ie. f3(X))
          ,  - pair
             - implicit (smashing) print

```

# Answer
> 4 votes
# Python 2, ~~208~~ ~~204~~  ~~203~~ ~~201~~ 197 bytes

Takes input as a list of strings, and an int of `yyyymmDD`

```
def f(l,d):
 A=a=d>20170407;r=[]
 for n in l[:-1]:x=set(n)=={'4'};S=' '*x*a;r+=['<s>'+S+n+S+'</s>'];A=x*n or A
 print', '.join(r+l[-1:])+'\ncrossed out %s is still regular %s ;('%(A,A)*(a*A<A)

```

Try it online!

# Answer
> 3 votes
# Excel VBA, 217 bytes

VBE immediate window function that takes input array from range `[A:A]`, and date from range `[B1]` and outputs to the console.

```
c=[Count(A:A)]:d=[B1]>42832:For i=1To c-1:n=Cells(i,1):l=InStr(44444,n):s=IIf(d*l," ",""):v=IIf((d=0)*l,n,v):?"<s>"s;""&n;s"</s>, ";:Next:?""&Cells(i,1):?IIf(v,"crossed out "&v &" is still regular "&v &" ;(","");

```

### Ungolfed and Commented

```
c=[Count(A:A)]                  ''  Get numer of elements
d=[B1]>42832                    ''  Check if date is after 7 Apr 2017,
For i=1To c-1                   ''  Iterate over index
n=Cells(i,1)                    ''  Get array val at index
l=InStr(44444,n)                ''  Check if val is all 4s
s=IIf(d*l," ","")          ''  If after 7 Aug 2017, and All 4s, let `s` be " "
v=IIf((d=0)*l,n,v)              ''  If all 4s, and not after date, let v hold n, else hold v
?"<s>"s;""&n;s"</s>, ";         ''  Print striked vales, with " ", if applicable
Next                            ''  Loop
?""&Cells(i,1)                  ''  Print last value in array
                                ''  (below) Print meme, if needed
?IIf(v,"crossed out "&v &" is still regular "&v &" ;(","");

```

-2 bytes for changing date format to `YYYYMMDD`

-1 byte for comparing to `42832` (int value for `07 Apr 2017`), Thanks @Neil

-2 bytes for removing `1,` from the `InStr` statement, Thanks @SeaDoggie01

# Answer
> 2 votes
# Retina 0.8.2, 130 bytes

```
$
;42833
O`;.{5}
\b(4+),(?=.*;42833;)
&$1&,
&

.{12}$

\b(4+),.*
$&¶crossed out $1 is still regular $1 ;(
(.+?),
<s>$1</s>,

```

Try it online! Link includes test cases. Uses Excel date stamps (days since 1899-12-31 but including 1900-02-49). 141 bytes for a version that takes ISO dates:

```
$
;2017-04-08
O`;.{10}
\b(4+),(?=.*;2017-04-08;)
&$1&,
&

.{22}$

\b(4+),.*
$&¶crossed out $1 is still regular $1 ;(
(.+?),
<s>$1</s>,

```

Try it online! Link includes test cases. Explanation:

```
$
;2017-04-08

```

Append the cut-off date to the input.

```
O`;.{10}

```

Sort the dates. If the given date is on or after the cut-off date then the first date will be the cut-off date.

```
\b(4+),(?=.*;2017-04-08;)
&$1&,
&

```

In that case, wrap the `4+` in ` ` (using two stages as it saves a byte).

```
.{22}$

```

Delete the dates as they have done their job.

```
\b(4+),.*
$&¶crossed out $1 is still regular $1 ;(

```

If there's an unspaced `4+`, then append the meme.

```
(.+?),
<s>$1</s>,

```

Strike out all of the obsolete byte counts.

# Answer
> 2 votes
# Haskell, 227 bytes

```
i[]=1>0;i('4':s)=i s;i(_:_)=0>1
f l d=m l++c where a=head$filter i l;t d|d<42832=("","\ncrossed out "++a++" is still regular "++a++" ;(")|1>0=(" ","");(b,c)=t d;w n|i n=b++n++b|1>0=n;m[n]=n;m(x:s)="<s>"++w x++"</s>, "++m s

```

Try it online! Run `f` with list `l` and date `d`. 42832 is the changing date.

# Answer
> 2 votes
# Ruby, ~~208~~ ~~184~~ 180 bytes

TIO-test

Thanks for @KevinCruijssen for saving 2 bytes!

```
->n,d{*h,t=n;i=20170408>d;f=?\n;h.map{|u|o=u.digits|[]==[4];f=o&&i ?f+"crossed out #{u} is still regular #{u} ;(":f;o&&!i ?"<s> #{u} </s>":"<s>#{u}</s>"}*", "+", #{t}"+f}

```

It's a lambda function that takes a list of numbers and an integer as a date in the format of `YYYYmmdd`.

# Answer
> 2 votes
# JavaScript (Node.js), 173 bytes

```
a=>d=>a.map(x=>--i<1?x:`<s>${(b=/^4+$/.exec(x)?(c=x,d)<14915808e5?n=[]:" ":"")+x+b}</s>`,n="",c=0,i=a.length).join`, `+(n&&`
crossed out ${c} is still regular ${c} ;(`)

```

Try it online!

Using curry syntax `f(array)(js_timestamp)`

# Answer
> 1 votes
# JavaScript, 194 bytes

```
(a,d,l=a.pop(),n=a.find(x=>/^4+$/.exec(x)),s=a.map(n=>`<s>${n}</s>, `).join``+l)=>d<1491609600?n?s+`
crossed out ${n} is still regular ${n} ;(`:s:s.replace(/>(4+)</g,(_,m)=>`> ${m} <`)

```

```
f=
(a,d,l=a.pop(),n=a.find(x=>/^4+$/.exec(x)),s=a.map(n=>`<s>${n}</s>, `).join``+l)=>d<1491609600?n?s+`
crossed out ${n} is still regular ${n} ;(`:s:s.replace(/>(4+)</g,(_,m)=>`> ${m} <`)

const date = s => Date.parse(s) / 1000
for(const output of [
 f([50, 48, 44, 41], date('January 1, 2017')),
 f([500, 475, 444, 301, 248], date('June 2, 2018')),
 f([8, 6, 4], date('December 5, 2017')),
 f([8, 6, 4, 3, 2], date('September 15, 2015')),
 f([119, 99, 84, 82, 74, 60, 51, 44, 36, 34], date('February 29, 2016')),
 f([404, 123, 44], date('March 4, 2016')),
 f([4, 3], date('April 8, 2017')),
 f([44], date('October 22, 2017')),
 f([50000, 44444, 1500], date('August 1, 2018')),
 f([50, 38, 23], date('September 8, 2001')),
]) console.log(output)
```

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


title: Everyone Ought to Have a Friend

text:
# Question
Title: Everyone Ought to Have a Friend
An isolated character is a character (other than a newline) that doesn't have an adjacent character of the same type. Adjacent characters can be to the left, the right above or below, but not diagonals. For example in the following text `H` is isolated:

```
Ybb
YH%
%%%%

```

All the other characters are not isolated because each of them has at least one other character of the same type adjacent.

Your task is to write a program that takes a string as input and determines the number of isolated characters.

## Scoring

You answer will be scored by two metrics. The first is the number of isolated characters in your program. You should aim to minimize this. The second will be the number of bytes in your program. You should minimize this as well. Program size will act as a tie breaker for the first criterion.

## Additional Rules

* You should support input on the printable ascii range plus any characters you use in your program.
* You may consider a line break to either be a newline character or a newline followed by a line feed.
* You may take input in any reasonable format. This includes a list of lines.

## Test Cases

```
Ybb
YH%
%%%%

```

\\$1\\$

---

```
Aaaab
uuu
yyybbb

```

\\$2\\$

---

```
A

```

\\$1\\$

---

```
qqWWaaww

```

\\$0\\$

# Answer
> 7 votes
# Python 2, 0 (~~350~~ ~~344~~ ~~314~~ ~~309~~ ~~301~~ ~~298~~ 291 bytes)

```
def f(tt):11
def f(tt):
 tt=tt.split('\n')
 r =0#.split('\n')
#r  0#
#for
 for  ii,ll in enumerate(tt):
  for jj,cc in enumerate(ll):
##for+=1-(
    r+=1-(cc in ll[(jj or 2)-1:jj+2:2]    +''.join(ll[jj:
 jj+1]for ll in tt[(ii or 2)-1:ii+2:2]))##+''.join(ll[jj:
#  +1]for
#print r
 print r

```

Try it online!

<sub>-7 bytes, thanks to Jo King</sub>

# Answer
> 5 votes
# Clean, 0 (~~439~~ ... 415 bytes)

*-11 thanks to Ørjan Johansen*

Finally a challenge where I can score 0 with Clean!
(and normally it's *bad* at source-layout challenges!)

```
//module
  module d
import StdEnv,ArgEnv,Data.List,Data.Maybe
import StdEnv,ArgEnv,Data.List,Data.Maybe
Start=sum[1\\i<-l&v<-[0..],_<-i&u<-[0..]|all((<>)(?u v))[?(u-1)v,?(u+1)v,?u(v-1),?u(v+1)]]
Start=sum[1\\i<-l&v<-[0..],_<-i&u<-[0..]|all((<>)(?u v))[?(u-1)v,?(u+1)v,?u(v-1),?u(v+1)]]
l=mklines[c\\c<-:getCommandLine.[1]]
l=mklines[c\\c<-:getCommandLine.[1]]
?x=mapMaybe(\k=k!?x)o(!?)l
?x=mapMaybe(\k=k!?x)o(!?)l

```

Try it online!

The TIO link uses `module main` due to the way Clean is implemented on TIO, but `module d` will work if you name the file `d.icl` instead of `main.icl` as TIO does.

One of the old lines explained (new version is the same thing in a different order):

```
Start                                       // entry point
 = let                                      // define locals
  l = mklines                               // `l` is argument split at newlines
   [c \\ c <-: getCommandLine.[1]];         // the second command-line arg turned into a [Char]
  ? x y                                     // function ? of coordinate (x,y)
   = mapMaybe                               // if the argument isn't Nothing
    (\k = k!?x)                             // try taking the `x`-th index
    (l!?y)                                  // of the `y`-th index of `l`
  in                                        // in the context of
   sum [                                    // the sum of
    1                                       // the integer one
    \\ i <- l & v <- [0..]                  // for every index in `l`
    , _ <- i & u <- [0..]                   // for every subindex in `l`
    | all (                                 // where all of the second argument
      (<>)(?u v)                            // doesn't equal the first argument
     ) [?(u-1)v, ?(u+1)v, ?u(v-1), ?u(v+1)] // over every adjacent element
   ]

```

# Answer
> 5 votes
# JavaScript (ES6), 0 (154 bytes)

*Saved ~~2~~ 4 bytes thanks to @ØrjanJohansen*

Takes input as an array of strings.

```
s  =>
s//=>(s,y,a
.map((s,y,a)=>[...s]
.map((c,x  )=>[...s]
&&//++c,x
 s[x+1]==c|
 s[x-1]==c|
(a[y-1]||0)[x]==c|
(a[y+1]||0)[x]==c||
  i++),i=0)
&&i//),i=

```

Try it online!

# Answer
> 4 votes
# Jelly, 0 (~~41 27~~ 25 bytes)

```
ŒĠạþ`€Ẏ§CẠ€S
ŒĠạþ`€Ẏ§CẠ€S

```

Try it online!

Takes input as list of lines. The first line in the code never does anything and is only there to minimize isolated characters.

```
ỴŒĠạþ`€Ẏ§1eⱮCS
Ỵ                 Split the text on newlines.
 ŒĠ               Group the multidimensional indices by their value.
      €           For each list of indices:
   ạ                Take the absolute difference...
    þ`              ...between each pair.
       Ẏ          Concatenate the lists of differences.
        §         Sum the x & y differences. This computes the Manhattan distance.
                  At this point we have a list for each character in the text of
                  Manhattan distances between it and it's identical characters.
         1eⱮ      Is there a 1 in each of the lists? None for isolated characters.
            C     Complement: 0 <-> 1.
             S    Sum. Counts the isolated characters

```

# Answer
> 3 votes
# MATL, 0 (54 bytes)

```
TTTTf"Go@X!0JQJ&(d@_X!]***ggss
%%%%f"Go@X!0JQJ&(d@_X!]

```

Input is a cell array of strings, one for each line: `{'line 1', 'line 2', 'and line 3'}`.

Try it online! Or verify test cases and source code.

# Answer
> 2 votes
# 05AB1E, 0 (101 bytes)

```
žGçU|€SXζζD"εγεDgDisëXи]"©.V˜sø®.V€Sø˜‚øʒË}ʒXå≠}gq
žGçU|€SXζζD"εγεDgDisëXи]"©.V˜sø®.V€Sø˜‚øʒË}ʒXå≠}gq

```

Try it online.

This is one of the ugliest and longest 05AB1E programs I've ever written.. \>.\> This challenge is deceivingly hard in 05AB1E. I have no doubt in mind the byte-count can at least be halved or even three/four times as small by using a different approach (or even with a similar approach), but I currently don't see how. I'm just glad it's working right now.. If someone else posts a much shorter 05AB1E answer with some smart tricks I'll probably delete this answer out of shame... xD

**Explanation:**

```
žGç                # Character with unicode 32768 ('耀')
   U               # Pop and store it in variable `X`
                   # (This character is not part of the printable ASCII, nor of my 05AB1E code)
|                  # Take the multi-line input as list
                   #  i.e. "Ybb\nYH%\n%%%%" → ["Ybb","YH%","%%%%"]
 €S                # Convert each string to a list of characters
                   #  i.e. ["Ybb","YH%","%%%%"] → [["Y","b","b"],["Y","H","%"],["%","%","%","%"]]
   Xζζ             # Zip with character `X` as filler twice to make the lines of equal length
                   #  i.e. [["Y","b","b"],["Y","H","%"],["%","%","%","%"]]
                   #   → [["Y","b","b","耀"],["Y","H","%","耀"],["%","%","%","%"]]
      D            # Duplicate this list
"             "    # Create a string
               ©   # Which we store in the register (without popping)
                .V # And execute that string as 05AB1E code
 ε                 #  Map each inner list to:
  γ                #   Split in chunks of the same characters
                   #    i.e. [["Y","b","b"],["Y","H","%"],["%","%","%","%"]]
                   #     → [[["Y"],["b","b"]],[["Y"],["H"],["%"]],[["%","%","%","%"]]]
   ε               #   Map each of those to:
    D              #    Duplicate the current inner list
     gDi           #    If its length is exactly 1:
        s          #     Swap so the mapping keeps the duplicated single character (as list)
       ë           #    Else:
        Xи         #     Take character `X` repeated the length amount of times
                   #      i.e. ["%","%","%","%"] (length 4) → ["耀","耀","耀","耀"]
          ]        #  Close the if-else and both maps
           ˜       #  Flatten the list to a single list of characters
                   #   i.e. [[["Y"],["耀","耀"],["耀"]],[["Y"],["H"],["%"],["耀"]],[["耀","耀","耀","耀"]]]
                   #    → ["Y","耀","耀","耀","Y","H","%","耀","耀","耀","耀","耀"]
s                  # Swap so the duplicate list is at the top of the stack
 ø                 # Swap its rows and columns
                   #  i.e. [["Y","b","b","耀"],["Y","H","%","耀"],["%","%","%","%"]]
                   #   → [["Y","Y","%"],["b","H","%"],["b","%","%"],["耀","耀","%"]]
  ®.V              # Execute the same piece of code again that we've stored in the register
     €S            # Convert each to a list of characters
                   #  i.e. [[["耀","耀"],["%"]],[["b"],["H"],["%"]],[["b"],["耀","耀"]],[["耀","耀"],["%"]]]
                   #   → [["耀","耀","%"],["b","H","%"],["b","耀","耀"],["耀","耀","%"]]
       ø           # Swap its rows and columns back again
                   #  i.e. [["耀","b","b","耀"],["耀","H","耀","耀"],["%","%","耀","%"]]
        ˜          # Flatten this list as well
‚                  # Pair both lists together
                   #  i.e. [["Y","耀","耀","耀","Y","H","%","耀","耀","耀","耀","耀"],
                   #        ["耀","b","b","耀","耀","H","耀","耀","%","%","耀","%"]]
 ø                 # Swap its rows and columns to create pairs
                   #  i.e. [["Y","耀"],["耀","b"],["耀","b"],["耀","耀"],["Y","耀"],["H","H"],["%","耀"],["耀","耀"],["耀","%"],["耀","%"],["耀","耀"],["耀","%"]]
  ʒË}              # Filter out any inner lists where both characters are not equal
                   #  i.e. [["耀","耀"],["H","H"],["耀","耀"],["耀","耀"]]
     ʒXå≠}         # Filter out any inner lists that contain the character `X`
                   #  i.e. [["H","H"]]
g                  # Take the length as result
                   #  i.e. [["H","H"]] → 1
 q                 # Stop the program, making all other characters no-ops
                   # (and output the length above implicitly)

```

# Answer
> 1 votes
# Python 3, 0 (323 bytes)

```
def f(s,e=enumerate):S={(x,y,c)for y,l in e(s.split("\n"))for x,c in e(l)};return-sum(~-any((x+u,y+v,c)in S for u,v in[(1,0),(~0,0),(0,~0),(0,1)])for x,y,c in S)
def f(s,e=enumerate):S={(x,y,c)for y,l in e(s.split("\n"))for x,c in e(l)};return-sum(~-any((x+u,y+v,c)in S for u,v in[(1,0),(~0,0),(0,~0),(0,1)])for x,y,c in S)

```

Try it online!

# Answer
> 1 votes
# Ruby, score 0, ~~237~~ 209 bytes

```
##->a{['',*a,''].each_cons(3).sum{|a,b,c|(0..b.size).count{|x|[[x>0&&b[x-1],a[x],b[x+1],c[x]]&[b[x
  ->a{['',*a,''].each_cons(3).sum{|a,b,c|(0..b.size).count{|x|[[x>0&&b[x-1],a[x],b[x+1],c[x]]&[b[x]]]==[[]]}}}

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 0 (279 bytes)

```
  s=>(b=s.map(Buffer)).map((x,i)=>x.filter((y,j)=>y-(g=(x,y)=>~~(b[x]&&b[x][y]))(i,j-1)&&y-g(i,j+1)&&y-g(i-1,j)&&y-g(i+1,j))).join``.length
//s=>(b=s.map(Buffer)).map((x,i)=>x.filter((y,j)=>y-(g=(x,y)=>~~(b[x]&&b[x][y]))(i,j-1)&&y-g(i,j+1)&&y-g(i-1,j)&&y-g(i+1,j))).join``.length

```

Try it online!

Receive input as array of lines.

---
Tags: string, source-layout, self-scoring
---


title: Without using numbers, Calculate Pi

text:
# Question
Title: Without using numbers, Calculate Pi
Inspired by Nicola Sap's Challenge

# Goal

Your challenge is to simply produce π with 232-1 digits. However today's twist, like the title implies, is to produce it without using any numbers or any π constants in your source-code.

# Input/Output

Your program will not be provided usable input. It can output in any reasonable format.

# Rules

* Standard Loop-Holes forbidden
* You cannot use numbers in your source code nor can you use a pi constant if it exists. If your language also has tau defined as 2pi, that's also banned. Numbers are in the range \[0-9\]
* ~~You must output as many digits as you can~~ You must output 2^32-1 digits of pi, including the 3. (This has been changed due to the arbitrary nature of the original task)
* Your Program must terminate, or at least theoretically terminate given enough time. Crashing is an acceptable way to terminate.

# Scoring

This is code golf so shortest answer wins.

A Million Digits of Pi for your use

# Answer
# Perl 6, 67 bytes

```
{$!=.FatRat²/$!+$_+$_-?e}for ²…¹;say substr ⁴/$!,^²³²

```

Try it online!

Takes a *very* long time to compute. As an example here's an altered version that only prints the first 1000 digits.
> 3 votes

# Answer
# Mathematica, ~~42~~ 39 bytes

`N[Log[-(d=I/I)]/I,((c=d+d)^c^c^c)^c-d]&`

~~Output~~ Returns exactly 4294967295 digits as requested.

If more digits were allowed, then by outputting 7.76e17 digits (if even possible lol), 26 bytes would be possible:

`N[Log[-E/E]/I,E^(E^E*E)]&`

### Sorry but `Pi = Ln(-1)/i`.
> 1 votes

# Answer
# GolfScript, ~~70~~ 85 bytes

```
;''!..):t{](..+.*:a@~@*\a(*@)\@}t.+.+t+:T t..*.*t*?(:b?*@;\{.@[\].~/\~%T*@}b*;;]("."@

```

*+15 bytes because I can't read.*

Try it online!

Or, actually, don't. Try this online instead, which calculates 4 digits.
> 1 votes

---
Tags: code-golf, restricted-source, pi
---


title: Hyperoperation Golfing

text:
# Question
Title: Hyperoperation Golfing
# Introduction

> In mathematics, the hyperoperation sequence is an infinite sequence of arithmetic operations (called hyperoperations) that starts with the unary operation of successor (n = 0), then continues with the binary operations of addition (n = 1), multiplication (n = 2), and exponentiation (n = 3), after which the sequence proceeds with further binary operations extending beyond exponentiation, using right-associativity.

(Source)

---

# Challenge

Your challenge is code this sequence, given 3 inputs, *n*, *a*, and *b*, code a function such that $${\displaystyle H\_{n}(a,b)={\begin{cases}b+1&{\text{if }}n=0\\a&{\text{if }}n=1{\text{ and }}b=0\\0&{\text{if }}n=2{\text{ and }}b=0\\1&{\text{if }}n\geq 3{\text{ and }}b=0\\H\_{n-1}(a,H\_{n}(a,b-1))&{\text{otherwise}}\end{cases}}}$$ (Also from Wikipedia.)

---

# Input

3 positive decimal integers, *n*, *a*, and *b*, taken from STDIN, function or command line arguments, in any order. Make sure to specify this in your answer

---

# Output

The result of applying \\$H\_{n}(a,b)\\$ with the inputs

---

# Example inputs and outputs

Input: `0, 6, 3` Output: `4`

---

Input: `4 5 2` Output: `3125`

---

# Restrictions

* Your program/function should take input in base 10
* Don't use any built in function that already provides H(n, a, b)
* Standard loopholes apply

---

This is , so shortest code in bytes wins!

# Answer
# JavaScript (ES6),  ~~49~~  47 bytes

Takes input as `(a)(b,n)`.

```
a=>g=(b,n)=>n*b?g(g(b-1,n),n-1):-~[b,a-1,-1][n]

```

Try it online!

### Commented

```
a =>                  // main function taking a
  g = (b, n) =>       // g = recursive function taking b and n
    n * b ?           // if neither n nor b is equal to 0:
      g(              //   go recursive:
        g(b - 1, n),  //     b = g(b - 1, n)
        n - 1         //     decrement n
      )               //   end of recursive call
    :                 // else:
      -~[             //   this is a leaf node:
        b,            //     if n = 0, return b + 1
        a - 1,        //     if n = 1, return (a - 1) + 1 = a
        -1            //     if n = 2, return -1 + 1 = 0
      ][n]            //     if n > 2, return -~undefined = 1

```
> 3 votes

# Answer
# Dyalog APL, 35 bytes

```
{⍺=0:⍵+1⋄⍵=0:⍺⍺⍵1⊃⍨3⌊⍺⋄(⍺-1)∇⍺∇⍵-1}

```

Try it online!
> 3 votes

# Answer
# Elixir, 86 bytes

(assumes functions can take a reference to itself as an argument)

```
fn 0,_,b,_->b+1
1,a,0,_->a
2,_,0,_->0
_,_,0,_->1
n,a,b,f->f.(n-1,a,f.(n,a,b-1,f),f)end

```

Try it online!
> 1 votes

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


# Question
Title: The Characters in the String Go Round and Round
<sup>(Inspired by an early draft of PhiNotPi's fractal line challenge.)</sup>

You're given a width `W > 1`, a height `H > 1` and string consisting of `2(W+H-2)` printable ASCII characters. The task is to print this string wrapped around a rectangle of the given width and height, starting in the top left corner, in a clockwise sense. The rectangle's inside is filled with spaces. The test cases should hopefully make this very clear.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and either printing the result to STDOUT (or closest alternative) or returning it as a string.

There must be no leading or trailing spaces (apart from those that might be in the input string). You may optionally output a single trailing newline.

This is code golf, so the shortest submission (in bytes) wins.

## Test Cases

Each test case is `"String" W H` followed by the expected output.

```
"Hello, World! "
5 4
Hello
    ,
!
dlroW

"+--+|||+--+|||"
4 5
+--+
|  |
|  |
|  |
+--+

">v<^"
2 2
>v
^<

"rock beats scissors beats paper beats "
11 10
rock beats
          s
s         c
t         i
a         s
e         s
b         o
          r
r         s
epap staeb

Note that the following string contains an escaped '"'.
"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
46 3
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN
~                                            O
}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQP

```

## Leaderboards

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

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

```
# Language Name, N bytes

```

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

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

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=47710;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

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

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

# Answer
# CJam, 27 bytes

```
Nl~:L/(os\2-{)L2-S*@(N@}*W%

```

I don't really CJam, but I think this beats Martin. The main difference is that we push a newline *before* reading input and print the first line immediately, negating the need to store the height.

Takes input in the order

```
H "String" W

```

Try it online.
> 9 votes

# Answer
## Python 2, 95 bytes

```
s,m,n=input()
print s[:n]
for i in range(m-2):print s[~i]+' '*(n-2)+s[n+i]
print s[1-m::-1][:n]

```

Prints the first line, then the two vertical lines, then the last line.

There's got to be something shorter than writing `print` three times, but everything I've tried so far with saving to a variable and `'\n'.join` has been longer.
> 10 votes

# Answer
# Pyth, 47 46 45 40 37 36 bytes

This is the obvious approach implemented in Pyth. It prints the first line by indexing `0:width` and then the middle, then the end.

Thanks to @Jakube for the tip with using `z` and `Q` for two inputs and using `p`.

```
AkYQ<zkV-Y2p*d-k2@zt_N@z+kN;<_<z-2Yk

```

Takes input from stdin as a string and as a tuple of dimensions, newline separated:

```
Hello, World!
5, 4

```

and writes to stdout.

Try it here.

```
A              Double assignment
 kY            The vars k and Y
 Q             The dimension tuple
<zk            Prints out first line by doing z[:width]
V-Y2           For N in height-2
 p             Print out everything
  *d           Repeat " "
   -k2         Width-2 times
  @z           Index z
   -_N1        At index -N-1
  @z           Index z
   +kN         At index k+N
;              Close out loop
<_<z-2Yk       Print last line

```
> 9 votes

# Answer
# CJam, ~~31~~ 30 bytes

At Optimizer's insistence, here is my own attempt. I'm not a fan of winning my own challenges, so I'm counting the APL family (or someone better at CJam) to beat this. ;)

```
l~:H;:V/(N@s{)V2-S*@(N@}H2-*W%

```

Takes input in the same order as given in the question:

```
"Hello, World! " 5 4

```

Test it here.

One byte saved thanks to Optimizer.

## Explanation

Originally, I had a really nice idea for starting with the rectangle of spaces and then literally wrapping the string around it while rotating the entire grid four times. However, I couldn't seem to get that to work in case where width or height or both are `2`. So I tried the naive approach (print top, loop over sides, print bottom), and surprisingly it turned out to be really short.

```
l~                             "Read and evaluate the input.";
  :H;                          "Store the height in H and discard it.";
     :V/                       "Store the width in V and split the input into chunks of size V.";
        (N                     "Slice off the first such chunk and push a newline.";
          @s                   "Pull up the other chunks and join them back together.";
            {          }H2-*   "Repeat this block H-2 times, printing the sides.";
             )                 "Slice off the last character of the string.";
              V2-S*            "Push V-2 spaces.";
                   @(          "Pull up the remaining string and slice off the first character.";
                     N@        "Push a newline and pull up the remaining string.";
                            W% "Reverse the remainder of the string, which is the bottom row.";

```
> 9 votes

# Answer
# J, 61 bytes

Method:

Starting from a `(height-2)*(width-2)` block of spaces we take the necessary amount of characters from the end of the string and add it to the current block. We repeat this 4 times. The total 5 states illustrated with the `'Hello, World! ' 5 4` example (spaces replaced with `X`s for readability):

```
XXX   !_   orld   ,_W   Hello
XXX   XX   XXX!   XXo   _XXX,
      XX   XXX_   XXr   !XXX_
      XX          XXl   dlroW
                  _!d

```

The code:

```
4 :'|:>{:((}.~{:@$);({.~{:@$)|.@|:@,])&>/^:4(|.x);'' ''$~y-2'

```

Explicit function definition. The two-operand function takes a string as left argument and a list of two integers as right argument.

Example usage:

```
   wrap_on=.4 :'|:>{:((}.~{:@$);({.~{:@$)|.@|:@,])&>/^:4(|.x);'' ''$~y-2'

   'Hello, World! ' wrap_on 5 4
Hello
    ,
!
dlroW

   '>v<^' wrap_on 2 2
>v
^<

```

Try it online here.
> 5 votes

# Answer
# Pyth, ~~38~~ 37

```
AGHQ<zGFNC,_>z_ttH>zGj*dttGN)<>_zttHG

```

I originally had a different 38 solution, but it was basically golfed solution of Maltysen's answer. So I decided to go a little bit different.

Try it online.

```
              implicit: z=string from input, Q=pair of numbers from input
AGHQ          G=Q[0] (width), H=Q[1] (height)
<zG           print z[:G]
    _>z_ttH     last H-2 chars reversed
    >zG         all chars from the Gth position to end
  C,           zip these 2 strings to pairs
FN            for each pair N:
  j*dttGN       seperate the two chars by (G-2) spaces and print
)             end for
<>_zttHG     print last line z[::-1][H-2:][:G]

```
> 4 votes

# Answer
# JavaScript (ES6), 110 ~~115~~

Function with 3 parameters, returning a string

```
F=(s,w,h,q=h+(w-=2),t=b='')=>
[for(c of s)q?t+=q<h?c+'\n'+s[w+h+w+q--]+' '.repeat(q&&w):(b+=s[w+q--],c):q]
&&t+b

```

**Chrome** version **119**: no short format for functions, no default parameters. No reason to use `for(of)` even if it is supported

```
function F(s,w,h){
  for(q=h+(w-=2),t=b=i='';
      q;
      q<h?t+='\n'+s[w+h+w+q--]+' '.repeat(q&&w):b+=s[w+q--])
    t+=s[i++];
  return t+b
}

```

**ES5** version **126**: no for(of), no string.repeat

```
function F(s,w,h){
  for(q=h+(w-=2),t=b=i='';
      q;
      q<h?t+='\n'+s[w+h+w+q--]+Array(q&&-~w).join(' '):b+=s[w+q--])
    t+=s[i++];
  return t+b
}

```

**Ungolfed**

```
F=(s,w,h)=>
{
  var q = h+(w-=2), // middle length
      t = '', // top and body
      b = ''; // bottom row
  for(c of s)
    if (q > 0)
    {
      if (q < h)
      {
        t += c+'\n'; // right side, straight
        t += s[w+h+w+q]; // left side, backwards
        if (q > 1) // body fill, except for the last line
          t += ' '.repeat(w)
      }
      else
      {
        t+=c, // top, straight
        b+=s[w+q] // bottom, backwards
      }
      --q
    }
  return t+b

```

**Test** In Firefox/FireBug console

```
;[["Hello, World! ", 5, 4],["+--+|||+--+|||",4,5],[">v<^",2,2]
,["rock beats scissors beats paper beats ",11,10]
,["!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",46,3]]
.forEach(test => console.log(F(...test)))

```

*Output*

```
Hello
    ,
!
dlroW

+--+
|  |
|  |
|  |
+--+

>v
^<

rock beats
          s
s         c
t         i
a         s
e         s
b         o
          r
r         s
epap staeb

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN
~                                            O
}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQP

```
> 4 votes

# Answer
# Python 2, 97 bytes

```
def f(s,w,h):print s[:w];i=0;exec'print s[~i]+" "*(w-2)+s[w+i];i+=1;'*(h-2);print s[1-h:w+h-3:-1]

```

Taking the direct approach.
> 3 votes

# Answer
# Haskell, ~~164~~ 156 bytes

```
import Data.List
r=replicate
p w h(s:t)=unlines$fst$n$n$n$n(r h$r w ' ',(w,h,s:t++[s]))
n(_:b,(w,h,s))=(transpose$map reverse$(take w s):b,(h,w,drop(w-1)s))

```

The function `p` doesn't print the output, but returns it as a string, e.g `p 4 5 "+--+|||+--+|||"` -\> `"+--+\n| |\n| |\n| |\n+--+\n"`. For better display use `putStr`:

```
putStr $ p 4 5 "+--+|||+--+|||"

+--+
|  |
|  |
|  |
+--+

```

How it works: I create a `w` x `h` block of spaces and replace the first line with the beginning of the input string. Then I rotate the block counterclockwise and repeat replacing the first line another three times.

To prevent cutting of the first character again after turn #4, I append it to the input string before starting.

```
"Hello World" example, 5 x 4

         |  Start               Turn #1          Turn #2     Turn #3   Turn #4
---------+--------------------------------------------------------------------
String   |  "Hello, World! H"   "o, World! H"    "World! H"  "d! H"    ""
left     |
         |
Block    |  <empty>             Hello            o, W        World     d! H
before   |                                       l                     l  e
rotating |                                       l           ,         r  l
         |                                       e           olleH     o  l
         |                                       H                     W ,o

```

Edit: found a better way to solve the cut-off-first-character-after-turn-#4 problem.
> 3 votes

# Answer
# \>\<\>, ~~82~~ 80 + 3 = 83 bytes

```
:2-&\
v!?:<oi-1
/?(0:i
\~ao{2-{~}
\{:?!v1-}o&:&
>:?v!~{{o}ao4.
^  >" "o1-
o;!?l<

```

**Esolang page for \>\<\> (Fish)**

This turned out to be shorter than I expected. It uses the straightforward approach of printing the first line, then the columns padded with the central spaces, then the last line.

Input the string via STDIN and the height and width via command line with the `-v` flag, like so:

```
py -3 fish.py round.fish -v <height> <width>

```

---

## Explanation

```
:2-&           Put W-2 in the register
:?!v1-io       Directly print the first W characters of the input
i:0(?/         Read the rest of the input
~ao{2-{~}      Pop a few leftovers 0s from above, decrement H by 2 and print a newline
               Stack now consists of H = H-2 at the bottom and the rest of the input reversed

[loop]

{:?!v          If H is 0...
  ~                Pop the 0
  l?!;o            Print the rest of the (reversed) input

               Otherwise...
  1-}              Decrement H
  o                Output the top of stack
  &:&              Copy I = W-2 from the register
  :?               If I is nonzero...
    " "o1-             Print a space and decrement I, then repeat from the previous line
  {{o}ao           Print the bottom input character and output a newline
  4.               Jump to the start of the loop (note that I = 0 is leftover from above)

```
> 3 votes

# Answer
# Postscript, 62 bytes

This of course uses binary tokens, but it is equivalent to:

```
/Courier findfont setfont

0 h moveto

s [
    w {1 0} repeat pop pop
    h {0 -1} repeat pop pop
    w {-1 0} repeat pop pop
    h {0 1} repeat
] xyshow

```

Here is a hexdump of the file (`xxd round.ps`):

```
0000000: 91c7 9243 9295 3020 6892 6b73 5b77 7b31  ...C..0 h.ks[w{1
0000010: 2030 7d92 8392 7592 7568 7b30 202d 317d   0}...u.uh{0 -1}
0000020: 9283 9275 9275 777b 2d31 2030 7d92 8392  ...u.uw{-1 0}...
0000030: 7592 7568 7b30 2031 7d92 835d 92c3       u.uh{0 1}..]..

```

Run as:

```
gs -dw=11 -dh=10 -ss="rock beats scissors beats paper beats " round.ps

```

The output is really small (as a result of not scaling the font at all), so you need to zoom in a fair bit to see it.

This takes advantage of the `xyshow` operator to write out the string using custom character spacings. In this case, I use the negative vertical spacing to write down, then negative horizontal space to write backwards, then positive vertical space to write upward. Because of this, I don't need to use any sort of string manipulation.
> 3 votes

# Answer
# Bash+coreutils, 124

A shell script to get you started:

```
echo "${3:0:$1}"
fold -1<<<"${3:$1*2+$2-2}"|tac|paste - <(fold -1<<<"${3:$1:$2-2}")|expand -t$[$1-1]
rev<<<"${3:$1+$2-2:$1}"

```

Pass input as command-line args:

```
$ ./roundnround.sh 5 4 "Hello, World! "
Hello
    ,
!
dlroW
$

```
> 2 votes

# Answer
# JavaScript, ~~161~~ ~~160~~ 158 bytes

The method I've come up with turned out way too long, but oh well, it's been practice. (Also, I got it to spell out `r+o[u]+'\n':d`.)

```
function f(o,w,n){s=o.slice(0,w)+'\n';o=o.slice(w);n-=2;r='';for(u=w-2;u--;)r+=' ';for(u=d=0;d=o[2*n+w+~u],u<w+n;u++)s+=(u<n)?(d||' ')+r+o[u]+'\n':d;return s}

```

For input that doesn't make sense the output is undefined (literally, and a bunch of times), but it works for all the test cases.
> 2 votes

# Answer
# Groovy, 140

```
f={a,x,y->println a.substring(0,x);(1..y-2).each{println a[a.length()-it]+' '*(x-2)+a[it+x-1]}println a.substring(x+y-2,2*x+y-2).reverse()}

```

call:

```
f('rock beats scissors beats paper beats ',11,10)

```

output:

```
rock beats
          s
s         c
t         i
a         s
e         s
b         o
          r
r         s
epap staeb

```
> 2 votes

# Answer
# K, 80 68 bytes

```
f:{[s;y;n]`0:(,n#s),({s[(#s)-x+2],((n-2)#" "),s@n+x}'!y-2),,n#|-4!s}

```

Shortened from 80 thanks to @JohnE.

Original:

```
f:{s:x;n:z;`0:(,s@!n),({s[(#s)+-2-x],({" "}'!n-2),s@n+x}'!y-2),,(|s@!-4+#s)@!n}

```

I barely even know how this thing works.

Example usage:

```
f["Hello, world! ";5;4]

```

There are some possible optimizations, but I keep making Kona segfault...
> 2 votes

# Answer
# K, 55 54 bytes

Using the same approach as randomra's J implementation; Start with a block of spaces and add from the tail of the string to the edge while rotating four times:

```
f:{`0:*4{((,r#*|x),|:'+*x;(r:-#*x)_*|x)}/((y-2)#" ";x)}

```

And some examples:

```
  f["Hello,_World!_";4 5]
Hello
_   ,
!   _
dlroW

  f[">v<^";2 2]
>v
^<

```

Breaking it down a little for readability,

Generate an NxM block:

```
  t:2 3#!6
(0 1 2
 3 4 5)

```

Rotate 90 degrees by using transpose(`+`) and reverse-each (`|:'`):

```
  |:'+t
(3 0
 4 1
 5 2)

```

So if we have a block of spaces `t` and a string `s`, we can prepend a slice of the tail of `s` to `t`:

```
  s: 12 18 17 8 9
12 18 17 8 9
  (,(-#t)#s),|:'+t
(8 9
 3 0
 4 1
 5 2)

```

We use the form `4 {[x] ... }/( ... )` to repeatedly apply a function to a tuple consisting of the string and the matrix we're building. Each time we do this rotate-and-concatenate step we also chop down the string.

**edit:**

Another idea is to try splitting the input string into the fragments we want at each rotation, which simplifies the main body of the program. Unfortunately this works out to be slightly longer at 56 bytes:

```
f:{`0:((y-2)#" "){|:'(,y),+x}/(+\(0,y[0 1 0]-2 1 1))_|x}

```

If there's a better way to calculate those split points I'm open to suggestions.

**edit2:**

Rearranging slightly lets me remove a pair of parentheses. 54 bytes!

```
f:{`0:((y-2)#" "){|:'(,y),+x}/(0,+\y[0 1 0]-2 1 1)_|x}

```
> 2 votes

# Answer
# R, 178

This is an unnamed function taking `s, w, h` as parameters. I wish there was a nicer way to split the string.

```
function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')}

```

Ungolfed

```
W=w+h-1;                                 # additional index points
H=w+W-1;                                 # additional index points
S=strsplit(s,'')[[1]];                   # vectorize the string
O=array(" ",c(h,w+1));                   # create an array of spaces
O[,w+1]="\n";                            # set newlines
O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);    # build middles lines
O=t(O);                                  # transpose array
O[1:w,c(1,h)]=c(S[1:w],S[H:W]);          # build top and bottom lines
cat(O,sep='')                            # cat out results

```

Test run

```
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("Hello, World! ",5,4)
Hello
    ,
!
dlroW
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("+--+|||+--+|||",4,5)
+--+
|  |
|  |
|  |
+--+
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})(">v<^",2,2)
>v
^<
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("rock beats scissors beats paper beats ",11,10)
rock beats
          s
s         c
t         i
a         s
e         s
b         o
          r
r         s
epap staeb
> # Escaped the \ as well
> (function(s,w,h){W=w+h-1;H=w+W-1;S=strsplit(s,'')[[1]];O=array(" ",c(h,w+1));O[,w+1]="\n";O[1:h,c(w,1)]=c(S[w:W],S[(W+W-1):H]);O=t(O);O[1:w,c(1,h)]=c(S[1:w],S[H:W]);cat(O,sep='')})("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",46,3)
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN
~                                            O
}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQP
>

```
> 2 votes

# Answer
# T-SQL, 307

While still horrendously long, this turned out to be quite a bit easier (and shorter) than I thought in a query. Implemented as an inline table valued function for T-SQL.

```
CREATE FUNCTION f(@S VARCHAR(MAX),@ INT,@H INT)RETURNS TABLE RETURN WITH R AS(SELECT 2i,LEFT(@S,@)S,STUFF(@S,1,@,'')+'|'R UNION ALL SELECT i+1,CASE WHEN i<@H THEN LEFT(RIGHT(R,2),1)+REPLICATE(' ',@-2)+LEFT(R,1)ELSE REVERSE(LEFT(R,@))END,STUFF(STUFF(R,LEN(R)-1,1,''),1,1,'')FROM R WHERE i<=@H)SELECT S FROM R

```

This recurses through the string @h times. First recursion clips @W characters from the string. The middle recursions take the last and first from remaining string with string padding between. The last recursion reverses what is left. There is a few lost characters dealing with the way SQL Server treats trailing spaces on VARCHARS.

**Test Run**

```
WITH TestSet AS (
    SELECT *
    FROM (VALUES
        ('Hello, World! ',5,4),
        ('+--+|||+--+|||',4,5),
        ('>v<^',2,2),
        ('rock beats scissors beats paper beats ',11,10),
        ('!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~andfoure',50,3)
        ) Test(S,W,H)
)
SELECT x.S
FROM TestSet
    CROSS APPLY (
        SELECT S FROM dbo.F(S,W,H)
        )x

S
----------------------------
Hello
    ,
!
dlroW
+--+
|  |
|  |
|  |
+--+
>v
^<
rock beats
          s
s         c
t         i
a         s
e         s
b         o
          r
r         s
epap staeb
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR
e                                                S
ruofdna~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUT

(24 row(s) affected)

```
> 2 votes

# Answer
# Pyth, 33 bytes

```
J-vw2<zQFkC,_z<>zQJj*-Q2dk;<>_zJQ

```

Demonstration.
> 2 votes

# Answer
# MATLAB, 101

```
function f(H,W,S)
w=1:W;h=(0:H-3).';n=W+H-2;S(3*n)=' ';S([w;[2*n-h,3*n*ones(H-2,W-2),h+W+1];n-w+W+1])

```
> 2 votes

# Answer
# C++, 398 bytes

**Compiler used - *GCC 4.9.2* with `-std=c++14` flag**

```
#include<bits/stdc++.h>
using namespace std;string s;vector<vector<char>> M;int w,h,p,i,j;void F(int x,int y){if(p<s.size()&&(((!y||y==h-1)&&x>=0&&x<w)||((!x||x==w-1)&&y>=0&&y<h))&&!M[y][x])M[y][x]=s[p++],F(x+1,y),F(x,y+1),F(x-1,y),F(x,y-1);}int main(){getline(cin,s);cin>>w>>h;M.resize(h,vector<char>(w,0));F(0,0);while(i<h){j=0;while(j<w){if(!M[i][j])M[i][j]=32;cout<<M[i][j++];}i++;cout<<endl;}}

```

Test it here.

## Explanation

```
#include<bits/stdc++.h>
using namespace std;

string s; // input string
vector<vector<char>> M; // output matrix
int w, h, p, i, j;
// w = width
// h = height
// p = iterator over s
// i, j = iterators used later for printing answer

void F( int x, int y )
{
    // If the coordinates (x, y) are either on the first row/column or the last row/column and are not already populated with the input characters, populate them
    if ( p < s.size() && ( ( ( y == 0 || y == h - 1 ) && x >= 0 && x < w ) || ( ( x == 0 || x == w - 1 ) && y >= 0 && y < h ) ) && !M[y][x] )
    {
        M[y][x] = s[p++];
        F( x + 1, y );
        F( x, y + 1 );
        F( x - 1, y );
        F( x, y - 1 );
    }
}

int main()
{
    getline( cin, s );
    cin >> w >> h;
    // Input taken !!

    M.resize( h, vector<char>( w, 0 ) ); // Fill the matrix with null characters initially

    F( 0, 0 ); // This function does all the work

    // Now printing the matrix
    while ( i < h )
    {
        j = 0;
        while ( j < w )
        {
            if ( !M[i][j] )
            {
                M[i][j] = ' ';  // Replace '\0' with ' '
            }
            cout << M[i][j++];
        }
        i++;
        cout << endl;
    }

}

```
> 1 votes

# Answer
# Perl, 193 ~~195~~ bytes

```
($s,$w,$h,$i,$y)=(@ARGV,0,2);
$o.=substr$s,$i,$w;
$i+=$w;
$o.=sprintf"\n%s%*s",substr($s,2*($w+$h)-$y++-3,1)||' ',$w-1,substr($s,$i++,1)while$y<$h;
print$o."\n".reverse(substr($s,$i,$w))."\n";

```

I'm sure this can be greatly improved. I'm a noob. \>,\<
> 1 votes

# Answer
# Java 11, 180 bytes

```
(s,w,h)->{var r=s.substring(0,w)+"\n";int i=w;for(var S=s.split("");i<w+h-2;)r+=S[3*w+2*h-i-5]+" ".repeat(w-2)+S[i++]+"\n";return r+new StringBuffer(s.substring(i,i+w)).reverse();}

```

Try it online (NOTE: `String.repeat(int)` is emulated as `repeat(String,int)` for the same byte-count, because Java 11 isn't on TIO yet.)

**Explanation:**

```
(s,w,h)->{               // Method with String & 2 int parameters and String return-type
  var r=s.substring(0,w)+"\n";
                         //  Result-String, starting at the the first row of output,
                         //  which is a substring in the range [0, `w`)
  int i=w;               //  Index-integer, starting at `w`
  for(var S=s.split(""); //  Split the input-String into a String-array of characters
      i<w+h-2;)          //  Loop `i` in the range [`w`, `w+h-2`)
    r+=                  //   Append the result-String with:
       S[3*w+2*h-i-5]    //    The character at index `2*w+2*h-4 - i+w-1`
       +" ".repeat(w-2)  //    Then append `w-2` amount of spaces
       +S[i++]           //    Then append the character at index `i`
       +"\n";            //    And a trailing new-line
  return r               //  After the loop, return `r` as result
         +new StringBuffer(s.substring(i,i+w)).reverse();
                         //  Appended with the last row of output,
                         //  which is a substring in the range [`i`, `i+w`) reversed

```
> 0 votes

# Answer
# Charcoal, 4 bytes

```
ＢＮＮＳ

```

Try it online (verbose) or try it online (pure).

**Explanation:**

Basically a builtin for this challenge. Take the first two integer-inputs as width and height, and prints a box with the third input-string as border:

```
Box(InputNumber(), InputNumber(), InputString())
ＢＮＮＳ

```
> 0 votes

---
Tags: code-golf, ascii-art, string
---


# Question
Title: Print out the first N characters of your code
You should write a program or function that receives a positive integer `N` as input and prints out the first `N` characters of your code. If `N` is larger than the length of your code you should continue output your code cyclically.

Reading your source code in any way and reading from file, stdio, etc. are disallowed.

## Examples

(assuming your code is `yourcode`)

Input =\> Output:

`5` =\> `yourc`
`10` =\> `yourcodeyo`
`22` =\> `yourcodeyourcodeyour`

## Clarification

Your program should be at least 1 byte long.

# Answer
> 16 votes
## Python 2, 61 bytes

```
def f(n):a='def f(n):a=%r;print(a%%a*n)[:n]';print(a%a*n)[:n]

```

Try it online!

# Answer
> 10 votes
# \>\<\>, 49 bytes

```
'3d*}r0ff+0i:&0(?.~~a*&"0"-+60.&~:?!;1-&:o}&" "0.

```

Half the code is converting the input from a string to an int. If we're allowed to use the code point of a single char read from STDIN instead, then this program would be much shorter at 21 bytes:

```
'3d*}ri:?!;1-&:o}&60.

```

## Explanation

I'll use the second program for the explanation.

`'` starts string parsing, pushing every char until a closing quote is found. Since the rest of the line has no `'` quote, every char except the initial `'` is pushed onto the stack.

But \>\<\> is a toroidal 2D language, so after the line is over the instruction pointer wraps back to the start, hitting the `'` again and *stops* string parsing. The result is that we've pushed everything necessary except the initial quote, namely

```
3d*}ri:0=?;1-&:o}&60.

```

`'` is ASCII 39, so we push the initial quote by pushing `3d* = 3*13 = 39`. We then shift the stack right (`}`) and reverse (`r`), giving:

```
.06&}o:&-1;?=0:ir}*d3'

```

Now we're all set up to start printing. `i` reads in a char of input, but \>\<\> chars are basically integers. In the first program, the `i` is replaced with a loop that converts a digit string from STDIN into an integer.

We then execute the following loop to print out the first N chars:

```
:?!;               If the top of the stack (N) is 0, then terminate
                   Otherwise...
1-                 Subtract 1 from N
&                  Move N to the register temporarily
:o                 Output the next char in the program
}                  Shift the stack right
&                  Put N back on the stack
60.                Repeat loop by jumping back to the first :

```

# Answer
> 9 votes
# CJam, ~~34 17~~ 16 bytes

This can be golfed a lot..

```
{`"_~"+ri_@*<}_~

```

**Code expansion**:

```
{`"_~"+ri_@*<}_~
{            }_~      "Put this code block on stack, take a copy and execute the copy";
 `                    "When executed, this block will the top element on stack to a string";
  "_~"                "Then put this string on stack";
      +               "Concat it to the the previous string on stack which ` created";
       ri             "Read an integer from STDIN";
         _@           "Copy the integer and put the concatinated string on top of stack";
           *          "Repeat the string input number of times";
            <         "Take the first input number of characters from the repeated string";

```

Finally, anything on stack gets printed to STDOUT automatically

Try it online here

# Answer
> 5 votes
# JavaScript (ES6), ~~65~~ ~~52~~ ~~50~~ ~~47~~ ~~41~~ 39

```
q=n=>('q='+q).repeat(n/39+1).slice(0,n)

```

Uses ES6 `repeat()` to clone the code, then slices down. Uses a hardcoded length.

---

Old version (50):

```
q=n=>n>(l=(t='q='+q).length)?t+q(n-l):t.slice(0,n)

```

Creates a function `q`, taking a single parameter.

It stringifies the function text, and recursively calls the function if `n` is greater than the text's length. Otherwise, it returns a substring of the text.

Non ES6 version (65):

```
function q(n){return t=q+'',l=t.length,n>l?t+q(n-l):t.slice(0,n)}

```

# Answer
> 5 votes
# Python 2, 117 bytes

```
b=input();a=lambda x:(b*(2*(x+chr(34))+')'))[:b];print a("b=input();a=lambda x:(b*(2*(x+chr(34))+')'))[:b];print a(")

```

Life protip: don't execute `list(itertools.cycle(x))`. For some reason, I can't imagine why, it crashes the interpreter.

# Answer
> 5 votes
# J - 24 char

Takes a single positive integer argument and spits out a string.

```
($],quote)&'($],quote)&'

```

J doesn't have any self-reference tricks, so we just do it the quine way. Explained by explosion:

```
  ],quote                 NB. right arg prepended to quotation of right arg (quine)
 $                        NB. cyclically take left-arg characters from that
(        )&'($],quote)&'  NB. preload right arg with  ($],quote)&

```

The dyadic `$` operator in J cyclically takes items from its right argument to fit the dimensions specified on the left. When the dimension is a single number, this is a simple 1D list of characters, so we do exactly what the question asks.

Try it for yourself at tryj.tk.

# Answer
> 4 votes
# k2 - 7 char

```
{x#$_f}

```

In English, this is a function with argument `x` whose definition is "`x` take string self".

* *Self* (the noun `_f`) is the innermost currently executing function. Here it is the function `{x#$_f}`.
* *String* (monadic `$`) converts its argument to a string. In the case of a function, it creates a string with the function's original definition.
* *Take* (dyadic `#`) takes *left-arg* items form the list in *right-arg*. In the case of a string, the items are characters, so this is doing exactly what we want.

This *will not* work in the open-source Kona, because it seems to create black holes which eat all attempts to use them as arguments to anything. I am unsure of proper k3 semantics but they are probably not much kinder.

In Q, this is `{x#string .z.s}` and in k4 `{x#2_$.z.s}`. We have to use `2_` to drop two initial characters in k4, for reasons only a mother could love.

# Answer
> 3 votes
# Ruby, ~~66 64~~ 63 bytes

```
eval s=%q(puts"eval s=%q(#{s})".chars.cycle.take(gets.to_i)*'')

```

The same using a function to avoid calling `gets` is a bit longer (81 bytes):

```
def f(i);eval s=%q(puts"def f(i);eval s=%q(#{s});end".chars.cycle.take(i)*'');end

```

Lambda versions of the same are 69 and 65 bytes:

```
l=->i{eval s=%q(puts"l=->i{eval s=%q(#{s})}".chars.cycle.take(i)*'')}
->i{eval s=%q(puts"->i{eval s=%q(#{s})}".chars.cycle.take(i)*'')}

```

# Answer
> 3 votes
# Mathematica, 65 bytes

```
Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] &

```

All spaces is necessary to make this a proper quine, including the trailing one. This is a pure function, which you can use as follows:

```
Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & [75]

```

which prints

```
Print[StringTake[StringJoin @@ Table[ToString[#0], {#1}], #1]] & Print[Stri

```

Unfortunately, applying `ToString` to a function doesn't yield exactly the way you entered the function, so I can't shorten this by removing whitespace, shortening `#1` to `#` or using prefix notation for function calls.

# Answer
> 3 votes
# MATLAB, ~~319~~ 141 characters

I managed to squeeze a few bytes from the original one:

```
function d=g(n);d='gvodujpo!e>h)o*<e>(<e>\e)2;2:*.2-e-e)2:;foe*.2^<e>e)2,npe)1;o.2-252**<';d=[d(1:19)-1,d,d(19:end)-1];d=d(1+mod(0:n-1,141));

```

# Answer
> 3 votes
# JavaScript, 34 bytes

```
f=n=>n&&('f='+f+f(n-1)).slice(0,n)

```

Recursive function that repeats the code `n` times, then slices the result.

# Answer
> 3 votes
# Japt, 2 bytes

```
îî

```

Try it online!

The first `î` is a number method that takes one parameter, and repeats it to length `n`. Because it is the first method, `n` becomes the input. The second `î` gets cast into a string, and gets repeated.

This transpiles to:

`n.î("î")` -\> Repeat `"î"` until it reaches length `n`

## 8 byte solution

```
îQi"îQi"

```

Try it online!

`îQi"îQi"` transpiles to `n.î(Qi"îQi")`

```
n.î(Qi"îQi")
      "îQi"    // String "îQi"          -> îQi
    Qi         // Insert "              -> îQi"
n.î            // Repeated to length n  -> îQi"îQi"îQi"  (n=12)

```

# Answer
> 2 votes
# Matlab (57)

```
function s=f(n);s=evalc('type f');s=s(mod(1:n,nnz(s))+1);

```

The initial `1` index (instead of `0`) in the last line is because Matlab's function `type` introduces an initial line-feed, which should be removed. Thanks to Dennis for his correction (last index) and for his suggestion (`nnz` shorter than `numel`).

# Answer
> 2 votes
# R, 203 bytes

When N = 203, the code fully print itself.

```
(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\n"), ")}(", N, ")")
cat(rep(str, floor(N/nchar(str))), sep = "")
cat(substr(str, 1, N%%nchar(str)))})(203)

```

When N = 50, the code trims itself.

```
(f <- function(N){
str <- paste0("(f <- function(N

```

When N = 300, the code partially repeats itself.

```
(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\n"), ")}(", N, ")")
cat(rep(str, floor(N/nchar(str))), sep = "")
cat(substr(str, 1, N%%nchar(str))))}(300)(f <- function(N){
str <- paste0("(f <- function(N)", paste0(as.character(body(f)), collapse = "\

```

# Answer
> 2 votes
# Unary(1-8 version), 23855 bytes

Takes input as unary of '1's, and the code is 23855 '1's (`,[.,]`)

# Answer
> 2 votes
# Japt, ~~40~~ 28 bytes

```

"îR+Q+V+Q+R+V"
îR+Q+V+Q+R+V
```

First time writing a quine, so this can probably be shortened quite a bit. On the other hand, I'm quite happy I got it to work at all.

Leading newline intentional, the second line is data and the rest of it unwraps the data, then repeats the whole resulting string until it reaches length equal to the input.

Shaved off a whopping 12 bytes thanks to Oliver.

Try it online!

# Answer
> 1 votes
## C++, 305

```
int L=305;string s="int main(){string t=\"string s=\";int n;cin>>n;t+=s;t+=\"\";\";t+=s;while(n>0){if(n>L){cout<<t;n-=L;}else{cout<<t.substr(0,n);}return 0;}";
int main(){string t="int L=305;string s=\"";int n;cin>>n;t+=s;t+="\";";t+=s;while(n>0){if(n>L){cout<<t;}else{cout<<t.substr(0,n);}n-=L;}return 0;}

```

**Explanation** Apart from the escape character all other characters are printed out. The main method is inside the string s and inside main the full string is built and printed to stdout

# Answer
> 1 votes
## Pyth, ~~15~~ ~~13~~ 14 bytes

```
<jN*Q]"<jN*Q]"

```

Try it online!

Modified version of the standard Pyth quine.

# Answer
> 1 votes
## Hoon, 185 bytes

```
=/(f "=/(f k |=(n=@ =+((trim 5 f) `tape`(scag n `tape`(zing (reap n :(weld p <f> (slag 1 q))))))))" |=(n=@ =+((trim 5 f) `tape`(scag n `tape`(zing (reap n :(weld p <f> (slag 1 q))))))))

```

Set `f` to the program's code as a tape, but with "k" for itself. Split the tape at character 5, setting variables `[p=left q=right]`. Weld together the strings `p`, the original string `f`, and everything after the 1st character of `q`. Repeat that string `n` times, then return the first `n` characters of it.

Doing this was *slightly* hampered by Hoon's stdlib not having a format function or find-and-replace...Also, I'm not sure why we need another cast after the `scag`, since it should keep type information. So it goes.

# Answer
> 1 votes
# Jstx, 7 bytes

```
/£↕:1Fn

```

Try it online!

# Answer
> 1 votes
# SmileBASIC, ~~106~~ 66 bytes

```
INPUT N?MID$(("+CHR$(34))*3,23,N)INPUT N?MID$(("+CHR$(34))*N,23,N)

```

# Answer
> 1 votes
## Perl 5 with `-pa`, 48 bytes

```
$_=q{$_=substr"\$_=q{$_}:eval"x"@F",0,"@F"};eval

```

Try it online!

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

```
"r2ssIFLko|;

```

Try it online!

### How it works

```
"r2ssIFLko|;

"..."   Push the chars in reverse order
r2ss    Reverse the stack, then push `"`
IF...|  Input n, and repeat the following n times...
  L     Push the loop counter (0 to n-1)
   k    Pop x and copy x-th from the top
    o   Pop and print as char
;       Halt

```

`k` can wrap any number of times, so we don't need to duplicate the whole stack depending on the input.

# Answer
> 0 votes
# KSFTgolf \- 4 chars, 6 bytes

KSFTgolf if a language I've been attempting to design for code golf. I've been changing it a lot, so this probably shouldn't actually count.

```
☃\@2

```

# Answer
> 0 votes
# Ly, 28 bytes

```
"r(34)<ns>l[p&:l,s]p<[>o<,]p

```

Try it online!

# Answer
> 0 votes
# J, 41 Bytes

Now that was a brain teaser!

```
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~

```

### Explanation:

```
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~  | Expression taking 1 argument
                                       $~  | Reshape left argument to fit right, taking cyclically.
(                                     )    | One large expression that evaluates to a string
                 '((,quote,'')$~''"_)'     | String literal containing the code to the left of it
 (,quote,'$)~'"_)                          | A 4-Hook:
         '$)~'"_                           | The string '$)~'
   quote,                                  | Appended to the quoted version of the string
  ,                                        | Appended to the raw string

```

Examples:

```
   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 10
((,quote,'

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 20
((,quote,')$~'"_)'((

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 30
((,quote,')$~'"_)'((,quote,'')

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 41
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~

   ((,quote,')$~'"_)'((,quote,'')$~''"_)')$~ 50
((,quote,')$~'"_)'((,quote,'')$~''"_)')$~((,quote,

```

# Answer
> 0 votes
# Stax, 24 bytes

```
"34bLNca*]$("34bLNca*]$(

```

Run and debug it

Adaption of the `"34bL"34bL` quine.

# Answer
> 0 votes
# Java 10, ~~193~~ 176 bytes

```
n->{var s="n->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}";s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}

```

**Explanation:**

Try it online.

```
n->{                       // Method with integer parameter and String return-type
  var s="n->{var s=%c%s%1$c;s=s.format(s,34,s);for(int i=n;i>0;i/=176)s+=s;return s.substring(0,n);}";
                           //  Unformatted source code
  s=s.format(s,34,s);      //  Create the formatted quine
  for(int i=n;i>0;         //  Loop `i` as long as it's not 0
      ;                    //    After every iteration:
       i/=176)             //     int-divide `i` by the hardcoded length of the source code
    s+=s;                  //   Exponentially enlarge the source code
  return s.substring(0,n);}//  Return the first `n` characters of the source code

```

-part:

* The `var s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.

Challenge part:

* `for(int i=n;i>n;i/=176)` loops `ceil(n/176)` times, where `176` is the length of the source code.
* `s+=s;` exponentially increases the size of the source code String. (`ab` becomes `abab`; `abab` becomes `abababab`; `abababab` becomes `abababababababab`; etc.)
* `s.subtring(0,n);` takes the first `n` characters of the String.

# Answer
> 0 votes
# \>\<\>, ~~22~~ 19 bytes

```
'rd3*$:?!;1-$:o}50.

```

Try it online!

Takes input through the `-v` flag.

# Answer
> 0 votes
# Stax, 8 bytes

```
",:m",:m

```

Run and debug it

# Answer
> 0 votes
# 05AB1E, 17 bytes

```
0"D34çýI∍"D34çýI∍

```

Try it online.

**Explanation:**

```
0                    # Push a 0 to the stack
                     #  STACK: [0]
 "D34çýI∍"           # Push the string 'D34çýI∍' to the stack
                     #  STACK: [0, 'D34çýI∍']
          D          # Duplicate this string
                     #  STACK: [0, 'D34çýI∍', 'D34çýI∍']
           34çý      # Join the entire stack by the character '"'
                     #  STACK: ['0"D34çýI∍"D34çýI∍']
               I     # Take the input
                ∍    # Shorten/lenghten the string to that size (and output implicitly)
                     #  i.e. 3 → '0"D'
                     #  i.e. 25 → '0"D34çýI∍"D34çýI∍0"D34çýI'

```

# Answer
> -1 votes
# Tcl, 31 bytes

```
puts [read [open $argv0] $argv]

```

Try it online!

---
Tags: code-golf, quine
---