text:
Oops, I blew it up (with numbers)
Inspired by There, I fixed it (with rope), There, I fixed it (with Tape), There, I broke it (with scissors)
Given a string with characters from a-z or A-Z (whichever you prefer), turn missing letters into numbers and make them explode.

Example
Input: abcafabc
Output: a12344321c
Why?
1) Find the missing letters (only going forward in the alphabet): abca(bcde)fabc
2) Replace them with the number of missing letters: abca4fabc
3) Replace the number with

Itself twice if it's even
Itself + 1 if it's odd

In this case: abca44fabc
4) Explode those numbers outwards replacing any letters: a12344321c

Challenge Rules

Explosions can't exceed the boundaries of the string

ae -> 343 (3 letters are missing but since 3 is odd, it's been replaced by 4)

Numbers can be greater than 9

az -> 23242423 (24 letters are missing and since 24 is even, it's repeated twice)

You can have multiple explosions

abcefghijmnop -> ab121fghi1221nop

Multiple explosions can overlap, take the sum of the number when they do

abceghij -> abc(2)e(2)ghij -> ab12(1+1)21hij -> ab12221hij

It's possible that no explosions occur, in that case simply return the string
No explosions between ab, aa, aaa, etc.
You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output.

General Rules

This is code-golf, so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-golfing languages.
Standard rules apply.
Default Loopholes are forbidden.
If possible, please add a link to a test for your code, preferably Tio.
Also, please add an explanation if necessary.

Test cases:
Input  : 'abcdefgklmnopqrstuvwxyz'
Output : 'abcd1234321nopqrstuvwxyz'

Input  : 'abdefgjkl'
Output : 'a121ef1221kl'

Input  : 'xyzaz'
Output : '20212223242423'

Input  : 'abceghij'
Output : 'ab12221hij'

Input  : 'zrabc'
Output : 'zrabc'

I'm sorta confused on how to decide what the ground 0 is.

@NoOneIsHere : ground zero is the place where the missing letters should have been. Example: abcefg ground zero (represented by HERE would be abcHEREefg

But what about acca?

edit: why isn't it 1331 because both blanks explode?

Shouldn't it be 121ca?

This really would have been a lot more elegant without the even/odd rule. Though it could have been even messier if the explosions reflected at the start and end of the string :)

I think you should include an example where the grounds zero overlap such as aeae -> 355553 (if that is correct)

Can my output be an array of chars and ints (eg. ['a','b',1,2,2,2,1,'h','i','j'] for example 1)?

Please work e.g. this example, that should clarify a lot  (overlap over multiple explosions with even steps) : abcfghabceazabcazabcefghabcfabcd

In case return array, [a, z, a] => [23, 24, 24, 23] or [2, 3, 2, 4, 2, 4, 2, 3] botk okay?

@l4m2 [23, 24, 24, 23]

Are you out of these challenge ideas yet lol?

@MagicOctopusUrn, no not yet! I wanted to do a 2D version of if was better received!

Since output through function parameters is permitted as per the standard rules, may I assumed that such a parameter points to a “sufficiently“ large memory area to hold the (correct) result?

Perl 5, -p 110 109 bytes
Handling the even/odd rules waste around 20 bytes
#!/usr/bin/perl -p
s#.#$p+=$.;$c{$p-$_}+=$-=$z-abs$_+$z%2/2for-25..($z=ord($')-ord$&);$&x($.=$z<2||$z%2+2)#eg;s##$c{+pos}||$&#eg

Try it online!

Ruby, 162 bytes
->a{b=[*a=a.reduce{|x,y|[*x,*[(n=y.ord+~x[-1].ord)+n%2]*(n<1?0:2-n%2),y]}];i=-1;b.map{|x|d=-~i+=1;a.map!{|y|(z=x.to_i-(d-=1)*s=d<=>0)<1||x==b[i-s]?y:z+y.to_i}};a}

Try it online!
Takes input as an array of chars, returns a mixed array of chars/ints. (I'm still not sure whether this is allowed after reading the comments to the original post. If not allowed, it's +3 bytes to fix).
Explanation
First, we apply a reduce operation, where we aren't actually reducing anything, but rather reconstruct the array a as [*x,*[...],y], where the middle part contains the numbers inserted at ground zero.
We also make a copy of the array: b=[*a] to serve as a reference, so that we don't get confused which numbers are at the center of the explosion, and which ones are introduced later on.
Then we iterate through b and for each element x, iterate through a to record, what effect x will have on each element y of a.
Conveniently, to_i method returns 0 for non-numeric chars, so that we don't have to worry about distinction between numbers and text.
In my initial code, arrays were indexed by i and j, but this was golfed down to use a "delta" value d=i-j.
Another helper variable is the sign of the delta: s=d<=>0. At the first occurrence it performs the same function as abs, and at the second - it helps us to block the other side of one-sided explosions as in 12344321.
Ultimately, if z is estimated to be positive, we add it up with the integer equivalent of y and store in a, otherwise, y remains intact.

Python 3, 351 348 bytes
Z=zip
R=range
E=lambda o:R(o,0,-1)
D=lambda d:[]if d<1else[[E(d),E(d+1)]]if d%2else[[E(d-1),[d]],[[],E(d)]]
def f(s):
	s=sum(([c]+D(ord(n)+~ord(c))for c,n in Z(s,s[1:]+' ')),[]);l=len(s);v=[0]*l
	for i,c in enumerate(s):
		if len(c)>1:
			for j,d in list(Z(R(i-1,-1,-1),c[0]))+list(Z(R(i,l),c[1])):v[j]+=d
	print(*(d or c for c,d in Z(s,v)),sep='')

Try it online!

−3 thanks to Kevin

The function f takes one string as input and prints the result to standard output.
Ungolfed
def range_downto_0(o):
    return range(o, 0, -1)

def D(d):
    return (
        []
        if d >= 0 else
        [[range_downto_0(d), range_downto_0(d + 1)]]
        if d % 2 else
        [[range_downto_0(d - 1), [d]], [[], range_downto_0(d)]]
    )

def f(s):
    s = sum(([c] + D(ord(n) + ord(c) - 1) for c, n in zip(s, s[1:] + ' ')), [])
    v = [0] * len(s)
    for i, c in enumerate(s):
        if len(c) == 2:
            for j, d in itertools.chain(
                zip(range(i - 1, -1, -1), c[0])),
                zip(range(i, len(s)), c[1])
            ):
                v[j] += d
    return ''.join(str(d) if d else c for c, d in zip(s, v))

Explanation

Expand the string s to insert number range objects as placeholders for the "outward explosions". Save the result as a list s.
Create a list of zeros v with the same length as s.
Inspect s and, for every number range, add the numerical values to the value at their respective position in v. v now contains all the numbers that are going to be in the result at their correct positions.
Iterate over s and v simultaneously, take the entry from v if it is greater than 0 or the entry from s otherwise and print each chosen entry in order.

The expensive repeated array concatenation in step 1 is at best in O(n2) but could be expressed in O(n) using a generator (assuming Python can construct lists from generators in O(n)). The remainder of this algorithm is in O(n ⋅ min{n, |Σ|} ⋅ log |Σ|) with Σ being the alphabet or, if you want to regard Σ as a constant, straight out O(n) (assuming that Python can join string generators in O(n)). “min{n, |Σ|}” comes from the outward range expansion and “log |Σ|” results from the conversion of numbers to strings.

You can remove three spaces at d<1else[[E(d) (-2) and d%2else (-1).

C (gcc), 395 bytes
#include<stdlib.h>
#include<stdio.h>
f(char*s){char*S=s;while(*S++);const int l=S-s-1;int i=1,j=0,k,d,o,t[l*3],*v;for(;i<l;i++)(d=s[i]+~(t[j++]=s[i-1]))>0&&(t[j++]=-d,d%2||(t[j++]=0));l>0&&(t[j++]=s[l-1]);v=calloc(k=j,4);for(i=0;i<k;i++){if((d=-t[i])>0){d+=o=d%2;for(j=0;j<d&&j<=i;j++)v[i-j]+=d-j;i+=!o;for(j=o;j<d&&i+j<k;j++)v[i+j]+=d-j;}}for(i=0;i<k;i++){d=v[i];printf(d?"%d":"%c",d?d:t[i]);}}

Try it online!
f takes input as a null-terminated character array and returns its result on standard output.
Explanation
This is my first C submission to Code Golf. The algorithm is the same as in my Python submission.


text:
Help John watch movies!
Introduction
So John finally has his holidays! And what better could he do than watching some movies. He indeed has a lot of movies to watch, but he is unable to decide which one to watch first. He has a list of movies, each in the format: <Movie name> (<Year>). So he makes a simple set of rules to decide his order of watching movies.
1) The first preference is given to the release year. If a movie released a year or earlier than others, then he would watch them first.
2) If two or more movies released in the same year, and one of them begins with a number, then he would prefer to watch that movie first.
3) If two or more movies released in the same year begin with a number as well, then the movie which comes first on the original list would be watched first.
4) If two or more movies released in the same year begin with a letter, then the movie beginning with a letter which comes earlier in the English alphabet will be chosen first. If two movies begin with the same letter, then the one containing a lesser number of characters in the movie name(including spaces) will be chosen first.
5) If the number of characters is also same, then the movie which comes later in the original list would be watched first.
Well, what a great set of rules indeed. Now the challenge.
Challenge
The input will be a list of movies, i.e, strings - all following the specified format, and you need to output the sorted list, following the above stated rules. Be case insensitive , i.e, treat both uppercase and lower case characters equally and assume all inputs to be valid, and the list will contain no duplicate elements. Also, every character in the movie name is either a letter, or a number and there are blank spaces only in between. You can assume the release year is 4 digits long.
Examples
Input
Output

['The Town (2010)', 'The Prestige (2006)', 'The Departed (2006)']
['The Departed (2006)', 'The Prestige (2006)', 'The Town (2010)']

['Hello (2001)', '15 minutes (2001)', '25 Minutes (2002)']
['15 minutes (2001)', 'Hello (2001)', '25 Minutes (2002)']

['15 (1960)', '25 days (1960)']
['15 (1960)', '25 days (1960)']

['Jjjj (2004)', 'Hello (2004)']
['Hello (2004)', 'Jjjj (2004)']

['all gone (2018)', 'Be careful (2018)']
['all gone (2018)', 'Be careful (2018)']

['Be careful (2018)', 'all gone (2018)']
['all gone (2018)', 'Be careful (2018)']

Scoring
This is code-golf , so the shortest code wins!

"i.e. be case in-sensitive" - does this mean "treat upper and lowercase characters from the input as equal" or does it mean "you may assume input will always be in a single case" or does it mean "it does not matter how you compare different cases" or does it mean something else? (none of the examples help decipher it)

@JonathanAllan Sorry for confusion. I have made it clear in my post now.

@JonathanAllan I think "case insensitive" says it all. In addition to that, <Movie name> and all the examples are mixed case.

@Titus it does not say it all - it can be interpreted in multiple ways and is therefore ambiguous. The fact that none of the examples shows lowercase letters in the first position means they don't help explain. At least one of the answers here treats B as less than a, which according to the post clarification is incorrect, so others made assumptions about the interpretation.

@Titus the clarification affected three of the four answers.

@JonathanAllan added examples

It was autocorrect. I just realised it when editing finished. Fixed now

Is the output format relaxed (i.e. can I print additional stuff)?

@Titus depends. Like what stuff.

@ManishKundu look at my TiO

@Titus yes, that's acceptable.

I feel like this isn't a complete test suite for all rules, but then again it may be because I can't think of the exception off the top of my head.

Figured it out... I want this test case please: ['21 Jump Street (2012)', '210 Jump Street (2012)', '22 Jump Street (2012)']

I'm not sure what order that needs to be in, right now I'm thinking 21,22,210, and if that's the case all answers fail.

@MagicOctopusUrn Order remains same. Rule 3

@ManishKundu misunderstood, I thought you meant the lower number comes first.

Python 3, 115 bytes
lambda a:sorted(a[::-1],key=lambda s:(s.split()[-1],-("/"<s[0]<":"),a.index(s)*("/"<s[0]<":"),s[0].lower(),len(s)))

Try it online!
-11 bytes thanks to spec change (thanks Jonathan Allan for pointing it out)
-6 bytes thanks to Lynn

I believe that since it has been confirmed that the year is guaranteed to be four digits that you could replace int(s.split()[-1][1:-1]) with s.split()[-1]

@JonathanAllan cool, thanks!

A new rule clarification has made this solution invalid (it should be case-insensitive).

Unfortunately (due to clarification of the intended meaning of "be case in-sensitive") this fails for ['all low (2018)','B movie (2018)']

@EriktheOutgolfer thanks fixed

@JonathanAllan fixed

Instead of adding the final tie-break in the tuple you can simply sort a[::-1], as sorted performs a stable sort. 115 bytes!

R, 95 87 85 bytes
-2 thanks to Wheat Wizard
function(v)v[order(unlist(regmatches(v,gregexpr("[0-9]{4}",v))),tolower(v),nchar(v))]

Try it online!

Hello and welcome to the site! I don't know R so I might be wrong here but I don't think you need the f=.  It looks like you are making an anonymous function and assigning it to a variable.  If this is an anonymous function that can be called in line you can get rid of the assignment.

you're right, it worked thanks!

What is the purpose of tolower ?

Perl 6, 58 bytes
*.sort({~m/\(\d+/,/^\d/??(0,$++)!!(1,.uc.ord,.chars,$--)})

Try it online!

You can use .uc instead of .uc.ord. Also you could use <( to ignore the \( as in / \( <( \d+/ would return 2010 instead of (2010. Since movies have only ever been produced in 4 digit years what you have is shorter and works.

@BradGilbertb2gills .uc.ord is required to only sort on the first letter. An equally short alternative is m/./.uc.

Red, 108 bytes
func[b][s: copy[]foreach m b[append/only s reverse split m"("]foreach m sort/all s[print rejoin[m/2"("m/1]]]

Try it online!
Explanation:
f: func[b] [                                 the argument is a block of strings
    s: copy []                               prepare an empty block
    foreach m b [                            for each string in the input block
       append/only s reverse split m "("     split it on "(" and append in reversed order
    ]
    foreach m sort/all s [                   sort the new block
       print rejoin[m/2 "(" m/1]             and print it in the right order
    ]
]

Red's sort/all (sort function with refinement all) performs a stable sort, comparing all the fields of a compound argument:
sort/all [[1 2 3 1] [1 1 6] [2 1 3] [1 2 3 4]]
== [[1 1 6] [1 2 3 1] [1 2 3 4] [2 1 3]]

PHP, 231 115 113 bytes
PHP sort stabilized by using keys including the position
while($s=$argv[++$i])$a[substr($s,-6).($s<A?:$s&_).str_pad($s<A?$i:$argc-$i,$argc,0,0)]=$s;ksort($a);print_r($a);

Run with php -nr '<code>' 'movie1 (year1)' 'movie2 (year2)' ... or try it online.

Jelly,  28 26 25  24 bytes
-1 thanks to Erik the Outgolfer (use a zip to replace pair then transpose)
µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ

A monadic link taking and returning lists of lists of characters.
Try it online! - footer reformats the result like the input (which is interpreted as a list of lists of characters)
...or see a test-suite
How?
µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ - Link: list of lists of characters, X
                                                     e.g. ["RV (2006)", "iChannel (2006)", "300 (2006)"]
                      ðÞ - sort by the following ðyadic key function (right is now X)
µ                        - ...start a monadic chain (left is now an item in X):
 Ḳ                       -   split at spaces              ["RV","(2006)"] / ["iChannel","(2006)"] / ["300","(2006)"]
  Ṛ                      -   reverse                      ["(2006)","RV"] / ["(2006)","iChannel"] / ["(2006)","300"]
          Ʋ              -   last four links as a monad:
     ”<                  -     literal '<' character (resides between digits*  and alphas ...* also the spaces and parentheses)
    >                    -     greater than? (vectorises) [1,1,0,0,0,0,0,0,0] / [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0] / [0,0,0,0,0,0,0,0,0,0]
        Œl               -     lower-case                 ["rv (2006)"] / ["ichannel (2006)"] / ["300 (2006)"]
       a                 -     AND (vectorises)           ['r','v',0,0,0,0,0,0,0] / ['i','c','h','a','n','n','e','l',0,0,0,0,0,0,0] / [0,0,0,0,0,0,0,0,0,0]
   ż                     -   zip together                 [["(2006)",'r'],["RV",'v'],[0],[0],[0],[0],[0],[0],[0]] / [["(2006)",'i'],["iChannel",'c'],['h'],['a'],['n'],['n'],['e'],['l'],[0],[0],[0],[0],[0],[0],[0]] / [["(2006)",0],["300",0],[0],[0],[0],[0],[0],[0],[0],[0]]
           Ḣ             -   head                         ["(2006)",'r'] / ["(2006)",'i'] / ["(2006)",0]
            O            -   cast to ordinal (vectorises) [[40,50,48,48,54,41],114] / [[40,50,48,48,54,41],105] / [[40,50,48,48,54,41],0]
                         -   (Jelly cannot compare characters with integers)
              L          -   length                       9 / 15 / 10
             ;           -   concatenate                  [[40,50,48,48,54,41],114,9] / [[40,50,48,48,54,41],105,15] / [[40,50,48,48,54,41],0,10]
                   Ɗ     -   last three links as a monad:
                 i       -     1st index of item in...
                ⁹        -     chain's right argument, X    1 /  2 /  3
                  N      -     negated                     -1 / -2 / -3
               ;         -   concatenate                  [[40,50,48,48,54,41],114,9,-1] / [[40,50,48,48,54,41],105,15,-2] / [[40,50,48,48,54,41],0,10,-3]
                     \   -   cumulative reduce with:
                    ȧ    -     AND (does not vectorise)   [[40,50,48,48,54,41],114,9,-1] / [[40,50,48,48,54,41],105,15,-2] / [[40,50,48,48,54,41],0,0,0]
                         -                           i.e. max / middle / min
                         -                                so the sort, Þ, reverses this input:
                         -                                ["300 (2006)", "iChannel (2006)", "RV (2006)"]

Hint: (A),(B)Z == (A)ż(B)

Still a-golfin' but thanks!

You can remove the need for Y :P (thank Dennis for that)

I don't think that suggested dyadic function being called as a monad works.

Right, you'd need µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ, which doesn't save any bytes. It would make the test suite a lot cleaner though.

µḲṚż>”<aŒlƲḢO;L;⁹iNƊȧ\ðÞ would work as a monadic link for the same byte count

@Dennis ^- snap

Jelly, 35 bytes
³i
ḲṪ$ḊṖV;1ịeØDƲ×Çṭ1Ɗ;Œlḷ/$;L;ÇN$µÞ

Try it online!
-4 bytes thanks to Mr. Xcoder

Perhaps 34 bytes?

And 33 bytes using a helper link (saves a byte from the 34-byte version, but if that’s not valid, then you can use these in your solution to get 35). Other than this, you can use ḷ\ instead of 1i$ to save another byte.

@Mr.Xcoder It's ḷ/, not ḷ\. ḷ\ is the same as ḷ/WẋLƲ.

@EriktheOutgolfer I don’t think it matters here though.

@EriktheOutgolfer not sure it makes a difference, but thanks, I fixed it

@HyperNeutrino The difference is that, for example, 5,1,6,2,3ḷ/ will result in 5, while 5,1,6,2,3ḷ\ will result in [5, 5, 5, 5, 5].

A new rule clarification has made this solution invalid (it should be case-insensitive).

@EriktheOutgolfer ._. fixed

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Make a hammer animation
The goal is to make a two frame animation with ASCII art of a hammer smacking a table.
Trailing white-space is allowed and the frames need to repeat continuously. The program should iterate over both frames with a time of 0.5 seconds between frames.
Lowest byte count wins for each language!
Sample:
Animation Frames:
Frame 1:
 -------------------
|                   |
|                   |
|                   |
 -------------------
         /  /
        /  /
       /  /
      /  /
     /  /
    /  /
   /  /
  /  /
 /  /
 \ /

                        ---------------------------
                       |                           |

Frame 2:

                                        ----------
                                       |          |
                                       |          |
                                       |          |
 --------------------------------------|          |
|                                      |          |
 --------------------------------------|          |
                                       |          |
                                       |          |
                                       |          |
                                        ----------
                                  -------------------------------
                                |                                |

Welcome to the site! This sounds like a good idea, but you need to be way more specific, and spell out what the anination should be like. See other challenges in the [tag:ascii-art] or [tag:animation] tags for reference

@LuisMendo Is This Better?

@PythonDude29 If the answer needs to be a program/function which takes a number (say 1/2 or 0/1) and produces the appropriate frame, then you need to state so. If frame 1 needs to be displayed and then exchanged for frame 2 after a predetermined time or event, you need to state so.

You also need to clarify if trailing whitespace is acceptable.

I think I am Done.

@Scrooble Is that everything? Or is there more specifics I need

I'm not a fan of these line controllers—it is my understanding that languages like Charcoal don't operate that way. I'd refer to other [tag:ascii-art] and [tag:kolmogorov-complexity] questions. However, this challenge does now fall within this site's requirements (IMO), so I'm voting to reopen.

@Scrooble Hmm I only know a couple languages. I know Python, A Bit Of JavaScript And A bit Of C#. I used the line controllers when I did my own(Where I got the idea)

Must the font be monospace? Is graphical output allowed?

Also please don't write in title case.

Doesn't this pretty much end up as run length encoding in just about every language?

This is kinda a combination of this and most ascii art with high repetition/run length, but i'm not sure if it should be considered a duplicate.

@fəˈnɛtɪk I think it's more like this one, then the one you linked. That one also replaces the current ASCII art at every iteration.

Perl 5, 391 355 293 286 296 bytes
Whack whack whack, golfing those chars off, down to 296 b :)
.5s sleep as per the question specs.
This also requires perl -E
$r="| 19|n"x 3;$p="| 10|n";$R=" 39$p"x 3;$T=" -38$p";$t=" 40-10n";$m=" -19n$r -19n 9H 8H 7H 6H 5H 4H 3H 2H 2\\ /n3 24-27n 23| 27|n";$M="$t$R$T| 38$p$T$R$t 34-30n 33| 30|n";for($m){say"\033[2J";map{s:H:/  /n:;y!n!\n!;print$1x($2?$2:1)if/(\D+)(\d*)/}(split/(.\d*)/);($m,$M)=($M,$m);select$v,$V,$v,.5;redo}

Explanation/comments:
# initial vars build strings that the print will understand later
$r="| 19|n"x 3;
$p="| 10|n";
$R=" 39$p"x 3;
$T=" -38$p";
$t=" 40-10n";

# set $_ to first frame
$_=" -19n$r -19n 9H 8H 7H 6H 5H 4H 3H 2H 2\\ /n3 24-27n 23| 27|n";

# M is second frame
$M="$t$R$T| 38$p$T$R$t 34-30n 33| 30|n";

# main loop
{

# clear screen
say"\033[2J";

# or windows, -1b
# system"cls";

# start map...
map{

# sed replace H for /  /n
s:H:/  /n:;

# tr replace n for newline
y!n!\n!;

# parens around ?: necessary due to x operator precedence
# if/regex/ prints $1 $2 times
print$1x($2?$2:1)if/(\D+)(\d*)/

# map runs on char followed by a number or not
}(split/(.\d*)/);

# rotate frames
($_,$M)=($M,$_);

# sleep for 1 second would be shorter, but perl does
# not deal with integer sleep without time::hires
# sleep 1;

# select for decimal second sleep
select$v,$v,$v,.5;

# do the current block again
redo
}

GIF of original in action:

Welcome to PPCG! It's common courtesy to have a header with the language name and byte count. Hope you stick around!

Thanks, I missed adding the title the first time through.

Python 3, 337  331 319 bytes
-12 bytes thanks to Amphibological
import os,time
t,e,q,p='- \n|'
j=e+t*19+q
L=p+e*19+p+q
l=j+3*L+j
for i in range(9):l+=e*(9-i)+'/  /'+q
l+=' \\ /'+3*q+e*24+t*27+q+e*23+p+27*e+p+q
c=39*e
C=p+10*e+p+q
m=10*t+q
R=e+38*t+C
f=(c+C)*3
r=q+c+e+m+f+R+p+38*e+C+R+f+c+e+m+34*e+31*t+q+32*e+p+32*e+q
b=0
while 1:print([r,l][b]);time.sleep(.5);os.system('cls');b=~b

Try it online!
It uses 'cls', so will only work on Windows, use 'clear' for Linux with +2 bytes.
Will add a gif later.

Nice! You could change r if b else l to [r,l][b]  and import os\nimport time to import os,time to save some bytes.

Python 3.6, 413 bytes
from os import*
from time import*
s,y=' -';b=y*19;d=b+b;f=y*10;i=y*26;g=s*9;c=s+g;h=s*26;j=s*32;a=c+g;e=a+a;p=print;k=f'\n|{a}|';t,v=system,sleep;z='cls'
while 1:
 t(z);p(f' {b} {k*3}\n {b}')
 for x in range(9):p(f'{g[x:]}/  /')
 p(f' \\ /\n {a} {i}\n {a}|{h}|');v(1);t(z);p(f' {e} {f}')
 for w in range(7):p(f' {e}|{c}|')if w!=3else p(f' {d}|{c}|\n|{e}|{c}|\n {d}|{c}|')
 p(f' {e} {f}\n {j} {i}\n {j}|{h}|');v(1)

Doesn't work on TIO, so here's a GIF:

Not the prettiest thing in the world, but I'm pretty proud of it. Suggestions on golfing it further are welcome!
P.S.: I used a 1 second delay because it looked better to me, but you can replace 1 with .5 to change that, at +2 bytes.
P.P.S: This will only work on Windows, to try on Unix, change cls to clear at +2 bytes.

That's as amazing how does it work how long did it take you

@PythonDude29 thanks. It didn't take too long, maybe about 45 mins. It works mostly by substituting variables into strings with the new python f-strings. I'll post a more detailed explanation when I get a chance.

Ok it's really cool

@PythonDude29 thanks. I really appreciate it!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Decompose Polynomials
Given an integral polynomial of degree strictly greater than one, completely decompose it into a composition of integral polynomials of degree strictly greater than one.
Details

An integral polynomial is a polynomial with only integers as coefficients.
Given two polynomials p and q the composition is defined by (p∘q)(x):=p(q(x)).
The decomposition of an integral polynomial p is a finite ordered sequence of integral polynomials q1,q2,...,qn where deg qi > 1 for all 1 ≤ i ≤ n and p(x) = q1(q2(...qn(x)...)), and all qi are not further decomposable. The decomposition is not necessarily unique.
You can use e.g. lists of coefficients or built in polynomial types as input and output.
Note that many builtins for this task actually decompose the polynomials over a given field and not necessarily integers, while this challenge requires a decomposition integer polynomials. (Some integer polynomials might  admit decomposition into integer polynomials as well as decomposition that contain rational polynomials.)

Examples
x^2 + 1
[x^2 + 1] (all polynomials of degree 2 or less are not decomposable)
x^6 - 6x^5 + 15x^4 - 20x^3 + 15x^2 - 6 x - 1
[x^3 - 2, x^2 - 2x + 1]
x^4 - 8x^3 + 18x^2 - 8x + 2
[x^2 + 1, x^2 - 4x + 1]
x^6 + x^2 + 1
[x^3 + x + 1, x^2]
x^6
[x^2, x^3]
x^8 + 4x^6 + 6x^4 + 4x^2 + 4 = (x^2 + 1)^4 + 3
[x^2 + 3, x^2, x^2 + 1]
x^6 + 6x^4 + x^3 + 9x^2 + 3x - 5
[x^2 + x - 5, x^3 + 3*x], [x^2 + 5*x + 1, x^3 + 3*x - 2]

Use Maxima for generating examples: Try it online!
Some decomposition algorithms can be found here and here.

Pari/GP, 84 bytes
f(p)=[if(q'',[f(q),r],p)|r<-x*divisors(p\x),r''&&p==subst(q=substpol(p,r,x),x,r)][1]

Based on the algorithm described here.
Try it online!

Do you check (or filter out) whether you actually get a decomposition into integral polynomials? (I'm asking because the algorithms in the linked paper describe the factorization over some field, and I don't know any Pari/GP.)

@flawr I'm using the second algorithm in the paper, which always returns integral polynomials when the input is integral. In fact, the divisors function in Pari/GP always returns primitive polynomials when it takes an integral polynomial. It can be proved that if p=q∘r, where p and r are integral, and r is primitive with r(0)=0, then q must also be integral. Here p, q, r correspond to f, g, h in the paper.

Wolfram Language (Mathematica), 29 bytes
Decompose[#/.x->x+a,x]/.a->0&

Try it online!
I have the example set up here to compose a random polynomial from random quadratics (or less), expand it out, and then try to decompose it.
It's necessary to complicate the polynomial with dummy variable (a) since the built-in will not attempt to decompose a monomial.
I notice that the answer often has much larger coefficients than in the original composition, but they are indeed always integers.

Where did you find the information that Decompose[] will always return integral polynomials (if fed with integer polynomials)? When discussing in chat recently we could not find anything about that.

Do Options@Decompose and it will tell you {Modulus->0}.  Now look up Modulus and you'll see "The setting Modulus->0 specifies the full ring [DoubleStruckCapitalZ] of integers. "

Ah that is nice, thanks for elaborating!


text:
Generate a heap of boxes

(The text asks how many boxes there are in the picture)
Now you are required to generate such a problem and its answer.
Input

an integer n
(optionally) random source of two values, in case you don't want to use the default random.

Output can be

a 3D array A[n][n][n] of booleans, where A[i][j][k] => (i==0 || A[i-1][j][k]) && (j==0 || A[i][j-1][k]) && (k==0 || A[i][j][k-1]) (assuming 0-index)
where && is logical AND, || is logical OR, and => is "implies" (if X is true, then Y is true).
Basically this says that if you have a box at some position then for each coordinate that coordinate must be either 0 or also have a box if that coordinate is one less. So no holes in any direction that gets you closer to the origin.
a 2D array B[n][n] of integers, where B[i][j] means how many k satisfy A[i][j][k]
Basically this is the height of the stacks where these heights can't become lower in any direction that gets you closer to the origin.
Besides the array, the amount of boxes (how many i,j,k satisfy A[i][j][k])

Every valid output should have nonzero probability to be outputted.
Example: (Here use 2D output format for convenience)
1 => [[0]] 0 or [[1]] 1
2 => [[0,0],[0,0]] 0
     [[1,0],[0,0]] 1
     [[1,0],[1,0]] 2
     [[1,1],[0,0]] 2
     [[1,1],[1,0]] 3
     [[1,1],[1,1]] 4
     [[2,0],[0,0]] 2
     [[2,0],[1,0]] 3
     [[2,0],[2,0]] 4
     [[2,1],[0,0]] 3
     [[2,1],[1,0]] 4
     [[2,1],[1,1]] 5
     [[2,1],[2,0]] 5
     [[2,1],[2,1]] 6
     [[2,2],[0,0]] 4
     [[2,2],[1,0]] 5
     [[2,2],[1,1]] 6
     [[2,2],[2,0]] 6
     [[2,2],[2,1]] 7 or
     [[2,2],[2,2]] 8

So for input 2 your program should randomly return one of the 20 possible outputs, and if run enough times every one of them should be returned at some point.
Your program must terminate.
Winning criteria
This is code-golf, shortest code in bytes win!

Sandbox

I didn't define "behind" or anything in the output array

Rust: std::collections::BinaryHeap::new<Box<i32>>() (generates a heap of boxes)

True no empty hidden, but not only that. [[0,1],[1,0]] also shows the space, but not allowed

The outputs are called (3D) Young diagrams. Related. (Asks for an ASCII art representation instead of an array representation.)

What is the source of that image? The site you're copying from may require attribution.

Can any close-voters explain? Re @FryAmTheEggman : Is that OK now? I have added the explanation for every symbols appearing in the expression.

I think it is fine now, but I can't speak for the people who voted to close.

Perl 5, -ap 121 bytes / 56 bytes
This 121 byte solution has a uniform distribution over all valid arrangements of boxes. It tries to be somewhat efficient but still times out on TIO for size 4 or more
#!/usr/bin/perl -ap
@a=((0 x$_.$")x$_.$/)x$_."";s%0%/0(|.{@F}|(\X{@F}\X){@F})\G/+${$z="$`1$'"}++||push@a,$z;0%eg for@a;$_=$a[rand@a];$\=y/1//

Try it online!
If you don't care about uniformity it's of course easy to go shorter, e.g. this 56 bytes solution is very biased towards the origin (it probably gives more nice pictures for the motivating example though)
#!/usr/bin/perl -a
say map{\@$_[rand@;+1,$#{$_-1}];@;-$#$_.$"}@;for@;=1..$_

Try it online!
(checked for size 2 and 3 that it indeed generates all possible outputs)

Python 2, 144 bytes
from random import*
n=input()
a=[n]*n*n
for x in range(n*n):a[x]=randint(0,min(a[x-(x%n>0)],a[x-n]))
print[a[i*n:i*n+n]for i in range(n)],sum(a)

Try it online!
Quick and dirty solution.
Generates a random number (which is upper-bounded by its left (if present) and upper cells) for each cell as a linear array, and then prints its 2D version and the sum.

JavaScript (ES6), 100 bytes
n=>[...Array(n)].map((_,i,a)=>k=a.map((_,j)=>l=0|Math.random()*-~(i?j?Math.min(k[j],l):k[0]:j?l:n)))

Jelly, 16 bytes
³‘X’¤þ`ṂƤ€Z$⁺ṄS⁺

Try it online!

I made a terrible mistake. No idea why no-one noticed that.
Full program. Prints the array and the sum.
Not uniform, of course. Return all-zero most of the time.
Verification for side length 2.


text:
Third time the charm
Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). If the source code is duplicated the output must remain the same. The tricky part is that if the source code is typed three times (triplicated?) the output will be multiplied by 3.
Rules

You must build a full program. That is, your output has to be printed to STDOUT.

The initial source must be at least 1 byte long.

Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden).

Your program must not take input (or have an unused, empty input).

Outputting the integers with trailing / leading spaces is allowed.

Leading Zeroes are allowed only if the numbers of digits is consistent eg: 001 - 001 - 003 or 004 - 004 - 012

You may not assume a newline between copies of your source.

This is code-golf, so the shortest (original) code in each language wins!

Default Loopholes apply.

Example
Let's say your source code is Abc and its corresponding output is 4. If I write AbcAbc instead and run it, the output must still be 4. However if I write AbcAbcAbc and run it, the output must be 12.

Shamelessly stolen Derived from Mr. Xcoder's challenge

Is our code allowed to read its own source code?

@AdmBorkBork I'd assume so, since this isn't tagged as [tag:quine].

@AdmBorkBork Yes.

I don't think the 1 byte restriction is needed since it wouldn't be possible to tell the difference between nothing and nothing repeated 3 times.

May we print blank lines  before the output in the multiplied cases?

Are we allowed leading zeroes?

@xnor No blank lines before the output.

@JoKing Only if the numbers of digits is consistent eg: 001 - 001 - 003 or 004 - 004 - 012

What does "the source code is duplicated" mean?

@r12 "Let's say your source code is Abc and its corresponding output is 4. If I write AbcAbc instead and run it, the output must still be 4. However if I write AbcAbcAbc and run it, the output must be 12."

Thank you for trying to explain it to me.  I read that text several times and wasn't able to understand it.  At the time, I didn't know what "Abc" was when I read the post and kept rereading it.  I scrolled up and down through this post and thought "Abc" was one of these weird programming languages with unusual symbols doing unusual things.  Very little on this page makes any sense to me.

@r12 "Abc" is an example for any programming language program, say if your code is (int i=1;print i;) then the duplicated code of (int i=1;print i;int i=1;print i;) must output the same number as the original code, and when the code is triplicated to (int i=1;print i;int i=1;print i;int i=1;print i;) it must show the number multiplied by 3

@r12 You should not expect to be able to understand something without learning it first. Especially on PPCG.

Can the program print leading zero?

@user202729 Only if the numbers of digits is consistent eg: 001 - 001 - 003 or 004 - 004 - 012

I suggest adding the rule to the question instead of in the comment. / What about 4-4-12 or 04-04-12?

Wumpus, 6 bytes
{~)
@O

Try it online!
Try it doubled!
Try it tripled!
Prints 1 and 3.
Explanation
I found a ton of 6-byte solutions by brute force search, but none for 5 bytes. That doesn't necessarily mean there aren't any at 5 bytes but they'd probably use weird characters or something.
I ended up picking this solution because it doesn't print any leading zeros (most of them do) and it has some interesting control flow. Let's start with the single program:

So the executed code is:
{~)O@

{   Turn the IP left by 60°.
~   Swap two implicit zeros on the stack, does nothing.
)   Increment the top zero to 1.
O   Print it.
@   Terminate the program.

Easy enough. Now the doubled program. Since the first line gets appended onto the second line, the grid extends to width 5 (and height 3) which changes the control flow significantly:

The IP goes around that loop exactly once, so the executed code is:
{~){~)){~O@

{~) As before, we end up with a 1 on top of the stack.
{   Turn left by 60° again.
~   Swap the 1 with the 0 underneath.
))  Increment the zero to 2.
{   Turn left by 60° again.
~   Swap the 2 with the 1 underneath.
O   Print the 1.
@   Terminate the program.

Finally, the tripled program is quite similar to the doubled one, but we get a couple more important commands onto that third line:

So the executed code is:
{~){~)){~~)O@

{~){~)){~
    As before. We end up with a 1 on top of the stack and a 2 underneath.
~   Swap the 1 with the 2 underneath.
)   Increment the 2 to a 3.
O   Print the 3.
@   Terminate the program.

i think i'm in love with this language.

Cubix, 5 bytes
)<@OP

Try it online: once, twice, thrice.

Explanation
Cubix is a stack-based language whose instructions are wrapped around the outside of a cube. Important to note is that the stack is initially filled with infinite zeroes, which allows us to "pull values out of thin air" with operators rather than pushing them explicitly.
I must admit that this was found by a brute-forcer; I never would have found it on my own. In fact, @MartinEnder was the one who asked me to try brute-forcing, as he had been looking for this solution without luck. This is the only solution the brute-forcer found, and I do believe it is the one and only shortest solution in Cubix.
Single program
Watch it run!
The original program fits on a unit cube. Here's the unfolded net:
  )
< @ O P
  .

The IP (instruction pointer) starts on the leftmost face (the <) headed east. The < immediately points it west, and it wraps around to the P. P is exponentiation, and since there's nothing on the stack, the interpreter pulls out two 0s and calculates 00, which is 1 according to JavaScript. O then prints this value, and @ ends the program.
Double program
Watch it run!
)<@OP)<@OP

The 10-byte program is too long to fit onto a unit cube, and so it is expanded to a size-2 cube:
    ) <
    @ O
P ) < @ O P . .
. . . . . . . .
    . .
    . .

As before, the IP starts out at the top-left of the left-most face. This time, the very first instruction is P, which pushes a 1 as before. Next is ), which increments the top item, turning it into a 2. Then < turns the IP around, and it hits the ) again, transforming the 2 into a 3.
Here's where it gets interesting. P raises the second-from-top item to the power of the first item, which gives 03 = 0. Then the IP wraps around to the rightmost face and passes through two no-ops . before hitting another P. Here we see another quirk of Cubix: binary operators (such as P) don't remove their operands from the stack. So since the stack is now [3, 0], we calculate 30 = 1, which O outputs, and @ terminates the program.
Triple program
Watch it run!
)<@OP)<@OP)<@OP

As with the double program, the triple can fit on a size-2 cube:
    ) <
    @ O
P ) < @ O P ) <
@ O P . . . . .
    . .
    . .

This program starts out in the same way as the previous: P pushes 1, ) increments, < points the IP west, ) increments again, and P now pushes 0. The IP is then wrapped around to the < on the rightmost face, which does nothing since the IP is already pointed west.
Here is the one difference from the double program: the ) increments the 0 on top of the stack to a 1. When P performs its magic again, this time it calculates 31 = 3. O outputs and @ terminates, and we prove conclusively that the third time is indeed the charm.

I really enjoyed your explanation. +1

Husk, 5 bytes
KΣK+1

Try it online!
Repeated twice!
Repeated thrice!
Explanation
It's quite difficult to construct a repeatable program in Husk.
Because the type system forbids a function that can be applied to itself, I have to somehow allow the first part to evaluate to a function, and the remainder to evaluate to a value, and the types of existing built-ins are designed to prevent this kind of ambiguity.
The tokens of the program are

K, which constructs a constant function. K a b is equivalent to a.
Σ, which takes an integer n and returns the nth triangular number.
+, which adds two numbers.
1, which is the literal 1.

The original program is interpreted like this:
   K Σ (K+) 1
== Σ 1
== 1

The (K+) is a nonsensical function that gets eaten by the first K.
The twice repeated program is interpreted like this:
   K Σ (K+1KΣK+) 1
== Σ 1
== 1

The function in parentheses is again eaten by the first K.
The thrice repeated program is interpreted like this:
   K (Σ (K (+1) (KΣK+) 1)) (KΣK+1)
== Σ (K (+1) (KΣK+) 1)
== Σ ((+1) 1)
== Σ (+1 1)
== Σ 2
== 3

This takes really long time to run ...

@WeijunZhou If you have many occurrences of K in a program, type inference becomes very slow, because each of them could potentially "eat" any number of tokens and the interpreter will try all combinations...

I see, thank you for your explanation.

@Zgarb +1 for kek +1

Haskell, 24 bytes
main=print.div 3$4
 -1--

Prints 1: Try it online!
main=print.div 3$4
 -1--main=print.div 3$4
 -1--

Also prints 1: Try it online!
main=print.div 3$4
 -1--main=print.div 3$4
 -1--main=print.div 3$4
 -1--

Prints 3: Try it online!

Jelly, 7 5 bytes
»‘µ*Ḃ

Try it online!
Try it doubled!
Try it tripled!
How it works
»‘µ*Ḃ            Main link. No arguments. Implicit argument: x = 0

 ‘               Increment; yield x + 1 = 1.
»                Take the maximum of x and 1. Yields 1.
  µ              Begin a new, monadic chain. Argument: y = 1
    Ḃ            Bit; yield 1 if y is odd, 0 if it is even. Yields 1.
   *             Power; yield y**1 = 1.

»‘µ*Ḃ»‘µ*Ḃ       Main link.

»‘µ*Ḃ            As before.
      ‘          Increment; yield y + 1 = 2.
     »           Take the maximum of 1 and 2. Yields 2.
       µ         Begin a new, monadic chain. Argument: z = 2
         Ḃ       Bit; yield 1 if z is odd, 0 if it is even. Yields 0.
        *        Power; yield z**0 = 1.

»‘µ*Ḃ»‘µ*Ḃ»‘µ*Ḃ  Main link.

»‘µ*Ḃ»‘µ*Ḃ       As before.
           ‘     Increment; yield z + 1 = 3.
          »      Take the maximum of 1 and 3. Yields 3.
            µ    Begin a new, monadic chain. Argument: w = 3
              Ḃ  Bit; yield 1 if w is odd, 0 if it is even. Yields 1.
             *   Power; yield w**1 = 3.

Brain-Flak, 10 bytes
<>([]{}())

Try it online!
Try it doubled!
Try it tripled!
Explanation:
#Toggle stacks
<>

#Push
(
    #Stack-height (initially 0) +
    []

    #The TOS (initially 0) +
    {}

    #1
    ()
)

When we run this once, it will put (0 + 0 + 1) == 1 onto the alternate stack. Ran a second time, it puts the same onto the main stack. Run a third time however, it evaluates to (1 + 1 + 1) == 3, and pushes that to the alternate stack and implicitly prints.

SQL, 25 24 23 bytes

(-1 Byte Removed a mistyped character that was always commented out and doing nothing)
(-1 Byte Changed SELECT to PRINT as recommended by Razvan Socol)
PRINT 2/*
*2+1--*/-1
--

How it works:
In SQL, you can comment out the comment tags, like so:
/*
'Comment'--*/

vs
--/*
'Not Comment'--*/

Code on 1 line with comments excluded:
First iteration: SELECT 2-1 Output: 1
Second iteration: SELECT 2-1*2+1 Output: 1
Third iteration: SELECT 2-1*2+1*2+1 Output: 3

PRINT instead of SELECT would save an extra byte.

05AB1E, 6 5 bytes
.gDÈ+

Try it online!
or Try it doubled! or Try it tripled!
Explanation
.g     # push length of stack
  D    # duplicate
   È   # check if even
    +  # add

Single: 0 + (0 % 2 == 0) -> 1
Double: 1 + (1 % 2 == 0) -> 1
Triple: 2 + (2 % 2 == 0) -> 3

Should that be % 2 in the triple explanation?

@LarsW: Yes indeed :)

@Emigna I think "check if even" is actually 2%_ right?

2 + (2 % 2 == 0) -> 2 but 2 + !(2 % 2 == 0) -> 3 (for your explanation).

@MagicOctopusUrn 2%_ is the same as È yes. Not sure what you mean about the explanation. 2+(2%2==0) = 2+(0==0) = 2+1 = 3. It probably would have been clearer if I had explanded the computations.

2 + (2 % 2 == 0) -> 2 + 0 -> 2+0 != 3 is how I was reading it, but I guess == does mean check for equality in most languages other than 05AB1E.

SOGL V0.12, 7 5 4 bytes
ē»«I

Try it here!
Try it doubled!
Try it tripled!
Explanation:
ē»«I
ē     push counter, then increment it.
      First time running this will push 0, then 1, then 2.
             TOS on each: 0  1  2
 »    floor divide by 2   0  0  1
  «   multiply by 2       0  0  2
   I  and increment       1  1  3

I tried to do something along the lines of ē1|, but apparently there's no command for bitwise OR...

@ETHproductions Yeah, I wanted to try something like that too, and the best I got was ē:2\+ :/

Lost, 38 bytes
\\<<<<</<<<<>
2>((1+@>?!^%^
.........v

Try it online!
\\<<<<</<<<<>
2>((1+@>?!^%^
.........v\\<<<<</<<<<>
2>((1+@>?!^%^
.........v

Try it online!
\\<<<<</<<<<>
2>((1+@>?!^%^
.........v\\<<<<</<<<<>
2>((1+@>?!^%^
.........v\\<<<<</<<<<>
2>((1+@>?!^%^
.........v

Try it online!
Explanation
Lost is a very interesting language for this challenge.  The usual Lost technique is to build a "trap".  A trap is a section of the program designed to catch all the ips in one place so that their stacks can be cleared and they can be controlled to go in a specific direction.  This makes writing programs in Lost a lot more manageable.  However since the program is duplicated we need to avoid trap duplication as well.  This requires us to design a new trap that works properly but when duplicated only one of the traps works.  My basic idea here is the following
v<<<<>
>%?!^^

While the stack is non-empty the ? will remove a item and cause it to jump back to the begining if that item is non-zero.  The key here is that when this stacks the ^^s line up
v<<<<>
>%?!^^v<<<<>
>%?!^^v<<<<>
>%?!^^v<<<<>
>%?!^^v<<<<>
>%?!^^

Meaning that no matter how you enter you will always exit in the same place.
From here we can attempt to implement the same idea from my Klein answer.
\\<<<<<v<<<<>
2>((1+@>?!^%^

The backbone of our program is the left had side which pushes a number of 2s. Each time we add a copy of the program another 2 gets added to the backbone of the program meaning an additional 2 is pushed to the stack. Once it goes off the bottom it bounces through \\> and executes the code
((1+@

This removes the first 2 stack items, adds one to the whatever is left, and exits. Once our backbone has 3 2s we will add 1 and get 3, if we have any less than 3 items we will just discard the entire stack and return 1.
Now the only problem left is that the ! in our program can cause an infinite loop.  If the ip starts on ! going upwards it will jump and land right back where it was.  This means we have to add another line underneath to prevent the loop.
\\<<<<</<<<<>
2>((1+@>?!^%^
.........^

This has the slight problem of putting some slashes in between our ^s in the trap. However, rather miraculously, everything works out. Our ips bounce around properly so that it doesn't make a difference.

27 bytes, doubled, tripled

@joking unfortunately I'm stuck on mobile for the time being.  Could you post it as an answer with an explanation?

Posted

R, 37 31 28 bytes
Thanks to Giuseppe for golfing off the final 3 bytes.
length(readLines())%/%2*2+1

(with a trailing newline).
Try it once!
Try it twice!
Try it thrice!
This uses the readLines() trick from Giuseppe's answer to the 8-ball challenge, where stdin redirects to the source file. This code basically just counts up how many lines exist below the first line and outputs 1 if there are 1 or 3 lines (i.e. code is single or doubled), or 3 if  there are 5 lines (i.e. code is tripled).

oh, neat, +1! Wasn't sure how to do this in R. I think you need a newline after the s for this to work properly, BUT you should be able to golf it to 28 bytes by re-working some of the calculations.

@Giuseppe Thanks for pointing out the newline problem! I wasn't able to get your version to work when the code is tripled - am I missing something?

oh weird I musta had a trailing newline, but if you do %/%2 it should work

><>, 9 bytes
\5 n;
\\1

Try it online!
Try it doubled!
Try it tripled!
I found this sort of by luck, using the philosophy that "if you make the fish's path convoluted enough, eventually something will work". The original and doubled versions print a 5, and the tripled version prints 1 then 5 to make 15 = 3×5. Here are the multiplied versions, for your perusal:
\5 n;
\\1\5 n;
\\1

\5 n;
\\1\5 n;
\\1\5 n;
\\1

Python 2,  46 45  39 bytes
Inspired by Halvard's answer. I'm glad that my challenge inspired a new one, which I find even more interesting. Saved 6 bytes thanks to Kevin Cruijssen.
print open(__file__,"a").tell()/79*3|1#

Try it online!
Try it doubled!
Try it tripled!
How it works (outdated)
k=open(__file__,"a").tell() # Read the source code in "append" mode and get its length.
                            # Assign it to a variable k.
;print k>>(k==90)#          # Print k, with the bits shifted to the right by 1 if k
                            # is equal to 90, or without being shifted at all overwise.
                            # By shifting the bits of a number to the right by 1 (>>1),
                            # we basically halve it.

When it is doubled, the length becomes 90, but the new code is ignored thanks to the #, so k==90 evaluates to True. Booleans are subclasses of integers in Python, so k>>True is equivalent to k>>1, which is essentially k / 2 = 45. When it is tripled, the new code is again ignored, hence the new length is 135, which doesn't get shifted because k==90 evaluates to False, so k>>(k==90) ⟶ k>>(135==90) ⟶ k>>False ⟶ k>>0 ⟶ k, and k is printed as-is.

Python 2, 36 bytes
This was a suggestion by Aidan F. Pierce at 38 bytes, and I golfed it by 2 bytes. I’m not posting this as my main solution because I didn’t come up with it by myself.
0and""
True+=1
print True>3and 3or 1

Try it online!
Try it doubled!
Try it tripled!

Thanks for the idea of using a comment - saved me 6 bytes.

print open(__file__,"a").tell()/79*3|1# perhaps?

@KevinCruijssen Great, thanks!

One fewer byte, no source code reading: https://tio.run/##K6gsycjPM/r/3yAxL0VJSYcrpKg0VdvWkKugKDOvRME4M00BJGJnnJpTnKpg@P8/AA
Prints with leading spaces for two and three repetitions, but that appears to be allowed.

@AidanF.Pierce Thank you so much! I golfed it a bit more and posted it as an alternate solution.

C (gcc), 107 bytes
My first submission in C (gcc). Way too long ...
i;
#ifdef c
#define c
#ifdef b
i=2;
#else
#define b
#endif
#else
#define c main(){putchar(i+49);}
#endif
c

TIO links: single, double, triple.

Japt, 8 6 5 bytes
-1 byte thanks to @ETHproductions
°U-v

Explanation:
°U-v
 U     # variable U=0                # U=0
°U     # ++U                         # U=1
  -    # minus:
   v   #   1 if U is divisible by 2
       #     else
       #   0                         # U=1

This evaluates to 1-0 = 1
Doubled evaluates to 2-1 = 1
Tripled evaluates to 3-0 = 3

Rearranging a little, I think you can do °U-v (plus newline) to save on the second U.

@ETHproductions Thanks! v is perfect for this challenge :-)

><>, 10 9 8 bytes
562gn|

Try it online!
Try it doubled!
Try it tripled!
I'm sure there's an 8 byte solution somewhere out there.
The unprintable at the end has ASCII value 1, and is only fetched by the get command on the third iteration. For the first two it prints 05, and then prints 15.

The 8 byte solution is proving elusive, but here are a couple more 9 byte ones in case they inspire you: TIO, TIO

@Notatree Got the 8 byte with an unprintable

Pure Bash (no wc or other external utils), 27
trap echo\ $[a++&2|1] EXIT

Try it once.
Try it twice.
Try it thrice.

Nice! Replace EXIT with 0

Stax, 5 bytes
|dhH^

Run and debug online! · Doubled · Tripled
Explanation
|dhH^
|d       Push Current stack depth `d`, originally 0
         Doubled -> 1, Tripled -> 2
  hH^    Map d to 2*(floor(d/2))+1
         Implicit print

C (gcc), 95 91 85 bytes
#ifndef a
#define a-1
main(){puts(3
#include __FILE__
?"1":"3");}
#define a
#endif
a

Try it online!

Then I suggest that you edit the correct TIO link in.

I sometimes can't connect to TIO, I don't know why

Perl 5, 18 15 13 12 11 bytes
-3 bytes thanks to nwellnhof
say 1|
+.7#

Once Try it online!
Twice Try it online!
Thrice Try it online!

n;$_=$a++|1;say (15 bytes)

@nwellnhof Of course!. Thanks.

JavaScript, 81 77 74 70 bytes
Saved 4 bytes thanks to Shaggy

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

Pretty lame JS solution. Consumes the values from the [3,1,1] array from the right (pop()). Registers a timeout to display the current value in the future. If a timeout was already registered, cancel it.
Relies on the dirty nature of var, which hoists variable declarations.
Two times:

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

Three times:

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

This needs a trailing semi-colon or newline in order to work but you can save 4 bytes by passing a as the 3rd argument of setTimeout: setTimeout(alert,9,a)

@Shaggy Thanks! It works fine even without an extra semi-colon.

Labyrinth, 12 11 9 bytes

:#%!@
 7

TIO (1x), TIO (2x), TIO (3x)

C (gcc), 53 52 bytes
Note the space after #endif.
n;main(){putchar(n+49);}
#if __LINE__>7
n=2;
#endif

Try it online!

Lost, 27 bytes
\\<<<<//<<<>
2>((1+@>((%^
v

Try it online!
Try it doubled!
Try it tripled!
This is mostly an improvement of Post Left Garf Hunter's answer that removes all the pesky no-ops from that last line,
To do this, we have to remove the !, otherwise the program always gets stuck in a loop. So we change the clearing section from >?!^%^ to >))%^' since there can only be a max of two elements on the stack anyway. Unfortunately, this means that the path from the extra copies to the original is broken, so we place an extra / in the first line to compensate. This forces the pointer to go through the clearing section for all copies of the program until it reaches the first one, where the ^ instead redirects it to the > instead.

C# (178 Bytes)
Console.WriteLine(1+2*4%int.Parse(System.Configuration.ConfigurationManager.AppSettings["z"]=(int.Parse(System.Configuration.ConfigurationManager.AppSettings["z"]??"0"))+1+""));

crazy C# solution, but I am happy it's possible in one line in C# at all. :)
For me the hardest part was having valid C# that would either intialize or increment the same variable, so I ended up abusing the ConfigurationManager because I needed a global static NameValueCollection and ConfigurationManager was the only one I could think of that I could update in memory. EnvironmentVariables was another option I Iooked at but it doesn't have an indexer so I am not sure how to do that in one line that can be copy pasted to produce the required output as per the spec.

Charcoal, 12 bytes
⎚≔⁺ι¹ιＩ⁻ι⁼ι²

Try it online! Link is to verbose code.
Try it doubled!
Try it tripled!
Explanation
⎚             Clear
 ≔⁺ι¹ι        Assign plus(i, 1) to i
       Ｉ      Cast (and implicitly print)
         ⁻ ⁼ι² Subtract equals(i, 2) from
          ι    i

MapAssignRight(Plus, 1, i) saves you a byte, which gets you down to the same length as a port of my answer to @Mr. XCoder's challenge: ＰＩ∨›³Ｌ⊞Ｏυω³

ＰＩ⊕⊗÷Ｌ⊞Ｏυω³ is another version of my answer, but still 11 bytes...

Found a 10-byter!

:/ I should really fix MapAssign(Incremented, i)

PowerShell, 54 48 45 44 bytes
if(99-gt(gc $PSCOMMANDPATH|wc -c)){1;exit}3#

Try it online!
Try it doubled!
Try it tripled!
Gets its own invocation path with $PSCOMMANDPATH and performs a get-content on the file. If the character count of that file is less than 99 (checked via wc -c from coreutils), then we output 1 and exit (i.e., stop execution). That accounts for the original code and the doubled code. Otherwise we output 3 and exit. The actual code that's in the doubled or tripled sections is meaningless, since either we'll exit before we get to it, or it's behind a comment #.
Saved 6 bytes thanks to Mr. Xcoder
Saved 3 4 bytes thanks to Pavel

@Pavel Aha, yes. I need to swap around the -lt99 to a 99-gt to get the casting to work correctly, but that is indeed one byte shorter. Thanks!

JavaScript, 43 40 Bytes

var t=t?--t:~!setTimeout`t=alert(1|~t)`;

2x:

var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;

3x:

var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;

p.s. this solution doesn't break the environment

Ruby, 31 25 bytes
p [*DATA][3]?3:1
__END__

Try it online!
Try it online!Try it online!
Try it online!Try it online!Try it online!
Explanation:
__END__ is not part of the code and everything that follows it is returned by the iterator DATA as lines of text, simply count those lines and check if there are enough of them to switch from 1 to 3.

Runic Enchantments, 35 bytes
^w3'\
    f
    1
/1@
/
 '54\w
/yyy

Try it online!
Working on this one allowed me to find an error in my parser dealing with the new delay modifier characters, although the final result ends up not being affected by it, as I ended up not needing them.
Functions due to the fact that the final line does not have a trailing newline (or for that matter, trailing spaces), allowing the duplicate IPs to spawn in a different place. The top-left one ends up making a large loop around the grid while the second IP performs a Reflection operation to replace the \ on the 6th line with a . This IP then will loop forever and do nothing.
The third IP also makes this same replacement at the same time, but because it's situated on the 13th line, its copy of that reflector sends it upwards and it executes the 1f'3w sequence present in the upper right corner, which replaces the 1 with a 3 on the 14th line, just before the original IP executes it, causing the tripled program to output 3 instead of 1 (values could also be 2 and 6, 3 and 9, 4 and 12, or 5 and 15 due to the availability of a-f numerical constants; 1 and 3 were chosen arbitrarily). It is then left in an endless loop performing more reflection commands that do nothing.
Try it in triplicate!

29 bytes, though I think I could get it lower if I actually understood it :P

@JoKing Not really surprised that a lot of that whitespace could come out. Did this one at work and due to running into an issue with the interpreter I was happy just to get something that worked (my original was 52 bytes and after getting the interpreter fixed, I was able to remove a good chunk).

Perl 5, 28 25 bytes
-3 bytes thanks to @neil!

print"\e[D$a"if(++$a!=2);

Moves the cursor backwards (does nothing on start of line) and prints the value of $a, first and third time (i.e., the third time a 1 is printed, the cursor moves, and a 3 is printed on the position of the 1).

print"\e[D$a"if(++$a!=2); perhaps?

Haskell (runhaskell), 46 bytes
-8 bytes thanks to BMO.
main=do x<-readFile"a";print$length x`gcd`3 --

Try it online!
Needs the file name to be a. Apparently GHC needs the file to end with .hs, but runhaskell doesn't care.

DOS .BAT, 60 Bytes
@cls&find /n " " %0|findstr /b .^3>nul&&set/p=^1<nul&echo 5

QBasic, 19 bytes
CLS
x=2^x
?x-1OR 1

The source should include a trailing newline.
Explanation
We want output of 1, 1, 3. Observe that these numbers are one less than powers of 2. So:
CLS      ' CLear Screen of any output from previous copies of the code

x        ' Numeric variables are preset to 0...
 =2^x    ' so as this statement is repeated, the value of x goes 1, 2, 4

 x-1     ' Therefore x-1 goes 0, 1, 3...
    OR 1 ' and we bitwise OR it with 1 to change the 0 to 1...
?        ' and print.

Perl 6, 17 bytes
0 x 0;say .++ +|1

Try it online!
Try it doubled!
Try it tripled!

Python 2, 38 bytes
1
id=id<3and-~id
exec"print id|1"*0**0

Try it online! (doubled, tripled)
Outputs 1, 1, or 3.

Python 2, 33 bytes
1
True+=1
exec"print 7%True"*0**0

Try it online! (doubled, tripled)
Outputs 1,1,3. Uses the True-modifying idea by Aidan F. Pierce from Xcoder's solution.

Zsh, 25 bytes
<<<$[`wc -c<$0`>70?3:1] #

Zsh lets you use here-docs and here-strings in place instead of regular commands, so we can replace a call to echo with <<< which saves two bytes.
-2 thanks to Digital Trauma

Bash, 26 bytes
exit $[`wc -c<$0`>70?3:1];

Includes trailing newline.
Outputs via exit code.
Very similar to my zsh answer.
exit instead of echo means instead of <space># at the end, we only have a single ;.
-2 bytes thanks to Digital Trauma

$[...] instead of $((...)) saves 2 bytes.  I don't know if this works for zsh too...

PHP, 29 bytes
<?=filesize(__FILE__)<86?:3;#

Try it online!
Try it doubled!
Try it tripled!
How it works

<?= -- Opens a PHP tag and echos whatever's inside. It's a shorthand for <?php echo.
filesize(__FILE__) -- Gets the size of the current file.
<86 -- Checks that the size is less than 86 since when the code is triplicated, it's 87 bytes long.
?:3; -- If the condition is true, it outputs 1 since the middle of the ternary is omitted. If not, then output 3.
;# -- PHP supports shell-style comments (#) and they're less bytes than the C++ style comment (//). This just makes the compiler ignore the other two copies of code.

Klein 000 or 010, 8 bytes
\((1+@
2

Try it online!
\((1+@
2\((1+@
2

Try it online!
\((1+@
2\((1+@
2\((1+@
2

Try it online!
Explanation
The backbone of our program is the left had side which pushes a number of 2s.  Each time we add a copy of the program another 2 gets added to the backbone of the program.  Once it goes off the bottom it executes the code
((1+@

Which removes the first 2 stack items and adds one to the remainder. Once our backbone has 3 2s we will add 1 and get 3, if we have any less we will just discard the entire stack and return 1.
Klein 001 or 011, 8 bytes
\(1+@2
.

Try it online!
\(1+@2
.\(1+@2
.

Try it online!
\(1+@2
.\(1+@2
.\(1+@2
.

Try it online!
Explanation
The 010 and 011 topologies work a little differently.  When the ip goes of the bottom on the left it comes down on the right.  Here we do something very similar except our ending bit is
\(1+@

which will output 1 until the stack is two high.  The . causes the 2 to be cut off when we extend the program meaning we only pick up our second 2 when we reach the third iteration of the program.

Wolfram Language (Mathematica), 23 bytes
Once[c=0];c++//1-#+#^2&

Try it online!
Try it doubled!
Try it tripled!
Explanation:
In Wolfram Language Once evaluates the contained expression once in each session, always returning the result from the first evaluation.  This lets me set an anchor point for c. Now it's just a matter of math.

I think the reason it works locally is that you've already redefined Times on the first prompt, so on the last prompt it's already redefined. Does it still work if you only execute the tripled line?

Ahh that's probably it

Back to the drawing board

According to Wolfram Sandbox, directly executing the tripled line outputs a 1.

Yes I need to modify

Perl 5, 10 bytes
say+0|++$i

Try it once!
Try it twice!
Try it thrice!

Attache, 34 bytes
Echo@Sum@ProperDivisors@`#<|1
'1??

Try it online! Implements A001065. There are probably shorter ways, but this was fun.
Prints A001065(# of repetitions + 1).
Doubled program
Tripled program

Powershell, 14 bytes
Sum array elements. An operator + can work as a unary and binary operator.
+(1,0,2)[$i++]

Test script:
+(1,0,2)[$i++]

$i=0 # or start new powershell session

+(1,0,2)[$i++]+(1,0,2)[$i++]

$i=0 # or start new powershell session

+(1,0,2)[$i++]+(1,0,2)[$i++]+(1,0,2)[$i++]

Note: $i=0 emulates a new session. You can type three times in a new powershell terminal window to start a pure test instead.
Output:
1
1
3

Befunge-98 (PyFunge), 12 9 6 bytes (by Jo King)
3g.@
`

Try it once!
Try it doubled!
Try it tripled!

Old solution:
2g' `4\kc.@

Try it online!

Nice one. Edited the post.

Also just realized, that your answer makes it a valid Befunge-93 program, instead of being limited to Befunge-98.

Aha! 6 bytes by printing the fetched character value outright.

TI-Basic, 14 bytes

A+1→A
1+2(Ans=3

There is a newline at the beginning.

19 bytes

Ai+not(A→A
2-real(Ans)-imag(Ans

There is a newline at the beginning.

Batch, 28 bytes
@cmd/cset/a1+2*!(%~z0%%3)
:

Conveniently the file length is not a multiple of 3 until the file is tripled, so it remains to take the remainder modulo 3, take the logical not, double that, and add 1.

SmileBASIC, 18 bytes
X=X+1CLS?(X>2)*2+1

Charcoal, 10 bytes
Ｐ§311Ｌ⊞Ｏυω

Try it online! Based on my answer to I double the source, you double the output! but I cyclically look up the appropriate character to print instead of just printing the current length cast to string. (The 3 is first because the iteration numbers are 1-indexed but Charcoal's string indexing is 0-indexed.)

sed, 37 bytes
g
s/^/1/
H
s/\n//g
s/1111/3/
s/11/1/

Using the pattern space to preserve state is the key here.
Try it online!

05AB1E, 4 bytes
X3Ur

Try it online!, doubled, tripled.
X           # push X on the stack (X defaults to 1)
 3U         # set X = 3
   r        # reverse the stack