text:
D&D 5e HP Calculator
I have trouble remembering everything I have to do when leveling up a D&D character. For whatever reason, one of the things that gives me trouble is figuring out what their new maximum HP value should be. For this challenge, you will write a program or function to calculate the correct value automatically.
Terminology
The first thing you need to know about to calculate max HP is the "Constitution modifier". Each DND character has six integer ability scores, including one for Constitution. The only relevant knowledge required for this challenge is how the Constitution ability score affects another stat, which is the Constitution modifier. In short, the modifier is equal to floor( (ability_score - 10) / 2 ). Adventurers can only have ability scores from 1 to 20, inclusive. Your code will never have to handle scores outside that range, which also means it will never have to handle a modifier lower than -5 or greater than +5. Though the Constitution modifier can change as a character levels up, its effects on HP are applied retroactively, so only its current value is needed to calculate current max HP.

(This is entirely irrelevant to the challenge, but if you're curious about how it affects maximum HP: You can assume the "Tough" feat adds 2 to a character's Constitution modifier for the purposes of HP calculation, since that's effectively what it does. That's not the text of the feat but the math works out to be exactly the same. You don't have to handle this feat in your answer.)

Next, every class has an assigned "hit die" type, which is involved in calculating HP. The following table lists the hit dice for each class.
Sorcerer:  d6
Wizard:    d6
Bard:      d8
Cleric:    d8
Druid:     d8
Monk:      d8
Rogue:     d8
Warlock:   d8
Fighter:   d10
Paladin:   d10
Ranger:    d10
Barbarian: d12

Finally, the character's level. All that this affects is how many times to add a value to the running total in the following section. A character's level is an integer from 1 to 20, inclusive1. Your code will never have to handle a level outside that range. To reach level n, a character starts at level 1 and levels up n-1 times. For example, a level 3 character got to where they are by being a level 1 character and levelling up twice.
How to Calculate Max HP
A character's maximum HP is equal to their HP at level 1 plus the sum of the increase they received at each level.
At level 1
At level 1, a character's HP is equal to the highest possible roll on their hit die (the number in the name of the die, for those of you unfamiliar with dice that have more than 6 sides) plus their Constitution modifier. Remember that when calculating HP at a later level, you may assume a character's Constitution has always been the same, as this part of the calculation is re-done every time Constitution changes.
When levelling up
Every time a character levels up, they have two options. They may either roll one of their hit dice or take the average roll of that die (rounded up). Whichever they choose, their Constitution modifier is added to the result. This total is the amount that their HP increases. For this challenge, the average roll is always taken, so output is deterministic. (Again, if you're not familiar with >6 sided dice, you can calculate the rounded-up average roll as (highest_possible_roll / 2) + 1.)
There is one notable exception. A character's maximum HP always increases by at least 1 each time they level up2. If the instructions in the above paragraph would result in an increase of 0 or less when leveling up, it increases by 1 instead.
The Challenge
Your program or function will take three inputs:

The character's class, as a string
The character's level
The character's Constitution ability score (not modifier)

It will output only one thing: The character's current maximum HP.
Examples
Every possible combination of inputs and their associated outputs can be found at this link. For the sake of having something to look at on this page, here are 30 test cases chosen at random:
Barbarian, 15th level, 13 CON: 125
    Rogue, 10th level, 18 CON: 93
   Wizard, 15th level, 18 CON: 122
   Wizard, 16th level,  1 CON: 16
Barbarian, 15th level,  7 CON: 80
  Warlock, 15th level,  3 CON: 18
   Ranger, 14th level,  1 CON: 18
  Warlock,  3rd level, 14 CON: 24
    Druid,  3rd level,  4 CON: 9
   Cleric, 11th level,  5 CON: 25
     Bard, 20th level, 11 CON: 103
Barbarian, 11th level, 13 CON: 93
     Bard,  8th level, 19 CON: 75
     Bard, 16th level, 17 CON: 131
  Fighter, 10th level,  6 CON: 44
     Monk, 10th level,  2 CON: 13
   Cleric, 14th level, 17 CON: 115
   Cleric,  6th level,  5 CON: 15
    Rogue,  7th level, 13 CON: 45
   Cleric,  4th level, 14 CON: 31
    Rogue, 19th level, 15 CON: 136
  Paladin, 13th level, 13 CON: 95
   Cleric, 13th level, 15 CON: 94
     Bard,  8th level,  5 CON: 19
     Monk, 20th level, 11 CON: 103
Barbarian,  8th level, 20 CON: 101
     Monk,  1st level,  4 CON: 5
     Bard,  5th level, 17 CON: 43
     Monk, 18th level,  7 CON: 57
   Wizard, 17th level,  5 CON: 19

1. Strictly speaking, I don't think there's a rule that says 20 is the maximum level. However, 21 is the point where there stop being tables in the book to tell you what some of the various numbers in the rules should be, including the amount of experience you need to obtain to reach it. That's a good enough level cap for me.
2. I actually don't think this is true with RAW. I asked on rpg.se and such a thing doesn't appear to be written down anywhere. However, Mike Mearls, lead designer of D&D, tweeted it in March 2015. This is not authoritative the way that you could argue a tweet from lead rules developer Jeremy Crawford would be, but it is evidence that it's what they intended, so I'll use it for this challenge.

Does class have to be given as a string, or can it be given as the number of the hit die, given that's the only relevant information for a class. Otherwise people will just need a generic table of "If these classes then this die, if these classes then this die" etc.

Also are level and constitution passed as integers, or as strings saying "xth level" and "y CON"?

Gosh, I'm old, I still remember this table: http://www.ancientscrossroads.com/adnd_tools/con_table.htm

@Mayube Probably shouldn't have asked a question and immediately gone out for pizza, huh? :P The class has to be a string, because I think there's enough data in those strings to find patterns to shorten the table (which appears to be the case, based on the answers that have come in so far). Level and constitution are ints.

I don't think you have enough edge cases in your sample test cases.

I found it pretty hard to parse out the relevant information from all the info being thrown at me.

@undergroundmonorail In that case I'm gunna post a non-competing answer, because my language can't handle string parsing :(

Here is a verbose (i.e. non-golfed) reference implementation with the listed test cases. (It's a tinyurl as the TIO link itself was too long for a comment).

<Fondly remembers his 6 con, 6 hp kobold> Oh wait, he's still alive. It was the rest of the party that died a horrific death.

Jelly, 34 bytes
OSị“#®Ʋ?[’ṃ6¤ð+‘»1×⁵’¤+⁸Ḥ¤+ð⁹_10:2

Full program taking three command line arguments: class, score, level.
Try it online!
How?
The middle of the code, separated by ðs is a dyadic link which calculates the result from some previously calculated values:
+‘»1×⁵’¤+⁸Ḥ¤+ - maxHitPoints(halfDieValue, modifier)
+             - add: halfDieValue + modifier
 ‘            - increment
  »1          - maximum of that and 1: this is the level-up delta
       ¤      - nilad followed by links as a nilad:
     ⁵        -   program's 3rd argument, level (5th command line argument)
      ’       -   decrement: this is the number of level-ups
    ×         - multiply: level-ups * level-up delta
           ¤  - nilad followed by links as a nilad:
         ⁸    -   link's left argument: halfDieValue
          Ḥ   -   double: dieValue
        +     - add: level-ups * level-up delta + dieValue
            + - add: level-ups * level-up delta + dieValue + modifier

The modifier is calculated at the right hand side:
⁹_10:2 - getModifier(class, score)
⁹      - link's right argument, the 2nd argument, the score
 _10   - minus 10
    :2 - integer divide by 2

Half the die value is calculated at the left hand side:
OSị“#®Ʋ?[’ṃ6¤ - getHalfDieValue(class)
O             - cast to ordinals
 S            - sum
            ¤ - nilad followed by link(s) as a nilad:
   “#®Ʋ?[’    -   base 250 literal 140775266092
          ṃ6  -   convert to base 6 but with 6s in place of 0s
  ị           - index into (1-indexed and modular)

Considering the ordinal sums of the class names modulo m such that m is minimal while keeping the classifications (by die) from colliding  yields m=15. Placing the required values (half-die roll) at those indexes in a list of length 15 allows lookup using Jelly's modular indexing with ị. Compressing the list as a base 6 number with the lone 6 replaced by a 0 is a byte shorter than the alternatives of base-7 compression or base-4 compression & increasing the values (with the byte overhead associated with using an extra nilad in the chain). The base 6, rather than 7, decompression is achieved by using the fact that base decompression, ṃ (rather than base conversion, b), has implicit range construction when it's right argument, r, is an integer, which means is is like converting to base r and then changing any 0 to an r all in one go.
That is:
         class: Sorcerer,Wizard,Bard,Cleric,Druid,Monk,Rogue,Warlock,Fighter,Paladin,Ranger,Barbarian
   Ordinal sum: 837,     625,   377, 594,   504,  405, 514,  723,    713,    697,    607,   898
        mod 15:  12,      10,     2,   9,     9,    0,   4,    3,      8,      7,      7,    13
required value:   3,       3,     4,   4,     4,    4,   4,    4,      5,      5,      5,     6

Rearranging to the list, converting the 6 at index 13 to a zero and making it minimal in base 6:
mod 15:    2   3   4           7   8   9  10      12  13      0
 value: 1, 4,  4,  4,  0,  0,  5,  5,  4,  3,  0,  3,  0,  0,  4

Making the code
                list: [1,4,4,4,0,0,5,5,4,3,0,3,0,0,4]
         from base 6: 140775266092
         to base 250: [36,9,154,64,92]
code page characters:   # ®   Ʋ  ?  [
          final code: “#®Ʋ?[’ṃ6

JavaScript (ES6), 81 78 76 74 bytes
Takes input as (class, level, constitution_ability_score). The class is case-insensitive.
(c,l,s,h=(d=parseInt(c,34)*59.9%97%77%6|4)+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

This is essentially using the same math as my initial version, but d is now computed without any lookup table.
Test cases

let f =

(c,l,s,h=(d=parseInt(c,34)*59.9%97%77%6|4)+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

console.log(f('Barbarian', 15, 13))  // 125
console.log(f('Rogue',     10, 18))  // 93
console.log(f('Wizard',    15, 18))  // 122
console.log(f('Wizard',    16,  1))  // 16
console.log(f('Barbarian', 15,  7))  // 80
console.log(f('Warlock',   15,  3))  // 18
console.log(f('Ranger',    14,  1))  // 18
console.log(f('Warlock',    3, 14))  // 24
console.log(f('Druid',      3,  4))  // 9
console.log(f('Cleric',    11,  5))  // 25
console.log(f('Bard',      20, 11))  // 103
console.log(f('Barbarian', 11, 13))  // 93
console.log(f('Bard',       8, 19))  // 75
console.log(f('Bard',      16, 17))  // 131
console.log(f('Fighter',   10,  6))  // 44
console.log(f('Monk',      10,  2))  // 13
console.log(f('Cleric',    14, 17))  // 115
console.log(f('Cleric',     6,  5))  // 15
console.log(f('Rogue',      7, 13))  // 45
console.log(f('Cleric',     4, 14))  // 31
console.log(f('Rogue',     19, 15))  // 136
console.log(f('Paladin',   13, 13))  // 95
console.log(f('Cleric',    13, 15))  // 94
console.log(f('Bard',       8,  5))  // 19
console.log(f('Monk',      20, 11))  // 103
console.log(f('Barbarian',  8, 20))  // 101
console.log(f('Monk',       1,  4))  // 5
console.log(f('Bard',       5, 17))  // 43
console.log(f('Monk',      18,  7))  // 57
console.log(f('Wizard',    17,  5))  // 19

Initial version, 87 84 bytes
(c,l,s,h=(d=+'55654607554506'[parseInt(c,35)%24%15])+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

How it works
The tricky part is to convert the class string c into the corresponding hit dice. More precisely, the value that we're going to store is d = dice / 2 + 1.
We use the formula parseInt(c, 35) % 24 % 15 which gives:
Class       | Base 35 -> decimal | MOD 24 | MOD 15 | d
------------+--------------------+--------+--------+---
"Sorcerer"  |      1847055419467 |     19 |      4 | 4
"Wizard"    |               1138 |     10 |     10 | 4
"Bard"      |             484833 |      9 |      9 | 5
"Cleric"    |          662409592 |     16 |      1 | 5
"Druid"     |           20703143 |     23 |      8 | 5
"Monk"      |             973475 |     11 |     11 | 5
"Rogue"     |           41566539 |      3 |      3 | 5
"Warlock"   |        59391165840 |      0 |      0 | 5
"Fighter"   |        28544153042 |      2 |      2 | 6
"Paladin"   |        46513817828 |     20 |      5 | 6
"Ranger"    |         1434103117 |     13 |     13 | 6
"Barbarian" |     25464249364423 |      7 |      7 | 7

By inserting the values of d at the corresponding positions into a string and padding unused slots with zeros, we get:
00000000001111
01234567890123
--------------
55654607554506

Hence the final formula:
d = +'55654607554506'[parseInt(c, 35) % 24 % 15]

Once we have d, we compute:
h = d + ((s - 10) >> 1))

which is the theoretical number of points that are gained at each level-up.
If h is positive, we simply compute:
h * l

If not, we need to take into account the fact that at least 1 point is gained at each level-up. So we compute instead:
h + l - 1

In both cases, we adjust the result by adding d - 2, so that the initial number of points is correctly integrated.
Test cases

let f =

(c,l,s,h=(d=+'55654607554506'[parseInt(c,35)%24%15])+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

console.log(f('Barbarian', 15, 13))  // 125
console.log(f('Rogue',     10, 18))  // 93
console.log(f('Wizard',    15, 18))  // 122
console.log(f('Wizard',    16,  1))  // 16
console.log(f('Barbarian', 15,  7))  // 80
console.log(f('Warlock',   15,  3))  // 18
console.log(f('Ranger',    14,  1))  // 18
console.log(f('Warlock',    3, 14))  // 24
console.log(f('Druid',      3,  4))  // 9
console.log(f('Cleric',    11,  5))  // 25
console.log(f('Bard',      20, 11))  // 103
console.log(f('Barbarian', 11, 13))  // 93
console.log(f('Bard',       8, 19))  // 75
console.log(f('Bard',      16, 17))  // 131
console.log(f('Fighter',   10,  6))  // 44
console.log(f('Monk',      10,  2))  // 13
console.log(f('Cleric',    14, 17))  // 115
console.log(f('Cleric',     6,  5))  // 15
console.log(f('Rogue',      7, 13))  // 45
console.log(f('Cleric',     4, 14))  // 31
console.log(f('Rogue',     19, 15))  // 136
console.log(f('Paladin',   13, 13))  // 95
console.log(f('Cleric',    13, 15))  // 94
console.log(f('Bard',       8,  5))  // 19
console.log(f('Monk',      20, 11))  // 103
console.log(f('Barbarian',  8, 20))  // 101
console.log(f('Monk',       1,  4))  // 5
console.log(f('Bard',       5, 17))  // 43
console.log(f('Monk',      18,  7))  // 57
console.log(f('Wizard',    17,  5))  // 19

Something seems to be wrong with your code; Bards with a CON of 1 or Wizards with a CON of 2 or 3 get the same number of hit points whatever their level.

@Neil Thanks for noticing. I think this is fixed.

Batch, 172 bytes
@set/aa=1-%3/2,h=4-a
@for %%c in (-1.Sorcerer -1.Wizard 1.Fighter 1.Paladin 1.Ranger 2.Barbarian)do @if %%~xc==.%1 set/aa-=c=%%~nc,h+=c*2
@cmd/cset/a"a*=(a>>9),-~a*~-%2+h

Takes class, level, and constitution as command-line arguments. Explanation: The HP can be calculated as (HP at level 1) + (level - 1) + min(further HP per level, 0) * (level - 1). The further HP per level is half the hit die plus the constitution modifier. Most classes use d8 so this becomes one less than half the constitution (%3/2-1), while the HP at level 1 is 3 more than that. The further HP per level and HP at level 1 are then adjusted for the six classes that don't use d8. The further HP per level is then limited to 0 (this actually uses the negative value as it's slightly golfier this way.)

R, 181 163 bytes
function(s,n,t){a=Hmisc::Cs(rc,za,rd,er,ui,mk,gu,rl,gh,la,ng,rb)
b=c(6,6,rep(8,6),rep(10,3),12)
d=b[a == substr(s,3,4)]
m=floor((t-10)/2)
d+m+(n-1)*max(d/2+1+m,1)}

Anonymous function. Runs as f(class, level, CON).
Explanation:
Creates vectors for class s to dice max d, using the 3rd and 4th letters in the class name (smallest unique mapping I found).
CON mod m is straight from the spec, and HP = first level (d + m) + the rest of the levels ((n-1) * max(average_die + m, 1).
> f("Barbarian", 15, 13)
[1] 125
> f("Rogue", 10, 18)
[1] 93
> f("Wizard", 15, 18)
[1] 122
> f("Wizard", 16, 1)
[1] 16
> f("Barbarian", 15, 7)
[1] 80
> f("Warlock", 15, 3)
[1] 18
> f("Ranger", 14, 1)
[1] 18


text:
Build a Mass Spectrometer!
Challenge
Given the high resolution molecular mass of an organic molecule, output the molecule's molecular formula.
Explanation
The input will be a single number to three decimal places of precision, the relative molecular mass of the molecule.
Here, the molecular mass is defined as the sum of the masses of the atoms in the compound. Since you only are finding the molecular formulae of organic compounds, the atomic masses you need to know are:

C, Carbon: 12.011
H, Hydrogen: 1.008
O, Oxygen: 15.999
N, Nitrogen: 14.007

Your formula should only ever contain carbon, hydrogen, oxygen or nitrogen.
When writing the formula, it should take the form:
CaHbOcNd

Where the elements must be in that order (C -> H -> O -> N, so C2O8N4H6 should be C2H6O8N4) and a, b, c and d are numbers of the preceding element in the molecule (i.e. C2 means that there are two carbon atoms in the molecule).
If a, b, c or d are zero, that element should not be included in the formula (e.g. C2H6O2N0 should be C2H6O2). Finally, if a, b, c or d are one, you should not include the number in the formula (e.g. C1H4 should be CH4).
The input will always be valid (i.e. there will be a molecule with that mass). If the input is ambiguous (multiple molecules have the same mass), you must only output one of the molecules. How you choose this molecule is up to you.
Worked Example
Suppose the input is 180.156, there is only one combination of the elements which can have this molecular mass:
12.011*6 + 1.008*12 + 15.999*6 + 14.007*0 = 180.156

So there are:

6 Carbons
12 Hydrogens
6 Oxygens
0 Nitrogens

Therefore, your output should be:
C6H12O6

More Examples
Input -> Output

28.054 -> C2H4
74.079 -> C3H6O2
75.067 -> C2H5O2N
18.015 -> H2O

Winning
Shortest code in bytes wins.

What if the input is ambiguous?

@NoOneIsHere AFAIK the input should not be ambiguous, but I'll add that into the rules anyway.

Can input be taken as int (i.e., no period - ethene would be 28054)

@StephenS Yes, it can

Can you reformat the test cases into something like input -> output? It's quite hard to read as-is.

12.011 is the relative atomic mass of carbon, which is a weighted average of the relative isotopic masses of the isotopes. In a mass spectrometer, where different isotopes are distinguished, you should see exactly 12. Similar for other atoms.

@LeakyNun Oh right. Whoops... :/

For a fun test, note that the input 672.336 has 24 possible solutions, including a pure-nitrogen and a pure-hydrogen solution.

Mathematica, 108 bytes
Print@@Join@@({Characters@"CHON",#}ᵀ/.a_/;Last@a<2:>Table@@a)&/@{12011,1008,15999,14007}~FrobeniusSolve~#&

Pure function expecting the input as an integer (1000 times the relative molecular mass); it prints all possible answers to STOUD (and returns an array of Nulls).
The heavy lifting is done by the builtin {12011,1008,15999,14007}~FrobeniusSolve~#, which finds all nonnegative integer combinations of the hardcoded weights that equal the input. {Characters@"CHON",#}ᵀ puts each such combination in a form like {{"C", 0}, {"H", 1}, {"O", 2}, {"N", 3}}. (ᵀ is actually the 3-byte private Mathematica character U+F3C7.)
The transformation rule /.a_/;Last@a<2:>Table@@a changes pairs of the form {x, 0} to {} and pairs of the form {x, 1} to {x} (and spits out errors as it tries to apply to the whole expression as well). Then Print@@Join@@ prints the result in the correct form, avoiding the need to cast the integers as strings and concatenate.

What's the result of 672336? :)

The ᵀ seems to be the wrong character. Should be .

Yeah, have to make the choice between easy to read and easy to cut/paste.

JavaScript (ES6), 159 158 bytes
Not exactly fast...
w=>[...Array(w**4|0)].some((_,n)=>![12011,1008,15999,14007].reduce((p,c,i)=>p-c*(x[i]=n%w|!(n/=w)),w*1e3,x=[]))&&x.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

Demo

let f =

w=>[...Array(w**4|0)].some((_,n)=>![12011,1008,15999,14007].reduce((p,c,i)=>p-c*(x[i]=n%w|!(n/=w)),w*1e3,x=[]))&&x.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

console.log(f(28.054))  // -> C2H4
console.log(f(18.015))  // -> H2O

Faster version, 174 173 bytes
w=>[...Array(w**3|0)].some((_,n)=>r=(d=w*1e3-14007*(a=n/w/w%w|0)-15999*(b=n/w%w|0)-12011*(c=n%w|0))%1008|d<0?0:[c,d/1008,b,a])&&r.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

All test cases

let f=

w=>[...Array(w**3|0)].some((_,n)=>r=(d=w*1e3-14007*(a=n/w/w%w|0)-15999*(b=n/w%w|0)-12011*(c=n%w|0))%1008|d<0?0:[c,d/1008,b,a])&&r.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

console.log(f(180.156)) // -> C6H12O6
console.log(f(28.054))  // -> C2H4
console.log(f(74.079))  // -> C3H6O2
console.log(f(75.067))  // -> C2H5O2N
console.log(f(18.015))  // -> H2O

Python 2, 242 bytes
b=[12011,1008,15999,14007]
def p(m):
 if m in b:x=[0,]*4;x[b.index(m)]=1;return x
 elif m<1:return 0
 else:
  for i in range(4):
   x=p(m-b[i])
   if x:x[i]+=1;return x
  return 0
print''.join(a+`n`*(n>1)for n,a in zip(p(input()),'CHON')if n)

Try it online!
Recursive function, the input is an integer (1000 times the relative molecular mass) thanks Stephen S for the idea

My machine took 40 segs to turn 672336 into C33H115O3N8 with this modified code. It contains a lookup table for hits/fails to reduce the amount of recursive calls and a optimization to count an element multiple times (if the mass is high enough)

Why does 180156 timeout when all of the test cases are so fast? (without the cache hit)

@BetaDecay hmm, could be 18015 instead?

Nope, 18015 is H2O, not C6H12O6

source: Stack Exchange

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

sort: votes


text:
May the fourth be with flu
Since tomorrow is the 4th of May, here's a little Star Wars themed post to prepare you mentally to all the bad jokes coming tomorrow.
BACKSTORY
During a session of the galactic senate all the senators are sitting in an n*n grid.
A sudden outbreak of JarJar flu (which lasts forever and causes the infected to speak like JarJar Binks) causes some of the senators to get infected.
Here's an example with a 6*6 grid where the X are the infected senators, the corresponding list is : [[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[0,5]]:

After that the infection begins to spread step by step. Two senators are adjacent if they share a whole edge on the grid (i.e., top,bottom,right,left), which means we exclude diagonals.
We can conclude a senator can be adjacent to 2,3 or 4 other senators and claim the following rules for the infection :

A senator that has been infected stays infected forever
A senator is infected at a step if he was adjacent to 2 or more infected senator at the previous step

Here's an example with the previous grid which shows the 2 first steps of the infection :

After the nexts steps all the senate will be infected
YOUR TASK
Your code doesn't need to handle invalid inputs like a list greater than n*n or coordinates that aren't distincts.
Your code will take as input a list of couples of integers (or a binary grid or any other format that suits your language) and an integer n (which can be unnecessary if you use another format than a list) , for instance :
8 [[1,2],[1,1],[7,4],[2,7],[4,3]]

n being the side of the grid which means the grid will be a n*n grid, and the list of couples of integers being the coordinates of the cells of the initally infected senators.
The bottom left of the grid is [0,0] and the top right is [n-1,n-1]. The top left is [0,n-1].
Your code must output an integer :
-1 or a falsy value or an error if the whole grid will never be totally infected
or the minimum number of steps required to infect the whole grid
Test cases
6 [[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[5,0]] => 7

4 [[1,1][0,3][1,0][3,0][3,3]] => 9

Remember that this is code-golf, thus the shortest answer in bytes wins !

Related post on Mathematica.SE.

Related

What's the minimum value of n? Is there a max value?

@mbomb007 there's no max value in theory but it should be computable. For the minimum value I'd say 1 which outputs 0 or -1

Looks like a job for Mathematica's CellularAutomaton...

@mbomb007 See the post I linked in the first comment. ListConvolve is probably shorter.

@Antoine Can we use 1-based indexing for number of generations, i.e. 1=senate is already fully infected, 2=fully infected one step later, 3=... And then 0=infection never takes over? Is this ok?

@Adám Well I don't know if it's fair for those who are using the 0-indexing but personally I don't mind

Minecraft reference: a water will be a full block of water if there are two adjacent full blocks (provided that the well is 1 block deep).

MATL, 29 28 bytes
tn:"tlY6Z+1>Z|t?@.]]Nl=?l_]&

Input is in the form of a 2D matrix of 1's and 0's
Try it at MATL Online
Explanation
        % Implicitly grab user input as a 2D matrix
t       % Duplicate the inputs
n:      % Count the number of elements in the input (N) and create the array [1...N]
"       % Loop this many times (maximum number of steps we analyze)
  t     % Duplicate the top element
  lY6   % Push the 2D array => [0 1 0; 1 0 1; 0 1 0]
  Z+    % Perform 2D convolution (and maintain the size)
  l>    % Find all values that are >= 2
  Z|    % Perform an element-wise OR with the previous state
  t?    % If all elements are 1's
    @.  % Push the current index and break out of the loop
  ]     % End of if
]       % End of for loop
Nl=?    % If there is only one element on the stack
  l_    % Push a negative one
]       % End of if statement
&       % Display the top stack element

@LuisMendo Unfortunately I don't think so because there are some 0's in the output of the convolution which would become -1 and therefore be "true"

How about tn:"tlY6Z+1>Z|t?x@D.]]N?xl_? (I'm haven't tested much). If all elements are 1 at some point, display the loop index immediately and delete stack. At the end of the loop, if the stack is non-empty delete and push -1

APL (Dyalog 16.0), 54 characters or 60 bytes
Takes enclosed matrix as argument, returns the step number which completes infection, i.e. 1=is already fully infected. 0=does not fully spread, which is just 1 + the OP's numbers.
54 characters (Unicode):
(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⌺3 3)⊃⍵:⍵⋄(⊂f⊃⍵),⍵}⍣≡

60 bytes (Classic):
(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⎕U233A 3 3)⊃⍵:⍵⋄(⊂f⊃⍵),⍵}⍣≡

⌺ is equivalent to ⎕U233A
Examples' run:
      g←(≢×0=0∊⊃){(⊢≡f←⊢∨2≤{+/,⍵×3 3⍴0 1}⌺3 3)⊃⍵:⍵ ⋄ (⊂f⊃⍵),⍵}⍣≡
      ⎕IO←0
      b←⊂⊖⍉~@(⎕JSON'[[0,5],[1,4],[2,3],[2,1],[3,3],[3,0],[4,5],[5,0]]')⊢0⍴⍨2⍴6
      g b
8
      b←⊂⊖⍉~@(⎕JSON'[[1,1],[0,3],[1,0],[3,0],[3,3]]')⊢0⍴⍨2⍴4
      g b
10

The steps are as follows:

┌─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┐
│ X       X   │ X X     X   │ X X X   X   │ X X X X X   │ X X X X X   │ X X X X X   │ X X X X X   │ X X X X X X │
│   X         │ X X X       │ X X X X     │ X X X X X   │ X X X X X   │ X X X X X   │ X X X X X X │ X X X X X X │
│     X X     │   X X X     │ X X X X     │ X X X X     │ X X X X X   │ X X X X X X │ X X X X X X │ X X X X X X │
│             │     X       │   X X X     │ X X X X X   │ X X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │
│     X       │     X X     │     X X X   │   X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │
│       X   X │     X X X X │     X X X X │     X X X X │   X X X X X │ X X X X X X │ X X X X X X │ X X X X X X │
└─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┘
┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐
│ X     X │ X     X │ X     X │ X     X │ X     X │ X     X │ X   X X │ X X X X │ X X X X │ X X X X │
│         │         │         │         │       X │     X X │   X X X │ X X X X │ X X X X │ X X X X │
│   X     │   X     │   X X   │   X X X │   X X X │   X X X │   X X X │   X X X │ X X X X │ X X X X │
│   X   X │   X X X │   X X X │   X X X │   X X X │   X X X │   X X X │   X X X │   X X X │ X X X X │
└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘

Python, 231 bytes
g=input()
q=lambda r,c:g[r][c]if(0<=r<m)*(0<=c<m)else 0
m=len(g);p=t=0;n=range(m)
while not all([r for k in g for r in k]):h=[[g[r][c]or sum([q(r+1,c),q(r-1,c),q(r,c+1),q(r,c-1)])>1 for c in n] for r in n];t+=1;0/(g!=h);g=h
print t

It raises an error if it isn't possible.
Try it online!

0/0 saves two bytes from raise. Maybe 1/(g!=h) would work? (then the whole while could be inlined too).

@JonathanAllan I updated it, thanks for the input.

q=lambda r,c:g[r][c]if(0<=r<m)*(0<=c<m)else 0 saves 12. You can remove the space between (a) 1 and for and (b) ] and for too.

@JonathanAllan Updated again. Thanks

Pyth, 49 bytes
J^UE2*lK.uS{+NeMf>hT1r8S@Jsmm+VdkNs_MB_MBU2Q)qJeK

Test suite.
Uses 1-indexing for the output.

JavaScript (ES6), 132 bytes
f=s=>(w=s.search`\n`,t=` `.repeat(w+1),t+=s+t,t=s.replace(/0/g,(_,i)=>1-t[i]-t[i+=w]-t[i+=2]-t[i+w]>>>31),t==s?0/!/0/.test(s):1+f(t))

Where \n represents the literal newline character. Takes input as a string of 0s and 1s in a newline-delimited array. Returns NaN if the grid will never become fully infected.

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:
Find the nearest greater number
The task
Given any array of integers, e.g.:
[-1,476,578,27,0,1,-1,1,2]

and an index of that array (this example uses 0 based indexing, though you can use 1 based indexing as well.):
         index = 5
                 v
[-1,476,578,27,0,1,-1,1,2]

Then return the nearest number greater than the element at that index. In the example, the closest number greater than 1 is 27 (at 2 indices away).
         index = 5
                 v
[-1,476,578,27,0,1,-1,1,2]
            ^
Nearest greater number

Output = 27

Assumptions

Nearest does not include wrapping.
The program will never be given an array of length 1 (e.g; [55]).
You are to assume there is always a number greater than the given element.
If there are 2 numbers greater than the element at equal distances, you can return either one.

This is code-golf so the shortest code in bytes wins
I/O pairs
Input:
Index = 45
Array = [69, 43, 89, 93, 62, 25, 4, 11, 115, 87, 174, 60, 84, 58, 28, 67, 71, 157, 47, 8, 33, 192, 187, 87, 175, 32, 135, 25, 137, 92, 183, 151, 147, 7, 133, 7, 41, 12, 96, 147, 9, 134, 197, 3, 107, 164, 90, 199, 21, 71, 77, 62, 190, 122, 33, 127, 185, 58, 92, 106, 26, 24, 56, 79, 71, 24, 24, 114, 17, 84, 121, 188, 6, 177, 114, 159, 159, 102, 50, 136, 47, 32, 1, 199, 74, 141, 125, 23, 118, 9, 12, 100, 94, 166, 12, 9, 179, 147, 149, 178, 90, 71, 141, 49, 74, 100, 199, 160, 120, 14, 195, 112, 176, 164, 68, 88, 108, 72, 124, 173, 155, 146, 193, 30, 2, 186, 102, 45, 147, 99, 178, 84, 83, 93, 153, 11, 171, 186, 157, 32, 90, 57, 181, 5, 157, 106, 20, 5, 194, 130, 100, 97, 3, 87, 116, 57, 125, 157, 190, 83, 148, 90, 44, 156, 167, 131, 100, 58, 139, 183, 53, 91, 151, 65, 121, 61, 40, 80, 40, 68, 73, 20, 135, 197, 124, 190, 108, 66, 21, 27, 147, 118, 192, 29, 193, 27, 155, 93, 33, 129]
Output = 199

Input:
Index = 2
Array = [4,-2,1,-3,5]
Output = 4 OR 5

Input:
Index = 0
Array = [2124, -173, -155, 146, 193, -30, 2, 186, 102, 4545]
Output = 4545

Input:
Index = 0
Array = [1,0,2,3]
Output = 2

Input:
Index = 2
Array = [3,-1,-3,-2,5]
Output = -1 OR -2

Could you add a test case where it looks for a result to the left instead of to the right? i.e. 1; [7,1,-4,2]

I think 2; [3,-1,-3,-2,5] is a nice test case. There are positive numbers, but the result is negative.

Can I use 2-indexed?

@Titus I mean if you really want to

MATL, 10 bytes
yt&y)>fYk)

This uses 1-based indexing. Try it online!
Explanation
Consider inputs [4,-2,1,-3,5], 3 as an example.
y     % Take two inputs implicitly. Duplicate 2nd-top element in the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5]
t     % Duplicate top of the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5]
&y    % Duplicate 3rd-top element in the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5], 3
)     % Index: select elements from first input as indicated by second input
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], 1
>     % Greater than, element-wise
      % STACK: [4,-2,1,-3,5], 3, [1,0,0,0,1]
f     % Find: gives indices of non-zero entries
      % STACK: [4,-2,1,-3,5], 3, [1,5]
Yk    % Closest element: gives closest element of each entry in second input
      % ([1,5]) to each entry in the first input (3). In case of a tie it
      % gives the left-most one
      % STACK: [4,-2,1,-3,5], 1
)     % Index: select elements from first input as indicated by second input
      % STACK: 4
      % Implicitly display

Do you have an explanation?

@NickClifford Sure! I was waiting for OP clarification. Explanation added

Jelly, 10 bytes
ị<ṛTạ⁸$ÞḢị

Try it online!

I was fiddling for ages trying to get sorting to work with the absolute value :(

Jelly, 11 12 bytes
+1 byte - No wrapping allowed.
Jạż⁸ṢZṪ»\Q2ị

1-indexed.
Try it online!

Previous 11 byter (wrapping indexing), 0-indexed:
ṙżU$Fµ>ḢTḢị

This fails on e.g. 0 [1,0,2,3].

@ØrjanJohansen Ah - it returns 3, which is 1 away so, um, yeah "nearest" is not defined...

I asked OP to add that test case.

JavaScript (ES6), 57 55 bytes
Takes the array a and the index i in currying syntax (a)(i).
a=>g=(i,p)=>(x=a[i-p])>a[i]||(x=a[i+p])>a[i]?x:g(i,-~p)

Test cases

let f =

a=>g=(i,p)=>(x=a[i-p])>a[i]||(x=a[i+p])>a[i]?x:g(i,-~p)

console.log(f([-1, 476, 578, 27, 0, 1, -1, 1, 2])(5))

console.log(f([69, 43, 89, 93, 62, 25, 4, 11, 115, 87, 174, 60, 84, 58, 28, 67, 71, 157, 47, 8, 33, 192, 187, 87, 175, 32, 135, 25, 137, 92, 183, 151, 147, 7, 133, 7, 41, 12, 96, 147, 9, 134, 197, 3, 107, 164, 90, 199, 21, 71, 77, 62, 190, 122, 33, 127, 185, 58, 92, 106, 26, 24, 56, 79, 71, 24, 24, 114, 17, 84, 121, 188, 6, 177, 114, 159, 159, 102, 50, 136, 47, 32, 1, 199, 74, 141, 125, 23, 118, 9, 12, 100, 94, 166, 12, 9, 179, 147, 149, 178, 90, 71, 141, 49, 74, 100, 199, 160, 120, 14, 195, 112, 176, 164, 68, 88, 108, 72, 124, 173, 155, 146, 193, 30, 2, 186, 102, 45, 147, 99, 178, 84, 83, 93, 153, 11, 171, 186, 157, 32, 90, 57, 181, 5, 157, 106, 20, 5, 194, 130, 100, 97, 3, 87, 116, 57, 125, 157, 190, 83, 148, 90, 44, 156, 167, 131, 100, 58, 139, 183, 53, 91, 151, 65, 121, 61, 40, 80, 40, 68, 73, 20, 135, 197, 124, 190, 108, 66, 21, 27, 147, 118, 192, 29, 193, 27, 155, 93, 33, 129])(45))

console.log(f([4, -2, 1, -3, 5])(2))

console.log(f([2124, -173, -155, 146, 193, -30, 2, 186, 102, 4545])(0))

Can you not use | instead of ||?

@Neil No, we don't want x to be overwritten when the first condition is fulfilled.

PHP, 106 Bytes
<?for($y=($a=$_GET[0])[$x=$_GET[1]];$y>=$a[$x-++$i]&&$y>=$a[$x+$i];);echo$y<$a[$x+$i]?$a[$x+$i]:$a[$x-$i];

Online Version

Looks like these don't work for the first test case.

@NickClifford Now it should work. I have take a wrong approach

Haskell, 48 bytes
i%l=minimum[[j*j,x]|(j,x)<-zip[-i..]l,x>l!!i]!!1

Try it online! Test framework from Ørjan Johansen.

You can save a byte by using a list and !!1 instead (just change Integer to Int in the header).

@ØrjanJohansen Thanks, I had tried that and was unsure why it complained about types.

x86-64 Assembly, 40 bytes
Inspired by analyzing Johan du Toit and 2501's C solutions, the following is a function that can be assembled with MASM for x86-64 platforms.
It follows the Microsoft x64 calling convention for passing parameters, so the total length of the array is passed in ECX, the position of interest is passed in EDX, and the pointer to the integer array is passed in R8 (it's a 64-bit platform, so it's a 64-bit pointer).
It returns the result (the "nearest greater number") in EAX.
             FindNearestGreater PROC
8B F2       \    mov     esi, edx     ; move pos parameter to preferred register
8B D9       |    mov     ebx, ecx     ; make copy of count (ecx == i; ebx == count)
            | MainLoop:
8B C6       |    mov     eax, esi     ; temp  = pos
2B C1       |    sub     eax, ecx     ; temp -= i
99          |    cdq
33 C2       |    xor     eax, edx
2B C2       |    sub     eax, edx     ; temp = AbsValue(temp)
            |
41 8B 14 B0 |    mov     edx, DWORD PTR [r8+rsi*4]
41 39 14 88 |    cmp     DWORD PTR [r8+rcx*4], edx
7E 04       |    jle     KeepGoing    ; jump if (pValues[i] <= pValues[pos])
3B D8       |    cmp     ebx, eax
77 02       |    ja      Next         ; jump if (count > temp)
            | KeepGoing:
8B C3       |     mov     eax, ebx    ; temp = count
            | Next:
8B D8       |     mov     ebx, eax    ; count = temp
E2 E3       |     loop    MainLoop    ; equivalent to dec ecx + jnz, but smaller (and slower)
            |
            |     ; Return pValues[temp + pos]
03 C6       |     add     eax, esi
41 8B 04 80 |     mov     eax, DWORD PTR [r8+rax*4]
C3          /     ret
             FindNearestGreater ENDP

If you wanted to call it from C code, the prototype would be:
extern int FindNearestGreater(unsigned int count,
                              unsigned int pos,
                              const    int *pValues);

Python, 62 bytes
lambda a,i:min((v<=a[i],abs(j-i),v)for j,v in enumerate(a))[2]

Try it online!

Java, 96 Bytes
int f(int n,int[]a){for(int s=1,i=1,x=a[n];0>(n+=i++*s)|n>=a.length||a[n]<=x;s=-s);return a[n];}

Identifiers are named like @Leaky Nun's answer. Furthermore, most parts have been aligned to be basically the same: In comparison, the if has been replaced by the for-condition (sacrificing the additional semicolon). A colon has been removed by moving increment-part into condition (so the parentheses of the previous if-statement practically "moved") - changing & to | did not have impact on character count.

Brachylog, 17 bytes
hH&∋₎<.&t:I≜+:H∋₍

Try it online!
Explanation
hH                      Call the list H
  &∋₎<.                 Output is greater than the number at the specified index
       &t:I≜            Label I (0, then 1, then -1, then 2, then -2, …)
            +           Sum I with the input Index
             :H∋₍       Output is the element of H at index <the sum>

Java (OpenJDK 8), 98 bytes
int f(int n,int[]a){for(int s=1,i=1,x=a[n];;n+=i++*s,s=-s)if(0<=n&n<a.length&&a[n]>x)return a[n];}

Try it online!
Checks the indices in the order specified by the partial sums of the following sum:
initial value + 1 - 2 + 3 - 4 + 5 - 6 + ...

I was just reading the question and wanted to start writing an answer.. Btw, why the s=1, and ,s=-s, it has no use in your answer.. Did you forgot to remove it from an old approach?

@KevinCruijssen it is a mistake and I'm fixing it now. It passed the testcases because in all those testcases, the nearest greater number is to the right.

C, 69 bytes
t;b;f(*d,c,p){for(b=c;c--;)d[c]>d[p]&(t=abs(p-c))<b?b=t:0;*d=d[p+b];}

First argument is an in/out argument. Output is stored in its first element.
See it work online.

PHP, 73 bytes
function($i,$a){for(;$b<=$a[$i];)$b=max($a[++$d+$i],$a[$i-$d]);return$b;}

closure takes 0-based index and array from arguments. Verify all test cases.

Not the next higher value. You need a value with the lowest distance that is higher

@JörgHülsermann Thanks for pointing out.

R, 59 bytes
function(l,i)l[j<-l>l[i]][which.min(abs(1:length(l)-i)[j])]

returns an anonymous function. In the event that there are two elements greater at equal distances, will return the first (lesser index).
Try it online!

Ruby, 64 bytes
->a,i{a[(0...a.size).select{|j|a[j]>a[i]}.min_by{|j|(i-j).abs}]}

Try it online!

Ohm, 20 bytes
Basically a translation of this Ruby answer.
Dl#)░┼_ª┼┘ª>;╥┘_-A;ª

Try it online!
Explanation will come later when I'm not doing homework.

Pyth - 28 bytes
JEehf>@T1@JQo@NZm(adQ@Jd)UlJ

Try it

Haskell, 53 bytes
(#) takes an Int and a list of Ints or Integers (actually any Ord type), and returns an element of the list.
n#l=[x|i<-[1..],x:_<-(`drop`l)<$>[n-i,n+i],x>l!!n]!!0

How it works

n is the given index and l is the given list/"array".
i, taking on values from 1 upwards, is the distance from n currently being tested.
For each i, we check indices n-i and n+i.
x is the element of l being tested. If it passes the tests it will be an element of the resulting list comprehension.

Indexing arbitrary indices with !! could give an out of bounds error, while drop instead returns either the whole list or an empty list in that case. The pattern match with x:_ checks that the result is not empty.
x>l!!n tests that our element is greater than the element at index n (which is guaranteed to exist).
!!0 at the end returns the first match/element of the list comprehension.

Try it online!

Jelly, 9 bytes
>ị@TạÞị⁸Ḣ

Try it online!
How it works
>ị@TạÞị⁸Ḣ - Main link. Takes the array A on the left and the index i on the right
 ị@       - Get the i'th element of A, k
>         - Is k greater than each element of A?
   T      - Get the indices of the 1s
     Þ    - Sort these indices by:
    ạ     -   Absolute difference with i
      ị⁸  - Index back into A
        Ḣ - Take the first element

Clojure, 95 bytes
#(%(nth(nth(sort-by first(for[i(range(count %)):when(>(% i)(% %2))][(Math/abs(- i %2))i]))0)1))

This is the shortest I could come up with :( I also tried playing around with this but couldn't bring it to the finish line:
#(map(fn[f c](f c))[reverse rest](split-at %2 %))

C (gcc), 110 108 bytes
c,o;e(g,l,f)int*g;{for(o=g[l],c=1;c<f;c++)l+c<f&&g[l+c]>o?o=g[l+c],c=f:0,l>=c&&g[l-c]>o?o=g[l-c],c=f:0;g=o;}

-2 bytes thanks to ceilingcat!!
Try it online!

Suggest l/c instead of l>=c

Pyth, 16 bytes
JEh>#@JQ@LJaDQUJ

Test suite.

JavaScript, 44 bytes
a=>g=(i,p)=>(x=a[i-p])>a[i]?x:g(i,p<0?-p:~p)

Try it online!
from https://codegolf.stackexchange.com/a/118765/

05AB1E, 10 bytes
è›ƶ0K<¹.xè

0-based indexing.
Try it online or verify all test cases.
Explanation:
è           # Get the item in the second (implicit) input-list at the first (implicit)
            # input-index
 ›          # Check for each value in the second (implicit) input-list if it's larger
            # than this value (1 if truthy; 0 if falsey)
  ƶ         # Multiply each by its 1-based index
   0K       # Remove all 0s from this list
     <      # Decrease each value by 1 to make it a 0-based index
      ¹.x   # Pop the list and get the item closest to the first input-index
         è  # Use that to index into the second (implicit) input-list
            # (after which the result is output implicitly)

Japt -g, 11 bytes
gUð>UgV)ñaV

Try it

APL(Dyadic Classic), 21 bytes
A[1↑{⍵[⍋|I-⍵]}⍸A>I⌷A]

Try it online!

Welcome to code golf, and nice first answer! Make sure to check out our tips for golfing in APL to see if there's any way to golf your code.

TI-Basic, 46 bytes
Prompt A
Prompt I
seq(abs(J-I),J,1,dim(ʟA→B
SortA(ʟB,ʟA
ʟA(1+sum(not(cumSum(ʟA>ʟA(1

Index is 1-based. Output is stored in Ans and is displayed at the end.

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


text:
Powerprogramming: O(1^N), O(N^1), O(2^N), O(N^2) all in one
Write a program (or function) that exhibits four common big O time complexities depending on how it is run. In any form it takes in a positive integer N which you may assume is less than 231.

When the program is run in its original form it should have constant complexity. That is, the complexity should be Θ(1) or, equivalently, Θ(1^N).
When the program is reversed and run it should have linear complexity. That is, the complexity should be Θ(N) or, equivalently, Θ(N^1).
(This makes sense since N^1 is 1^N reversed.)
When the program is doubled, i.e. concatenated to itself, and run it should have exponential complexity, specifically 2N. That is, the complexity should be Θ(2^N).
(This makes sense since the 2 in 2^N is double the 1 in 1^N.)
When the program is doubled and reversed and run it should have polynomial complexity, specifically N2. That is, the complexity should be Θ(N^2).
(This makes sense since N^2 is 2^N reversed.)

These four cases are the only ones you need to handle.
Note that for preciseness I'm using big theta (Θ) notation instead of big O because the runtimes of your programs must be bounded both above and below by the required complexities. Otherwise just writing a function in O(1) would satisfy all four points. It is not too important to understand the nuance here. Mainly, if your program is doing k*f(N) operations for some constant k then it is likely in Θ(f(N)).

Example
If the original program were
ABCDE

then running it should take constant time. That is, whether the input
  N is 1 or 2147483647 (231-1) or any value in between, it should terminate in
  roughly the same amount of time.
The reversed version of the program
EDCBA

should take linear time in terms of N. That is, the time it takes to
  terminate should be roughly proportional to N. So N = 1 takes the
  least time and N = 2147483647 takes the most.
The doubled version of the program
ABCDEABCDE

should take two-to-the-N time in terms of N. That is, the time it
  takes to terminate should be roughly proportional to 2N. So
  if N = 1 terminates in about a second, N = 60 would take longer than
  the age of the universe to terminate. (No, you don't have to test it.)
The doubled and reversed version of the program
EDCBAEDCBA

should take squared time in terms of N. That is, the time it takes to
  terminate should be roughly proportional to N*N. So if N = 1
  terminates in about a second, N = 60 would take about an hour to terminate.

Details

You need to show or argue that your programs are running in the complexities you say they are. Giving some timing data is a good idea but also try to explain why theoretically the complexity is correct.
It's fine if in practice the times your programs take are not perfectly representative of their complexity (or even deterministic). e.g. input N+1 might sometimes run faster than N.
The environment you're running your programs in does matter. You can make basic assumptions about how popular languages never intentionally waste time in algorithms but, for example, if you know your particular version of Java implements bubble sort instead of a faster sorting algorithm, then you should take that into account if you do any sorting.
For all complexities here assume we are talking about worst-case scenarios, not best-case or average-case.
The space complexity of the programs does not matter, only the time  complexity.
The programs may output anything. It only matters that they take in positive integer N and have the correct time complexities.
Comments and multiline programs are allowed. (You may assume \r\n reversed is \r\n for Windows compatibility.)

Big O Reminders
From fastest to slowest it's O(1), O(N), O(N^2), O(2^N) (order 1, 2, 4, 3 above).
Slower terms always dominate, e.g. O(2^N + N^2 + N) = O(2^N).
O(k*f(N)) = O(f(N)) for constant k. So O(2) = O(30) = O(1) and O(2*N) = O(0.1*N) = O(N).
Remember O(N^2) != O(N^3) and O(2^N) != O(3^N).
Neat big O cheat sheet.
Scoring
This is normal code golf. The shortest original program (the constant time one) in bytes wins.

Excellent question! Minor point: we don't have to specify worst-case / best-case / average-case, because the only input that counts as size N is the number N itself (which BTW is not the usual notion of input size: that would treat input N as being of size log N). So there is only one case for each N, which is simultaneously the best, worst, and average case.

It appears that you've deviated from the usual definitions of complexity. We always define the time complexity of an algorithm as a function of the size of its input. In the case where the input is a number, the size of the input is the base-2 logarithm of that number. So the program n = input(); for i in xrange(n): pass has exponential complexity, because it takes 2 ** k steps, where k = log_2(n) is the input size. You should clarify whether this is the case, as it dramatically changes the requirements.

Python 3, 102 bytes
try:l=eval(input());k=1#)]0[*k**l(tnirp
except:k=2#2=k:tpecxe
print(k**l*[0])#1=k;))(tupni(lave=l:yrt

Try it online!
This is of O(1^n), since this is what the program does:

evaluate the input
create the array [0]
print it

Reversed:

try:l=eval(input());k=1#)]0[*l**k(tnirp
except:k=2#2=k:tpecxe
print(l**k*[0])#1=k;))(tupni(lave=l:yrt

Try it online!
This is of O(n^1), since this is what the program does:

evaluate the input
create the array [0]*input (0 repeated as many times as the input)
print it

Doubled:
try:l=eval(input());k=1#)]0[*k**l(tnirp
except:k=2#2=k:tpecxe
print(k**l*[0])#1=k;))(tupni(lave=l:yrt
try:l=eval(input());k=1#)]0[*k**l(tnirp
except:k=2#2=k:tpecxe
print(k**l*[0])#1=k;))(tupni(lave=l:yrt

Try it online!
This is of O(2^n), since this is what the program does:

evaluate the input
create the array [0]
print it
try to evaluate the input
fail
create the array [0]*(2^input) (0 repeated as many times as 2^input)
print it

Doubled and reversed:

try:l=eval(input());k=1#)]0[*l**k(tnirp
except:k=2#2=k:tpecxe
print(l**k*[0])#1=k;))(tupni(lave=l:yrt
try:l=eval(input());k=1#)]0[*l**k(tnirp
except:k=2#2=k:tpecxe
print(l**k*[0])#1=k;))(tupni(lave=l:yrt

Try it online!
This is of O(n^2), since this is what the program does:

evaluate the input
create the array [0]*input (0 repeated as many times as the input)
print it
try to evaluate the input
fail
create the array [0]*(input^2) (0 repeated as many times as the input squared)
print it

Why does it not hang awaiting user interaction when there are multiple calls to input()?

@JonathanAllan I guess Ctrl+D (end of transmission) is sent to the program from TIO. EDIT: it should be "end of file".

It's certainly not the default, but whether it is a loophole or not is beyond me.

It's a loophole that "end of transmission" is transmitted at the end of transmission?

I have no idea, it just seems wrong that a normal run will require more input from the user. Input is not usually part of the program transmission.

You did that in a mainstream language too! Awesome! Hats off!

@Arjun Thanks for your appreciation.

Can you explain it?

Re: the "end of file" argument, you're looking at things backwards. When you're using a terminal, requests for input hang because there's something connected to it; ctrl-D can be sent to explicitly send no input. If the input is connected to an empty file (like TIO does if you leave the input box empty), or if it's connected to a file where all the input has been read, there's no need for the request for input to do anything; it already knows there's no input. On UNIX/Linux, "end of file" and "no input available" are indistinguishable on regular files.

A @AnderBiguri asked, can you please explain why your programs have the correct time complexities? From the OP: "You need to show or argue that your programs are running in the complexities you say they are. Giving some timing data is a good idea but also try to explain why theoretically the complexity is correct."

@Kevin calm down, I just came back.

For the first case, k is the input, and l is one, so you're still computing 1**k, right? Which should take O(log(k)) time, despite that fact that you and I and everybody knows in advance that it's one?

@RichardRast that is a good point. That would depend on the implementation of power.

Perl 5, 82 73 71+1 (for -n flag) = 72 bytes
I'm certain I can golf this (a lot) more, but it's bedtime, I've spent enough time debugging as is, and I'm proud of what I have so far anyway.
#x$=_$;
$x.=q;#say for(1..2**$_)#)_$..1(rof _$=+x$;;
eval $x;$x=~s/#//;

The program itself doesn't use the input, and just evaluates a string beginning with a comment and then does a single string substitution, so this is clearly in constant time. It's basically equivalent to:
$x="#";
eval $x;
$x=~s/#//;

Doubled:
#x$=_$;
$x.=q;#say for(1..2**$_)#)_$..1(rof _$=+x$;;
eval $x;$x=~s/#//;
#x$=_$;
$x.=q;#say for(1..2**$_)#)_$..1(rof _$=+x$;;
eval $x;$x=~s/#//;

The bit that actually takes exponential time is the second eval: it evaluates the command say for(1..2**$_), which lists all the numbers from 1 to 2^N, which clearly takes exponential time.
Reversed:
;//#/s~=x$;x$ lave
;;$x+=$_ for(1..$_)#)_$**2..1(rof yas#;q=.x$
;$_=$x#

This (naively) computes the summation of the input, which clearly takes linear time (since each addition is in constant time). The code that actually gets run is equivalent to:
$x+=$_ for(1..$_);
$_=$x;

The last line is just so that when these commands are repeated it will take quadratic time.
Reversed and doubled:
;//#/s~=x$;x$ lave
;;$x+=$_ for(1..$_)#)_$**2..1(rof yas#;q=.x$
;$_=$x#
;//#/s~=x$;x$ lave
;;$x+=$_ for(1..$_)#)_$**2..1(rof yas#;q=.x$
;$_=$x#

This now takes the summation of the summation of the input (and adds it to the summation of the input, but whatever). Since it does order N^2 additions, this takes quadratic time. It's basically equivalent to:
$x=0;
$x+=$_ for(1..$_);
$_=$x;
$x+=$_ for(1..$_);
$_=$x;

The second line finds the summation of the input, doing N additions, while the fourth does summation(N) additions, which is O(N^2).

Great! Doing that in a mainstream language would have been tough! This has my upvote!

Well done, this is pretty nice. You probably meant $x.=q;##say... instead of $x.=q;#say... though (with two # instead of 1). (That would explain why you counted 76 bytes instead of 75). Also, you should count -n flag in your bytecount, as your program doesn't do much without it.

@Dada I accidentally transposed the eval and the s/// commands. If you do the eval first you only need the one #. Good catch!

@Chris Right, it works indeed. You might be able to omit the last #: $x=~s/#//; reversed produces ;//#/s~=x$, which in your context does nothing, as it would with a leading #. (I haven't test it though). Regardless, have a +1 !

@Dada Nice catch once again!

Actually, 20 bytes
";(1╖╜ⁿr"ƒ"rⁿ@╜╖1(;"

Try it online!
Input: 5
Output:
rⁿ@╜╖1(;
[0]
5

Reversed:
";(1╖╜@ⁿr"ƒ"rⁿ╜╖1(;"

Try it online!
Output:
rⁿ╜╖1(;
[0, 1, 2, 3, 4]
5

Doubled:
";(1╖╜ⁿr"ƒ"rⁿ@╜╖1(;"";(1╖╜ⁿr"ƒ"rⁿ@╜╖1(;"

Try it online!
Output:
rⁿ@╜╖1(;
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
rⁿ@╜╖1(;
rⁿ@╜╖1(;
[0]

Doubled and reversed:
";(1╖╜@ⁿr"ƒ"rⁿ╜╖1(;"";(1╖╜@ⁿr"ƒ"rⁿ╜╖1(;"

Try it online!
Output:
rⁿ╜╖1(;
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
rⁿ╜╖1(;
rⁿ╜╖1(;
[0, 1, 2, 3, 4]

Main idea
Actually is a stack-based language.

abc is a program which has O(1n) complexity, and its double has O(2n) complexity.
def is a program which has O(n1) complexity, and its double has O(n2) complexity.

Then, my submission is "abc"ƒ"fed", where ƒ is evaluate. That way, "fed" will not be evaluated.
Generation of individual program
The pseudocode of the first component ;(1╖╜ⁿr:
register += 1 # register is default 0
print(range(register**input))

The pseudocode of the second component ;(1╖╜ⁿ@r:
register += 1 # register is default 0
print(range(input**register))

I never thought this will be even possible! Great work, sir! +1

@Arjun Thank you for your appreciation.

This is excellent and truly rises to the challenge by not using comments IMO. Awesome!

Well this actually has comments... the strings are unevaluated and are NOPs...

Jelly, 20 bytes
Partly inspired by Leaky Nun's Actually solution.
The leading and trailing newlines are significant.
Normal:

⁵Ŀ⁵
R
R²
2*R
‘
⁵Ŀ⁵

Try it online!
Input: 5
Output:
610

Reversed:

⁵Ŀ⁵
‘
R*2
²R
R
⁵Ŀ⁵

Try it online!
Input: 5
Output:
[1, 2, 3, 4, 5]10

Doubled

⁵Ŀ⁵
R
R²
2*R
‘
⁵Ŀ⁵

⁵Ŀ⁵
R
R²
2*R
‘
⁵Ŀ⁵

Try it online!
Input: 5
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]10

Doubled and Reversed

⁵Ŀ⁵
‘
R*2
²R
R
⁵Ŀ⁵

⁵Ŀ⁵
‘
R*2
²R
R
⁵Ŀ⁵

Try it online!
Input: 5
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]10

Explanation
The key here is in Ŀ, which means "calls the link at index n as a monad." The links are indexed top to bottom starting at 1, excluding the main link (the bottom-most one). Ŀ is modular as well, so if you try to call link number 7 out of 5 links, you'll actually call link 2.
The link being called in this program is always the one at index 10 (⁵) no matter what version of the program it is. However, which link is at index 10 depends on the version.
The ⁵ that appears after each Ŀ is there so it doesn't break when reversed. The program will error out at parse-time if there is no number before Ŀ. Having a ⁵ after it is an out of place nilad, which just goes straight to the output.
The original version calls the link ‘, which computes n+1.
The reversed version calls the link R, which generates the range 1 .. n.
The doubled version calls the link 2*R, which computes 2n and generates the range 1 .. 2n.
The doubled and reversed version calls the link ²R, which computes n2 and generates the range 1 .. n2.

Befunge-98, 50 bytes
Normal
\+]#:\-1vk  !:;#
@k!:-1 .: ;#]#$ <;
[*:>@
&$< ^&;

This is by far the simplest program of the 4 - the only commands that are executed are the following:
\+]
  !
  : @
&$< ^&;

This program does some irrevelant stuff before hitting a "turn right" command (]) and an arrow. Then it hits 2 "take input" commands. Because there is only 1 number in input and because of how TIO treats &s, the program exits after 60 seconds. If there are 2 inputs (and because I can without adding bytes), the IP would travel up into the "end program" function.
Try it online!
Reversed
;&^ <$&
 @>:*[
;< $#]#; :. 1-:!k@
#;:!  kv1-\:#]+\

This one is a little more complicated. the relevant commands are as follows:
;&^  $
  >:*[
;< $#]#; :. 1-:!k@
  :

which is equivalent to
;&^                   Takes input and sends the IP up. the ; is a no-op
  :                   Duplicates the input.
  >:*[                Duplicates and multiplies, so that the stack is [N, N^2
     $                Drops the top of the stack, so that the top is N
     ]#;              Turns right, into the loop
         :.           Prints, because we have space and it's nice to do
            1-        Subtracts 1 from N
              :!k@    If (N=0), end the program. This is repeated until N=0
;< $#]#;              This bit is skipped on a loop because of the ;s, which comment out things

The important part here is the  :. 1-:!k@ bit. It's useful because as long as we push the correct complexity onto the stack before executing in a lower time complexity, we can get the desired one. This will be used in the remaining 2 programs in this way.
Try it online!
Doubled
\+]#:\-1vk  !:;#
@k!:-1 .: ;#]#$ <;
[*:>@
&$< ^&;\+]#:\-1vk  !:;#
@k!:-1 .: ;#]#$ <;
[*:>@
&$< ^&;

And the relevant command are:
\+]
  !
  :
&$< ^&;\+]#:\-1vk  !:;#
@k!:-1 .: ;#]#$ <;

This program goes into 2 loops. First, it follows the same path as the normal program, which pushes 1 and N onto the stack, but instead of wrapping around to the second &, the IP jumps over a comment into a loop that pushes 2^N:
        vk!:    If N is 0, go to the next loop.
      -1        Subtract 1 from N
 +  :\          Pulls the 1 up to the top of the stack and doubles it
  ]#            A no-op
\               Pulls N-1 to the top again

The other bits on line 4 are skipped using ;s
After (2^N) is pushed onto the stack, we move down a line into the aforementioned printing loop. Because of the first loop, the time complexity is Θ(N + 2^N), but that reduces to Θ(2^N).
Try it online!
Doubled and Reversed
;&^ <$&
 @>:*[
;< $#]#; :. 1-:!k@
#;:!  kv1-\:#]+\;&^ <$&
 @>:*[
;< $#]#; :. 1-:!k@
#;:!  kv1-\:#]+\

The relevant commands:
;&^

;< $#]#; :. 1-:!k@

 @>:*[

  :

This functions almost identically to the reversed program, but the N^2 is not popped off of the stack, because the first line of the second copy of the program is appended to the last line of the first, meaning that the drop command ($) never gets executed, so we go into the printing loop with N^2 on the top of the stack.
Try it online!

JavaScript (Node.js), 90 bytes
f=n=>n&&f(--n)+f(n);f(t);var t=process.argv[1]//;);--i;]1[vgra.ssecorp:t*t?t=i=t rav(rof"

Try it online!
Trivial


text:
Insist on an answer
At runtime, keep prompting for a line of input until the user inputs something (other than an empty newline), i.e. does not just press Enter or OK. Output or result is neither required nor prohibited.
Pseudo-code 1
myform = new form("GUI")
myform.mytxt = new editfield("")
myform.ok = new button("OK")
repeat
  waitfor(myform.ok,"click")
until myform.mytxt.content <> ""

Pseudo-code 2
LET TEXT = ""
WHILE TEXT = "" DO
  TEXT = PROMPT("")
ENDWHILE

Example 1
Program runs and immediately pops up a form with a single text field and an OK button.
User clicks the OK button.
Nothing happens.
User pastes "hello world" into the text field and clicks the OK button.
Program terminates.
Example 2
Function is called and immediately displays a blank line and a blinking cursor.
User presses Enter.
Cursor moves down one line.
User presses Enter.
Cursor moves down one line.
User presses PPCGEnter
Function returns.

is it allowed to count space-only lines as empty?

@12431234123412341234123 No.

Is it necessary to wait for the full line once the user starts to input data?

Ok, from a comment in @CodyGray's deleted answer it seems like it's not allowed.

@MatteoItalia Yes, correct; a line of input.

TI-BASIC, 2 bytes
:Prompt X

TI-BASIC does this automatically. Once input is given, it will quit.
Here is a GIF:

Watch the count on the enter key in the Key Press History. Created with TI-SmartView CE and ezgif.com.

Hmm.. this is 2 bytes?

TI-BASIC is token based.

And it will not take Enter for an answer? Is there anywhere to test this online?

@Adám It won't take enter for an answer. As far as I am aware, there isn't any place you can go to online without already having a TI ROM image. I can post a .gif when I get home, though.

Great answer, I would have posted it if I had the fastest gun in the west ;)

@Adám It's illegal to test TI-BASIC online without owning a ROM yourself.

Python 3, 18 bytes
while''==input():0

Try it online!

So, you'll keep adding another language every 9 minutes?

JavaScript, 37 22 17 bytes
while(!prompt());

while(!prompt());

Explanation
The while keyword starts the while loop. In the condition of the loop, !prompt() asks for input and checks whether it is given or not. If it isn't given, the body of the loop is executed, which in our case is empty, then the interpreter goes back to the loop condition. The same process happens over and over again until the user gives the input.

while(""==prompt(""));

@Adám Wow. I was just thinking about how to make the solution smaller, and you came up with an answer thanks!

It seemed obvious. However, my browser console refuses to execute without a trailing ;, while your initial expression worked fine without ;. Any idea why?

No, Chrome. So if any JavaScript engine can handle omission of the current expression's ;, you can save that byte :-)

@Adám Just figured out the real cause of the error produced after the removal of semicolon from the source code. The reason why that happens is that while loop expects a statement (or a group of statements) as the loop body after the loop condition. Adding the semicolon makes it think that the loop body is over. However, removing the semicolon causes it to expect the next statement as the loop body. But in our case, no new statements comes after the loop condition. So, it throws an error. I hope it is clear now. I am terrible at explaining stuff!! :p

You know, if you change prompt``  to prompt() it'll work in non-ES6 browsers as well ;-)

@ETHproductions Thanks!

sed, 4
/./q

Waits for a line of input that has 1 or more characters, then quits.
Try it online.  But it works better on a live shell:
sed '/./q'

HTML5, 33 22 bytes
<form><input required>

<form><input required>

Explanation
The required attribute on the <input> causes the browser to inform the user "this field is required"-sort-of-message, if they do not enter a value. However, when they enter a value, the value is sent to the URL of the action attribute of the <form> (which in our case is the current file itself, since we haven't specified any value explicitly).
This was tested on the latest version of Google Chrome (version 55.0). May work in other browsers and versions.

action=/ might work on some browsers.

You could probably ditch the action attribute altogether.

@Arjun The action=y.p isn't necessary, as most User Agents will submit to the same location if no action is specificed

@Arjun I've tried <form><input required> on the latest Google Chrome version and works as intended. And if you're skeptical, just use action=#. That saves 2 bytes.

@Arjun That is a terrible idea for code golfing. I can't say about every browser, since I don't own any Android 1.0, 1.6, 2.0, 2.1, 3.0, 3.1, 4.x.x, 5.x, 6.x, ..., iPhone 2 - 7, every single release of Google Chrome, Firefox 3.0+ and on and on and on and on... In fact, not all HTML5 browsers implement the required attribute! Also, # is a path available since HTML 1.0, if I'm correct. And adding no action to your form is the same as action=".", which is the file itself.

@IsmaelMiguel Realized my mistake, hence implemented what you said. Thanks!

@Shaggy Thanks! I implemented it!

@MayorMonty Thanks! Implemented!

Java, 55 bytes
void f()throws Exception{while(System.in.read()==10);}}

If I remember correctly (it's been a while since I've been active on PPCG), my program can just be a function.
This is system specific; it only works on systems where the end-of-line character is a single newline. If the end-of-line character is instead a carriage return, replace the 10 with 13. On Windows, this doesn't work, as end-of-line on windows is \r\n.
This makes use of the fact that I can read directly from System.in.

Welcome back, if only for this answer! :D

Welcome back @Justin!

Not planning on being active;  just dropping by for a question here and there

To avoid the "doesn't work on Windows" problem, can't you just test the first character and see if it is \r, as opposed to testing the entire string, and then running into problems with there being 2 EOL characters?

@CodyGray No. I'm reading 1 char at a time; that's all that System.in let's you do directly (well, you chan read an array of chars at a time). My loop body (empty) is run for every char in the input

Jelly, 3 bytes
ɠṆ¿

Not much to look at on TIO, I'm afraid.
Try it online!
How it works
This is a niladic program, meaning that it takes no input arguments. The implicit argument and return value are both 0 in this case.
¿ (while) is a quick that pops two links from the link stack: a condition (Ṇ) and a body.
Ṇ is a monadic atom: flat logical NOT. If the previous return value is falsy (here, 0 or an empty string), it returns 1 and the body is called.
ɠ is a niladic atom; it reads a raw line from STDIN and returns the result.
Once ɠ reads a non-empty line, Ṇ returns 0 and we break out of the loop.

That fast, eh? Ah, well.

Pyth, 3 bytes
W!w

Try it online!
Translated to Python:
while Pnot(input()):
 pass

brainfuck, 26 bytes
+[>,----------[[-]<[-]>]<]

Try it online!

That TIO link is all nice and well, but it is a bit hard to tell what happens when run… ;-)

@Adám you can append ,. to the end to verify.

Perl 5, 8+1 (-p or -n flag) bytes
/./&&die

Takes input from stdin and dies as soon as the regex matches anything except a newline.

R, 27 24 23 22 bytes
while(!sum(scan()^0))t

Takes input from stdin, and repeat as long as input is of length 0. Cut off some bytes due to Jarko Dubbeldam and MickyT. Replaced the {} with t to save another byte.

I think you can omit the ,'', since neither input (string or numeric) nor way of terminating was specified in the challenge.

@JarkoDubbeldam: good catch! I didn't realize errors were a valid termination.

would while(!sum(scan()^0)){} work as well?

@MickyT Seems to work. Apparently even Inf^0 is 1. Nice catch with the sum(). Too bad the ^0 is need to handle 0 as input.

@MickyT That's a great find with the use of sum, thanks! I've updated the answer.

Bash, 51 bytes (39 without "#!/bin/bash")
It's my first time participating in PPCG, so dont be to rude ;D
#!/bin/bash
read a
while [ -z "$a" ]
do
read a
done

Welcome to PPCG.

Welcome to PPCG!, if you're planning on using Bash as a golfing language you might find This Post Interesting, it has a bunch of tips for making bash programs as small as humanly possible, there's also a More General Version you might want to skim through too.

@ConnorLSW Wow, thanks, that Post will help me a lot. I'll try to edit my Answer with this new tips ASAP.

you do not need #!/bin/bash

Well, also the first time for me :) But you could perhaps use recursion: [ -z \line` ] && $0or if the deprecatedlineis not on your system:[ -z `head -n1` ] && $0`. That should either be 20 or 24 bytes.

Got rid of the -z too: [ \head -n1` ] || $0(21 bytes) or[ `line` ] || $0` (17 bytes).

For a pure Bash solution, there's while [ ! "$a" ];do read a;done or something similar with recursion.

@Yeti All of these need double quotes or they will fail if the input contains whitespace. You should be able to get rid of the spaces surrounding || though.

One tip- you don't need the first read a, since bash variables that are not set are empty by default.

C, 52 bytes, 33 bytes, 29 bytes
-19 bytes thanks to Justin
-4 bytes thanks to Christoph
main(){while(getchar()==10);}

10 is equal to '\n' - In case this isn't obvious.

You can golf it by 1 char by using a ; instead of the {} for the while loop

Although not standards compliant, you can remove the #include<stdio.h> if you switch to while(getchar()==10): int main(){while(getchar()==10);}.

@Justin main(){while(getchar()==10);} is enough no need for default int.

main(){scanf("%s");} would also work, if space-only lines can count as empty.

Won't this quit if user enters a blank line? Requirement is to check they enter some other characters first.

@DanielEarwicker nope. A blank line is simply a newline character, so this loops in that case

@Justin - It quits as soon as I type something other than enter? That seems non-conforming with Example 2 from the question, where the function returns after typing multiple characters and user hits return.

@DanielEarwicker You are right. That didn't seem clear to me the first time I read the question, but now I see what you are saying. In that case, there are many non-conforming answers to this question.

AWK, 8 11 bytes
NF{exit}

Wait for input. If the number of fields in input is more than 0, exit.
EDIT:
I've just realized that this doesn't work for input containing whitespace characters only. IFS needs to be set to empty string using -F "" command line option. Therefore +3 bytes.
Try it online!

Actually, you could replace NF with 1.  Then you don't need to set IFS. And grumble you beat me to and AWK solution.

@RobertBenson I tried replacing NF with 1. In that case the program exits given any input, including empty newline.

I missed that part of the spec.

QBasic 4.5, 15 bytes
INPUT a$:IF a$=""THEN RUN

Asks for input, then checks if any was given. If not, RUN restarts the program.

Didn't know about the RUN. +1. (That rhymes too; RUN and PLUS ONE :) )

Two things: IF""=a$ saves a byte; but I think to be fully correct you need to use LINE INPUT, because a regular INPUT statement won't accept input containing a comma.

Ruby, 13 bytes
gets until/./

I wish gets took a Regexp argument.

C# (.NET Core), 66 bytes
class C{static void Main(){for(;System.Console.ReadLine()!="";);}}

Try it online!
-6 bytes thanks to raznagul.

You can save 6 bytes by writing System.Console.ReadLIne directly and drop the using-Statement.

A while loop would be the same number of bytes, but methinks a more idiomatic way of writing the code than a for loop.

you can save 24 bytes by writing it as a lambda in the form () => {}

or alternatively, 7 by making it an instance method

Java, 128 126 bytes
2 bytes thanks to Kevin Cruijssen.
import java.util.*;class a{public static void main(String[]a){for(Scanner s=new Scanner(System.in);s.nextLine().isEmpty(););}}

Try it online!

You can golf it by two bytes: Change the while to a for and put the Scanner s=new Scanner(System.in); inside it. And change the .equals("") to .isEmpty().

I'm pretty sure you can remove the import if you inline the use of the scanner; pretty sure leaking a scanner works just fine: while(new java.util.Scanner(System.in).nextLine().isEmpty());

PHP, 18 bytes
while(!readline())

Does it check that the line of text is not empty?

Yes, as soon as the line is not empty readline() returns something else than an empty string. Non empty strings evaluate to true in php - atleast most of them do. "0" seems to be an exception as I just read in the docs. Well I guess my answer is wrong now.

Perl, 15 12 bytes (11 + -n flag)
-3 bytes thanks to manatwork
1/0if$/ne$_

Explanation:
The -n flag places a read loop around the program, turning it into:
LINE:
while (<>) {
    1/0 if $/ ne $_  # Spaces added for clarity.
}

Where "<>" reads a line from stdin to the variable $_. If the line contained more than the ending newline (ne is string inequality, $/ is the input record separator which defaults to newline), a division by zero is performed which causes the program to output an error message and terminate.

Welcome to PPCG. Can you explain your code?

As 3aw5TZetdf suggests in his tip in Tips for golfing in Perl?, “Use $/ instead of "\n"”. And if you reverse the compered terms, you will not need the space.

@user68838 Are you the OP? Did you create a new account to edit this?

Nice one! You should be able to drop this to 9 (7 code + -nl, or just 7 bytes as Perl + -nl) bytes: Try it online!

Mathematica, 26 20 bytes
For[,Input[]==Null,]

Shave off six bytes with For[,Input[]==Null,]. Works just as well.

SpecBAS - 34 bytes
1 DO : INPUT a$: LOOP UNTIL a$<>""

Just loops until non-empty string is entered.

Haskell, 19 17 bytes
f=do""<-getLine;f

Defines a function f that if it reads the empty line calls itself again. When reading a non-empty line an exception is raised and the recursion is stopped.
Edit: @Laikoni replaced the parameter with a pattern match and saved 2 bytes. Thanks!

Didn't think Haskell IO code could be as short as this!

17 bytes: f=do""<-getLine;f

@Laikoni: nice catch. Thanks!

Aceto, 9 5 4 bytes
read a value, negate it (!; implicitly casting to a boolean), and mirror horizontally if the value is truthy (|).
!
r|

Wait, Aceto runs up‽ And they say APL is strange for running from right to left…

@Adám Aceto runs along a 2D Hilbert curve.

Java, 66 64 60 bytes
int a(){return!System.console().readLine().isEmpty()?0:a();}

My first Java answer, would love some tips!

You can probably remove the space between return and !. .equals("") == .isEmpty(). You can return int instead of String. OTOH, return void but either while(System...) or if(System...)a();

you can do int a(){..?0:a();}, saves 3 bytes

@Khaled.K actually 4!

To @Justin and Khaled.K, thank you for your advice!

Pure Bash, 19 bytes
A pure Bash solution using recursion in which a line is read into the variable $a (19 bytes):
read a;[ "$a" ]||$0

Notes
In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

-x
aoeu aoeu aoeu
!

The only thing that breaks it is escaping the newline with \, or using a  character. But how to handle these special characters is not mentioned in the original question.

Do you need the spaces between the brackets?

x86 Assembler (NASM - Linux), 227 bytes
SECTION .bss
i: resb 5

SECTION .text
global  _start

_start:
    mov     edx, 5
    mov     ecx, i
    mov     ebx, 0
    mov     eax, 3
    int     80h
    cmp byte [ecx], 0xa
    je _start
    mov     eax, 1
    int     80h

Well done! Nice first answer

Umm, is this really 227 bytes? Usually we count assembler variants based on the size of the compiled outcome.

Ruby, 8 bytes (7 + '-n' flag)
~/./&&a

Try it online!

ZX81 BASIC, 20 bytes
10 INPUT A$
20 IF NOT LEN A$ THEN RUN

Because ZX81 BASIC is tokenised, NOT LEN A$ is a byte shorter then A$<>"". Program lines count 5 bytes each including the line number.

Why can't you use line numbers 1 and 2?

@Adám Line numbers are stored internally as 16-bit integers, so they don't affect the byte count.

Bash + line, 16 bytes
[ "`line`" ]||$0

Backticks are short for $(), to execute a command. line reads a line. If line is empty, then [ will return false, and thus $0 will be executed - the 0th argument which refers to itself. If there is any non-zero string, [ will return true and because of lazy evaluation $0 won't be executed (|| is a logical OR).
Notes
Instead of line you can also use head -n1, which is more common (but also longer).
In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

-x
aoeu aoeu aoeu
!

The only thing that breaks it is escaping the newline with \, or using a  character. But how to handle these special characters is not mentioned in the original question.

Hi, and welcome to PPCG! This seems like an entirely reasonable answer. Sometimes I like to use multiple headers for posts which have multiple answers like this, e.g. "# bash + line, 16 bytes" … "# pure Bash, 19 bytes", but that's optional. Note that if you have dependencies on an external program or library (like line in this case), it helps to mention that in the header. (Also, I think the last solution might break if the user types something like -x? Not sure on that one.)

Thank you, I updated the answer accordingly. The last solution, somehow it didn't work at all. But now I updated it so that it works. I tested all of them and listed which input I tested for. There exist no special parameters that would break anything to my knowledge.

I'd rather you post each answer separately so people (including me) can vote for specific answers.

They're now separated, however I'm sure you'll upvote all of them anyway :)

Charcoal, 4 bytes
Ｗ¬Ｓω

Explanation
Ｗ      While
  ¬Ｓ   Logical not of string input
     ω  Print ""

05AB1E, 5 bytes
[IõÊ#

Explanation:
[     Start infinite loop
 I    One line of input
   Ê  Not equal to
  õ   Empty string
    # Break if true

Try it online!

These are 5 Unicode code points, not 5 bytes; they are 7 bytes in UTF-8, 10 bytes in UTF-16 or 20 bytes in UTF-32.

@MatteoItalia 05AB1E uses its own encoding, therefore each of these characters are 1 byte.

Uh, sorry, I stand corrected!

PowerShell, 20 Bytes
for(;!(read-host)){}

runs a for loop,
read-host prompts for input
if read-host returns nothing it evals to false, so we invert that !(...) and use that as the loop end check.
much shorter than any do{$a=read-host}while($a-eq"") type solution involving variables.

MATL, 4 bytes
`jn~

This needs to be executed with the MATL interpreter running in Octave (not in Matlab). The reason is that in Matlab, unlike in Octave, the underlying function input('','s') (unevaluated input) interprets an input consisting of only spaces as empty input.
Gif or it didn't happen:

Explanation
`     % Do...while loop
  j   %   Take input as a string
  n   %   Number of elements
  ~   %   Negate. Gives true if number of elements was zero, and false otherwise
      % End loop (implicit). If top of the stack is true: next iteration. Else: Exit

"Gif or it didn't happen" That's the best part!

Swift, 22 bytes
while readLine()==""{}

CJam, 5 bytes
{l!}g

Try it online!
(TIO doesn't really show the proper behaviour)
Explanation
{      e# Do:
 l     e#  Read next line of input
  !    e#  Boolean negate (empty strings are falsy)
   }g  e# Pop the top of stack, if truthy, repeat.

Clojure, 32 bytes
(some seq(repeatedly read-line))

some returns the first true value of (seq x).
seq gives a sequence for a collection (e.g. a String) or nil if the collection is empty.
nil counts as false for some, so it will ignore any empty input, completing when a non-empty string is entered.

x86 machine code on DOS, 13 bytes
00000000  43 b4 01 cd 21 3c 0d 75  f7 4b 74 f4 c3           |C...!<.u.Kt..|
0000000d

Commented assembly:
    org 100h

section .text

    ; notice: on virtually every DOS bx starts at 0 at program start
    ; see http://www.fysnet.net/yourhelp.htm
start:
    inc bx      ; bx counts the number of read characters; increment it
    mov ah,1
    int 21h     ; read a character into al
    cmp al,0dh  ; check if it's a newline
    jne start   ; repeat if it's not
    dec bx      ; got a newline; decrement the counter
    jz start    ; if the counter became 0, it means that we only read the
                ; newline; restart (with bx being 0, as on startup)
    ret         ; otherwise quit

VBScript, 26 bytes
while InputBox("")=""
wend

This one is sort of fun because the only way to stop the programs asking for an answer is either giving one or killing 'wscript.exe' in the task manager.

Red, 20 16 Bytes
until[""<>ask""]

Explanation:
until   does the code that's inside the [blocks] until it's true
<>      checks empty string "" isn't returned by rest of code
ask ""  prompts with "" (empty msg), returns user input

Thanks to @endo64 for the code
-4 bytes thanks to @sqlab

Save 4 bytes by omitting the spaces

APL (Dyalog Unicode), 10 bytes
Doesn't seem to work in TIO, works for me in Dyalog APL 18.0
{0=≢⍞:∇0}0

Try it online!

{⍞}⍣≢'' should do the trick.

Acc!!, 33 bytes
N
Count i while _/10*(10/_) {
N
}

(Don't) Try it online!
Explanation
N reads a character into the accumulator. If it is 10 (newline), we want to halt, otherwise keep looping. The loop condition _/10*(10/_) accomplishes this: _/10 is 0 if _ is less than 10, and 10/_ is 0 if _ is greater than 10. The only way their product can be truthy (nonzero) is if _ is exactly 10.
If the input is guaranteed to be printable ASCII (and not contain, for example, the tab character), the loop condition could be 10/_ for -7 bytes.

REXX, 24 bytes
do until n>''
  pull n
end

Tcl, 26
while {![gets stdin t]} {}

demo

Excel VBA 25 bytes
while Inputbox(0)="":wend

You can run it via immediate window. It's  a simple while loop with inputbox.

Pure Bash, 21 bytes
A pure Bash solution using shift and recursion with parameter (21 bytes):
shift||(read a;$0 $a)

shift shifts the arguments (and defaults to shifting 1). Which fails if there is no argument, upon which it will try to execute itself again with the next read line as the first argument.
Note that double quotes are here not needed if the line contains spaces, because it does not matter if it's just one word or multiple.
Notes
In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

-x
aoeu aoeu aoeu
!

The only thing that breaks it is escaping the newline with \, or using a  character. But how to handle these special characters is not mentioned in the original question.

Bash + line, 16 bytes
Another approach using recursion with parameter (16 bytes), using shift:
shift||$0 `line`

shift shifts the arguments (and defaults to shifting 1). Which fails if there is no argument, upon which it will try to execute itself again with the next read line as the first argument.
Notes
Instead of line you can also use head -n1, which is more common (but also longer).
In all cases I tested for empty lines, which behaves accordingly. And the following special inputs that may break the behavior (but did not ;) ):

-x
aoeu aoeu aoeu
!

The only thing that breaks it is escaping the newline with \, or using a  character. But how to handle these special characters is not mentioned in the original question.

Pyke, 2 bytes
W!

Try it online!
See the debug output to show it's actually reading input
W  - do v
 ! -  not(input())
   - while ^

Javascript, 17 bytes
for(;!prompt(););

A for alternative to the while answer already here

Mathematica, 20 bytes
While[Input[]==Null]

C#, 36 bytes
_=>while(System.Console.Read()==13);

Compiles to a Action<int>.
Or if a full program is required, 62 bytes.
class P{static void Main(){while(System.Console.Read()==13);}}

Batch, 35 bytes
@set s=
@set/ps=
@if "%s%"=="" %0

Rather unfortunately, Batch doesn't clear the variable if you don't enter anything.

I guess this crashes if %s% == "

@SteveFest Indeed, but it still stops insisting on an answer... you can probably crash-resist it by using %s:"=""%.

It would make a error message without the replace... Which is unnecessary

Kotlin, 38 35 29 bytes
-3 bytes by negating any() rather than calling isEmpty()
-6 bytes thanks to Adám pointing out the function doesn't need to be named to be called
{while(!readLine()!!.any());}

called like so:
{while(!readLine()!!.any());}()

Try it online!

Something wrong with your TIO link.

You just have to click the click here link to remove the message about TIO v2

In that case you could just link to https://tio.run/nexus, but why not fill in the necessary fields on https://tio.run/nexus/kotlin and get the full URL (hint: press Esc, S)?

@Adám Updated the link to use tio.run/nexus, never used TIO before :)

Nice. I think you only have to count the 29 char brace, as the function does not need to be named in order to be called.

Lithp, 90 bytes
((import readline)(readline "?" #A::((f A)))(def f #A::(if(== "" A)((readline "?"(get f/1)

Try it online! (Also works on command line in node)
A side effect of the current parser is that not all trailing ) brackets are required. The very last one is, but the rest can be omitted saving quite a few bytes.
The readline module works in browser and via command line, and uses a callback. We exploit this to call readline before defining f, and save many bytes not needed all the closing brackets to invoke f after it's defined.

AHK, 19 bytes
While !a
InputBox,a

Not very interesting, I'm afraid.

C, 83 bytes
e(char*t){*t>32?1+e(t+1):0;}
f(){size_t l;char*t;getline(&t,&l,stdin)+1&&e(t)&&f();}

The above answer will read full lines, and check if the read line has content beside spaces\tabs.
shorter non-conforming version, 23 bytes
f(){getchar()-10?:f();}

Java, 79 bytes
boolean f(){System.console().readLine().replaceAll("\\t| ","").isEmpty()&&f();}

The above answer will read full lines, and check if the read line has content beside spaces\tabs.
shorter non-conforming version, 38 bytes
void f(){if(System.in.read()==10)f();}

C, 31 Bytes
p[99];main(){for(;!*gets(p););}
Try it online

QBIC, 7 5 bytes
≈A|_?

Saved 2 bytes because empty string is falsy.
Explanation:
≈ |     WHILE <condition>
 A      A$ gets set by _? below. Empty string is false, so it stays in the WHILE
   _?   Ask the user for input, implicitly assign to A$

Ruby, 19 bytes
while gets==?\n;end

Scala, 21 bytes
while(readLine==""){}

Scala can run code as a script without the need for a class/main method so this is a complete program.
readLine is deprecated since Scala 2.11 but it's still available in 2.12

QBasic, 34 bytes
INPUT A$
WHILE A$=""
INPUT A$
WEND

I think nothing can be more self-explanatory than that. To test, go to this website and copy-paste the following code in their text-editor :
10 INPUT A$
20 WHILE A$=""
30 INPUT A$
40 WEND

The reason why line numbers are required is that their website only supports unstructured BASIC.

Why the final END?

@Adám The final END is required to terminate the program when the interpreter comes out of the while loop (WEND is to terminate While Loop)

So what happens if there is no more program to execute, even though END hasn't been reached?

@Adám According to the standard,  a program must have an END statement as the last statement. However, many interpreters don't require it. But I will keep it just for the sake of compatibility.

This has been discussed on Meta, concluding that a language is defined by its implementation, not its documentation.

As long as you're relying on implementation-specific behavior (which, BTW, I think is absurd), you can eliminate the first line of code, too. It works on the "Simple Basic Interpreter" website you linked to!

A safer way would be to rewrite it as a DO loop that tests the condition at the bottom of the loop, instead of the top. For example: DO|INPUT A$|LOOP WHILE A% = "" (where | means a new line). That would be 30 bytes, still more than the 25-byte "unsafe" method I proposed, but it would at least be correct code. If you left out the spaces around the equals sign(s), you could golf it down even further, but I'm not sure if that's legal, since any QBasic interpreter will add those spaces back in automatically.

Python 3, 26 bytes
a=""
while not a:a=input()

Try it online!

Batch 31 bytes
@Set $=&Set/p$=&Set $ 2>nul||%0

APOL, 7 bytes
w(!(i))
This simply repeats until i returns a non-empty string.

Pip, 4 bytes
T#q0

Replit! (Leave command-line arguments blank; when prompted to enter your program, type T#q0 followed by a newline and Ctrl-D.)
Explanation
T     Loop till
 #     length of
  q    read a line of stdin
      is truthy (nonzero):
   0   No-op

The shorter Tq0 doesn't work because an input like 0 will still be falsey and fail to terminate the loop.