text:
Circle intersection area
Description :
Given x and y positions of two circles along with their radii, output the area of intersection of the two circle.

Input :
You will be given following input :
array 1 = x and y positions of circle a
array 2 = x and y positions of circle b
radius  = radii of the two congruent circles

Input method :
([12 , 20] , [20 , 18] , 12)     ---> two array and number
([12 , 20 , 20 , 18] , 12)       ---> array and a number
(12 , 20 , 20 , 18 , 12)         ---> all five numbers
('12 20' , '20 18' , 12)         ---> 2 strings and a number
('12 20 20 18' , 12)             ---> string and a number
('12 20 20 18 12')               ---> one string

Output :

A non-negative integer (no decimal) equal to area of intersection of two circles.

A string equal to the above mentioned integer.

Note :

Output must be >= 0, since area can't be negative.
In case of decimal round down to nearest integer

Examples :
([0, 0], [7, 0], 5)                   ---> 14

([0, 0], [0, 10], 10)                 ---> 122

([5, 6], [5, 6], 3)                   ---> 28

([-5, 0], [5, 0], 3)                  ---> 0

([10, 20], [-5, -15], 20)             ---> 15

([-7, 13], [-25, -5], 17)             ---> 132

([-12, 20], [43, -49], 23)            ---> 0

Winning criteria :
This is code-golf so shortest code in bytes for each language wins.

Suggestions :

Provide a TIO link so it can be tested.
Provide an explanation so others can understand your code

These are only suggestions and are not mandatory.

Ravioli, ravioli...

@FrownyFrog: Excuse me ? I am not aware of what you are talking about? nvm check on internet and I am sorry to report that is part of the problem. see the tag that says math and geometry. It is a good excuse to brush up on your math. What do you think. But if you disagree I think I will update the question and add formula.

@MuhammadSalman Change answer must be positive to answer must be >= 0 - If the circles don't intersect (as in examples 4, 7, 10) then the correct answer is 0, which last I checked is not positive.

@manassehkatz : Ok , sure. Done

JavaScript (ES6), 72 bytes
Alternate formula suggested by @ceilingcat
Takes input as 5 distinct parameters (x0, y0, x1, y1, r).
with(Math)f=(x,y,X,Y,r)=>-(sin(d=2*acos(hypot(x-X,y-Y)/r/2))-d)*r*r*2>>1

Try it online!

JavaScript (ES7), 81 80 77 bytes
Saved 3 bytes thanks to @Neil
Takes input as 5 distinct parameters (x0, y0, x1, y1, r).
(x,y,X,Y,r,d=Math.hypot(x-X,y-Y))=>(r*=2)*r*Math.acos(d/r)-d*(r*r-d*d)**.5>>1

Try it online!
How?
This is based on a generic formula from MathWorld for non-congruent circles:
A = r².arccos((d² + r² - R²) / 2dr) +
    R².arccos((d² + R² - r²) / 2dR) -
    sqrt((-d + r + R)(d + r - R)(d -r + R)(d + r + R)) / 2

where d is the distance between the two centers and r and R are the radii.
With R = r, this is simplified to:
A = 2r².arccos(d / 2r) + d.sqrt((2r - d) * (2r + d)) / 2

And with r' = 2r:
A = (r'².arccos(d / r') + d.sqrt(r'² - d²)) / 2

Note: If d is greater than 2r, Math.acos() will return NaN, which is coerced to 0 when the right-shift is applied. This is the expected result, because d > 2r means that there's no intersection at all.

d*(r*r-d*d)**.5 saves 3 bytes.

@ceilingcat Thanks! Using with(Math) and moving the definition of d saves 2 more bytes.

Mathematica 66 57 51 bytes
Floor@Area@RegionIntersection[#~Disk~#3,#2~Disk~#3]&

A Disk[{x,y},r]refers to the region circumscribed by the circle centered at {x,y} with a radius of r.
RegionIntersection[a,b] returns the intersection of regions a, b.
Area takes the area.
IntegerPart rounds down to the nearest integer.

For the record, I didn't see alephalpha's submission as I was doing my own.   His is a shorter (hence a more successful) entry, but I left mine in anyway.

You could replace IntegerPart with Floor.

@mathe,  Thanks.  If I use the dedicated Floor brackets, do you know how I am to count the bytes?

@DavidC each one is 3 bytes, so the substitution is neutral in this case for byte count. They're useful if the expression would otherwise need parenthesizing, though (-1 byte compared to Floor[ ]).

Jelly,  27 25 24  22 bytes
×,²I½
÷ÆA×²}_çHḞ
ạ/çḤ}

A full program accepting a list of the two centres as complex co-ordinates and the radius which prints the result (as a dyadic link it returns a list of length 1).
Try it online!
To take the two co-ordinates as pairs add Uḅı to the main link, like this.
How?
×,²I½ - Link 1, get [√(s²d² - s⁴)]: separation of centres, s; diameter, d
 ,    - pair = [s, d]
×     - multiply (vectorises) = [s², sd]
  ²   - square (vectorises) = [s⁴, s²d²]
   I  - incremental differences = [s²d² - s⁴]
    ½ - square root (vectorises) = [√(s²d² - s⁴)]

÷ÆA×²}_çHḞ - Link 2, get intersection area: separation of centres, s; diameter, d
÷          - divide = s/d
 ÆA        - arccos = acos(s/d)
    ²}     - square right = d²
   ×       - multiply = acos(s/d)d²
       ç   - call last Link (1) as a dyad (f(s,d)) = [√(s²d² - s⁴)]
      _    - subtract (vectorises) = [acos(s/d)d² - √(s²d² - s⁴)]
        H  - halve (vectorises) = [(acos(s/d)d² - √(s²d² - s⁴))/2]
         Ḟ - floor = [⌊(acos(s/d)d² - √(s²d² - s⁴))/2⌋]
           -  ...Note: Jelly's Ḟ takes the real part of a complex input so when
           -           the circles are non-overlapping the result is 0 as required

ạ/çḤ} - Main link: centres, a pair of complex numbers, c; radius, r
 /    - reduce c by:
ạ     -   absolute difference = separation of centres, s
      -   ...Note: Jelly's ạ finds the Euclidean distance when inputs are complex
      -            i.e. the norm of the difference
   Ḥ} - double right = 2r = diameter, d
  ç   - call last Link (2) as a dyad (f(s,d))
      - implicit print

numbers only. And what is that [-7+13j,-25+-5j] ? I don't have that example. You might have to explain what you did ?

I explained it in the answer already... they are co-ordinates on the complex plane... I can do [[x1,y1],[x2,y2]] instead but it costs 3 bytes. (Note also that -7+13j is a number :)) -- the  [-7+13j,-25+-5j] corresponds to the example that returns 132, [-7, 13], [-25, -5], 17

I don't know Jelly so I am lost on that. Also I sent the message before the explanation.  But yeah , sure this works (I guess?)

It's nothing to do with Jelly per-se, it's just mathematics. A point in 2-space is the same as a complex number.

Not what I meant. Normal languages I would be able to read and tell what is going on. Jelly and other such languages are a pain to read.

...there will be an explanation when I am done :)

Well I will read it and hopefully learn a thing or two about it.

Wolfram Language (Mathematica), 50 bytes
Floor@Area@RegionIntersection[#~Disk~#3,Disk@##2]&

Try it online!

+1 Floor.  Of course!

C (gcc), 83 79 71 66 bytes
f(a,b,c,d,e){float g=cacos(hypot(a-c,b-d)/e/2)*2;e*=(g-sin(g))*e;}

Try it online!

Python 3, 106 chars with centers given as lists
from numpy import*
def f(a,b,r):d=min(1,hypot(*subtract(b,a))/2/r);return(arccos(d)-d*(1-d*d)**.5)*r*r//.5

100 chars with center coords separately
from math import*
def f(a,b,A,B,r):d=min(1,hypot(A-a,B-b)/2/r);return(acos(d)-d*(1-d*d)**.5)*r*r//.5

Haskell, 83 bytes
(k!l)m n r|d<-sqrt$(k-m)^2+(l-n)^2=floor$2*r^2*acos(d/2/r)-d/2*sqrt(4*r*r-d*d)::Int

Just the formula, really. Type has to be declared as Int for NaN to map to 0 with floor.
Try it online!

alternate formula

JavaScript (Node.js), 69 bytes
with(Math)f=(a,b,c,d,r)=>(-sin(x=2*acos(hypot(a-c,b-d)/2/r))+x)*r*r|0

Try it online!
Short not sure if it can be golfed any further. Any suggestions are welcome

Perl 6, 56 bytes
{{1>$_&&{$_-.sin}(2*.acos)}(abs($^p-$^q)/2/$^r)*$r²+|0}

Try it online!
Takes circle coordinates as complex numbers.

Excel, 119 bytes
=INT(IFERROR(2*E1^2*ACOS(((C1-A1)^2+(D1-B1)^2)^.5/2/E1)-((4*E1^2-((C1-A1)^2+(D1-B1)^2))*((C1-A1)^2+(D1-B1)^2))^.5/2,0))

Input taken as 5 separate variables:
x-coordinate    y-coordinate    x-coordinate    y-coordinate    radius
     A1              B1             C1                D1          E1

Python 2, 109 bytes
from math import*
a,b,x,y,r=input()
d,R=hypot(x-a,y-b),2*r
print int(d<R and R*r*acos(d/R)-d*sqrt(R*R-d*d)/2)

Try it online!
Pretty straightforward. Get the distance between circles, and use R=2r as a substituite in the equation. d<R and to short-circuit if circles don't overlap.

Pyth, 63 bytes
J@+^-hhQh@Q1 2^-ehQe@Q1 2 2K*2eQs&<JK-**KeQ.tcJK4c*J@-*KK*JJ2 2

Test suite
Takes input as a triple consisting of two doubles and a number.

T-SQL, 122 bytes
SELECT FLOOR(Geometry::Parse('POINT'+a).STBuffer(r).STIntersection(
             Geometry::Parse('POINT'+b).STBuffer(r)).STArea())FROM t

(line break for readability only).
Uses MS SQL's support of spatial geometry.
Per our IO standards, SQL can take input from a pre-existing table t with int field r and varchar fields
a and b containing coordinates in the format (x y).
My statement parses the coordinates as POINT geometry objects expanded by the radius using the function STBuffer(), then taking the STIntersection() followed by the STArea().
If I am allowed to input the actual geometry objects in the table instead, then my code becomes almost trivial (48 bytes):
SELECT FLOOR(a.STIntersection(b).STArea())FROM t


text:
Seats in a Finnish cinema
You're given the map of a cinema theatre as a boolean matrix: 0 represents a free seat, 1 - occupied. Each Finn who walks in chooses the seat farthest away (Euclidean distance) from the nearest occupied one, or if several such exist - the first among them in row-major order. Output a matrix showing the order seats will eventually be occupied in; that is, replace the 0s with 2, 3, 4, etc
// in
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
// out
 2  8  3  9  1
10  5 11  6 12
 4 13 14 15  7
16 17  1  1 18

// in
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
// out
  5  43  17  44  45  46  18  47   8  48  49   6  50  19  51   2
 52  24  53  54   1  55  56  25  57  26  58  59  27  60  28  61
 20  62  63  29  64  65   1  66  30  67  68  21  69   9  70  71
 72  73   1  74  31  75  76  77  78   1  79  80  32  81  82  11
 12  83  84   1  85  86  87  13  88  89  90  14  91  92  33  93
 94  34  95  96  97  15  98  99  35 100  36 101 102   1 103  22
104 105  37 106  38 107  39 108 109  16 110  40 111 112  41 113
  4 114 115   7 116  23 117   3 118 119  42 120   1 121 122  10

// in
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// out
  2  38 39  26  40   6 41  42  12  43  44   7  45  46  27  47   3
 48  49 15  50  28  51 52  29  53  30  54  55  56  16  57  31  58
 32  59 60  33  61  62 17  63  64  65  18  66  67  68  34  69  35
 70  10 71  72  13  73 74  75   1  76  77  78  11  79  80  14  81
 82  83 36  84  85  86 21  87  88  89  22  90  91  37  92  93  94
 19  95 96  97  23  98 99 100  24 101 102 103  25 104 105 106  20
107 108  4 109 110 111  8 112 113 114   9 115 116 117   5 118 119

I/O format is flexible within the established code golfing norms for your language. You can assume the input is correct, of size at least 3x3, and doesn't consist entirely of the same boolean value. Write a function or a complete program. The shortest solution per language is considered the winner; no answer will be accepted. Standard loopholes are forbidden.

Unless people are clambering over seats, I think Manhattan distance would be a more accurate metric :P

@Mego As an antisocial person, I can confirm that I would rather sit two seats to the side or two seats behind someone rather than diagonally one seat behind and to the side.

@Mego personal space is calculated with euclidean distance :)

@Pavel Asocial, not antisocial?

@Chromatix Nope. I want society to burn. :P

@Pavel infernosocial :)

@ngn "Pyrosocial".  ("Infernus" means "lower regions", "Pyr" means "fire"...)

@Chronocidal You sound right. Great username, by the way.

@ngn looking for social distancing algorithms before it was cool. ;)

MATL, 37 bytes
!t~z:Q"@yX:gG&n:!J*w:+X:&-|w/X<&X>(]!

Try it online! Or verify all test cases. You may also want to see the cinema being filled up in ASCII art.
Explanation
!t        % Implicit input: M×N matrix of zeros and ones. Transpose and duplicate.
          % The transpose is needed because MATL uses column-major (not row-major)
          % order. It will be undone at the end
~z        % Number of zeros, say Z
:Q        % Range, add 1 element-wise: gives the array [2, 3, ..., Z+1]. These are
          % the new values that will be written into the matrix
"         % For each k in that array
  @       %   Push k. Will be written in a position to be determined
  y       %   Duplicate from below: pushes a copy of the current matrix, that has
          %   values up to k-1 already written in
  X:      %   Linearize into an (R*C)×1 vector, in column-major order
  g       %   Convert to logical: this replaces non-zero values by 1
  G&n     %   Push input size as two separate numbers: M, N
  :!      %   Range, transpose: gives the column vector [1; 2; ...; N]
  J*      %   Multiply by imaginary unit, 1j, element-wise
  w:      %   Swap, range: gives the row vector [1, 2, ..., M]
  +       %   Add, with broadcast. Gives an N×M complex matrix defining a grid of
          %   coordinates: [1+1j, ..., M+1j; 2+1j, ... 2+1j; ...; N+1j, ..., N+Mj]
  X:      %   Linearize into an (M*N)×1 vector, in column-major order
  &-|     %   (M*N)×(M*N) matrix of absolute differences. This gives all distances
          %   between seats. Rows of this matrix represent currently used seats,
          %   and columns correspond to potential new positions
  w/      %   Swap, divide with broadcast. This divides the rows representing
          %   occupied seats by 1, and those with unocuppied seats by 0. So the
          %   latter rows are set to infinity, which effectively removes them for
          %   the subsequent minimization
  X<      %   Mimimum of each column: this gives the minimum distance to currently
          %   occupied seats for each potential new seat
  &X>     %   Argument maximum: gives the index of the first maximizing value
  (       %   Write value k at that position, using linear indexing
]         % End
!         % Transpose. Implicit display

JavaScript (ES6), 156 137 bytes
Saved 18 bytes thanks to @l4m2
That's quite a lot of map() ...
f=(a,n=1)=>a.map(B=(r,y)=>r.map((_,x)=>a.map(b=q=>q.map(v=>b=b<(d=X*X--+Y*Y)|!v?b:d,X=x)&Y--,Y=y)|v|b<=B||(R=r,C=x,B=b)))|B?f(a,R[C]=++n):a

Try it online!
Commented
f = (a, n = 1) =>               // a = input array; n = seat counter
  a.map(B =                     // initialize B to a non-numeric value
    (r, y) =>                   // for each row r at position y in a[]:
    r.map((_, x) =>             //   for each target seat at position x in r[]:
      a.map(b =                 //     initialize b to a non-numeric value
        q =>                    //     for each row q in a[]:
        q.map(v =>              //       for each reference seat v in q[]:
          b = b < (             //         if b is less than d, defined as
            d = X * X-- + Y * Y //           the square of the Euclidean distance
          ) | !v ?              //           or the reference seat is empty
            b                   //             let b unchanged
          :                     //           else:
            d,                  //             update b to d
          X = x                 //         start with X = x
        ) & Y--,                //       end of q.map(); decrement Y
        Y = y                   //       start with Y = y
      ) |                       //     end of inner a.map()
      b <= B ||                 //     unless b is less than or equal to B,
      (R = r, C = x, B = b)     //     update B to b and save this position in (R, C)
    )                           //   end of r.map()
  ) | B ?                       // end of outer a.map(); if B was updated:
    f(a, R[C] = ++n)            //   update the best target seat and do a recursive call
  :                             // else:
    a                           //   stop recursion and return a[]

Try it online!

b=b<(d=X*X--+Y*Y)|!v?b:d

v|b<=B v| is unnecessary cuz if v then b=0

Haskell, 216 213 185 184 bytes
import Data.Array
m a=[snd$maximum a|a/=[]]
f k=k//m[(r,((a,b),maximum(elems k)+1::Int))|s<-[assocs k],((a,b),0)<-s,r<-[minimum[(x-a)^2+(y-b)^2|((x,y),i)<-s,i>0]]]
(until=<<((==)=<<))f

Takes the input as an array. Input and output are in reverse order. Credit for fixed point magic to Laikoni.
Try it online!

180 bytes with until((==)=<<f)f

Python 2, 200 187 bytes
a=input()
z=len(a[0]);P=[divmod(i,z)for i in range(len(a)*z)];i=2
while 0in sum(a,[]):t,y,x=max((min((u-U)**2+(v-V)**2for V,U in P if a[V][U]),-v,-u)for v,u in P);a[-y][-x]=i;i+=1
print a

Try it online!
-13 bytes thx to a tip from Not that Charles by removing unneeded check for cells being 0.

I have nearly the same solution, but Python3, a function, and 194 bytes

Instead of posting mine, the main savings is that I add ,v,u to the end of the generator inside max, and you don't need to do if a[v][u]<1 since those will be 0 and therefore not max.  So my line is basically *_,y,x=max((min(...),-v,-u,v,u)for v,u in P)

amazingly similar code, though.  wow.

honestly, i'm not sure adding the *,v,u characters ISN'T a saving vs. the -- you have. :)

@Not that Charles: Nice, totally missed that the if a[v][u]<1 is redundant (since non-zero cells will have a min() of 0).

J, 74 70 60 bytes
(+(1+>./@,)*i.@$(=]i.>./)*<./@(#|@-/])&,j./&i./@$)^:(1#.0=,)

Try it online!

APL (Dyalog), 39 bytes
Thanks Cows quack for saving one byte, and ngn for saving another
1⌈2-≢∘⍸-⍴⍴∘⍋⍸∘~{⍵∪⍺[⊃⍒⌊/+.×⍨¨⍺∘.-⍵]}⍣≡⍸

Try it online!

Jelly, 43 bytes
,¬J;Ð€"T€Ẏ©Ʋ€ạ²Sɗþ/Ṃ€MḢị®⁸⁸ẎṀ‘¤ṛ¦€Ḣ}¦µẎċ0Ɗ¡

Try it online!

APL (Dyalog Unicode), 44 bytes
{×⍵:⍵⋄≢∪∊⍺}@1@{q=⌈/,q←⌊⌿+.×⍨¨(⍸×⍵)∘.-⍳⍴⍵}⍨⍣≡

Try it online!
Alternate solution at 44 bytes
{≢∪∊⍺}@1@{q=⌈/,q←⌊⌿+.×⍨¨(⍸×⍵)∘.-⍳⍴⍵}⍨⍣(~0∊⊣)

Wolfram Language (Mathematica), 121 bytes
Nest[p=Position;ReplacePart[#,#&@@Pick[a=#~p~0,m=Min/@DistanceMatrix[a,N@p[#,x_/;x>0]],Max@m]->Max@#+1]&,#,Total[1-#,2]]&

Try it online!

Jelly, 35 33 30 29 bytes
ZJæịþJFạþx¥F«/MḢṬ×FṀ‘Ɗo@FṁµÐL

Try it online!
Replaced the ×ı+ with æị (complex combine), a new dyad based on j. from J, saving a byte.
Here is a more efficient version for TIO. Try it online!
Explanation
ZJæịþJFạþx¥F«/MḢṬ×FṀ‘Ɗo@FṁµÐL  Input: matrix M
Z                              Transpose
 J                             Enumerate indices - Get [1 .. # columns]
     J                         Enumerate indices - Get [1 .. # rows]
  æịþ                          Outer product using complex combine
                                 (multiply RHS by 1j and add to LHS)
      F                        Flatten
           F                   Flatten input
          ¥                    Dyadic chain
         x                       Times - Repeat each of LHS by each of RHS
       ạþ                        Outer product using absolute difference
            «/                 Reduce by minimum
              M                Indices of maximal values
               Ḣ               Head
                Ṭ              Untruth - Return a Boolean array with 1's at the indices
                 ×             Times
                     Ɗ         Monadic chain
                  F              Flatten input
                   Ṁ             Maximum
                    ‘            Increment
                      o@       Logical OR
                        F      Flatten input
                         ṁ     Mold - Reshape to match the input
                          µÐL  Repeat until result converges

Clojure, 247 bytes
#(let[R(range(count %))C(range(count(% 0)))](loop[M % s 2](if-let[c(ffirst(sort-by last(for[x R y C :when(=((M x)y)0)][[x y](-(nth(sort(for[i R j C :when(>((M i)j)0)](+(*(- i x)(- i x))(*(- j y)(- j y)))))0))])))](recur(assoc-in M c s)(inc s))M)))

Input is a vec-of-vecs M, which is modified in a loop by assoc-in. When no free spot is found (if-let) then the result is returned.

K (ngn/k), 81 75 73 72 70 bytes
{(~&/,/){a[*>A*&/+/''b*b:i[&~A:~a]-/:\:i:+!n:(#x;#*x)]:#?a:,/x;n#a}/x}

Try it online!

source: Stack Exchange

license: 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/

sort: votes


text:
Pristine and Unique Code Bowling
Your challenge is simple: write as long of a pristine program as possible in the language of your choice using only unique bytes. (The full definition of a pristine program, copied from that link, is at the bottom of this question.)
That's right, no strings attached. Your code doesn't have to do anything at all, just run without erroring, meet the requirements for a pristine program (linked above), and include no duplicate bytes in the encoding you use.
For the purposes of the above explanation and linked definition of "pristine program", an error is defined as anything that causes the program to either entirely fail to run or to terminate with a nonzero exit code after a finite amount of time.
As this is code-bowling, longest, not shortest, code wins (measured by byte count). The maximum theoretically possible score is 256, as there are 256 distinct bytes possible. In case of a tie, the first answer at the highest score wins.

Here's the full definition of a pristine program, copied from the above link:

Let's define a pristine program as a program that does not have any errors itself but will error if you modify it by removing any contiguous substring of N characters, where 1 <= N < program length.
For example, the three character Python 2 program
`8`

is a pristine program because all the programs resulting from removing substrings of length 1 cause errors (syntax errors in fact, but any type of error will do):
8`
``
`8

and also all the programs resulting from removing substrings of length 2 cause errors:
`
`

If, for example,  `8 had been a non-erroring program then `8` would not be pristine because all the results of substring removal must error.

Hats off to you for managing to create a good [tag:code-bowling] challenge!

If a subprogram runs forever but does not error does that make the answer invalid?

@dylnan "an error is defined as [...] terminate [...] after a finite amount of time."

I would do great if this was code-golf instead!

is '8' allowed? ' isn't unique...

@Baldrickk No, it wouldn't be allowed for this challenge. (If you're referring to the example in the question, it's a demonstration of what a pristine program is, but which doesn't meet the additional requirement of unique bytes.)

Are pristine functions allowed? In other words, does this intentionally deviate from the default for code golf? I recognize that this isn't code golf, but I think [tag:restricted-source] gives similar motivations for deciding which structure to use.

@KamilDrakari I can think of arguments both ways, but I don't think I want to allow them for this challenge.

Nice choosing a question ID with unique digits (though not pristine ;-) )

Can we count undefined behavior as an error if in practice it usually results in an error? I'm thinking of something like JMP <address outside of the program's memory> in assembly. In principle on a real computer it could loop infinitely or exit with a non-zero error, but it will usually crash spectacularly.

@Chris It's a bit of a borderline case, but I'll allow it.

Jelly, 253 254 256 bytes
M“¢£¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#%&'()*+,-./0145689:;<=>?@ABCDEFGHIJKNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż”L»«’Ɗạ‘}237$¤¡

Try it online! or Verify it!
Turns out golfing languages can bowl...

+1 byte by working in ‘. Now only «» are not used
+2 bytes with with «». Now have the optimal score!

How?
The crucial feature of Jelly that makes this possible is that the opening and closing characters for string literals are not the same like in nearly all other languages.
The program structure is as follows:
M <239 character long string> L»«’Ɗạ‘}237$¤¡
M finds the indices of its argument that point to maximal elements. All that matters is that with no argument to this program Jelly assigns 0 to the chain and Jelly errors when M is applied to 0.
To prevent M from acting on 0 in the full program, we use the ¡ quick, which applies M a number of times determined by the result of the link immediately preceding it. In this case that link is <239 character long string> L»«’Ɗạ‘}237$¤.
L takes the length of this string (239), and »«’Ɗ decrements this to 238. The »« part doesn't do anything but Ɗ (last three links as a monad) makes it so that if they are deleted an error will occur. Then ạ takes the absolute difference between the result of »«’Ɗ and the monad ‘}237$ applied to the string. ‘ increments and is a monad, but the } turns this into a dyad and applies it to it's right argument, 237, yielding 238. Thus ạ yields 0 in the full program.
¤ links back to the string literal forming a nilad. The result of this is 0, so M is not applied at all, preventing any error.
Possible subprograms:

If any part of the string is removed, <string>..¤ will be nonzero and M gets applied to 0, causing an error.
If any part of L»«’Ɗạ‘}237$ is removed either M will get applied to 0 or there will be operations between the string and a number, resulting in a TypeError.
If any of ¤¡ is removed, M gets applied to 0.
If the string closing character ” and both of ’‘ get removed and “ doesn't, everything after M turns into a string so M will act on 0.

If the string closing character ” and ’ get removed and “ doesn't, everything between ” and ‘ turns into a list of integers.

If M alone is removed there is a an EOFError because ¡ expects a link before the preceding nilad.
If M“ and any number of characters after it is removed, there will be an EOFError because the ¤ looks for a nilad preceding it but doesn't find one. 238 doesn't count because it is part of a monad.

This pretty much covers everything.
I previously hadn't used «»‘ because the latter two cannot be included in the string because they match the “ character to form things other than strings. « can't be in a “” string either but I don't know why.

Haskell, 39 45 50 52 60 bytes
main=do{(\	陸 ⵙ商ߜ 新->pure fst)LT
EQ[]3
2$1}

Identifier main has to have type IO a for some type a. When the program is executed, the computation main is performed, and its result is discarded. In this case its type is IO ((a,b)->a).
The result is an application of the function (λ a b c d e f → return fst),
a six-argument constant function returning the function fst (which gives the first element of a 2-tuple), injected into the IO monad. The six arguments are LT (enum for less than), EQ (enum for equality), empty list [], 3, 2 and 1.
What would be spaces are replaced with unique characters that count as spaces: a tab, a non-breaking space, a formfeed, vertical tab, OGHAM SPACE MARK, regular space, newline and carriage return. If any of these are missing, there will be a mismatch in the number of arguments. The parameter names are chosen as three or four byte UTF-8 characters, 陸ⵙ商ߜ新, carefully choosing characters that don't result in duplicate bytes.
Thanks to @BMO for his valuable contributions.
Hex dump:
00000000: 6d61 696e 3d64 6f7b 285c f0a4 b6b8 09ef  main=do{(\......
00000010: a793 c2a0 e2b5 990c e595 860b df9c e19a  ................
00000020: 80e6 96b0 2d3e 7075 7265 2066 7374 294c  ....->pure fst)L
00000030: 540a 4551 5b5d 330d 3224 317d            T.EQ[]3.2$1}

Try it online!

Hm, '\109999' seems to be valid, at least in GHC 8.2.2. '\10999a' produces a lexical error.

@chepner: I just tested with GHC 8.2.2 and `` produces a lexical error as well.

@chepner: largest Char is maxBound :: Char, i.e. '\1114111'. Note: numbers are decimal by default, so if you want hex, you have to put an x after the \ , e.g. '\x10999a'.

@nimi Aaaand I think we've established how often I actually use Unicode escapes :) Using the correct form for hex values, \x10ffff works fine, and \x110000 provides an out-of-range error as one would expect.

Python 2,  20 21 33 39 45  50 bytes
Now very much a collaborative effort!
+2 thanks to Aidan F. Pierce (replace sorted({0}) with map(long,{0}))
+8 thanks to dylnan (use of \ and newline to replace space; suggestions to move from 0 to a mathematical expression; replacing -1 with -True; use of hexadecimal)
+11 thanks to Angs (4*23+~91 -> ~4836+9*1075/2 then later ~197836254+0xbCABdDF -> ~875+0xDEAdFBCbc%1439/2*6)

if\
map(long,{~875+0xDEAdFBCbc%1439/2*6})[-True]:q

Try it online! Or see the confirmation suite
0xDEAdFBCbc is hexadecimal and evaluates to 59775106236.
~ is bit-wise complement so ~875 evaluates to -876.
% is the modulo operator so 0xDEAdFBCbc%1439 evaluates to 293.
/ is integer division so 0xDEAdFBCbc%1439/2 evaluates to 146.
* is multiplication so xDEAdFBCbc%1439/2*6 evaluates to 876.
+ is addition so ~875+xDEAdFBCbc%1439/2*6 evaluates to 0.
...no stripped version also evaluates to 0.
{0} is a set containing a single element, 0.
Calling sorted with a set as the argument yields a list, which may be indexed into with [...].
Without sorted the code ({0}) would just yield the set and this cannot be indexed into in the same fashion, if({0})[-True]:q would raise a TypeError.
Indexing in Python is 0-based and allows negative indexing from the back and True is equivalent to 1, hence sorted({0})[-True] finds the element 0, while sorted({0})[True] will raise an IndexError, as will sorted({})[-True] and sorted({0})[] is invalid syntax.
The 0 that is found is falsey so the body of the if, q, is never executed, however if it were it would raise a NameError since q has not been defined.
Since a non-empty list is truthy we cannot trim down to if[-1]:q either.
See the confirmation suite to see: confirmation the bytes being unique; all the errors; and the success of the code itself.

C (tcc), x86_64, 29 31 33 39 40 bytes
main[]={(23*8),-~0xABEDFCfebdc%95674+1};

Returns 0. Thanks to @feersum for suggesting uppercase hex digits.
Try it online!
How it works
The assignment writes two ints (184 and 49664) to the memory location of main. With 32-bit ints and little-endian byte order, the exact bytes are b8 00 00 00  00 c2 00 00.
Since tcc doesn't declare the defined array as .data (most compilers would), so jumping to main executes the machine code it points to.

b8 00 00 00 00 (mov eax, imm32) stores the int 0 in the eax register.
c2 00 00 (ret imm16) pops 0 extra bytes from the stack and returns.  (The value in the eax register is the function return value).

The TIO link is showing a segmentation fault for me.

><>, 122 bytes
e"~l=?!z6-d0p}xwutsrqonmkjihgfcba`_]\[>ZYXWVUTSRQPONMLKJIHGFEDCB@<:98754321/,+*)('&%$# .	|{Ay

Try it online!
Does nothing. Based on the same format as my Programming a Pristine World answer.
First, we check that the length of the code is 122 and error if it isn't. ><> programs can't end without the use of the ; command, but if this command is in the program, we can just remove everything before it to make the program end immediately. To combat this, we use the p command to place a ; in the code during runtime. To do this, we subtract 6 from A and place it after the p.
I'll probably add most of the other values above 127 once I figure out the right two byte values. The missing 5 values are v^; and the two newlines.
Of the 7502 sub-programs, 7417 of them errored from invalid instructions, 72 from memory underflow, and 13 from running out of memory.

JavaScript, 42 bytes
if([0XacdCADE*Proxy.length]!=362517948)田

Removing i, f, or if will cause SyntaxError: missing ; before statement;
Removing 田 will cause SyntaxError: expected expression, got end of script;
Removing 1 or 2 bytes from 田 will cause Invalid or unexpected token;
Modify the boolean expression will cause either Syntax Error or Reference Error on 田

00000000: 6966 285b 3058 6163 6443 4144 452a 5072  if([0XacdCADE*Pr
00000010: 6f78 792e 6c65 6e67 7468 5d21 3d33 3632  oxy.length]!=362
00000020: 3531 3739 3438 29e7 94b0                 517948)...

(function () {
  let valid = code => { try { eval(code); return true; } catch (e) { return false; } };
  let test = P => {
    for (let i = 0; i < P.length; i++) for (j = i + 1; j <= P.length; j++) {
      let Q = P.slice(0,i) + P.slice(j);
      if (Q && valid(Q)) {
        console.log(Q);
        return false;
      }
    }
    return true;
  };
  let unique = P => !/(.).*\1/.test(P);
  let P = 'if([0XacdCADE*Proxy.length]!=362517948)田';
  console.log(unescape(encodeURIComponent(P)).length);
  console.log(valid(P));
  console.log(unique(P));
  console.log(test(P));
}());

Brain-Flak, 2 bytes
<>

Try it online!
Alternatively, [], {} or (). Removing either bracket causes the other bracket to become unmatched.
Proof that this is the optimal solution:
A Brain-Flak program is made out of nilads (a pair of brackets on their own) or monads (a pair of brackets containing 1 or more nilads). A monad cannot be in a pristine program, as you can simply remove one or more of the nilads. Similarly, you cannot have more than one nilad in the program, since you can remove one of them without breaking the program.
As such, this might be the least optimal language for pristine or unique programming.

Ada, 110 bytes (latin1)
Probably the best answer you'll get out of any language in use in industry?
Hexdump:
0000000: 7061 636b 4167 4520 6266 686a 6c6d 6f71  packAgE bfhjlmoq
0000010: 7274 7576 7778 797a e0e1 e2e3 e4e5 e6e7  rtuvwxyz........
0000020: e8e9 eaeb eced eeef f0f1 f2f3 f4f5 f6f8  ................
0000030: f9fa fbfc fdfe 0d69 730b 656e 6409 4246  .......is.end.BF
0000040: 484a 4c4d 4f51 5254 5556 5758 595a c0c1  HJLMOQRTUVWXYZ..
0000050: c2c3 c4c5 c6c7 c8c9 cacb cccd cecf d0d1  ................
0000060: d2d3 d4d5 d6d8 d9da dbdc ddde 3b0a       ............;.

Compile by saving to any file ending in .ads and running gcc -c <filename>. Produces an executable that does nothing. (Can't provide TIO link since TIO puts code in a .adb file and gcc by default tries to find a matching spec for them)
Basically declares a package with a name abusing capital/lowercase latin1 letters. Needs a different whitespace character for each of the spaces, so it uses space, CR, LF, and TAB.
How it looks in vim version:
packAgE bfhjlmoqrtuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ^Mis^Kend^IBFHJLMOQRTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ;

How it works
In Ada even spec's can be compiled. Spec's are like c's header files, but are more full-featured and can compile some basic code. In order to be valid any specification must have the format: package <NAME> is ... end <NAME>; with <NAME> matching. The nice thing about Ada is that it is completely case insensitive. Thus as long as your name has uppercase and lowercase variants, you'll be good to go!
The hard part was getting a compilable unit. Normally Ada programs have a 'main' procedure or function lying outside of any package that will become the final executable. Unfortunately procedures require the begin keyword, which leads to too many es (only 2 cases known) while functions require the return keyword, which leads to too many ns. Thus I had to just compile a package.

C, 8 bytes
main(){}

Does nothing.
Try it online!

Maybe I don't understand the challenge but what about main(){short x;}

@JerryJeremiah: no, main(){short;} compiles with only a warning: useless type name in empty declaration.  I think C99 and C++ require an explicit return type, so int main (or maybe unsigned main) could work, but not with gcc which only warns even with -std=c11.

@JerryJeremiah: a return 0; might be possible with C89, where there's no implicit return 0 at the end of main.  Exiting with non-zero status can be considered failure, according to other answers.  Does adding compiler flags like -Werror count towards the score in a good way in code bowling?  Because strictly enforcing violations of C11 could allow a much longer program.  Hmm, #include<> something and then use it; you can't remove both include and usage, and if it crashes without a prototype or macro def, you win.

@PeterCordes I thought about that, but main and include both contain i, so you can't have both. Similarly for declaring and using a function. Also using return at all come to think of it.

oops, I forgot about the unique bytes requirement; of course int main can't work.

Python 3 + Flask-Env, 7 13 14 17 bytes
import\
flask_env

No TIO because it doesn't have flask-env.
Found the longest module name that has no intersection with import and doesn't have any numbers at the end of the name. _sha256 is longer but 256 on it's own doesn't error. I did find one library, b3j0f.sync that is one byte longer but I could not get it to import properly.

+1 byte by replacing a space after import with \<newline>. Taking out either or both causes an error.

There still may be longer options than flask_env, I didn't really do an exhaustive search but I did look through ~70,000 modules. Open to suggestions.

256 runs without erroring.

@AidanF.Pierce Thanks, fixed.

I tried import *[hawkey] and similar but unfortunately doesn't work...

hawkey is not in the standard library, so this is "Python with hawkey" (probably can do better with some other module somewhere)

@JonathanAllan Good point. Have to go right now but I'll search later

JavaScript, 22 bytes
with(0xF?JSON:[])parse

Try it online!
Possible errors
When altered, it will throw one of the following errors1:
[some_identifier] is not defined
expected expression, got ')'
expected expression, got ':'
expected expression, got '?'
expected expression, got ']'
expected expression, got end of script
identifier starts immediately after numeric literal
missing ( before with-statement object
missing ) after with-statement object
missing : in conditional expression
missing ] after element list
missing exponent
missing hexadecimal digits after '0x'
missing octal digits after '0o'
unexpected token: ')'
unexpected token: ']'
unexpected token: identifier

1. The exact number of distinct errors depends on the engine. This list was generated with SpiderMonkey (Firefox).

R, 14 bytes
(Sys.readlink)

Try it online!
This might be the longest possible in R. Calling any function is doomed to failure, because you would be able to remove everything but the function name, which would just result in printing the function's source code. This is the longest named object in the default R setup with no duplicate characters and no object name left over when removing contiguous characters.
This first try didn't work, but I learned a lot by trying!
dontCheck({family;NROW})

Perl 5, 3 bytes
y=>

=> is the "fat comma," which quotes the bareword on the left. So this is equivalent to
"y",

which does nothing.
Without the fat comma, y is the transliteration operator, which is invalid without three of the same character repeated later.
The fat comma alone is also invalid, as is = and > alone.

brainfuck, 2 bytes
[]

Try it online!
Inspired by Jo King's Brain-Flak answer. This is optimal because the only error in brainfuck is unmatched brackets. (Again thanks to Jo King for this info.)

Yup. The only error brainfuck can have is unmatched brackets

Ruby, 28 bytes
(?2*0xA)[%r<\d{1}>].unpack$/

Try it online!
Verify it!

Tcl, 6 bytes
puts a

Try it online!

Tcl, 3 bytes
pwd

Try it online!

Tcl, 2 bytes
cd

Try it online!

valid and pristine.

Standard ML, 22 bytes
val 1089=op-(765,~324)

Try it online! op-(a,b) is the de-sugared form of a-b. ~ denotes the unary minus, so we are actually computing 765+324. This expression is pattern-matched on the constant 1089. This match succeeds if the program has not been tampered with and does - well, nothing.
If the match does not succeed because some digits were removed one gets an unhandled exception: Bind. Removing op- results in a type error because a tuple is matched on an int. All other removals should result in an syntax error.

Batch, 7 bytes
set/px=

A nice start

Retina, 2 bytes
I wouldn't be surprised if this is optimal...
()

Try it online!
The regex contains an empty group. Removing either paren will cause a parse error due to unmatched parentheses.
Other solutions are: \(, \), \[, \], \*, \+, \?, a]

a] doesn't error.

@jimmy23013 Ah, I don't know how I missed that. Rolled back.

Malbolge, 76 bytes
cba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwd

Try it online!
Malbolge is a great language for this challenge due to the way it translates normalized Malbolge into your familiar keyspam-esque Malbolge.

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


text:
Output some reserved words
For a computer language, a reserved word is a word that cannot be used as an identifier, such as the name of a variable, function, or label. For other computer languages, keywords can be considered as the set of the language instructions.
Challenge
Using your language of choice, write a code in the chosen language that given a number between one and ten, 1<=n<=10, outputs any n reserved words (keywords) of the chosen language.
Specifics

If the chosen language is case sensitive the outputted keywords must be also.
If the chosen language is not case sensitive the outputted keywords can be in any case.
If the chosen language has less than 10 keywords saying p, the code must output all the reserved words for any n between p and 10.
If possible specify in the answer whether you consider operators as keywords or not.

Possible samples for Java (JDK10)

n=1 --> true
n=3 --> try new interface
n=4 --> continue this long break

Possible samples for ><>

n=1 --> >
n=3 --> > < ^
n=4 --> > < \ /

Possible samples for Brain-Flak

n=1 --> (
n=3 --> ( ) [ ]
n=9 --> ( ) [ ] { } < >

Rules

The input and output can be given in any convenient format.
No need to handle invalid input values, valid inputs are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an on-line testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Comments are not for extended discussion; this conversation has been moved to chat.

continue this long break I wish! That's why I'm on SE!

the integers are reserved but I guess that would be a loophole.

APL (Dyalog Unicode), 9 bytesSBCS
Full program. Prompts stdin for n (actually works for the range 0–29). APL keywords are single character symbols, so this prints n symbols to stdout.
⎕↑156↓⎕AV

Try it online!
⎕AV the Atomic Vector (i.e. the character set)
156↓ drop the first 156 elements
⎕↑ prompt for n and take that many elements from the above

Python 2, 25 bytes
lambda n:'=+*/%&^|<>'[:n]

An unnamed function accepting an integer in [1,10] which returns a string of single-byte binary operators.
Try it online!
The operators:
=  Assign
+  Addition
*  Multiplication
/  Division
%  Modulo
&  Bitwise-AND
^  Bitwise-XOR
|  Bitwise-OR
<  Less Than?
>  Greater Than?

If only actual keywords are allowed: 40 bytes
from keyword import*
lambda n:kwlist[:n]

An unnamed function accepting an integer in [1,10] which returns a list of strings.
Try it online!
The code should be quite straightforward - it defines a function taking one argument, n, using lambda n:... which returns the first n (...[:n]) of the known keywords using the standard library's keywords.kwlist (along with the standard golfing technique of import*).

very minor point but surely = is "Assignment" as == is "Test for equality"

Oops, good catch, thanks @Noodle9

Weird down-vote! Edit: Someone decided all the answers here deserve a down-vote. LOL

Certainly wasn't me - I liked your answer and upvoted it! :)

Java 10, 83 72 bytes (keywords)
n->"do   if   for  int  new  try  var  byte case char ".substring(0,n*5)

Try it online.
Old 83 bytes answer:
n->java.util.Arrays.copyOf("do if for int new try var byte case char".split(" "),n)

Try it online.
Explanation:
n->                         // Method with integer parameter and String-array return-type
  java.util.Arrays.copyOf(  //  Create a copy of the given array:
    "do if for int new try var byte case char".split(" ")
                            //   The keywords as String-array,
    ,n)                     //   up to and including the given `n`'th array-item

List of available keywords for Java 8. Java 10 has the keyword var in addition to these.

Java 8+, 30 bytes (operators)
n->"+-/*&|^~<>".substring(0,n)

Try it online.

JavaScript (Node.js), 79 61 bytes
n=>'true int var for in if new try of do'.split` `.slice(0,n)

Try it online!
How :
n =>         // the input (will be an integer) between 1 and 10 (both inclusive)
    '        // beginning our string
        true int var for in if new try of do'. // space separated reserved words
    split` `.        // turn it into an array every time there is a space we add to array
    slice(0,n)      // return elements of array starting from 0 and upto n

If using operators is allowed (most likely will be since they are reserved words) then :
JavaScript (Node.js), 26 25 bytes
n=>'|/^%+<&*-='.slice(-n)

Try it online!
Saved 8 bytes thanks to @Adam and 1 more byte thanks to @l4m2
How :
n =>     // input (integer from 0-9 inclusive)
    '|/^%+<&*-='.    // operators make a shorter string
        slice(-n)   // outputs string chars from last upto n
            // this works since all operators are single chars and not multi chars.

n=>'|/^%+<&*-='.substr(-n)

Oh yeah , Lol still golfing. Thanks @Adám. Appreciate it.

I don't think int is a "reserved word" as per the definition in the challenge.  You can certainly name a variable int in JavaScript.

If I remember well, int is reserved as a possible future keyword by the ECMAScript specification.

Why substr instead of slice?

@l4m2 : Good point. LOL things that we miss. Thanks. I updated the answer

Ruby, 22 bytes
->n{'+-*/%&|^<>'[0,n]}

Try it online!
-2 bytes thanks to @benj2240

Ok. Will update my answer.

String#[] has a two-argument overload you can use for -2 bytes: [0,n]

p is not a reserved word, & should work

@AsoneTuhid : p is used for printing as well , but You are right I can probably replace it. Thanks

@I'mnoone Yes but it's a method, you can redefine it and you can create a variable named p which will be accessed instead of calling the method with no variables (p = 1; p p #=> 1)

Jelly, 3 bytes
ØAḣ

A monadic link accepting an integer and returning a list of characters.
Try it online!
The resulting characters are all monadic atoms in Jelly's code-page:
A   Absolute value.
B   Convert from integer to binary.
C   Complement; compute 1 − z.
D   Convert from integer to decimal.
E   Check if all elements of z are equal.
F   Flatten list.
G   Attempt to format z as a grid.
H   Halve; compute z ÷ 2.
I   Increments; compute the differences of consecutive elements of z.
J   Returns [1 … len(z)].

How?
ØAḣ - Link: integer n (in [1,10])
ØA  - yield uppercase alphabet = ['A','B','C',...,'Z']
  ḣ - head to index n

Oh - I see someone decided to down-vote ALL the answers; how sporting!

Think this answer deserves an upvoted too! :)

Charcoal, 16 bytes
✂”yＰＢＧ¤Ｔ⎚Ｍ↶↷Ｊ”⁰Ｎ

Too bad there isn't a preset variable for its own code-page in Charcoal.
Try it online.
Explanation:
Get a substring from index 0 to the input-number:
Slice("...",0,InputNumber)
✂”y...”⁰Ｎ

The string with 10 keywords:
”yＰＢＧ¤Ｔ⎚Ｍ↶↷Ｊ”

I assume the fullwidth letters have consecutive character codes so you can just print the first n of those, which I can do in 8 bytes.

@Neil But are ten of those consecutive characters used as commands/operators? The Ａ for example isn't used at all right now, is it? (Except in combination with ＫＡ or ⌕Ａ.)

Actually Ａ is a command and operator, but not a good one, as it can cause confusion between Find and FindAll, but you then get stuck again at Ｈ and Ｏ, which only get used as modifiers, and then Ｑ isn't used at all, which limits you. Greek letters, then?

Never mind, those are variables, not commands, I guess.

Perl 5 -lp, 24 bytes
#!/usr/bin/perl -lp
$_=(grep!eval,a..zz)[$_]

Try it online!
Easy to extend to more and longer keywords, but you will need to do special casing starting at 4 letters because you will run into problems with dump, eval, exit,getc etc..
Of course just outputting operators and sigils is boring but shorter at 11 bytes:
#!/usr/bin/perl -lp
$_=chr$_+35

Try it online!
(I skipped # since it's unclear how I should classify it in the context of this challenge)

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

Try it online!
Just doing my part to fill out the example languages. Outputs ()[]<>}{, popping off the front for numbers less than 8.

C# .NET, 76 62 bytes (keywords)
n=>"as  do  if  in  is  for int new out ref ".Substring(0,n*4)

Try it online.
Old 76 bytes answer:
using System.Linq;n=>"as do if in is for int new out ref".Split(' ').Take(n)

Try it online.
Explanation:
using System.Linq;  // Required import for Take
n=>                 // Method with integer parameter and IEnumerable<string> return-type
  "as do if in is for int new out ref".Split(' ')
                    //  The keywords as string-array,
  .Take(n)          //  and return the first `n` items

List of available keywords in C# .NET.

C# .NET, 30 bytes (operators)
n=>"+-/*&|^~<>".Substring(0,n)

Try it online.

Pyth, 4 bytes
>QPG

Try it online!
Unfortunately, many of the letters are variables (GHJKNQTYZbdkz).
p  <any>                  Print A, with no trailing newline. Return A.
q  <any> <any>            A == B
r  <str> 0                A.lower()
r  <str> 1                A.upper()
r  <str> 2                A.swapcase()
r  <str> 3                A.title()
r  <str> 4                A.capitalize()
r  <str> 5                string.capwords(A)
r  <str> 6                A.strip() - Remove whitespace on both sides of A.
r  <str> 7                Split A, eval each part.
r  <seq> 8                Run length encode A. Output format [[3, 'a'], [2, 'b'], [1, 'c'], [1, 'd']].
r  <str> 9                Run length decode A. Input format '3a2bcd' -> 'aaabbcd'
r  <seq> 9                Run length decode A. Input format [[3, 'a'], [2, 'b'], [1, 'c'], [1, 'd']].
r  <int> <int>            Range, half inclusive. range(A, B) in Python, or range(A, B, -1).
r  <str> <str>            String range. r(C(A), C(B)), then convert each int to string using C.
r  <int> <seq>            r(B, A)
s  <col(str)>             Concatenate. ''.join(A)
s  <col>                  reduce on +, base case []. (Pyth +)
s  <cmp>                  Real part. A.real in Python.
s  <num>                  Floor to int. int(A) in Python.
s  <str>                  Parse as int. "" parses to 0. int(A) in Python.
t  <num>                  A - 1.
t  <seq>                  Tail. A[1:] in Python.
u  <l:GH> <seq/num> <any> Reduce B from left to right, with function A(_, _) and C as starting value. G, H -> N, T ->. A takes current value, next element of B as inputs. Note that A can ignore either input.
u  <l:GH> <any> <none>    Apply A(_, _) until a result that has occurred before is found. Starting value B. A takes current value, iteration number as inputs.
v  <str>                  Eval. eval(A) without -s, ast.literal_eval(A) with -s (online). literal_eval only allows numeric, string, list, etc. literals, no variables or functions.
w                         Take input. Reads up to newline. input() in Python 3.
x  <int> <int>            Bitwise XOR. A ^ B in Python.
x  <lst> <any>            First occurrence. Return the index of the first element of A equal to B, or -1 if none exists.
x  <str> <str>            First occurrence. Return the index of the first substring of A equal to B, or -1 if none exists.
x  <non-lst> <lst>        All occurrences. Returns a list of the indexes of elements of B that equal A.
x  <str> <non-lst>        First occurence. Return the index of the first substring of A equal to str(B), or -1 if none exists.
y  <seq>                  Powerset. All subsets of A, ordered by length.
y  <num>                  A * 2.

Unary, 6072204020736072426436 378380483266268 bytes
+[>+<+++++]>---. (0o12602122222703334)

Thank Jo King for 99.999993768646738908474177860631% reducing

Is the bytes number correct?

@mdahmoune I think so

!!It’s very big

@mdahmoune It's actually pretty 'small' for Unary. ;) If you search for other Unary or Lenguage answers here on PPCG there are some much, much larger than this.

Does ,[.-] in Lenguage fits the requirement?

Charm, 52 bytes
This outputs all of the reserved words in Charm.
" [  := :: \"   " 0 2 copyfrom 3 * substring pstring

Since all non-recursive code in Charm is inline-able, this is an anonymous function. Call like this:
4 " [  := :: \"   " 0 2 copyfrom 3 * substring pstring

(outputs [  := :: ", the only four reserved words.)

Giving this function a name adds 5 bytes:
f := " [  := :: \"   " 0 2 copyfrom 3 * substring pstring

Japt, 3 bytes
Returns a string, with each individual character being a method name in Japt.
;îC

Try it
;C is the lowercase alphabet and î repeats it until its length equals the input.

@Downvoter, you forgot to leave a comment! :\

It seems that someone has down-voted all answers :/

R, 76 62 60 57 bytes
12 bytes saved thanks to MickyT
5 bytes saved thanks to snoram
cat(c("if","in",1:0/0,"for",F,T,"NULL","else")[1:scan()])

Try it online!
There aren't many Reserved words in R but these are among the shortest to encode. There are only 9 here, but if an input of 10 is given, a missing value NA is appended to the end of the list and printed.

Some quick little savings

@MickyT thanks! Realized I could store "NaN" as 0/0 or NaN as well for another couple bytes.

replace 1/0,0/0 with 1:0/0.

@snoram ah, excellent! And welcome to PPCG! I'm looking forward to your first answer here! Have a look at tips for golfing in R and feel free to ping me in chat! :-)

Thanks! @Giuseppe btw. 1[1:2] returns [1]  1 NA =>  you can skip NAin the original vector... if user input is 10 it will get appended at the end.

@snoram that's brilliant! Clearly I did not give this enough thought when I wrote it.

Ruby, 50 49 bytes
->n{%w[do if or in end not for def nil and][0,n]}

Try it online!
Not using any operators (+, |, etc.).

Ruby, 71 68 bytes
->n{(?a..'zzz').reject{|x|begin;eval x+'=n';rescue Object;end}[0,n]}

Okay, not the shortest approach, but too fun not to post. Programmatically finds all strings of up to three lowercase letters that can't be assigned to. There happen to be exactly 10: ["do", "if", "in", "or", "and", "def", "end", "for", "nil", "not"].
Edit: Saved 3 bytes thanks to Asone Tuhid.

Nice, you can save 3 bytes by rescuing Object since it's a superclass of Exception

Chicken, 7 bytes
chicken

Not a serious answer. But it has to be here.

Python 2, 64 bytes
lambda n:'as if def del for try elif else from pass'.split()[:n]

Try it online!

Python 2, 57 bytes (with operators)
lambda n:'as if in is or and def del for not'.split()[:n]

Try it online!

keywords
operators

a function is 2 bytes shorter

><>, 11 10 9 bytes
1-:n:0=?;

Try it online!
Turned out the simplest solution was the best. This outputs the first n numbers, starting from 0.
Old 10 byte solutions
"'r{$[>o<3

Try it online!
Some 10 byte alternatives:

"':1+{[>o<
"r:n[~>o<a
"'a{[>o<bc

Whitespace, 84 bytes
[S S S T    S S S S S N
_Push_32][S N
S _Duplicate][T N
S S _Print_as_character][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S S S T  N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   S N
_If_0_Jump_to_Label_EXIT][S S S T   S S T   N
_Push_9][T  N
S S Print_as_character][S S S T N
_Push_1][T  S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_EXIT][S S S T   S T S N
_Push_10][T N
S S _Print_as_character][N
S S N
_Create_Label_EXIT]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.
Whitespace only contains three valid 'keywords': spaces, tabs and new-lines.
Explanation in pseudo-code:
Print space
Integer i = STDIN as integer - 1
If i is 0:
  Exit program
Else:
  Print tab
  i = i - 1
  If i is 0:
    Exit program
  Else:
    Print new-line
    Exit program

Example runs:
Input: 1
Command       Explanation                 Stack      Heap      STDIN    STDOUT   STDERR

SSSTSSSSSN    Push 32                     [32]
SNS           Duplicate top (32)          [32,32]
TNSS          Print as character          [32]                          <space>
SNS           Duplicate top (32)          [32,32]
TNTT          Read STDIN as integer       [32]       {32:1}    1
TTT           Retrieve                    [1]        {32:1}
SSSTN         Push 1                      [1,1]      {32:1}
TSST          Subtract top two (1-1)      [0]        {32:1}
SNS           Duplicate top (0)           [0,0]      {32:1}
NTSN          If 0: Jump to Label_EXIT    [0]        {32:1}
NSSN          Create Label_EXIT           [0]        {32:1}
                                                                                error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
Outputs a single space.
Input: 2
Command       Explanation                 Stack      Heap      STDIN    STDOUT   STDERR

SSSTSSSSSN    Push 32                     [32]
SNS           Duplicate top (32)          [32,32]
TNSS          Print as character          [32]                         <space>
SNS           Duplicate top (32)          [32,32]
TNTT          Read STDIN as integer       [32]       {32:2}    2
TTT           Retrieve                    [2]        {32:2}
SSSTN         Push 1                      [2,1]      {32:2}
TSST          Subtract top two (2-1)      [1]        {32:2}
SNS           Duplicate top (1)           [1,1]      {32:2}
NTSN          If 0: Jump to Label_EXIT    [1]        {32:2}
SSSTSSTN      Push 9                      [1,9]      {32:2}
TNSS          Print as character          [1]        {32:2}             \t
SSSTN         Push 1                      [1,1]      {32:2}
TSST          Subtract top two (1-1)      [0]        {32:2}
NTSN          If 0: Jump to Label_EXIT    []         {32:2}
NSSN          Create Label_EXIT           []         {32:2}
                                                                                error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
Outputs a space, followed by a tab.
Input: 3 (or higher)
Command       Explanation                 Stack      Heap      STDIN    STDOUT   STDERR

SSSTSSSSSN    Push 32                     [32]
SNS           Duplicate top (32)          [32,32]
TNSS          Print as character          [32]                          <space>
SNS           Duplicate top (32)          [32,32]
TNTT          Read STDIN as integer       [32]       {32:3}    3
TTT           Retrieve                    [3]        {32:3}
SSSTN         Push 1                      [3,1]      {32:3}
TSST          Subtract top two (3-1)      [2]        {32:3}
SNS           Duplicate top (2)           [2,2]      {32:3}
NTSN          If 0: Jump to Label_EXIT    [2]        {32:3}
SSSTSSTN      Push 9                      [2,9]      {32:3}
TNSS          Print as character          [2]        {32:3}             \t
SSSTN         Push 1                      [2,1]      {32:3}
TSST          Subtract top two (2-1)      [1]        {32:3}
SSSTSTSN      Push 10                     [1,10]     {32:3}
TNSS          Print as character          [1]        {32:3}             \n
NSSN          Create Label_EXIT           []         {32:3}
                                                                                error

Program stops with an error: No exit defined.
Try it online (with raw spaces, tabs and new-lines only).
Outputs a space, followed by a tab, followed by a new-line.

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

Try it online!
# Push stuffs under the counter
({}<(((((((((((()()()()()){}){}){})())(([][][])){}{}())()())([][][])[]{})()())[][][][][])()())>)

# While True
{
    # Decrement the counter
    ({}<

        # Toggle a character
        ({}<>)<>
    >[()])
}

# Display alternate stack
<>

This prints extra null bytes for 9 and 10

Haskell, 22 bytes
(`take`"';,=\"@\\`|~")

Try it online!
Thanks to @Angs for catching keyword errors.
I felt like this could be shorter by generating the string instead of explicitly defining it, but I couldn't find a range of 10 consecutive ASCII characters that are Haskell keywords (I found some that are close, if you count language extension keywords). If there is one, you could reduce it to 15 bytes with this, replacing % with the starting character:
(`take`['%'..])

Without symbolic keywords:
Haskell, 58 bytes
(`take`words"of in do let then else case data type class")

Try it online!

! isn't reserved, e.g. let a!b=a+b is fine

Oops, you're right. Fixed both parts, since as is also a valid identifier.

. isn't reserved either - none of the other operators in prelude like + etc are - see this

C (gcc), 62 60 bytes
-2 thanks to GPS
f(n){puts("autocasecharelseenumgotolongvoidint do"+40-4*n);}

Try it online!
I mean... there was never any requirement to actually separate the keywords.
In case I misread - or you're more interested in something more in the spirit of the question - here's an alternate version with separating spaces:
C (gcc), 69 bytes
f(n){puts("auto case char else enum goto long void int  do"+50-5*n);}

Try it online!

Do you need the two spaces after do?

@JoKing Yeah, otherwise garbage characters could be written.

You could trim spaces after do if you use string output functions. 69 bytes: Tio

05AB1E, 2 bytes
A£

Try it online!

Every letter of the alphabet is a command in 05AB1E.
All this does is prints the first N letters of the alphabet.

Tcl, 37 bytes
puts [lrange [info commands] 1 $argv]

Try it online!

Bash and shell utils 20 bytes
compgen -b|head -$1

You can save that in a file with execute permissions (builtins) and run it under bash like this:
$ ./builtins 5
 .
 :
 [
 alias
 bg

Outputs the first N bash built ins.
If you are running some shell other than bash, you will need the shebang #!/bin/bash line at the start of the file, for +12b

QBasic, 60 bytes
INPUT n
?LEFT$("CLS FOR DEF RUN DIM PUT GET SUB END IF",n*4)

This answer fits the spirit of the question best, I believe: outputting alphabetic reserved keywords with spaces in between. I don't think symbolic operators really count as "words" in QBasic, but for completeness, here's a 30-byte answer using operators:
INPUT n
?LEFT$("+-*/\^=><?",n)

MATL, 5 bytes
:96+c

Try it online!
The lowercase alphabets all correspond to builtins in MATL, so this outputs the first n lowercase letters.
For a version with a smile, there's:
2Y2i:)

at 6 bytes.

Julia 0.6, 59 bytes
n->split("if do for try let end type else true macro")[1:n]

Try it online!
Using the list of reserved keywords from julia-parser.scm.
An operators-included version gets quickly confusing, as to what is an operator and what is a syntactic indicator (like @ for a macro). Going by julia-parser.scm again, a bunch of operators are termed "syntactic operators" and can't be assigned to or overloaded by the user (so fit the definition of "reserved"). Some of these are:
Julia 0.6, 45 bytes
n->split("= : :: && || ... >: <: -> .=")[1:n]

Try it online!

Cubix, 12 bytes
Based on some of the other answers I think this should qualify for reserved words.  I avoided using the numeric literals as I thought that might be stretching the definition a bit far.
SoI;W(>!@+/$

Try it online!
This wraps onto the cube as follows
    S o
    I ;
W ( > ! @ + / $
. . . . . . . .
    . .
    . .

Watch it run

WSI change lane, push 32 and get input.  This sets up the stack with 32 and the input value.
>!@ redirect, test for 0 and halt if true.
+/o; add stack items, reflect onto top face, output character and pop the sum.
!/$W( redundant test, reflect, skip the lane change, decrement the input and back into the main loop.

Output for 10
*)('&%$#"!

* multiply the top two items on the stack
) increment the TOS value
( decrement the TOS value
' push the next character's value to the stack
& pop top two items (integers) of the stack, concatenate and push the int result
% take modulo of top two stack items
$ Skip the next command
# push the stack length
" start and end of string literal.  Character codes of string are pushed to the stack
! test for truthy and skip next command if true

Taxi, 509 bytes
"[]a lrnsew" is waiting at Writer's Depot. Go to Post Office: w 1 l 1 r 1 l. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: s 1 l 1 r.Pickup a passenger going to The Underground.Go to Writer's Depot: n 1 l, 1 l, 2 l.Pickup a passenger going to Chop Suey.Go to Chop Suey: n, 3 r, 3 r.[a]Pickup a passenger going to Post Office.Go to Post Office: s 1 r 1 l 2 r 1 l.Go to The Underground: n 1 r 1 l.Pickup a passenger going to The Underground.Go to Chop Suey: n 2 r 1 l.Switch to plan "a".

This takes a hardcoded string at the top, and prints "n" characters from it, and then errors with "error: no outgoing passengers found".
The string contains:

[ and ], the characters used to declare a plan
a used in the "Pickup a passenger ..." syntax.
The space character, which is required to separate pieces of syntax
l and r, short for "left" and "right", used to tell the driver which way to turn.
n, s, e, and w, the four directions.

I believe all of those count as one character keywords. Ungolfed:
"[]a lrnsew" is waiting at Writer's Depot.
Go to Post Office: west, 1st left, 1st right, 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south, 1st left, 1st right.
Pickup a passenger going to The Underground.
Go to Writer's Depot: north, 1st left, 1st left, 2nd left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north, 3rd right, 3rd right.
[print character]
Pickup a passenger going to Post Office.
Go to Post Office: south, 1st right, 1st left, 2nd right, 1st left.
Go to The Underground: north, 1st right, 1st left.
Pickup a passenger going to The Underground.
Go to Chop Suey: north, 2nd right, 1st left.
Switch to plan "print character".

J, 15 bytes
[:u:46,"0~65+i.

Try it online!
Gives an array of strings A. to J..
Dotted words in J act as built-ins (such as a. or A.) or control structures (such as if. or do.), or simply throw spelling error. None of them can be used as identifiers.
Less interesting, 15 bytes
{.&'!#$%^*-+=|'

Try it online!
Gives some of the 10 one-byte verbs.

Thunno 2 Ṡ, 4 bytes
ıkCɼ

Try it online!
Explanation
ıkCɼ  # Implicit input
ı     # Input no. times:
   ɼ  #  Random character from
 kC   #  Thunno 2 Codepage
      # Join on spaces
      # Implicit output

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


text:
Print valid arithmetic expressions
Recursively define a "valid arithmetic expression":

Any natural number is a valid arithmetic expression.
If s is a valid arithmetic expression, then so is (-s).
If p and q are valid arithmetic expressions, then so is (p+q).

In the above, a "natural number" is recursively defined as follows:

0 1 2 3 4 5 6 7 8 9 are natural numbers.
If a natural number n is not 0, then n0 n1 n2 n3 n4 n5 n6 n7 n8 n9 are natural numbers.

Alternatively, via the regex /^(0|[1-9][0-9]*)$/
Examples of valid arithmetic expressions:
0
314
(-7)
(0+0)
(314+(-314))

Examples of invalid arithmetic expressions:
01
-5
5+10

The challenge is to print every valid arithmetic expression line by line, i.e. create a program that will output strings line by line with the constraint that every valid arithmetic expression is eventually printed, and that no invalid arithmetic expression is ever printed.
The valid arithmetic expressions can be printed more than once.
The challenge is to do so in as few bytes as possible, since this is code-golf.
Standard loopholes apply.

Can we expect the input to be non-empty?

The output should be infinite, presumably? How can we demonstrate that every valid expression will be printed?

@PhilH well you can challenge an answer that doesn't meet the criterion and the author of the answer would have to justify it...

@LiefdeWen you mean empty?

Suppose someone writes an entry which just enumerates the natural numbers, it would only finish that after infinity...

@PhilH then the entry is invalid.

@PhilH That doesn't satisfy "every valid arithmetic expression is eventually printed", as (-0) is never printed.

@user202729 I could claim it would do so eventually, but also isn't this supposed to be code rather than theory of code? What's the real difference between a program that prints all the positive natural numbers then starts on the negative numbers, and one that just prints the positive numbers? The outputs are the same for all time...

@PhilH Seems that you misunderstood the rules? The validity criteria is "for all expression E, there exists a (finite) natural number N, such that the N'th line printed is E" Your example does not satisfy that.

Jelly, ... 33 bytes
⁾()j
p`j”+Ç$€;;”-;ÇƊ€;®‘©¤Ṅ€
WÇ1¿

Try it online!
Wow, writing a correct submission is hard.

Python pseudocode equivalent:
import itertools

# Jelly: ⁾()j
def wrap_in_parentheses(x):
 return str(x).join(['(',')'])
 # or equivalently, `return '('+str(x)+')'

# Jelly: p`j”+Ç$€;;”-;ÇƊ€;®‘©¤Ṅ€
register = 0
def expand_and_print(expressions):
 # Jelly: p`
 result = list(itertools.product(expressions, repeat=2))

 # Jelly: j”+Ç$€
 result = [wrap_in_parentheses('+'.join(expr)) for expr in result]

 # Jelly: ;
 result.extend(expressions)

 # Jelly: ;”-;ÇƊ€
 result.extend([wrap_in_parentheses('-'+expr) for expr in expression])

 # Jelly: ;®‘©¤
 global register
 register += 1
 result.append(register)

 # Jelly: Ṅ€
 for expr in result:
  print(expr)

 return result

# Jelly: WÇ1¿
expressions = ['0']
while 1:
 expressions = expand_and_print(expressions)

JavaScript ES6, 79 bytes
for(x=[n=0];;++n)x.map(i=>x.map(j=>x.push(n,`(-${i})`,`(${i}+${j})`))+alert(i))

Infinite large integer in variable, assumed; 2. Totally unrunnable in fact

Python, 241 bytes
g=lambda n,s=0:s<6 and(l+r for x in(["\x13 8"]+list("I-x</"))[s]for a in range(n)for l in g(a,ord(x)%12)for r in g(n-a,ord(x)//12))or[]if n^1else s>7and["(-)+"[s-8]]or list("0123456789"[s==7:])*(s%6<2)
i=1
while i:print("\n".join(g(i)));i+=1

This isn't too short, but it's a table-driven approach that's semi-automatically generated from a CFG I wrote for this language. It's unreasonably fast (speed sacrificed for bytes) :)


text:
Render an ASCII maze
look! It's an ASCII maze! Soo coolzors, amazeballs and stuff.
+-+-----+---+
| |     |   |
| |  ++   | |
| |  ++ +-+ |
|       |   |
+-------+ | |
|         | |
+---------+-+

But, but, but... it's a pain to work out which direction all the parts of the maze are going. I just want to draw the layout and the maze make itself sooper kul without loads of time.
What if I could just draw this in...
#############
# #     #   #
# #  ##   # #
# #  ## ### #
#       #   #
######### # #
#         # #
#############

That would be soo sweet!

The rules (Because rules is cools):

Write code to convert a string into an ascii maze and output the result.
Any non-whitespace character will be read as a wall.
Each char of wall will decide which character to be based on it's neighbours (only in North, South, East and West directions).

If a char has no non-whitespace neighbours, it will be a plus sign (+).
If a char has neighbours in both vertical (North-South) and horizontal (East-West) directions, it will be a plus sign (+).
If a char has neighbours only in a vertical (North-South) direction, it will be a pipe symbol (|).
If a char has neighbours only in a horizontal (East-West) direction, it will be a minus sign (-).

The Input can be a single string (with lines separated by newline characters, or an array of strings).
All input characters will be printable ASCII characters, you don't need to deal with extended charsets.
Use any old language you please.
If there is white space before a line, it should be the same amount on each line. Any white space after each line of output is fine.
Attempt to solve it with the smallest number of bytes.

Test cases:
1: Frame
Input:
##########
#        #
#        #
#        #
##########

Output:
+--------+
|        |
|        |
|        |
+--------+

2: Classic maze
Input:
#################
        #       #
# ##### # ##### #
#   # # #     # #
# # # # ##### # #
#   # #       # #
### # ####### # #
#   # #    #  # #
# ### # ## # ##
#     # ##    #
#################

Output:
--------+-------+
        |       |
| --+-+ | ----+ |
|   | | |     | |
| + | | +---- | |
|   | |       | |
+-- | +----+- | |
|   | |    |  | |
| --+ | ++ | -+
|     | ++    |
+-----+-++----+--

3: Green eggs, man.
Input:
I do not like green eggs and ham.
I do not like them, sam I am.
Would you like them here or there?
I would not like them anywhere!

Output:
| ++ +++ ++++ +++++ +++- -++ ----
| ++ +++ ++++ +++++ +++ + +++
+-+++ +++ ++++ ++++ ++++ ++ +++---
| +++-+ +++ ++++ ++-+ +++++++++

4: Icicles
Input:
Word Icicle!
Word Icicle
Word  cicle
 ord  cicle
 ord   icle
 ord   i le
 or    i le
 or    i l
 or      l
 or
  r

Output:
++++ ++++++-
++++ ++++++
++++  +++++
 +++  +++++
 +++   ++++
 +++   | ++
 ++    | ++
 ++    | |
 ++      |
 ++
  |

Cab we take input as a string array for each line?

Is it guaranteed that all characters (except newlines of course) are printable ASCII?

@LiefdeWen Sure, why not?

@user202729 That sounds like a sensible restriction.

Shouldn't the third line of green eggs and ham end with ---?

@LiefdeWen I should really have spotted that. Completely correct.

Results for mixed neighbours still unclear; not sure why icicles would have any -s at all or why classic maze doesn't have four +s on the bottom row.

@Neil I've corrected those. The answer to the icicles one was that I was scrolled past the first line when I first converted it, then fixed up the top line when I saw it... (doh.jpg)

are we allowed to take the input as a square padded with spaces (i.e. matrix)? Is the output allowed to have extra whitespace around it? Also, do you really mean smallest number of characters, not bytes?

I think that 1) the classic maze should have a + in the middle of the 1st row 2) the ! of Icicles should be replaced with a -. Could you please double-check these ones?

Attention @all! I can't proof read for toffee, today. Corrected yet more of my errors.

By whitespace, do you just mean just space? I don't want to have to support tabs and you probably don't want me to transform newlines either

@JoKing All input characters are printable ASCII. Tabs are not printable.

APL (Dyalog Unicode), 57 35 bytesSBCS
–22 thanks to a novel solution by ngn.
Anonymous tacit function taking a character matrix as argument.
{⊃'+-|+'↓⍨2⊥5 4 2⊃¨⊂⍱∘⌽⍨' '≠,⍵}⌺3 3

Try it online!
{…}⌺3 3 on each 3-by-3 neighbourhood, apply the following function:
 ,⍵ ravel (flatten)
 ' '≠ Boolean where non-space
 ⍱∘⌽⍨ that NOR it's reverse (incl. neither top NOR bottom, neither left NOR right)
 5 4 2⊃¨⊂ pick 5th, 4th, and 2nd element from that entire list
  i.e. empty self, no vertical, no horizontal
 2⊥ evaluate in base-2 (binary)
  i.e. ≥4:empty self; 3:no neighbours; 2:no horizontal neighbours; 1:no vertical; 0: has both
 '+-|+'↓⍨ drop that many elements from this string
  i.e. empty self:; alone:+; vertical neighbour(s) only:|+; horizontal:-|+; both:+-|+
 ⊃ pick the first element (pad with space if non are available)
  i.e. empty self: ; alone:+; vertical neighbour(s) only:|; horizontal:-; both:+

Old solution
Anonymous tacit function taking a character matrix as argument.
{' +-|+'⊃⍨1⍳⍨(' '=5⊃,⍵),(∧/,⊢)∨/2 2⍴1⌽' '≠(9⍴0 1)/,⍵}⌺3 3

Try it online!
{…}⌺3 3 on each 3-by-3 neighbourhood, apply the following function:
 ,⍵ ravel (flatten)
 (…)/ filter using the following mask:
  9⍴0 1 cyclically reshape [0,1] to length 9 (selects N, W, E, S)
 ' '≠ Boolean where non-space
 1⌽ rotate one step left; [W,E,S,N]
 2 2⍴ reshape to 2-by-2 matrix; [[W,E],[S,N]]
 ∨/ row-wise OR reduction: [horizontal,vertical]
 (…) apply the following tacit function:
  ⊢ the identity; [horizontal,vertical]
  ∧/, preceded by its AND reduction; [both,horizontal,vertical]
 (…), prepend the following:
  ,⍵ ravel (flatten) the neighbourhood
  5⊃ pick the 5th element (itself)
  ' '= Boolean if space (i.e. empty)
 Now we have [empty,both,horizontal,vertical]
 1⍳⍨ index of leftmost 1 (gives 5 if no neighbours at all)
 ' +-|+'⊃⍨ use that to pick symbol

Python 2, 181 168 bytes
thanks to Leaky Nun for -13 bytes
m=input()
f=lambda x,y:(['']+m+[''])[y+1][x:x+1]>' '
print[[(c<'!')*' 'or'+-|+'[f(x+1,y)|f(x-1,y)|2*f(x,y+1)|2*f(x,y-1)]for x,c in enumerate(r)]for y,r in enumerate(m)]

Try it online!

JavaScript (ES6), 110 bytes
I/O format: array of strings.
a=>a.map((s,y)=>s.replace(/\S/g,(_,x)=>'+|-+'[[-1,p=0,1,2].map(c=>p|=(a[y+c%2]||0)[x+~-c%2]>' '?c&1||2:0)|p]))

Try it online!
Or 108 bytes by using a matrix of characters instead.

MATLAB, 113 110 101 bytes
function F(A)
B=A>32
c=[1 1 1]
f=@(c)conv2(B,c,'s')>1
h=f(c)
v=f(c')
char((13*h+92*v-94*(h&v)).*B+32)

Converts input to logical, applies convolution in horizontal and vertical and combines the outputs to make the corresponding chars.
3 bytes saved by @Adriaan for telling me that you can clog the output in PPCG :P
9 bytes saved thanks to numerous @flawr comments!

J, 49 47 bytes
Thanks to FrownyFrog for -2 bytes!
' +|-+'{~~:&' '*1+h&.|:+2*h=:g&.|.*g=:' '=#{.}.

Try it online!

Retina 0.8.2, 92 bytes
\S
0
(?<=(.)*)0(?=(?>.*\n(?<-1>.)*)0)|0(?=(.)*)(?<=0(?>(?<-2>.)*\n.*))
1
T`d`+|`\b.\b
T`d`-+

Try it online! Requires rectangular input. Link includes test cases. Explanation:
\S
0

Change all non-spaces to 0s.
(?<=(.)*)0(?=(?>.*\n(?<-1>.)*)0)|0(?=(.)*)(?<=0(?>(?<-2>.)*\n.*))
1

Look for all 0s with another 0 immediately above or below in the same column and change them to a 1. The 1s are now the places with vertical neighbours, while the 0s have no vertical neighbours.
T`d`+|`\b.\b

Look for all digits with no horizontal neighbours. The 0s have no vertical neighbours either, so they become +s, while the 1s have vertical neighbours, so they become |s.
T`d`-+

The remaining digits have horizontal neighbours. The 1s also have vertical neighbours, so they become +s, while the 0s only have horizontal neighbours, so they become -s.

Python 3, 336 bytes
def g(s):
 h,j,s=' +|-+','',s.splitlines()
 s+=['']
 for n in range(len(s)):
  s[n]+=' '
  for i in range(len(s[n])-1):
   l,r,k=s[n][i-1],s[n][i+1],0
   try:u=s[n-1][i]
   except:u=' '
   try:d=s[n+1][i]
   except:d=' '
   if not s[n][i]==' ':
    k+=1
    if not u==d==' ':k+=1
    if not l==r==' ':k+=2
   j+=h[k]
  j+='\n'
 print(j)

Try it online!
I had to use a lot of code to deal with edge case errors.

C (gcc), 143 bytes
char**y,*z,h,v;f(char**x){for(y=x;*y;++y)for(z=*y;*z;++z)if(*z-32){h=z[1]-32|z[-1]-32;v=y[1][z-*y]-32|y[-1][z-*y]-32;*z=h?v?43:45:(v?'|':43);}}

Try it online!
The function f modifies an array of strings in-place. The area around the array must be padded with spaces (a bit constrained). Even though this doesn't exactly meet the requirements most solutions are using, it does conform to the rules if we say that we represent a newline with two spaces (and take array of strings ending in newlines).
Ungolfed
f(char**x){
    char **y;
    for (y = x; *y; ++y) {
        char *z;
        for (z = *y; *z; ++z) {
            if (*z != ' ') {
                if (z[1] != ' ' || z[-1] != ' ') {
                    // Horizontal exists
                    if (y[1][z-*y] != ' ' || y[-1][z-*y] != ' ')
                        // Vertical exists
                        *z = '+';
                    else
                        *z = '-';
                } else {
                    // Horizontal doesn't exist
                    if (y[1][z-*y] != ' ' || y[-1][z-*y] != ' ')
                        // Vertical exists
                        *z = '|';
                    else
                        *z = '+';
                }
            }
        }
    }
}

This was a fun challenge of pointer arithmetic. Using C-style pointer iteration it is easy to get the horizontal neighbors, but the vertical ones were tougher. Luckily the y pointer is still around (which points to the initial value of z) so I can deduce my index from it and use that to access the same element on a different row. It felt very wrong writing y[-1][z-*y] as it flies in the face of any reasonable style!

120 bytes


text:
Polynomial -> Integrate
Given a polynomial in one variable with rational coefficients, output an equivalent expression containing only 1, variables, and definite integrals. For example, -x2 can be expressed as ∫x∫111dtxdu.
E := 1 | var | ∫EEEdvar
Any reasonable input/output method is allowed.
Examples:

Your score will be the your code length multiplied by the number of ∫ symbols  used on the test cases. You should be able to score your program. Lowest score wins.
Test cases:
4/381*x^2+49/8*x^3-17/6
311/59*x^2-92/9*x^3-7/15*x
333/29*x^3+475/96*x^8

Golfing is going to be difficult, because I can't golf just the code or just the output, and I therefore do not know if a change will help or hurt my score until I try it, which sucks in my opinion.

Don't let the score restrict your creation. You are welcomed to answer with mainly one part of the score well optimized, even if the other one badly left.

related. Duplicate?

@OlivierGrégoire Inverse work

This is an interesting challenge, made much worse by its scoring system. I could instantly claim a score of 0, irregardless of my code's length, simply by assigning chr(8747)(or equivalent) to a variable, and using that as the sign, incurring zero occurrences of the symbol. I'd strongly recommend making this a vanilla code golf challenge.

@cairdcoinheringaahing No matter you use any output format, e.g. 0=[1,1,1], it's still counted as "1 ∫". Thus you can only get 0 score on test case 1 and x

Personally, I think this would be better as a code-golf question. Any solution will be impressive, so I don't think there's a need to require as few integrations as possible.

Also, that way you can change the test cases or add more without changing the score of each answer, which I think is really important. What if someone's program doesn't work for input of 0, for example, or -1? Does it need to if the test cases above are the only ones?

@mbomb007 https://codegolf.meta.stackexchange.com/a/2507  It's not a pure golf cuz some way to shorten makes the result expression long that's not what I so want

@mbomb007 polynomial mean no negative exponent

@l4m2 The expression is going to be huge no matter what if the only integer we can use is 1...

@mbomb007 not that large as you think

JavaScript (Node.js), 220 bytes * 616 integrals = 135520 score
O=[1,T='t',1,1]
D=(q,t)=>[t,'c',[q,T,1,O],q]
N=n=>n>0?[N(-n),T,1,O]:n?[D(1,1),'c',n&1?[T,T,O,1]:O,N(n/2|0)]:O
P=n=>n?[D(n%2?'x':1,T),T,O,P(n>>1)]:1
F=([e,...s])=>e?[1,T,[F(s),T,'x',O],[N(e[0]),T,O,[P(e[1]-1),'x',O,1]]]:O

Try it online!

Equation->Latex: ```function unpack(x) { return x instanceof Array ? \\int_{${unpack(x[2])}}^{${unpack(x[3])}}${unpack(x[0])}\\text d${unpack(x[1])} : x };
console.log (unpack(F([[0, 1], [-7, 15], [311, 59], [-92, 9]])).replace(/{(.)}/g,'$1'));```

Just edit your existing answer. We don't need a separate answer for each attempt with a different score. Also, the equation images you included are not even worth including because they're not legible.

@mbomb007 Usually I place similar solution together and quite different ones separated. The previous few times I found some not-allowed symbols used when I get the image, so I keep it here to easier see it's legal

Python 2, 315 bytes * 5113 = 1610595 score
I'm still working on golfing the score. Golfing is going to be difficult, because I can't golf just the code or just the output, and I therefore do not know if a change will help or hurt my score until I try it, which sucks in my opinion.
Despite the annoyance of golfing this, I did enjoy the calculus.
t='t'
Z=lambda n:N(Z(-n))if n<0else[1,t,N(1),Z(n-1)]if n>1else[[1,t,1,1],1][n]
N=lambda a:[1,t,a,Z(0)]
x=lambda n:n>1and[x(n-1),t,Z(0),'x']or'x'
M=lambda a,b:[b,t,Z(0),a]
print reduce(lambda a,b:[1,t,N(a),b],[M((lambda a,b:M(Z(a),[x(b-1)if b>1else 1,'x',Z(0),1]))(*c),x(i)if i else 1)for i,c in enumerate(input())])

Try it online!
Run all test cases - to score, count all [ in the output.
The input polynomial is taken as a list of (numerator, denominator) coefficient pairs in order from lowest to highest power of x. (0, 1) (zero) is used for missing powers.
Output is given with each integral represented by a list [f,t,a,b] to represent ∫abf dt
Verification
Here is a slightly less golfed version that outputs valid Mathematica syntax for integration, which may be tested in an online notebook. Unfortunately, decently-sized programs will not complete in a free notebook.
Go here, scroll to bottom, "Create New Notebook", paste (Wolfram Language Input), and evaluate (Shift+Enter) (Note that using num-pad Enter doesn't work).
Explanation
Uses these equations:

Links

Tool that converts the output to Mathematica nested functions

Tool that converts the output to Mathematica, avoiding recursion

Run the Mathematica output on TIO

Equation images made with this tool.

@l4m2 I added the links to the question so we can remove these comments. Thanks.

Define Z(n) as def Z(n):return N(Z(-n)) if n<0 else[1,t,1,1] if n<1 else 1 if n<2 else[1,t,N(1),Z(n-1)]?

or Z=lambda n:N(Z(-n))if n<0else[1,t,N(1),Z(n-1)]if n>1else[[1,t,1,1],1][n]

JavaScript (Node.js), 152 bytes * 5113 integrals = 777176 score
T='t';P=n=>--n?[T,'u',O,P(n)]:1;N=n=>n-1?n>-1?[1,T,N(1-n),1]:[1,T,N(-n),O]:1;O=N(0)
F=([e,...s])=>e?[1,T,[F(s),T,'x',O],[N(e[0]),T,O,[P(e[1]),T,O,1]]]:O

Try it online!
Mainly use these two equations: