title: Create a Formatted Multiplication Table

text:
# Question
Title: Create a Formatted Multiplication Table
Your task is to create a good multiplication table for others to use. Given an integer \\$n\\$, generate a multiplication table that displays products up to \\$n×n\\$. You should start with \\$2×2\\$ as 1 times any number is itself and that is reflected in the row/column indices. Scientific notation and floating-points are NOT allowed. You must print every digit with no decimals (.00 or .00000034).

Formatting is a crucial component (after all, mutiplication tables are notorious for their formatting). The formatting criteria are listed below:

* At the top left corner or \\$ \text{table}\[0\]\[0\] \\$, there will be a single number `1`.
* Each row and column index will be \\$n\\$ digits + one whitespace.
* There is one row of hypens/dashes that span from the beginning of the table and ends at the last digit of the number who has the largest amount of digits in the rightmost column.
* There is 1 column of pipes `|` that start from the top of the multiplication table and ends at the \\$n\\$th row. This column of pipes should not get in the way of the row indices' formatting.
* The values of the table should have its leftmost digit aligned with the leftmost digit of the column index.
* Between each value in each column, there should be one whitespace seperating the value. There will be NO newlines seperating each row.

Below is an example the covers all of the above points. **Note: for brevity, the example table skips from 2 directly to 54, your actual program should include ALL digits from 2 to 54 and onwards to 654546.**

```
1      | 2       54       3443       654546
-------------------------------------------------
2      | 4       108      6886       1309092
54     | 108     2916     185992     35345484
3443   | 6886    185992   11854249   2260487878
654546 | 1309092 35345484 2260487878 431052650116

```
1. Observe how in the above table, the hypens take priority over the pipes.
2. Notice how, no matter the size of the numbers, each column has at least 1 whitespace seperating it.
3. The hypen row ends at the last digit of \\$431052650116\\$ NOT \\$654546\\$.
4. Each column has its leftmost digit aligned with the leftmost digit of the column index (ex. the "6" in 6886 is aligned with the "2" in the column index).
5. Refer to the above table when in doubt. Comment for any clarifications.

## SAMPLE INPUT

```
5

```

## SAMPLE OUTPUT

```
1 | 2  3  4  5
---------------
2 | 4  6  8  10
3 | 6  9  12 15
4 | 8  12 16 20
5 | 10 15 20 25

```

## Constraints

You will possibly need unsigned 64-bit integers. $$ 2 \leq n \leq 10^9 $$

# Answer
# 05AB1E, ~~30~~ ~~28~~ 22 bytes

```
Lć'|‚ìDδ*€.Bø¬»g'-×1ǝ»

```

-6 bytes thanks to *@Grimmy*.

Try it online.

**Explanation:**

```
L         # Push a list in the range [1, (implicit) input-integer]
 ć        # Extract head; pop and push [2,input]-list and 1 separated
  '|‚    '# Pair this 1 with "|"
     ì    # And prepend it back: [1,"|",2,3,4,...,input]
Dδ*       # Make a multiplication table:
D         #  Duplicate the list
 δ        #  Apply over the two lists double-vectorized:
  *       #   Multiply
          #   (we'll have a second row of single "|"s now)
€.B       # Box each inner list, appending leading spaces to make all values the same
          # length
   ø      # Zip/transpose; swapping rows/columns
¬         # Get the first row (without popping)
 »        # Pop and join it with newline delimiter
  g       # Pop and push its length (including those newlines)
   '-×   '# Pop and push a string with that many "-"
      1è  # Insert it at the second position in the list of lists
        » # Join each inner list by spaces; and then every string by newlines
          # (after which the result is output implicitly)

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 52 bytes (SBCS)

Full program. Requires fully printing high-precision floats.

```
r←' (\d)'⋄'-'@2↑r⎕R' |&'⍠'ML'1⊢r⎕R'\1'↓⍕⍕¨1(,∘.×⊢)⍳⎕

```

Try it online!

`r←' (\d)'` create the PCRE regex `r` as a space followed by a digit

prompt for \\$n\\$

**i**ndices 1 through \\$n\\$

`1(``)` apply the following tacit function with that as right argument and 1 as left argument:

`,` the concatenated arguments

`∘.×` as vertical axis for the multiplication table with horizontal axis being…

the right argument

(now we have the number we need, including an extra row which will be replaced by dashes)

`⍕¨` format each number as text (since strings are left-justified)

format the entire matrix (leaves double-spaces between columns)

split matrix into list of strings

`r⎕R'\1'` replaces matches for `r` with their digit (reduces column spacing to 1)

on that…

`r⎕R' |&'⍠'ML'1` insert a space and a pipe before the first `r` match on each line

mix list of strings into matrix

`'-'@2` replace with dashes **at** the second row
> 6 votes

# Answer
# C (gcc), ~~174~~ ~~172~~ ~~166~~ ~~164~~ 163 bytes

```
#define X u-=printf("\n\0-\0%-*i"
s(n){return!n?:s(n/10)+1;}i,j,u;t(n){for(i=0,u=2;j=i<n;X)){for(X"| "+4,s(n),++i);j<n;)X+4,s(n*n),i*++j);if(i<2)for(X);X+2)-2;);}}

```

Try it online!

-2 thanks to ceilingcat, by initialising `j` off the loop condition. -6 by introducing the macro `X` with a few changes to fit it in; -2 by extending it with some more changes. -1 thanks to ceilingcat, shortening `s` with `?:`.

Fairly straightforward:

* `s` produces the number of digits in a number plus 1, used to determine the column widths. `?:` is a GCC extension, producing the same value as the left expression if it's nonzero (and the value of the right expression otherwise).
* The macro `X` contains multiple (null-terminated) strings run together, allowing it to be used for any of those strings – `X` alone prints a line feed, while `X+2` (adding 2 to the pointer) prints a hyphen, and `X+4` uses the format string `%-*i`; in one place, `|`  is added to it, using concatenation of adjacent string literals.
* The return value of `printf` is the number of characters printed; `u` starts at 2 and has those values subtracted from it, making `u` 1 greater than the negative of the length of the first row excluding the extra space at the end. Using `X` to print a line feed subtracts the extra 1 from `u`, and then the row of hyphens is produced using `u`, subtracting -1 each iteration.
> 5 votes

# Answer
# Gaia, ~~27~~ 26 bytes

```
ṇ'|,¤+ṡ
×‡€[¦t↑¦ṇ:l'-×,¤+ṣ

```

Try it online!

`×‡€[¦tụ` generates the table without the lines.

**Commented**:

```
ṇ'|,¤+ṡ      -- helper function to insert '|' at the second position
ṇ            -- extract first element from list
 '|,         -- pair with "|"
    ¤+       -- prepend to the remaining list
      ṡ      -- join by spaces

×‡           -- multiplication table for 1..input
  €[¦        -- left-align each row to its maximum length
     t       -- transpose to swap rows/columns
      ↑¦     -- map helper function over each row

ṇ            -- extract first row from table
 :l          -- duplicate and take the length of the copy
   '-×       -- push a string of that many dashes
      ,      -- pair with first row
       ¤+    -- and prepend to table
         ṣ   -- join the table by newlines

```

---

My attempt of adding a helper function to insert both `-` and `|` is two bytes longer:

```
¤ṇ:l4ṁ×,¤+
×‡€[¦t⟨'|⇈ṡ⟩¦'-⇈ṣ

```

Try it online!
> 5 votes

# Answer
# Jelly,  ~~29 28 27~~  25 bytes

Probably not the right tool for the job.

```
Zż€Ẏ€
×þ`Dz€⁶Z€ç”|K€ç”-ZY

```

A full program that accepts a positive integer and prints the formatted multiplication table.

**Try it online!**

### How?

```
Zż€Ẏ€ - Link 1: transpose & insert chars: list of lists, M; character, C
Z     - transpose M
 ż€   - zip each with C
   Ẏ€ - tighten each

×þ`Dz€⁶Z€ç”|K€ç”-ZY - Main Link: integer N
  `                 - use N as both arguments of:
 þ                  -   table using:
×                   -     multiplication
   D                - covert to decimal digits (vectorises)
     €              - for each (list of digit lists):
    z ⁶             -   transpose with filler of a space character
       Z€           - transpose each
         ç”|        - call last Link (1) as a dyad, f(that, pipe charater)
            K€      - join each with space characters
              ç”-   - call last Link (1) as a dyad, f(that, dash charater)
                 Z  - transpose
                  Y - join with newline characters
                    - implicit, smashing print

```
> 3 votes

# Answer
# Ruby, ~~105 97~~  96 bytes

```
->n{(r=1..n).map{|x|A=r.map{|y|"%-*s"%["#{y*n}".size,y*x]}.insert(1,?|)*" "}.insert 1,?-*A.size}

```

Try it online!

* Saved 8 +1 thanks to @Dingus !

```
->n{...}    # lambda retuning an array of strings.
(a=r=1..n)  # a: used to take a line length to add '----...
              r: range used 2 times to build a table
"#{y*x}".ljust  # every value of table is converted to string and left-jusified by:

"#{y*n}.size "  #> length of max value of column
we insert a | at index 1
and finally we insert a row line--- of length a

```
> 3 votes

# Answer
# Factor, 153 bytes

```
[ [1,b] dup outer [ "|"1 rot insert-nth ] map [ simple-table. ] with-string-writer "\n"split harvest dup last [ drop 45 ] map 1 rot insert-nth "\n"join ]

```

Try it online!

## Explanation

It's a quotation (anonymous function) that takes a number from the data stack and leaves a string on the data stack as output. Assuming `5` is on top of the data stack when this quotation is called...

| Snippet | Data stack |
| --- | --- |
| ``` [1,b] ``` | ``` { 1 2 3 4 5 } ``` |
| ``` dup ``` | ``` { 1 2 3 4 5 }<br>{ 1 2 3 4 5 } ``` |
| ``` outer ``` | ``` {<br>    { 1 2 3 4 5 }<br>    { 2 4 6 8 10 }<br>    { 3 6 9 12 15 }<br>    { 4 8 12 16 20 }<br>    { 5 10 15 20 25 }<br>} ``` |
| ``` [ "|"1 rot insert-nth ] map ``` | ``` {<br>    { 1 "|" 2 3 4 5 }<br>    { 2 "|" 4 6 8 10 }<br>    { 3 "|" 6 9 12 15 }<br>    { 4 "|" 8 12 16 20 }<br>    { 5 "|" 10 15 20 25 }<br>} ``` |
| ``` [ simple-table. ] with-string-writer ``` | ``` "1 | 2  3  4  5\n2 | 4  6  8  10\n3 | 6  9  12 15\n4 | 8  12 16 20\n5 | 10 15 20 25\n" ``` |
| ``` "\n"split ``` | ``` {<br>    "1 | 2  3  4  5"<br>    "2 | 4  6  8  10"<br>    "3 | 6  9  12 15"<br>    "4 | 8  12 16 20"<br>    "5 | 10 15 20 25"<br>    ""<br>} ``` |
| ``` harvest ``` | ``` {<br>    "1 | 2  3  4  5"<br>    "2 | 4  6  8  10"<br>    "3 | 6  9  12 15"<br>    "4 | 8  12 16 20"<br>    "5 | 10 15 20 25"<br>} ``` |
| ``` dup last ``` | ``` {<br>    "1 | 2  3  4  5"<br>    "2 | 4  6  8  10"<br>    "3 | 6  9  12 15"<br>    "4 | 8  12 16 20"<br>    "5 | 10 15 20 25"<br>}<br>"5 | 10 15 20 25" ``` |
| ``` [ drop 45 ] map ``` | ``` {<br>    "1 | 2  3  4  5"<br>    "2 | 4  6  8  10"<br>    "3 | 6  9  12 15"<br>    "4 | 8  12 16 20"<br>    "5 | 10 15 20 25"<br>}<br>"---------------" ``` |
| ``` 1 rot insert-nth ``` | ``` {<br>    "1 | 2  3  4  5"<br>    "---------------"<br>    "2 | 4  6  8  10"<br>    "3 | 6  9  12 15"<br>    "4 | 8  12 16 20"<br>    "5 | 10 15 20 25"<br>} ``` |
| ``` "\n"join ``` | ``` "1 | 2  3  4  5\n---------------\n2 | 4  6  8  10\n3 | 6  9  12 15\n4 | 8  12 16 20\n5 | 10 15 20 25" ``` |
> 2 votes

# Answer
# jq, 217 bytes

```
. as$m|[1+range(.)]|map(["\(.*range($m)+.)"|split("")])|(.[$m-1]|map(keys))as$l|map([to_entries[]|[.value[$l[.key][]]|values//" "]|join("")]|[.[0],"|",.[1:][]]|join(" "))|[.[0],"-"*(.[$m-1]|length),.[1:][]]|join("\n")

```

Try it online!

## What

```
  . as $m
| [ 1 + range(.) ] # Convert to rows
| map(["\(.*range($m)+.)" | split("")]) # Multiply, then convert numbers to lists of digits
| (.[$m-1] | map(keys)) as $l # Store indices into last (longest) row, for padding
| map(  [
            to_entries[]
          | [.value[$l[.key][]] | values // " "] # Pad with nulls, then replace those with spaces
          | join("")
        ]
      | [.[0], "|", .[1:][]] # Insert vertical rule
      | join(" ") # Join lines into single strings
     )
| [.[0], "-"*(.[$m-1] | length), .[1:][]] # Insert horizontal rule
| join("\n")

```
> 2 votes

# Answer
# jq `-r`, 142 bytes

```
def f:transpose[];[range(.)+1]|. as$r|[.[]|[.*$r[]|@sh/""]|[f|map(.//" ")]|[f|add]]|[f|[.[0],"|"]+.[1:]|join(" ")]|(.[0]|.,"-"*length),.[1:][]

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES8), 138 bytes

```
n=>(g=i=>i++<n?(h=k=>s=++k<n?(k*i+'').padEnd((k*n+c).length)+[[,'| '][k]]+h(k):k*i)(c=`
`)+c+g(i):'')``.replace(c,c+s.replace(/./g,'-')+c)

```

Try it online!
> 1 votes

# Answer
# Charcoal, 36 bytes

```
Ｎθ≔Ｅ⊕θ↔⁻ι‹ι²ηＦη«Ｍ→⪫⎇ι×ηιＥη|¦¶Ｍθ↑»↙←ⅈ

```

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

```
Ｎθ

```

Input `n`.

```
≔Ｅ⊕θ↔⁻ι‹ι²η

```

Create a range from `0` to `n`, but swap the first two elements.

```
Ｆη«

```

Iterate over the range.

```
Ｍ→

```

Leave an empty column.

```
⪫⎇ι×ηιＥη|¦¶

```

If this is the `0` column, print a column of `|`s, otherwise multiply the range by the column and print it joined with newlines. This leaves the cursor to the right of the bottom number.

```
Ｍθ↑

```

Move back to the top row.

```
»↙←ⅈ

```

Overwrite the row of `0`s with a line of `-`s.
> 1 votes

# Answer
# , 157 bytes

Or **\>4.1, 150 bytes** by replacing the word `function` with `\`.

```
function(n,x=outer(1:n,1:n),y=apply(apply(cbind(x[,1],"|",x[,2:n]),2,format),1,paste,collapse=" "))paste(c(y[1],strrep("-",nchar(y[1])),y[2:n]),collapse="
")

```

Try it online!

### Explanation outline:

1. Compute the (unformatted) multiplication table using `outer`.
2. Add a column of `|`s, conveniently converting the array to type character.
3. Apply `format` to columns, which for character vectors does exactly what we need.
4. Collapse rows using spaces.
5. Add a row of `-`s.
6. Collapse everything using newlines.
> 1 votes

# Answer
# Julia 1.0, 137 bytes

```
!n=[(A=split(replace(repr("text/plain",[1:n fill(text"|",n) (1:n)*(2:n)']),r"( +)(\S+) ?"=>s"\2\1"),'
'))[2];"-"^~-length(A[2]);A[3:end]]

```

Try it online!

### Explanation:

* `[1:n fill(text"|",n) (1:n)*(2:n)']` creates a matrix: (here for n=5)

```
 5×6 Matrix{Any}:
 1  |   2   3   4   5
 2  |   4   6   8  10
 3  |   6   9  12  15
 4  |   8  12  16  20
 5  |  10  15  20  25

```
* the `@text_str` macro allows to hide the `"` around the `|`
* `repr("text/plain", ... )` formats it like seen above in a string
* since there is too many spaces and numbers are adjusted right instead of left, we apply the following regex: `replace( ... , r"( +)(\S+) ?" => s"\2\1")`

```
"""5×6Matrix{Any}:
1 | 2  3  4  5
2 | 4  6  8  10
3 | 6  9  12 15
4 | 8  12 16 20
5 | 10 15 20 25 """

```
* then we `split( ... , '\n')`, remove the first line and insert a line of `-`
* output is a list of strings:

```
6-element Vector{AbstractString}:
 "1 | 2  3  4  5  "
 "---------------"
 "2 | 4  6  8  10 "
 "3 | 6  9  12 15 "
 "4 | 8  12 16 20 "
 "5 | 10 15 20 25 "

```
> 1 votes

# Answer
# Perl 5, 128 bytes

```
$_='';for$i(@n=1.."@F"){$_.=pack(join('',map A.length$n[-1]*$_.0,@n),map$i*$_,@n).$/}s/.*/"$&
-".$&=~s|.|-|gr/e;s/^\d+ +/$&| /mg

```

Try it online!

```
$_='';                         # empty $_, to be used for building output
for$i(@n=1.."@F"){             # loop $i as 1 → n, "@F" is the input N, init array @n=1→N
  $_.=pack(                    # add a new line to output in $_ with a pack template
    join(                      # ...by joining
      '',                      # ...without delimiter
      map A.length$n[-1]*$_.0, # ...the template AxAyAz where x,y,z,... is the col widths
                               # ...of current $_ which is the widest cells which is
                               # ...always on last line
          @n                   # map 1 → N to create a widths template string
    ),
    map$i*$_,@n                # fill template with the multiplications of this line
  ).$/                         # add newline at end of each line
}
s/.*/"$&\n-".$&=~s|.|-|gr/e;   # add ------... second line, same width as first plus one -
s/^\d+ +/$&| /mg               # add | between col 1 and col 2 where col 1 is a number
                               # $_ now has the table string printed due to perl option -p

```
> 0 votes

# Answer
# Java (JDK), 166 bytes

```
n->{var s="";for(int i=0,j;i++<n;s+=i<2?"\n"+"-".repeat(s.length()-1)+"\n":"\n")for(j=0;j++<n;)s+=s.format("%-"+((j*n+"").length())+"d ",i*j)+(j<2?"| ":"");return s;}

```

Try it online!

## Credits
> 0 votes

---
Tags: code-golf
---


title: Stop, stand there where you are!

text:
# Question
Title: Stop, stand there where you are!
## Challenge

Write a function which takes one parameter: an integer `t`. Your function has to stop your program for `t` seconds before continuing, similar to `time.sleep(t)` in Python and `WAIT t` in BBC BASIC.

You must not use any built in waiting functions or any built in functions for executing code after a certain time, and your program must resume after `t` seconds.

For testing your function, there is tolerance of 0.1 seconds more or less than the given `t` on your own machine: variances between computers are fine.

If your answer is challenged by anyone, you must provide photographic (screenshotted) proof that your function works correctly for `t=1`, `t=5` and `t=25`. You may also provide the details of your computer so people can try to replicate it on their own machine.

Your program should and will be run on a computer whose clock speed is 1.6 GHz or higher.

## Winning

The shortest program wins.

## Bounty

A bounty will go out to the shortest program which stops the program *without* using a loop checking how much time has elapsed. If you are in the running for this bounty, add a footnote saying that your answer is for the bounty.

## Leaderboard

```
/* Configuration */

var QUESTION_ID = 55293; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 30525;

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

    var patt = new RegExp(/[Bb]ounty/);
    var res = patt.test(body);
    var bountyyn = "no";

    if (res) {
      bountyyn = "yes";
    }

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

  });

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

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

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

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

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

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

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

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

}
```

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

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

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

table thead {
  font-weight: bold;
}

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

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

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

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

# Answer
# x86\_64 machine code, 10 bytes

Hexdump of the code:

```
48 69 c9 ca fc 59 38 e2 fe c3

```

Source code (can be assembled by `ml64` of Visual Studio):

```
    TITLE   heh

PUBLIC  mywait
_TEXT   SEGMENT
mywait  PROC
    imul rcx, 945421514
myloop:
    loop myloop
    ret
mywait  ENDP
_TEXT   ENDS
END

```

Performs an empty loop, starting from the specified value down to 0. I chose the multiplier 945421514 empirically by trial and error, until my test program output satisfactory results.

Test program (waits 10 times for each of the durations 1, 5 and 25 seconds):

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

extern "C" void mywait(int);

int main()
{
    int durations[] = {1, 5, 25};
    for (int duration: durations)
    {
        for (int i = 0; i < 10; ++i)
        {
            clock_t before = clock();
            mywait(duration);
            clock_t after = clock();
            printf("%f\n", (after - before) / (double)CLOCKS_PER_SEC);
        }
    }
    getchar(); // now take a screenshot
}

```

The result:

```
1.003000
1.000000
1.004000
1.006000
1.005000
0.998000
0.995000
1.000000
1.005000
1.004000
4.999000
5.003000
5.035000
5.010000
4.992000
5.003000
5.003000
5.019000
5.026000
4.989000
25.041000
24.993000
25.049000
24.988000
25.038000
24.948000
25.007000
25.014000
25.053000
25.021000

```

I ran this program on a Windows computer that has nothing else to do. If it runs some applications, the waiting times are more erratic.

The CPU speed is 3.9 GHz. It seems that this code is barely good enough for current PC technology \- if the clock frequency is about 8.8 GHz, the multiplier will not fit into a signed 32-bit int.

---

P.S. As this answer doesn't check how much time has passed, it is a candidate for the bounty.
> 37 votes

# Answer
# Bash, ~~29~~ ~~25~~ ~~24~~ ~~23~~ 19 bytes

```
w()(ping -t$1 1.2)

```

Accuracy test (`time`) where `$1` = 1 second:

```
real    0m1.012s
user    0m0.001s
sys     0m0.002s

```

Thanks Dennis for shaving the byte count down to 19 from 23!

**EDIT**: I've changed the IP to avoid `ping` on Linux pinging 0.0.0.0, which is the loopback device.

---

### How this works

`ping` has a default timeout of 1 second, so, when contacting an IP address which does not exist, ping can't continue until either the time out has passed, or it has got a reply from the IP.

`-t` tells `ping` to try `$1` number of times on this fake IP address, forcing `ping` to take `$1` seconds to complete the ping.

---

**It's eligible for the bounty! No loop!**
> 22 votes

# Answer
## Matlab, 33 bytes

```
function f(t)
tic;while toc<t,end

```

Or you can also use this in Octave: try it online

## Matlab, 31 bytes

As suggested by @flawr, it can be done with an anonymous function (it should be assigned a name in order to use it):

```
@(t)eval('tic;while toc<t,end')

```

Example:

```
>> f=@(t)eval('tic;while toc<t,end');
>> tic, f(2), toc
Elapsed time is 2.000323 seconds.

```
> 18 votes

# Answer
# Java, ~~63~~ 62 bytes

```
t->{for(long a=System.nanoTime();System.nanoTime()-a<t*1E9;);}

```

Nothing surprising - just grabs the number of nanoseconds since 1/1/1970 multiple times and checks if a second has passed.

Saved 1 byte thanks to Ypnypn and aditsu.
> 12 votes

# Answer
# Batch, 27 Bytes

```
set /a c=%1+1
ping -n %c% 0

```

A popular batch trick, since batch didn't have a sleep function.

No loop, so bounty eligible
> 8 votes

# Answer
# JavaScript ES6, ~~50~~ ~~45~~ 40 bytes

```
n=>{for(g=Date.now,z=g();z+n*1e3>g(););}

```

this uses self-executing functions, not sure why `+new Date` isn't working.

---

## Usage

I've tested this with Safari Nightly but it will also work on Firefox. Tested with:

```
(
  n=>{for(g=Date.now,z=g();z+n*1e3>g(););}
)(1); // 1 is the delay is seconds
console.log( 'foo' );

```

---

You can run it by either surrounding it with parenthesis:

```
( n=>{for(g=Date.now,z=g();z+n*1e3>g(););} )(5)

```

Or by naming it:

```
const wait=n=>{for(g=Date.now,z=g();z+n*1e3>g(););}
wait(5)

```

## Explanation

Here's the main logic behind the program:

```
function (n) {
    var start = Date.now();   // Save start time (ms)
    while (                   // while is synchronous, it'll block the code execution until it has finished
           start + (n * 1000) // This is the end time (start + delay)
            > Date.now()      // When the current time is 1 ms past the target end time, stop. resuming the code execution
          );
}

```

The version I'm using uses the same logic:

```
n=>{ // Function with argument n, { is required if the functions is not just an expression
   for(           // For will also block code execution
                  // This first part is used to define variables
      g=Date.now, // Add an alias for Date.now as "g"
      z=g()       // get current time and store in z
      ;           // Next part, condition
      z + n*1e3   // Target end time, ( start + delay (converted to seconds) ) 1e3 is 1000 but in big e notation
      ;           // Is required for a valid for loop
   );
}

```
> 7 votes

# Answer
# Commodore 64 BASIC, 19 ~~16~~ bytes

```
1000 FORI=1TO930*N:NEXT:RETURN

```

With a call `N=<number-of-secods>:GOSUB1000`.

However, I cannot provide enough accuracy. Because C64 had about 1 MHz CPU speed, I remember it was good enough to make an empty `FOR`-`NEXT` loop 1000 times so that it was *about* 1 second.

In fact there were two main versions of the machine: PAL 0.985 MHz and NTSC 1.023 MHz (all data from C64 Wikipedia Page). As I had NTSC version, it was required to run loop about 930 times.

Tests with the following program (`N` seconds, provided by user in `INPUT`):

```
10 INPUT N
20 PRINT TI$
30 GOSUB 1000
40 PRINT TI$
50 END
1000 FOR I=1 TO 930*N:NEXT I:RETURN

```

where `TI$` is a system variable containing string (`hhmmss` format) with time elapsed from last reset (1 second accuracy, however also depending on CPU speed, so this is not quite relevant, because it's the same clock).

Screenshot made with online C64 emulator http://codeazur.com.br/stuff/fc64\_final/.

This program (line `1000` only) occupies ~~16~~ 19 bytes in memory, as tested with `PRINT FRE(0)+65535` both before typing the code (38908 bytes) and after (~~38893~~ 38889 bytes). `PRINT FRE(0)` returns free memory for BASIC program (it's a negative value and constant `65535` should be added, but in fact it does not matter).

**Because this program does not test the time elapsed in a loop, it qualifies for a bounty.**
> 7 votes

# Answer
# JavaScript, ~~68 54 51~~ 42

I think no screenshot is needed. But I suspect you could golf this even more...

New version: I now finally managed to avoid `new` and using `Date` twice:

```
f=t=>{for(x=(d=Date.now)();d()<x+t*1e3;);}

```

Older versions:

```
f=t=>{for(x=new Date();(new Date()|0)<x|0+t*1e3;);}

f=t=>{x=(new Date())|0;while((new Date()|0)<x+t*1e3);}

f=t=>{x=new Date().getSeconds();while(new Date().getSeconds()<x+t);}

```
> 6 votes

# Answer
# CJam, 15

```
{e3es+{_es>}g;}

```

This is a block that can be executed or stored into a variable (thus becoming a named function). Dennis and Mr Consensus agree that counting only the block is acceptable :)

**Explanation:**

```
e3       multiply the argument by 1000 (to get milliseconds)
es       get the current timestamp in milliseconds
+        add the values, obtaining the stopping time
{…}g     do…while
  _      duplicate the stopping time
  es>    check if we reached that time yet (loop condition)
;        discard the stopping time

```

Try it online
> 6 votes

# Answer
# Julia, ~~33~~ 20 bytes

```
t->watch_file(".",t)

```

Only works in Julia v0.4 due to changes in the function signature of `watch_file`. Defines an anonymous function with a single parameter `t` that (ab)uses the timeout parameter in the `watch_file` function.

This is a candidate for the bounty!

Demonstration using the Julia REPL:

```
julia> f=t->watch_file(".",t)
(anonymous function)

julia> @elapsed f(1)
1.002134983

julia> @elapsed f(5)
5.006161965

julia> @elapsed f(25)
25.026096192

```

Previous answer (33 bytes), also working in Julia stable

```
t->(b=time();while b+t>time()end)

```
> 6 votes

# Answer
# PHP, ~~171~~ ~~177~~ ~~84~~ ~~79~~ ~~65~~ ~~64~~ 62 bytes

```
<?php function a($i){for($f=microtime,$e=$f(1)+$i;$f(1)<$e;);}

```

**Usage:**
Call the function like so:
`php -d error_reporting=0 -r "require 'script.php'; a(5);echo 'Hello, World!';"`
Where 5 is the time in seconds the programm should wait before it echoes "Hello, World!".

**Explanation:**
At first the function gets the current time in milliseconds. Then the function does a loop until the current Time is smaller then the first time + the input. Afterwards "Hello World!" gets echo'ed.
**Log:**
Saved 113 bytes thanks to Voitcus
Saved 2 bytes thanks to axiac
> 5 votes

# Answer
# Windows CMD, 22 bytes

```
ping -w 1000 -n %1 1.1

```

This uses no loop (label and goto) so this qualifies for the bounty

It sends `t` pings to to 1.0.0.1 (invalid) and waits for a responce for 1000 ms
> 5 votes

# Answer
# R, 48 bytes

```
f=function(t){a={g=Sys.time}();while(g()<a+t){}}

```

Demonstration:

```
t0 <- Sys.time();f(1); Sys.time() - t0
## Time difference of 1.000272 secs

t0 <- Sys.time();f(5); Sys.time() - t0
## Time difference of 5.011189 secs

t0 <- Sys.time();f(25); Sys.time() - t0
## Time difference of 25.00848 secs

```
> 4 votes

# Answer
# PHP, 39 bytes

```
function a($a){while($i++<.4583e8*$a);}

```

---

(Note that I can actually get this shorter if a full program is required by taking advantage of arguments passed on command line. Down to **35**)

```
<?php while($i++<.4583e8*$argv[1]);

```

---

Program used for testing:

```
<?php function a($a){while($i++<.4583e8*$a);}

record(1);
record(5);
record(25);

function record($t)
{
    $time = microtime_float();
    a($t);
    echo microtime_float() - $time."\n";
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

```

Results:

```
JamesWebster:Documents jameswebster$ php A.php
1.0093479156494
4.9945771694183
24.971961975098

```

---

Though I qualify for the bounty, I'm hardly in the running with some of the other entries!
> 4 votes

# Answer
# TI-BASIC (84+SE), 21 bytes

Input method: `T:prgmT`. This is the closest equivalent of a function in TI-BASIC. Program:

```
For(A,1,841Ans
End

```

All accuracy is gained via trial-and-error; timing it with a stopwatch works for all of the given test cases to within a twentieth of a second.

Device information:

```
RAM FREE   23312
ARC FREE  889802

 TI-84 Plus Silver Edition
          2.55MP
PROD #: 0A-3-02-37
ID: 0A3DC-C3469-FFE8

```

---

W00T eligible for a bounty!
> 4 votes

# Answer
# JavaScript ES6, 40 bytes

```
t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);}

```

Tested with the following:

```
elapsed=(f,t,b=(d=Date.now)())=>(f(t),console.log(d()-b+"ms elapsed")) // accepts func, delay
STOP=t=>{for(t=(d=Date.now)()+t*1e3;d()<t;);}
elapsed(STOP,1)  // prints 1000ms elapsed
elapsed(STOP,5)  // prints 5000ms elapsed
elapsed(STOP,25) // prints 25000ms elapsed

```
> 3 votes

# Answer
# Python, 57 bytes

```
import time
b=time.time
def y(i):
 x=b()
 while x+i>b():x

```

Call function `y()`
> 2 votes

# Answer
# PureBasic, 92 bytes

```
Procedure z(t)
t=t*1e3+ElapsedMilliseconds()
While t>ElapsedMilliseconds():Wend
EndProcedure

```

It's the shortest I can think of. I suspect this will be the longest here as well...

To test:

```
OpenConsole()
i=Val(Input())
s=ElapsedMilliseconds()
z(i)
PrintN(Str(ElapsedMilliseconds()-s))
Input()

```
> 2 votes

# Answer
# PowerShell, 75 bytes

Long, descriptive procedure calls. Yay for clarity in a language. :)

```
function w{param($i);$n=(Get-Date).AddSeconds($i);while($n-gt(Get-Date)){}}

```

Called within a program with something like

```
Get-Date
w(15)
Get-Date

```

---

Alternatively, if we're allowed external programs to be called instead, we can get down to **59 Bytes** with the following:

```
$n=(Get-Date).AddSeconds($args[0]);while($n-lt(Get-Date)){}

```

This would be called within a program as follows (presuming the above to be saved as "wait-function.ps1" and saved in the same folder):

```
Get-Date
& ((Split-Path $MyInvocation.InvocationName) + "\wait-function.ps1 15")
Get-Date

```

What we save in writing the function/program is more than clobbered by the excess needed to actually execute it, though. Le sigh.
> 2 votes

# Answer
## Python, 66 bytes

Note, my implementation neither calls an inbuilt time function, nor using scheduling feature.

```
def S(t):
 try:__import__("Queue").Queue().get(1,t)
 except:pass

```

And yes, it is eligible for bounty.
> 2 votes

# Answer
# Pyth, 19 bytes

Late entry but after finding `.d0` in the docs last night I decided to give it a go.

```
DCNK.d0W<-.d0KNJ1))

```

Defines a function which loops until the time elapsed is `N` seconds.

Try it here.
> 2 votes

# Answer
# Hassium, 55 Bytes

```
func w(t){p=time().second;while((p+t)>time().second)0;}

```

Run and see expanded: http://HassiumLang.com/Hassium/index.php?code=9f4e2bdb292b14b150fba63677a11a79
> 2 votes

# Answer
# RProgN 2, 13 bytes

```
°°°)*™+]³]™>:

```

## Explained

```
°°°)*™+]³]™>:
°°°             # Push 3 tens to the stack.
   )*           # Get the product of the entire stack, including the implicit input. This is the shortest way to multiply the input by 1000.
     ™+         # Add it to the current time in miliseconds.
       ]        # Duplicate it to use as a (throwaway) conditional.
        ³   :   # Create a function using the next 3 concepts, and while the top of the stack is truthy, execute it.
         ]      # Duplicate the target time
          ™>    # Is it larger than the current time?

```

The bounty specifically says "without using a loop checking how much time has **elapsed**", which this does not do. This sets a target time, and keeps checking if it's passed that target time, thus it's eligible for the bounty.

Try it online!
> 2 votes

# Answer
# Tcl, 53 bytes

```
proc W t {while "\[clock mil]-[clock mil]<$t*1e3" {}}

```

Try it online!

# Explained

Command `clock milliseconds` can be reduced to `clock mil`, with escaped 1st bracket, it'll be interpreted at each loop, and w/o just once. As it measures milliseconds, we need to multpily by 1000 or 1e3 which saves 1 Byte.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler) \+ /u:System.Threading, 36 bytes

```
x=>new SemaphoreSlim(0).Wait(x*1000)

```

Try it online!

Creates a semaphore with no capacity and tries to get it for the specified number of seconds.

I realize I am "wait"ing on something here. To me this seems more like the ping/timeout solution as opposed to `Thread.Sleep`. The code tries to get a resource that it cannot get and stops trying after a limit.

===

Below is a variation that starts a `Task` with an infinite loop, then waits for it to complete with a timeout. All required namespaces are included by default, but the solution is a few bytes longer than the one above.

# C# (Visual C# Interactive Compiler), 40 bytes

```
x=>Task.Run(()=>{for(;;);}).Wait(x*1000)

```

Try it online!
> 1 votes

# Answer
# Vyxal, 9 bytes

```
kṡ+{:kṡ>|

```

Try it Online!

For accuracy, use the offline interpreter, dowloadable via the link in the header.

```
kṡ        # Push current epoch, in seconds
  +       # Added to input
   {    | # Until
     kṡ   # Current epoch
    :  >  # Is greater than this
   {    | # Loop

```
> 1 votes

# Answer
# 05AB1E, 22 bytes

```
žcžb60*+[Džcžb60*+αIQ#

```

Try it online.

NOTE: Depending on how many microseconds in the current second have already passed, the tolerance might be slightly larger than 0.1 sec. But since almost halve the answers have similar issues, I figured it's allowed.

**Explanation:**

05AB1E doesn't have any builtins for the current time. It does however have a builtin for the current year/month/day/hours/minutes/seconds/microseconds as separated builtins. Since only using seconds can potentially wrap around from 59 to 0 causing issues, I need both the minutes and seconds, making the code even longer than most answers in non-codegolfing languages unfortunately.

```
žc                # Push the current seconds
  žb              # Push the current minutes
    60*           # Multiply it by 60
       +          # Add them together
[                 # Start an infinite loop:
 D                #  Duplicate the initial (minutes*60 + seconds) from before the loop
  žcžb60*+        #  Push the current (minutes*60 + seconds) again
          α       #  And take the absolute difference between the two
           IQ     #  And if this is equal to the input:
             #    #   Stop the infinite loop

```
> 0 votes

# Answer
# SmileBASIC, 20 bytes

```
INPUT T
DIALOG"",,,T

```

Opens a dialog box that closes automatically after `T` seconds. I'm not sure if this counts as a "built in waiting function", but I think this is just as valid as using `ping`.

An alternative 37-byte program which definitely isn't cheating:

```
INPUT T
FADE.,T*60WHILE FADECHK()WEND

```

Causes the screen fade color to change to 0 (alpha=0,red=0,green=0,blue=0) (no effect) gradually over `T` seconds, then waits for that animation to finish.
> 0 votes

# Answer
# QB64, 31 bytes

Infinite loop until the time has elapsed

```
t=TIMER:DO:LOOP UNTIL t-TIMER>n

```
> 0 votes

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


title: Flatten the CUBE

text:
# Question
Title: Flatten the CUBE
Do you ever look at 3D shapes and think that we have 2 many dimensions. So let's make 3D into 1D! (See what I did there?)

# Task

Given a 2D representation of a cube (layout below), flatten it into a single string, based on pointers.

# The CUBE

This is the layout of the cube filled with no-ops (`,`) and pointers at the corners (`<>v^/`). The Navigation Pointer (NP) begins the program where shown.

```
         | NP begins here, moving right.
         V
         >,,,,,,,,,,,,,,,,,,v
        ,                  ,,
       ,                  , ,
      ,                  ,  ,
     ,                  ,   ,
    ,                  ,    ,
   ,                  ,     ,
  ,                  ,      ,
 ,                  ,       ,
/,,,,,,,,,,,,,,,,,,/        /
,                  ,       ,
,                  ,      ,
,                  ,     ,
,                  ,    ,
,                  ,   ,
,                  ,  ,
,                  , ,
,                  ,,
^,,,,,,,,,,,,,,,,,,<

```

The NP continues moving right from the start until it meets a corner. Each corner has a default direction that, unless overridden at the corner by a pointer, will point the NP in a new direction. They are shown on the above diagram. The pointers in the program are `v^<>/` (the `/` points it either down or up, due to the layout there will never be any confusion between the two)

The NP stops moving when it reaches the  symbol (Yes I know this is a multi-byte character, deal with it). Each character it goes over is added to the final output string except for the pointers, the no-op (`,`) and the  symbol.

# Input

Input will be a multi-line string that matches the layout of the **CUBE** with the non-whitespace characters replaced with any character in the range `0x21` to `0x7E` and **at least** one instance of the EOF.

You may take input as:

* A multiline string
* A list of strings where each line is a new element in the list
* A 2D list of strings where each line is broken down into a list

# Output

The cube, flattened down into a single line string.

# Conditional Pointer

The NP has a boolean value that is used for something called a "conditional" pointer that begins at `true`.

The "conditional" pointer (`?`) is a pointer which will alternate the NP value between `true` and `false` every time it is used. Conditional pointers only take effects when used on the corners where 3 tracks (3-point corner) meet. If the value is `true` when the NP reaches the conditional pointer, the NP moves to the default direction in the CUBE image and, **after** being directed, the NP value is toggled. Therefore, if it is on `false`, the NP follows the non-default direction.

There will never be an instance where the NP goes towards a conditional and the default direction is the direction it just came from. Imagine that this is the left corner of the front face and the NP value is currently `true`:

```
      NP direction
      /
     ,
    ,
,,,?
   ,
   ,

```

This will never happen as the default direction will mirror it back to how it was.

If the conditional pointer is on an 3-point corner:

* It isn't added to the final string
* The NP value is toggled between `true` and `false` **after** the NP has been directed.
* If the NP value is `true`, the NP is redirected to the **default** direction. Otherwise, it is redirected to the **non-default** direction.

If it is on a track or a 2-point corner:

* It is added to the final string
* the value **is** toggled
* The IP **isn't** directed

# Something to watch out for

If a pointer is on a track and it **doesn't** point into spaces, the NP is directed into the new track, adds the next character to the final string and rotates the NP by 90 degrees to the right.

```
 abcd
   >e
  g f
 /
NP direction

```

would flatten to

```
(...) gef (...)

```

NOT

```
(...) g>def (...)

```

A `/` pointer doesn't redirect the NP in this instance as it may redirect into a space so

```
     f
     e
> ab/d

```

would become `ab/def`

# Rules

* The width, height and depth of the cube may change
* The height and depth of the cube will always be the same and will be half the width, so the width will always be even.
* The width will be between (inclusive) 6 and 60.
* There will always be an EOF () that can be reached by the NP. E.g there will never be something like this in the cube: `<¶>` as the NP would never be able to reach the cube.
* As a space cannot be inserted into the cube's tracks, the final string shouldn't ever have a space in it.
* If a pointer is placed in one of the tracks (not on a corner) and it would direct the NP into spaces, the NP stays constant and the character is added to the final string.
* However, if the pointer keeps it on the track, the NP is directed and the pointer character isn't added
* As no-ops (`,`) aren't added to the final string, the final string shouldn't contain any `,` in it.
* You can assume that the input will be correct.
* This is a so shortest code in *bytes* wins!

# Examples

```
Input
Output
-----
Input
Output

  abcdef
 ¶    ,g
q,,,,, h
p    ,i
onmlkj

abcdefghijklmnopq

-----

         >,,,,,,,,,,,,,,,,,,v
        ¶                  ,,
       ,                  , ,
      ,                  ,  ,
     ,                  ,   ,
    ,                  ,    ,
   ,                  ,     ,
  ,                  ,      ,
 ,                  ,       ,
/,,,,,,,,,,,,,,,,,,/        /
,                  ,       ,
,                  ,      ,
,                  ,     ,
,                  ,    ,
,                  ,   ,
,                  ,  ,
,                  , ,
,                  ,,
^,,,,,,,,,,,,,,,,,,<

nothing

-----

                   Mr/~gm,Vc!r,0cbmPC@Zg9jb)7=m^ppwN*Nuk){r
                  c                                      ¶Z
                 J                                      ; #
                e                                      j  8
               ]                                      b   "
              #                                      `    4
             h                                      $     -
            p                                      n      2
           L                                      S       P
          B                                      ;        R
         @                                      J         D
        E                                      N          <
       O                                      \           p
      B                                      y            =
     |                                      9             ;
    T                                      x              [
   6                                      o               k
  !                                      L                =
 E                                      K                 ~
>mjmz6,?A*Q)^.a:IpGP"^bK}DSXL)2F!BV|"m6/                  T
a                                      A                 6
5                                      =                p
1                                      i               R
4                                      /              ?
-                                      Z             (
1                                      "            `
'                                      0           {
N                                      p          M
O                                      *         K
Z                                      J        $
"                                      (       d
4                                      +      o
f                                      U     g
i                                      v    b
U                                      ~   L
U                                      M  h
g                                      ^ D
2                                      (g
5]u*n<Ldn</9/XQyC444Va\m}W3Rf,rp"a@5cZB0

(Newlines added for readability)
Mr/~gmVc!r0cbmPC@Zg9jb)7=m^ppwN*Nuk){rZ#8"4-2PRD<p=;[k=~T
6pR?(`{MK$dogbLhDg0BZc5@a"prfR3W}m\aV444CyQX/9/ndLn*u]52g
UUif4"ZON'1-415amjmz6?A*Q)^.a:IpGP"^bK}DSXL)2F!BV|"m6KLox9
y\NJ;Sn$`bj;

-----

       NEWYORKCITYBABY!
      ¶              ,,
     ,              , ,
    ,              ,  ,
   ,              ,   ,
  ,              ,    ,
 ,              ,     ,
,,,,,,,,,,,,,,,,      ,
,              ,     ,
,              ,    ,
,              ,   ,
,              ,  ,
,              , ,
,              ,,
,,,,,,,,,,,,,,,,

NEWYORKCITYBABY!

-----

                          /{Y!_(=-)s<e!D^<+<+1o30d>QOx9kfu?3X2I:8],t>Ye~,Y9/6;u@
                         ]                                                    >Y
                        !                                                    1 )
                       c                                                    7  8
                      ^                                                    K   &
                     f                                                    K    9
                    M                                                    }     O
                   s                                                    _      ?
                  h                                                    N       e
                 ?                                                    u        ,
                g                                                    =         s
               >                                                    Q          M
              a                                                    0           9
             b                                                    c            (
            h                                                    {             c
           [                                                    m              *
          I                                                    R               %
         K                                                    E                >
        u                                                    5                 n
       W                                                    f                  ]
      }                                                    |                   y
     F                                                    E                    q
    )                                                    <                     ;
   X                                                    L                      S
  F                                                    M                       |
 u                                                    *                        Z
>XZpJ=L`+8ONRk?T7$qVr6-U^f14{>>ABEEP`Mjx&T[/&o*F=*qq{/                         e
¶                                                    <                        ^
+                                                    P                       C
.                                                    x                      m
;                                                    ^                     >
y                                                    4                    b
5                                                    v                   `
Q                                                    B                  c
2                                                    e                 r
a                                                    x                I
3                                                    1               Y
Q                                                    v              `
w                                                    ;             o
*                                                    S            h
E                                                    b           S
r                                                    6          P
M                                                    `         l
%                                                    M        A
-                                                    `       "
j                                                    \      s
}                                                    ~     J
$                                                    h    c
%                                                    p   O
I                                                    Z  Z
]                                                    N E
`                                                    3<
x^}}SI"-a3[%7U5EV}"UM?Aov|E_yjrMt<HAQ@}QAABO&y//R0$\2p

(Newlines added for readability)
]!c^fMsh?g>abh[IKuW}F)XFuXZpJ=L`+8ONRk?T7$qVr6-U^f14{ABEE
P`Mjx&T[/&o*F=*qq{*ML<E|f5ERm{c0Q=uN_}KK71Y)8&9O?esM9(c*%
>n]yq;S|Ze^Cm>b`crIY`ohSPlA"sJcOZE3NZph~\`M`6bS;;Sb6`M`\~
hpZN3p2\$0R//y&OBAAQ}@QAHtMrjy_E|voA?MU"}VE5U7%[3a-"IS}}^
x`]I%$}j-%MrE*wQ3a2Q5y;.+

-----

   %:biv+|?
  ¶      \+
 T      c ,
?{yX<//v  "
i      [ @
Q      Tj
U8sUNl.?

%:biv+|+"@jT[[T.lNUs8UQi{yXXy{T

-----

     FCf2hoYA)&*j
    F          ¶#
   3          p (
  &          ~  w
 ;          *   t
39Hq{F'MmmO/    9
5          \   D
-          |  }
8          c l
a          25
GKa"<0/7MG[?

FCf2hoYA)&*j#(wt9D}l5[GM7/0"aKGa8-53;&3FFCf2hoYA)&*j#(wt9D}l52c|\*~p

-----

           #S^[WNk3;9v;e2\h!@CI#Il?
          G                      g`
         $                      2 \
        V                      9  S
       m                      Y   b
      6                      )    *
     U                      '     V
    [                      g      V
   I                      8       X
  <                      T        U
 K                      ¶         C
?ozMt+xxxxutvQgkx&D9I/<v          '
w                      K         p
V                      y        h
(                      R       y
e                      P      i
]                      !     x
Z                      /    s
y                      w   '
#                      X  4
c                      ~ W
Z                      E,
~IdXPYS.Lc49lC~vjULUBv.?

(Newlines added for readability)
#S^[WNk3;9v;e2\h!@CI#Il`\Sb*VVXUC'phyixs'4WE~Xw/!PRyKKyRP!/wX~E
.vBULUjv~Cl94cL.SYPXdI~Zc#yZ]e(VwozMt+xxxxutvQgkx&D9I//I9D&xkgQ
vtuxxxx+tMzoK<I[U6mV$G#S^[WNk3;9v;e2\h!@CI#Ilg29Y)'g8T

```

# Answer
> 11 votes
# Vim, 971 bytes

```
Go<C-v><C-v><C-v>
elsei'<C-v><C-v><C-v><C-r>t'==<Esc>^"zC<C-v><C-v><C-v>
let@b=<Esc>^"fC<C-v><C-v><C-v>
let@O=<Esc>^"xC:if'<C-v><C-v><C-v><C-r>0'==' '<Esc>^"yC<C-v><C-v><C-v>
norm <Esc>^"wC<C-v><C-v><C-v>
let@m='<Esc>^"vC'<C-v><C-v><C-r>f0<C-v><C-v><C-v>
el<C-v><C-v><C-v>
if'<C-v><C-v><C-v><C-r>m'=='<Esc>^"aCyl:if'<C-v><C-v><C-v><C-r>0'!=' '<C-v><C-v><C-v>
let@T=<Esc>^"hC457||<C-v><C-v><C-v><C-r>t==147<C-v><C-r>vlk'<Esc>^"iC@n:if<C-v><C-v><C-v><C-r>t==<Esc>^"jC@nlylh<C-r>y<C-r>x'>'<C-r>w@m<C-r>z234568<C-r>wl<C-r>vj'<C-v>
el<C-r>wl<C-r>vl'<C-v>
en<C-v>
<Esc>^"rC@nhyll<C-r>y<C-r>x'<'<C-r>w@m<C-r>z1248<C-r>wh<C-r>vk'<C-v>
el<C-r>wh<C-r>vh'<C-v>
en<C-v>
<Esc>^"lC@nkylj<C-r>y<C-r>x'^'<C-r>w@m<C-r>z234568<C-r>wk<C-r>vl'<C-v>
el<C-r>wk<C-r>vk'<C-v>
en<C-v>
<Esc>^"uC@njylk<C-r>y<C-r>x'v'<C-r>w@m<C-v>
el<C-r>wj<C-r>vj'<C-v>
en<C-v>
<Esc>^"dC<C-r>j<C-r>i<C-r>z38<C-r>vhj'<C-v>
el<C-r>x'/'<C-v>
en<C-v>
<Esc>^"sC<C-r>j178<C-v>
if<C-v><C-r>b<C-r>vj<C-r>al'<C-r>vhj'<C-v>
el<C-r>vh'<C-v>
en<C-r>f1<C-v>
en<C-r>z147<C-v>
if<C-v><C-r>b<C-r>vlk<C-r>al'<C-r>vj'<C-v>
el<C-r>vh'<C-v>
en<C-r>f1<C-v>
en<C-r>z134<C-v>
if<C-v><C-r>b<C-r>vh<C-r>aj'<C-r>vlk'<C-v>
el<C-r>vk'<C-v>
en<C-r>f1<C-v>
en<C-r>z457<C-v>
if<C-v><C-r>b<C-r>vlk<C-r>ah'<C-r>vj'<C-v>
el<C-r>vl'<C-v>
en<C-r>f1<C-v>
en<C-v>
el<C-r>x'?'<C-r>f(<C-v><C-r>b+1)%2<C-v>
en<C-v>
<Esc>^"qC"tyl:if'<C-v><C-r>t'=='>'<C-r>w@r<C-r>z'<'<C-r>w@l<C-r>z'v'<C-r>w@d<C-r>z'^'<C-r>w@u<C-r>z'/'<C-r>w@s@e<C-r>z'?'<C-r>w@q@e<C-r>z'█'<C-r>wHdG"op<C-v>
k<C-r>z','<C-r>w@e<C-v>
el<C-r>w"Oyl@e<C-v>
en<C-v>
@c<Esc>^"cCma@myl<C-r>y<C-r>w`a@g<C-r>w@m<C-v>
en<C-v>
<Esc>^"eC<C-r>j58<C-r>vl'<C-r>z178<C-r>vj'<C-r>z38<C-r>vhj'<C-r>z134<C-r>vh'<C-r>z35<C-r>vk'<C-r>z<C-r>i<C-v>
en<C-v>
<Esc>^"gC:let@t=''<C-v>
h<C-r>h1<C-v>
en<C-v>
<C-v><Esc>k<C-r>h2<C-v>
en<C-v>
l<C-r>h3<C-v>
en<C-v>
l<C-r>h4<C-v>
en<C-v>
j<C-r>h5<C-v>
en<C-v>
j<C-r>h6<C-v>
en<C-v>
h<C-r>h7<C-v>
en<C-v>
h<C-r>h8<C-v>
en<C-v>
<C-v><Esc>kl<Esc>^"nC1l<Esc>"mx"bxgg
@c

```

Try it online!

That's a chonker of a Vim program right there. The inputted cube requires a padding of spaces around the sides. Additionally, I used  instead of  as the stopping point, but that is only because  has a special meaning in V. You can replace the  with  and it will run just fine in Vim.

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


title: Extract all keys from an object (json)

text:
# Question
Title: Extract all keys from an object (json)
## Description

Given an object (json), write code to extract all the keys from it. This is a question that I really wanted to ask everybody for a long time ago but I did not have time to write it up. It can be helpful in some cases in your daily work.

## Rule:

* You can use any parse function to get the JSON object, it does not cost you any bytes
* Since a JSON object is a data structure that is not available in some languages, you can use any kind of data that has a similar structure in your favorite language.
* To be clear, the input to your function should be a JSON object if it can.
* The object can have nested keys.
* The object can contain arrays and if it contains an array you will use the index of each element as a key.
* Output can be a list with any format but it is preferred to be line by line.
* The output keys can be arranged in **any order**, it does not matter.
* Shortest bytes for each language will be win.
* You can use any delimiter between each child key and its parent. Here I use `.` (please see the sample output for more detail).
* The key can be a special character. For example: The input I got from @tsh

```
{"":{"":4,".":5},".":2,"..":3}

```

But this is a special case and it is not required to handle it. You are better to avoid it.

## Example

Given an object:

```
A = {
"name" : {
  "first": "jane",
  "last": "doe"
},
"lang" : ["html", "css"]
}

```

Then the output should be:

```
"name"
"name.first"
"name.last"
"lang"
"lang.0"
"lang.1"

```

The index key (`0` and `1`) are a little tricky here, so for some languages like Javascript, it can be `[0]` and `[1]` instead.

So the example below is also correct:

```
"name"
"name.first"
"name.last"
"lang"
"lang[0]"
"lang[1]"

```

## A Sample test case:

### Input:

```
{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is a correct team name in the NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriors",
                    "Houston Rockets"
                ],
                "answer": "Houston Rockets"
            }
        },
        "maths": {
            "q1": {
                "question": "5 + 7 = ?",
                "options": [
                    "10",
                    "11",
                    "12",
                    "13"
                ],
                "answer": "12"
            },
            "q2": {
                "question": "12 - 8 = ?",
                "options": [
                    "1",
                    "2",
                    "3",
                    "4"
                ],
                "answer": "4"
            }
        }
    }
}

```

### Output:

```
[
  "quiz",
  "quiz.sport",
  "quiz.sport.q1",
  "quiz.sport.q1.question",
  "quiz.sport.q1.options",
  "quiz.sport.q1.options.0",
  "quiz.sport.q1.options.1",
  "quiz.sport.q1.options.2",
  "quiz.sport.q1.options.3",
  "quiz.sport.q1.answer",
  "quiz.maths",
  "quiz.maths.q1",
  "quiz.maths.q1.question",
  "quiz.maths.q1.options",
  "quiz.maths.q1.options.0",
  "quiz.maths.q1.options.1",
  "quiz.maths.q1.options.2",
  "quiz.maths.q1.options.3",
  "quiz.maths.q1.answer",
  "quiz.maths.q2",
  "quiz.maths.q2.question",
  "quiz.maths.q2.options",
  "quiz.maths.q2.options.0",
  "quiz.maths.q2.options.1",
  "quiz.maths.q2.options.2",
  "quiz.maths.q2.options.3",
  "quiz.maths.q2.answer"
]

```

This is my solution using jq:

```
jq -r '[paths|map(.|tostring)|join(".")]'

```

Full code:

```
jq -r '[paths|map(.|tostring)|join(".")]' file.json

```

The content of `file.json` is an object from input

# Answer
> 9 votes
# JavaScript (V8), 72 bytes

An edited version to support literal `false`, `true` and `null` values.

```
f=(o,s)=>!o|[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))

```

Try it online!

---

# JavaScript (V8), 69 bytes

Takes a native JSON object as input. Prints the results, using a comma as the delimiter.

```
f=(o,s)=>[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))

```

Try it online!

### How?

This is a recursive function walking through the keys at the root level and then in each sub-tree of the structure.

We need to process recursive calls on objects and arrays and to stop on strings and numbers. This is achieved with `[o]==o||Object.keys(o)`:

```
 type of o | [o]==o    | Object.keys(o)  | string coercion example
-----------+-----------+-----------------+-------------------------------------
 array     | false     | 0-based indices | ['foo', 'bar'] -> 'foo,bar'
 object    | false     | native keys     | {abc: 'xyz'}   -> '[object Object]'
 string    | true      | n/a             | 'hello'        -> 'hello'
 number    | true      | n/a             | 123            -> '123'

```

# Answer
> 5 votes
# Ruby, ~~108~~ ~~146~~ ~~115~~ 92 bytes

+38 bytes to fix test cases for objects inside arrays.....

-31 bytes because we can take a parsed JSON object as input now.

-17 bytes by removing the duplicated `flat_map` usage.

```
f=->j,x=''{z=j==[*j]?[*0...j.size]:j.keys rescue[];z.flat_map{|k|[r=x+k.to_s]+f[j[k],r+?.]}}

```

Try it online!

# Answer
> 5 votes
# JavaScript (Node.js), 75 bytes

```
f=o=>Object.keys(o+''===o||o||0).flatMap(k=>[k,...f(o[k]).map(i=>k+'.'+i)])

```

Try it online!

# Answer
> 4 votes
# Python 2, ~~122~~ ~~135~~ ~~122~~ 119 bytes

```
f=lambda d:`d`[0]in'{['and sum([[str(k)]+['%s.'%k+q for q in f(v)]for k,v in(enumerate,dict.items)['{'<`d`](d)],[])or[]

```

Try it online!

Now handles an even broader class of inputs, including `lists` of `dicts`.

# Answer
> 3 votes
# PHP, ~~147~~ 146 bytes

```
function f($j,$t){foreach($j as$k=>$v){if(is_array($v)){echo trim($t.="$k.",'.')."\n";f($v,$t);$t=str_replace("$k.",'',$t);}else{echo$t."$k\n";}}}

```

Try it online!

I'm sure that this is far from best solution in PHP, but I tried my junior talent. :D

```
$json = '{
    "name" : {
        "first": "jane",
        "last": "doe"
    },
    "lang" : [
        "html",
        "css"
    ]
}';

/** We need to define a text string variable. */
$text = ''; // or keysChainString

/** Assume that our json is decoded. */
$array = json_decode($json, true);

/**
 * Function that extract all multidimensional array keys.
 * The result will be as:
 * - firstKey
 * - firstKey.firstSubKey
 * - firstKey.firstSubKey.firstSubSubKey
 * - firstKey.secondSubKey
 * - secondKey
 * - etc.
 */
function extractAndFormatMultidimensionalArrayKeys($array, $text){
    /**
     * Iterate through array.
     */
    foreach($array as $key => $value) {
        /**
         * Check if key value is an array.
         * Echo key appended to previously declared $text variable.
         * Then make a recursive call to this function on that array.
         * After that, delete the key from text string.
         */
        if(is_array($value)) {
            echo trim($text .= "$key.", '.') . "\n";
            extractAndFormatMultidimensionalArrayKeys($v, $t);
            $text = str_replace("$key.",'',$text);
        /**
         * If the value is not an array, echo the text concatenated with the key.
         */
        } else {
            echo $text . "$key \n";
        }
    }
}

```

# Answer
> 2 votes
# Red, 159 bytes

```
func[s][r: :rejoin g: func[s m][foreach k keys-of m[print p:
r[s k]if map? t: m/:k[g r[p"."]t]if block? t[repeat n length?
t[print r[p"."n]]]]]g ""load-json s]

```

Doesn't work in TIO since `load-json` was introduced recently, but works fine in the Red console:

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~39~~ 27 bytes

```
MapIndexed[Echo@#2&,#,∞]&

```

Try it online! This function represents JSON arrays as `List`s and objects as `Association`s. The function takes a JSON object as input and prints a set of part specifications to the standard output, each on their own line and preceded by `>>` . A part specification is a list of indices, where each index is a 1-based number or a string wrapped in `Key`. The index of a parent object is printed after those of its children. The output for the first example is:

```
>> {Key[name], Key[first]}
>> {Key[name], Key[last]}
>> {Key[name]}
>> {Key[lang], 1}
>> {Key[lang], 2}
>> {Key[lang]}

```

If the `Key` wrapper is undesirable, it can be removed using a 36-byte function:

### Wolfram Language (Mathematica), 36 bytes

```
MapIndexed[Echo[#2/.Key->N]&,#,∞]&

```

The original challenge's formatting can be achieved with a 54-byte function:

### Wolfram Language (Mathematica), 54 bytes

```
MapIndexed[Print@StringRiffle[#2/.Key->N,"."]&,#,∞]&

```

# Answer
> 2 votes
# Julia 1.0, 57 bytes

```
!x=[(k->["$k";"$k.".*!x[k]]).(keys(x))...;]
!x::String=[]

```

Try it online!

# Answer
> 1 votes
# , 114 bytes

```
f=function(x){if(is.null(n<-names(x)))n<-seq(x);unlist(Map(function(y,z)c(z,if(is.list(y))paste(z,f(y))),x,n),,F)}

```

Try it online!

Defines a recursive function which takes an R list, possibly named, and returns the list of names using space as a separator. Here, a named list (or sub list) corresponds to an object in JSON, and an unnamed list corresponds to an array in JSON.

---
Tags: code-golf, json
---


title: Tips for golfing in jq

text:
# Question
Title: Tips for golfing in jq
Since jq is the Language Of The Month for September 2021, what general tips do you have for golfing in jq? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to jq (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
# Use try-// instead of if-then-else

~~`if A then B else C end`~~

The conditional expression is very lengthy and almost never1 worth it. Depending on your condition `A` and the values `B` and `C` there might be short alternatives based on indexing or arithmetic, but a general solution is to use `try` and `//`.

`try` is part of the try-catch exception handler, and returns `empty` for faulty code if the `catch` part is omitted.
`//` is the *alternative* operator which returns the left hand side if it evaluates to a truthy2 value, and the right hand side otherwise.

Putting these two together we can rewrite the conditional expression as:

```
(try(A//C)*1//B)

```

The `*1` assumes `C` is a number or a string, for lists you might need `+[]` instead and if C is a stream of multiple values, this gets a bit trickier. The outer parentheses can be removed in some cases.

The idea is that `A//C` returns `true` if `A` is `true`, and `true*1` throws an error, which is caught by `try`.

This can be shortened further by using `EXP ?`, which should be a shorthand for `try EXP`, though it seems like it does a lot more stuff, for example causing all subsequent filters to not throw errors. In this case `(1?*(A//C)//B)` works, but you might need to do some trial and error in your specific situation.
Note that `?//` is its own operator since 1.6, so you need to add a space there.

---

**Practical example: Fibonacci**

A recursive filter using a conditional expression comes in at 41 bytes:

```
def f:if.<2then. else[.-1,.-2|f]|add end;

```

Applying the general approach gets this to 39 bytes:

```
def f:try(.<2//([.-1,.-2|f]|add))*1//.;

```

In this case `add` can be used to throw an error in the truthy case, 35 bytes:

```
def f:try(.<2//[.-1,.-2|f]|add)//.;

```

Using `?` instead of `try` for 33 bytes:

```
def f:(.<2//[.-1,.-2|f]|add?)//.;

```

1 If you have a practical example where this is not the case, I'd like to see it.

2 Falsy values are `null` and `false`; all others are truthy. `empty` represents the empty stream - the absence of a value.
> 10 votes

# Answer
# Consult Secret Reference

**Spoiler: github.com/stedolan/jq/wiki/**

JQ has a tutorial & manual on the official site, both of which I highly recommend!

However, on the github repo, there's an extensive wiki on the language with loads more info sure to help your golfing.

It includes:

* FAQ section with:
    + Unofficial tutorials
    + Editor bindings, including vim & emacs
    + Language bindings, including Python & Java
    + Interactive playgrounds for JQ
* Sections for:
    + Processing invalid json
    + Modules
    + Cookbook
    + Implementation details for numbers, regex and other built-ins
* Other goodies
    + Lazy evaluation, generators and backtracking
    + Implement finite state machines in JQ?!
> 6 votes

# Answer
# Avoid `split`

When used on a string, the `/` operator behaves exactly like `split`, but is shorter by at least 3 bytes - and sometimes by as much as 7, such as when going from `now|todate|split(":")` to `now|todate/":"`
> 6 votes

# Answer
# Sugary JSON

#### Overview

Instead of `{foo:.foo, bar:.bar}`, use `{foo, bar}`.

In both case, we're creating a new JSON object with the key `foo` mapping to the value of `foo` in the input.

### Example

```
CODE:  {a, c}

IN:    {"a": 1, "b": 2, "c": 3, "d": 4}
OUT:   {"a": 1, "c": 3}

```

Try it online
> 5 votes

# Answer
# Pipe + Dot = Smell

They're sometimes needed, but this is often a code (golf) smell. You should be wary of any pipes followed by an expression containing a dot.

*Or could it be possible to rewrite every jq program with a period into one without?*

### Examples

`[99|range(.)]` -\> `[range(99)]`
> 4 votes

# Answer
# Avoid map()\[\]

Ungolfed: `[1,2,3]|map(.+1)[]`

Golfed: `[1,2,3][]|.+1`

or even better: `1,2,3|.+1`

Will add more here!
> 3 votes

# Answer
If the coding challenge calls for dealing with individual characters in the input using `explode` can be handy. It breaks a string into an array of codepoints, allowing you pipe the results to a loop to process each character.
> 2 votes

---
Tags: code-golf, tips
---


title: Character counts in source code

text:
# Question
Title: Character counts in source code
Write a program that outputs a list of the number of occurrences of each unique character in its source code.

For example, this hypothetical program `{Source_Print_1};` should produce this output:

```
; 1
P 1
S 1
_ 2
c 1
e 1
i 1
n 1
o 1
p 1
r 2
t 1
u 1
{ 1
} 1

```

The formatting should match this example. No extraneous whitespace is allowed, except an optional final newline.

Your program may not read its own source code from the source file.

The characters listed must be in one of two orders. Either the order of character values in the character encoding used by your language (probably ASCII), or the order the characters appear in your source.

This question inspired by this comment by Jan Dvorak.

# Answer
> 7 votes
# CJam, 14 bytes

```
{S2N`/}`{S2N}/

```

Try it here.

Output is in the order they firstly appears:

```
{ 2
S 2
2 2
N 2
` 2
/ 2
} 2

```

It simply appends `<SP>2<NL>` to each character in `{S2N`/}`.

# Answer
> 20 votes
# ///, 12 bytes

```
  4
4 4

 4

```

*A big thank you goes to @user23013, who suggested this improvement over my CJam code, outgolfing his own, highest-scoring answer in the process.*

The characters are sorted by appearance. This code works in any language that just prints its own source code under the given circumstances (PHP, ASP, etc.).

---

# CJam, 20 bytes

```
''S5N'5S5N'NS5N'SS5N

```

This approach doesn't use any built-in character counting.

Try it online in the CJam interpreter.

### How it works

```
''S5N e# Push a single quote, a space, the integer 5 and a linefeed.
'5S5N e# Push the character 5, a space, the integer 5 and a linefeed.
'NS5N e# Push the character N, a space, the integer 5 and a linefeed.
'SS5N e# Push the character S, a space, the integer 5 and a linefeed.

```

# Answer
> 9 votes
# CJam, 20 bytes

```
{`"_~"+$e`{)S@N}%}_~

```

**How it works**

We first start off with one of the standard quine in CJam

```
{`"_~"}_~

```

which pushes the first block on stack, copies it, and runs the copy, which makes it print the source code itself finally.

Then we add the logic to compute the character count from the source code:

```
{`"_~"+                         e# At this point, we have the full source code with us
       $e`                      e# Sort to get similar characters together and run RLE to
                                e# get count of each character as [count char] array
          {    }%               e# Run each array element through this loop
           )S@N                 e# Pop the character, put a space, rotate the count after
                                e# space and then finally put a newline after the trio
                 }_~            e# Second half of the standard quine explained above

```

Try it online here

# Answer
> 4 votes
# Python 3.5.0b1, ~~107~~ 73 bytes

```
s="t='s=%r;exec(s)'%s;[print(c,t.count(c))for c in sorted({*t})]";exec(s)

```

Rather than the usual string replacement quine, which requires writing everything twice, here's an `exec` quine.

# Answer
> 3 votes
# Mathematica, 101 bytes

```
Apply[Print[#1, " ", #2] &, Tally[Characters[StringJoin[ToString[#0, InputForm], "[];"]]], {1}] & [];

```

Unfortunately, I can't use any of the normal golfing tricks like removing whitespace, `<>` for `StringJoin`, `#` instead of `#1`, `@` for prefix function calls or `@@@` instead of `Apply[...,{1}]`, because `ToString[...,InputForm]` thinks it has to pretty print everything...

This prints the characters in the order they first appear in the code. If I can assume that this *isn't* run in a REPL environment (which is rather unusual for Mathematica) I can save two bytes by omitting the two `;`.

# Answer
> 2 votes
# Haskell, 178 bytes

```
main=putStr(unlines[s:' ':show t|(s,t)<-zip" \"'(),-0123456789:<=S[\\]aehilmnoprstuwz|"[3,3,3,3,3,41,4,1,6,19,12,5,5,2,2,2,2,3,2,2,2,3,3,3,2,2,2,4,2,2,4,2,3,2,5,5,3,2,2,2]])--178

```

Nothing fancy. All characters of the program are in a literal list (String). So are the frequencies. Zip both lists and print. Output:

```
  3
" 3
' 3
( 3
) 3
, 41
- 4
0 1
1 6
2 19
3 12
4 5
5 5
6 2
7 2
8 2
9 2
: 3
< 2
= 2
S 2
[ 3
\ 3
] 3
a 2
e 2
h 2
i 4
l 2
m 2
n 4
o 2
p 3
r 2
s 5
t 5
u 3
w 2
z 2
| 2

```

# Answer
> 1 votes
# Dart - 214 127

A direct version:

```
main(){print("  22\n\" 3\n( 3\n) 3\n1 3\n2 15\n3 8\n4 1\n5 2\n8 2\n; 2\n\\ 23\na 2\ni 3\nm 2\nn 23\np 2\nr 2\nt 2\n{ 2\n} 2");}

```

The "4" is just a fiddling factor to make the numbers add up. See/run on DartPad.

Original: Standard quine tactic, and Dart's function names are a little too long for good golfing.

```
main({m,v,q:r'''main({m,v,q:r''}'')''{m={};for(v in q.split(''))m[v]=m[v]==null?2:m[v]+2;m.forEach((k,v)=>print("$k $v"));}'''}){m={};for(v in q.split(''))m[v]=m[v]==null?2:m[v]+2;m.forEach((k,v)=>print("$k $v"));}

```

See/run it on DartPad.

# Answer
> 1 votes
# Vyxal `D`, 12 bytes

```
`:qpĊ⁋`:qpĊ⁋

```

Try it Online!

# Answer
> 0 votes
# Haskell, 146 bytes

```
main=mapM putStrLn[a:" "++show s|a<-[' '..],s<-[sum[2|b<-show"main=mapM putStrLn[a: ++show s|a<-[' '..],s<-[sum[2|b<-show,a==b]],s>0]",a==b]],s>0]

```

Try it online!

**Output:**

```
  8
" 4
' 4
+ 4
, 6
- 6
. 4
0 2
2 2
: 2
< 6
= 6
> 2
L 2
M 2
S 2
[ 8
] 8
a 10
b 4
h 4
i 2
m 6
n 4
o 4
p 4
r 2
s 12
t 4
u 4
w 4
| 4

```

(Plus an additional newline)

**Explanation:**

The code is

```
main=mapM putStrLn[a:" "++show s|a<-[' '..],s<-[sum[2|b<-show"<code>",a==b]],s>0]

```

where `"<code>"` is a string of the program code without the `"`.

`a` goes through the ascii characters starting with a space. `sum[2|b<-show"<code>",a==b]` counts how often the character appears in the string, with each occurrence counted twice. `a:" "++show s` builds a string of the current character, a space and the character count. Finally `mapM putStrLn` prints each string in the list with a trailing newline.

The hardest part was getting the count of `"` right. Using just `b<-"<code>"` would count zero quotation marks because there are none in the string. Using `show"<code>"` adds a `"` to the front and end to the string, resulting in a count of four. So I had to put two additional quotation marks in the code, so instead of the (shorter) `a:' ':show s` I used `a:" "++show s`.

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


title: ∀ a b. a + b = b + a

text:
# Question
Title: ∀ a b. a + b = b + a
*This question is a part of the LotM.*

A ring is a type of structure that takes the rules of addition and multiplication we are familiar with and abstracts them, so we can reason about them. To do this we state a number of expected properties as axioms and see what we can say about systems that follow these axioms. For example \\$a + (b + c) = (a + b) + c\\$, is one of the axioms commonly given.

But exactly what the ring axioms are depends on whom you ask. Because, rings can be defined in a number of equivalent ways. Often one of the given axioms is that for any \\$a\\$ and \\$b\\$ then \\$a + b = b + a\\$. We call this *additive commutativity*. However this axiom is not needed! Usually we can prove it from more basic axioms.

In this challenge I will give a minimal axiom set for rings in the Lean programming language and your task is to prove commutativity.

The `ring` class is defined as follows:

```
universe u

class ring (α : Type u) extends has_add α, has_mul α, has_one α, has_zero α, has_neg α :=
  ( add_assoc : ∀ a b c : α, a + (b + c) = (a + b) + c )
  ( mul_assoc : ∀ a b c : α, a * (b * c) = (a * b) * c )
  ( add_left_id : ∀ a : α, 0 + a = a )
  ( mul_left_id : ∀ a : α, 1 * a = a )
  ( mul_right_id : ∀ a : α, a * 1 = a )
  ( add_left_inv : ∀ a : α, (-a) + a = 0 )
  ( left_distribute : ∀ a b c : α, a * (b + c) = a * b + a * c )
  ( right_distribute : ∀ a b c : α, (a + b) * c = a * c + b * c)

open ring

```

Your goal is to create an object with the same type as:

```
axiom add_comm {α : Type*} [ring α] : ∀ a b : α, a + b = b + a

```

This is the same as proving the claim.

You may rename things here however you want as long as the underlying type is correct. So the following is a smaller but perfectly valid header for your proof:

```
def k{A:Type*}[ring A]:∀a b:A,a+b=b+a

```

You can't use different but similar looking types. So for example redefining the notation of `=` to make the proof trivial:

```
local notation a `=` b := true
def k{A:Type*}[ring A]:∀a b:A,a+b=b+a := λ x y, trivial

```

is not a valid answer, even though the type *looks* identical. (Thanks to Eric for pointing this possible exploit out.)

You must actually prove the claim, so you may not use `sorry` or `axiom` in your proof.

This is so answers will be scored in bytes with fewer bytes being the goal.

*If you want to do this challenge but don't know where to get started just use the links in the LotM post. I'll be happy to help anyway I can in chat.*

# Answer
## Lean, ~~451~~ ~~449~~ ~~445~~ ~~439~~ ~~414~~ 407 bytes

```
def k{A}[ring A](a b:A):a+b=b+a:=let
L:=@add_left_inv A,I:=@add_left_id A,K:=@congr_arg,c:=λx y,K(+y)$L x in
by{let C:=add_assoc,simp[I]at*,let
e:=λb,(λ(a:A)h:a+a=a,(eq.trans(by
rw[<-I a,<-L,<-C,h])$L _:a=0))(b+-b)$by simp[<-C]at*;rw c,let
d:=K(λx,-b+x+-a)(left_distribute(1+1)b
a),simp[c,C,right_distribute,mul_left_id,mul_right_id,λa b,(by
rw[<-C,e,λa:A,(by rw[<-L,C,e,I]:a+0=a)]:b+a+-a=b)]at*,rw
d}

```

Unpacked:

```
def add_comm {A} [ring A] (a b : A) : a + b = b + a :=
let
  L := @add_left_inv A,
  I := @add_left_id A,
  K := @congr_arg,
  c := λ x y, K (+ y) (L x)
in begin
  have C := add_assoc,

  simp [I] at c,
  -- c: ∀ (x y : A), -x + x + y = y

  have e : ∀ (b : A), b + -b = 0 := λ b,
    have ∀ (a : A), a + a = a → a = 0 :=
      λ (a : A) (h : a + a = a), show a = 0, from
        eq.trans (by rw [← I a, ← L, ← C, h]) (L _),
    this (b + -b) (by simp [← C] at c ⊢; rw c),

  have d : -b + ((1 + 1) * (b + a)) + -a = -b + ((1 + 1) * b + (1 + 1) * a) + -a :=
    K (λ x, -b + x + -a) (left_distribute (1+1) b a),

  simp [c, C, right_distribute, mul_left_id, mul_right_id,
    have ∀ (a b : A), b + a + -a = b :=
      λ a b : A, show b + a + -a = b, by
        rw [← C, e,
          have ∀ (a : A), a + 0 = a, from
            λ a : A, show a + 0 = a, by rw [← L, C, e, I],
          this],
    this] at d,
  -- d : a + b = b + a

  rw d
end

```
> 13 votes

# Answer
# Lean, 268 bytes

```
import tactic.cache
def k{A}[r:ring A](a b:A):a+b=b+a:=by{casesI
r with _ _ _ _ _ c _ d _ _ e f,let g:=λa:A,trans(by
simp*:_=-(a+-a)+(a+-a+a+-a))$by
simp[<-c,*],let:=λa,trans(by
rw[<-c,e,g]:a+b+_=a+(-a+a))$by
rw[c,g,d],transitivity-a+(1+1)*(a+b)+-b,rw f,simp*,simp*}

```

Run with Lean Web Editor
> 12 votes

---
Tags: code-golf, math, abstract-algebra, lean
---


title: Self-growing code codee codeee codeeee

text:
# Question
Title: Self-growing code codee codeee codeeee
Write a program (or function) (let's call it P1), that when run, outputs another program P2 of the same language and exactly 1 byte longer than P1.

Program P2 when run, should output a 3rd program P3 that's 1 byte longer than P2. P3 must output a program P4 that's one byte longer than P3, etc. The same for P5, P6, ..., P∞.

The program chain should go indefinitely, or to a place where the interpreter can't handle anymore (but must remain as a theoretically valid program in the language)

# Rules

* Standard loopholes forbidden
* All programs in the chain should be in one language
* No input is given. Output goes to stdout or function return value
* The program must end after a period of time. A program that stops generating output after a certain time spot but never terminates does not qualify

The shortest program P1 in bytes in each language wins!

# Answer
# JavaScript (ES6), ~~14~~ 12 bytes

-2 bytes thanks to @Shaggy

```
f=_=>"f=_"+f

```

## Testing snippet

```
s=`f=_=>"f=_"+f`;

for(i=10;i--;s=eval(s)())
  o.innerText+=s+"\n";
```

```
<pre id=o></pre>
```
> 30 votes

# Answer
# Haskell, ~~74~~ 66 bytes

EDIT:

* -2 bytes by H.PWiz by using `<>`, then -6 by moving the `(10*)<$>`.

This now uses the newly free `<>` operator (`Semigroup` multiplication, requires GHC 8.4 to work without an import.)

```
main=putStr$fst<>show$(10*)<$>("main=putStr$fst<>show$(10*)<$>",1)

```

Try it online! (Cheats with an import since TIO doesn't have GHC 8.4 yet.)

# How it works

* `main=putStr$` is boilerplate to output the following string value.
* `fst<>show` is a function that takes a tuple, and returns a string consisting of the first element of the tuple concatenated with the tuple's string representation. I.e.

```
(fst<>show)(s,t) = fst(s,t)<>show(s,t) = s++show(s,t)

```
* `(10*)<$>` multiplies the *last* element of the following tuple by 10, adding a digit `0` to its string representation.
> 9 votes

# Answer
# , 4 bytes of ASCII

```
1603

```

Try it online!

I know that 7 isn't normally encoded in ASCII, but this time it's a more convenient encoding so that we're adding 1 byte with each run, not 3 bits.

I'm also not sure whether this counts as cheating or not. (It's usual to be unclear whether or not a 7 quine is cheating, as it straddles the borderline in a number of ways.) You can make a decent argument that the `0` encodes the `6`, but in general it's unclear where the resulting characters "come from" in 7 because it has so many, fairly bizarre, implicit behaviours.

This program prints itself with `1` appended, and will do so even if you append a number of `1`s to it. Here's a commented debug trace of `160311`:

```
|| 160311      Initial data ||; initial program 160311
||7 60311      1 command = append 7 to data
|1 0311        6 command = escape from the last | onwards (7 escapes to 1)
|16e77         0311 commands = append 6e77 to data
|16e77 16e77   Implicit (program is empty): copy data past last | to program
|16e777 6e77   1 command = append 7 to data
71603111 e77   6 command = escape from the last | onwards
71603111 e77   e7 command = output in same encoding as the source

```

(There are no `|` left in the program, so `e` will immediately quit the program as a side effect, meaning that the final `7`s never run).

The basic confusion about where all the characters are coming from is that most commands in 7 just produce data when run, and then `6` attempts to reconstruct a sequence of commands that would produce the given fragment of data; this often ends up close to, but not identical to, the original. (For quining purposes, you normally write a 7 program in such a way that the result will be almost the same, normally differing in leading or trailing `7`s.) So for example, the `1` in the data becomes `716`, which is the easiest way to append `1` to the current data string. We originally produced it with `16`, a different (but similar) character sequence, destructively removing one of the `|` markers the data started with. (I guess perhaps the best argument that this isn't a literal-only quine is that the output is different from the input!)
> 9 votes

# Answer
# C (gcc), ~~134~~ 132 bytes

Slight reworking of the canonical C quine. Dreadfully long.

```
x;*s="x;*s=%c%s%c;main(i){for(i=__LINE__;i--;puts(&x));printf(s,34,s,34);}";main(i){for(i=__LINE__;i--;puts(&x));printf(s,34,s,34);}

```

Try it online!
> 8 votes

# Answer
# Pari/GP, 35 bytes

```
(f=(x)->print1("(f="f")("1x")"))(1)

```

Try it online!
> 7 votes

# Answer
## Fission 2, 7 bytes

```
'!+OR!"

```

Try it online!

The standard Fission quine, but with an extra `!` that prints an additional 0x01 at the beginning of the code on each iteration.
> 7 votes

# Answer
# Python 2, 38 bytes

```
s="print's=%r;exec s'%(s+'#')";exec s

```

Try it online!
> 5 votes

# Answer
# brainfuck, 420 bytes

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

```

Try it online!

This is a modification on the "standard" BrainFuck quine, with a `.` at the end that tacks on an extra `.` each iteration.

The quine itself encodes Brainfuck characters as a stack of hex digits: specifically, the hex digits of `c-0x2b`, which conveniently are the following:

```
+: 0x00
-: 0x02
[: 0x30
]: 0x32
<: 0x11
>: 0x13
,: 0x01
.: 0x03

```

The encoding covers two snippets of code: `>++[[>>+[>]++>++[<]<-]>+[>]<+<+++[<]<+]>>->[>]++++>++` pushes the encoding of the encoding itself, and `[[<++++++++++++++++>-]<+++++++++.<]` walks the stack and prints everything.
> 5 votes

# Answer
# Dirty, 9 bytes

```
'"n[!]a!␛

```

Try it online!

```
'   start and end a string literal
"   push a literal '
n   remove newlines
[!] print the string
a   push the alphabet
!   print the first character
␛   end the program

```

**If source-code reading is allowed:**

# Dirty, 8 bytes

```
Q[!]W33!

```

Try it online!

**Explained:**

```
Q   push the source code
[!] print each character
W   clear the now-empty stack
33! print an exclaimation mark

```

**Might be valid:**

# Dirty, 4 bytes

```
Q[‼]

```

Try it online!

It prints the source code with a trailing newline.
(And a bunch of spaces, due to a bug. It works the same without them though.)

Note that it only works in the native character set, and not when you use the UTF8 front-end - so to try it on TIO you need to replace the character it outputs between the `[]`s with , which is the UTF8 equivalent for what it's printing.
> 3 votes

# Answer
# GolfScript, 9 bytes

```
{'.~1'}.~

```

Try it online!

# CJam, 9 bytes

```
{"_~1"}_~

```

Try it online!

I'm posting both of these solutions in the same answer, since they're just trivial variations of each other and work in exactly the same way. They're both based on the common GolfScript quine `{'.~'}.~` (or `{"_~"}_~` in CJam), which is described in more detail e.g. in this previous answer of mine.

The only difference is that this variant appends a `1` byte to the end of its output. As it happens, any string of `1`s (or any other integer literal without leading zeros) is itself a trivial quine in both GolfScript and CJam, so any ones already present at the end of the code above will simply be copied verbatim to the output. Since GolfScript (and CJam) use arbitrary-length integers, this will work for arbitrarily long programs, at least as long as the computer running the code has enough memory to store it.
> 3 votes

# Answer
# Java 8, ~~162~~ 146 bytes

```
v->{String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s).replaceAll(%1$c1+$%1$c,%1$c%1$c);}"+1;return s.format(s,34,s).replaceAll("1+$","");}

```

Try it online.
Try the first output program; Try the second output program; Try the third output program.

**Explanation:**

```
v->{                       // Method with empty unused parameter and String return-type
  String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s).replaceAll(%1$c1+$%1$c,%1$c%1$c);}"
                           //  The unformatted source code
           +1;             //  Plus a random digit (1 in this case)
  return s.format(s,34,s)  //  Create the quine
          .replaceAll("1+$","");}
                           //  Then remove any trailing 1s

```

-part:

* The `String 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:

* `+1` adds a 1 to both the unformatted and formatted program.
* `.replaceAll("1+$","");}`: Because we only want to increase the program byte-count by one instead of two, we remove any trailing 1s before returning.
> 3 votes

# Answer
# Jstx, 4 bytes

```
£↕♣:

```

Try it online!
> 3 votes

# Answer
# \>\<\>, 9 bytes

```
#o<:}-1:"

```

Try it online!

Variation on a classic \>\<\> quine, which simply adds another dupe command to copy the `#` in the front.
> 2 votes

# Answer
## Perl 5, 32 bytes

```
$_=q{say"\$_=q{$_
};eval"};eval

```

Try it online!
> 2 votes

# Answer
# Attache, ~~76~~ ~~72~~ 61 bytes

```
Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]]",Repr[x+sp]]

```

Try it online!

Standard quine which adds a space to the end of `x` after each iteration.

First few iterations:

```
Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]]",Repr[x+sp]]

```

```
Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]] ",Repr[x+sp]]

```

```
Print!Format[x:="Print!Format[x:=%s,Repr[x+sp]]  ",Repr[x+sp]]

```

etc.

### Attache, 72 bytes

```
y:=1Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x]

```

Try it online!

This is simply a variation of the standard format quine, with a variable `y` that is set to `10*y` after each iteration

The first few iterations:

```
y:=1Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x]

```

```
y:=10Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x]

```

```
y:=100Print!Format[x:="y:=%sPrint!Format[x:=%s,y*10,Repr!x]",y*10,Repr!x]

```

etc.
> 2 votes

# Answer
# Runic Enchantments, 6 bytes

```
"'<S@>

```

Try it online!

> This one was weird. All I had to do was remove a `~` from the original quine found by Jo King.
>
> Every additional run appends another `<` to the end, e.g.:
>
> ```
> "'<S@><<<<<<<<<
>
> ```
>
> All of which do nothing.

Direct copy of this answer on a related challenge. It just so happened to already grow by 1 byte every iteration (strong argument for this challenge being a duplicate of that one or vice versa).
> 2 votes

# Answer
# Swift 4, 89 bytes

```
let(a,b)=(";print(\"let(a,b)=\\((a,b+\"-\"))\"+a)", "");print("let(a,b)=\((a,b+"-"))"+a)

```

Includes a trailing newline

Try it online!
> 1 votes

# Answer
# Haskell, 88 bytes

```
main=putStr$snd(span(<'m')s)++show s;s='#':"main=putStr$snd(span(<'m')s)++show s;s='#':"

```

Try it online! Grows by prepending `#` to the data string.
> 1 votes

# Answer
# Wonder, 33 bytes

```
f\ @(-> ol) ["f\ ";f;";f1";#0];f1

```

An interesting variant on the normal quine that appends a 1 after each iteration.

Progression:

```
f\ @(-> ol) ["f\ ";f;";f1";#0];f1
f\ @(-> ol) ["f\ ";f;";f1";#0];f11
f\ @(-> ol) ["f\ ";f;";f1";#0];f111
...

```

# Explanation

```
f\ @                               #. Sets f to a function that does the following:
    (-> ol) [                      #.   Output each:
             "f\ ";                #.     String for declaration of f
                   f;              #.     Formatted representation of f's function
                     ";f1";        #.     String for call of f
                           #0      #.     Argument passed into f
                             ];f1  #. Call f with 1 as the argument

```

One of the interesting parts of this quine is that Wonder can work with numbers of arbitrary precision, so the progression won't break after a certain amount of ones.
> 1 votes

# Answer
# Stax, ~~20~~ 18 bytes

```
"34s+cTZL"34s+cTZL

```

Run and debug it

Generates an extra space before the 2nd quotation mark every iteration.

## Explanation

Uses the program `"34s+cTZL "34s+cTZL` to explain.

```
"34s+cTZL "34s+cTZL
"34s+cTZL "            String literal
           34s+        Prepend a double quote, Now the string is `"34s+cTZL `
               cT      Copy and trim trailing spaces
                 Z     Put a 0 under the top of stack
                       Stack now (from top to bottom): `["34s+cTZL,0,"34s+cTZL ]`
                  L    Collect all elements on stack, from bottom to top
                       Implicit output, 0 is converted to space.

```
> 1 votes

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

```
":r2ssH

```

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

This is a simple variation of the regular Gol\>\<\> quine but adds a copy of `H` each time it's run. Since the `H` command halts the program, additional `H` at the end does not change the behavior.
> 1 votes

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

```
var s="var s={0}{1}{0}+8;Write(s.Trim('8'),(char)34,s);"+8;Write(s.Trim('8'),(char)34,s);

```

Inspired by Kevin Cruijssen's answer.

Try it online!
> 1 votes

# Answer
# Jelly, 11 bytes

```
“⁾;⁶;ØV” ṘV

```

Try it online!
> 0 votes

# Answer
## Windows Batch, ~~38~~ 36 bytes

```
echo|set/p"=q">q&copy/b/y %0+q %0
::
```

This code creates a file called "q", containing the letter 'q', and then appends it to the original file. Note that "::" is an alias for "rem" that does not require an additional space.

Saved 2 bytes thanks to user3493001.
> 0 votes

# Answer
## ColdFusion, 277 bytes

```
<cfset u=Chr(34)><cfset q="<cfset u=Chr(34)><cfset q=%s%s%s><cfoutput>%screateObject(%sjava%s,%sjava.lang.String%s).format(q,[u,q,u,Chr(35),u,u,u,u,Chr(35)])%s</cfoutput>
"><cfoutput>#createObject("java","java.lang.String").format(q,[u,q,u,Chr(35),u,u,u,u,Chr(35)])#</cfoutput>

```

This is a trivial modification of my ColdFusion quine which adds a newline each extra time it's called.

Tested locally on lucee-express-5.2.6.60
> 0 votes

# Answer
# T-SQL, 175 bytes

```
DECLARE @ VARCHAR(MAX)='DECLARE @ VARCHAR(MAX)=*SET @=TRIM(REPLACE(@,0x2a,CHAR(39)+@+CHAR(32)+CHAR(39)))PRINT @'SET @=TRIM(REPLACE(@,0x2a,CHAR(39)+@+CHAR(32)+CHAR(39)))PRINT @

```

First I wrote an SQL quine, then I modified it to add an extra space (somewhat inspired by this answer).
> 0 votes

# Answer
# Befunge-98 (PyFunge), ~~22~~ 19 bytes

```
r:#,_ #;'D2/'<,,@;"

```

Try it online!

Adds a \< before the last " every generation.
> 0 votes

# Answer
## Jstx, 4 bytes

```
£↕☺V

```

Try it online!

## Explanation

Verbose code:

```
meta.source    Push the source
load 1         Push 1
string.concat  Concatenate source with 1
               Implicit output

```
> 0 votes

# Answer
# C (gcc), 71 bytes

```
#define a(b)*s=#b;b
a(main(){printf("#define a(b)*s=#b;b\na(%s;)",s);})

```

Every iteration adds a semicolon after the closing brace of the main function.

Try it online!
> 0 votes

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