text:
Valid Badminton Score?
Introduction:
I saw there was only one other badminton related challenge right now. Since I play badminton myself (for the past 13 years now), I figured I'd add some badminton-related challenges. Here the first one:
Challenge:
Input: Two integers
Output: One of three distinct and unique outputs of your own choice. One indicating that the input is a valid badminton score AND the set has ended with a winner; one indicating that the input is a valid badminton score AND the set is still in play; one indicating the input is not a valid badminton score.
With badminton, both (pairs of) players start with 0 points, and you stop when one of the two (pairs of) players has reached a score of 21, with at least 2 points difference, up to a maximum of 30-29.
So these are all possible input-pairs (in either order) indicating it's a valid badminton score AND the set has ended:
[[0,21],[1,21],[2,21],[3,21],[4,21],[5,21],[6,21],[7,21],[8,21],[9,21],[10,21],[11,21],[12,21],[13,21],[14,21],[15,21],[16,21],[17,21],[18,21],[19,21],[20,22],[21,23],[22,24],[23,25],[24,26],[25,27],[26,28],[27,29],[28,30],[29,30]]

And these are all possible input-pairs (in either order) indicating it's a valid badminton score BUT the set is still in play:
[[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[0,10],[0,11],[0,12],[0,13],[0,14],[0,15],[0,16],[0,17],[0,18],[0,19],[0,20],[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10],[1,11],[1,12],[1,13],[1,14],[1,15],[1,16],[1,17],[1,18],[1,19],[1,20],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[2,8],[2,9],[2,10],[2,11],[2,12],[2,13],[2,14],[2,15],[2,16],[2,17],[2,18],[2,19],[2,20],[3,3],[3,4],[3,5],[3,6],[3,7],[3,8],[3,9],[3,10],[3,11],[3,12],[3,13],[3,14],[3,15],[3,16],[3,17],[3,18],[3,19],[3,20],[4,4],[4,5],[4,6],[4,7],[4,8],[4,9],[4,10],[4,11],[4,12],[4,13],[4,14],[4,15],[4,16],[4,17],[4,18],[4,19],[4,20],[5,5],[5,6],[5,7],[5,8],[5,9],[5,10],[5,11],[5,12],[5,13],[5,14],[5,15],[5,16],[5,17],[5,18],[5,19],[5,20],[6,6],[6,7],[6,8],[6,9],[6,10],[6,11],[6,12],[6,13],[6,14],[6,15],[6,16],[6,17],[6,18],[6,19],[6,20],[7,7],[7,8],[7,9],[7,10],[7,11],[7,12],[7,13],[7,14],[7,15],[7,16],[7,17],[7,18],[7,19],[7,20],[8,8],[8,9],[8,10],[8,11],[8,12],[8,13],[8,14],[8,15],[8,16],[8,17],[8,18],[8,19],[8,20],[9,9],[9,10],[9,11],[9,12],[9,13],[9,14],[9,15],[9,16],[9,17],[9,18],[9,19],[9,20],[10,10],[10,11],[10,12],[10,13],[10,14],[10,15],[10,16],[10,17],[10,18],[10,19],[10,20],[11,11],[11,12],[11,13],[11,14],[11,15],[11,16],[11,17],[11,18],[11,19],[11,20],[12,12],[12,13],[12,14],[12,15],[12,16],[12,17],[12,18],[12,19],[12,20],[13,13],[13,14],[13,15],[13,16],[13,17],[13,18],[13,19],[13,20],[14,14],[14,15],[14,16],[14,17],[14,18],[14,19],[14,20],[15,15],[15,16],[15,17],[15,18],[15,19],[15,20],[16,16],[16,17],[16,18],[16,19],[16,20],[17,17],[17,18],[17,19],[17,20],[18,18],[18,19],[18,20],[19,19],[19,20],[20,20],[20,21],[21,21],[21,22],[22,22],[22,23],[23,23],[23,24],[24,24],[24,25],[25,25],[25,26],[26,26],[26,27],[27,27],[27,28],[28,28],[28,29],[29,29]]

Any other pair of integer would be an invalid badminton score.
Challenge rules:

I/O is flexible, so:

You can take the input as a list of two numbers; two separated numbers through STDIN or function parameters; two strings; etc.
Output will be three distinct and unique values of your own choice. Can be integers (i.e. [0,1,2], [1,2,3], [-1,0,1], etc.); can be Booleans (i.e. [true,false,undefined/null/empty]); can be characters/strings (i.e. ["valid & ended","valid","invalid"]); etc.
Please specify the I/O you've used in your answer!

You are allowed to take the input-integers pre-ordered from lowest to highest or vice-versa.
The input integers can be negative, in which case they are of course invalid.

General rules:

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

Test cases:
These test cases are valid, and the set has ended:
0 21
12 21
21 23
28 30
29 30

These test cases are valid, but the set is still in play:
0 0
0 20
12 12
21 21
21 22

These test cases are invalid:
-21 19
-19 21
-1 1
12 22
29 31
30 30
42 43
1021 1021

Stax, 20 bytes
ÇåπßéD╩¬7▼ß▌ΣU¬í╡S┤╘

Run and debug it
It takes input in the same format as the examples.  0 means there's a valid winner. 1 means the game is in progress. -1 means invalid score.
In pseudo-code, with ordered inputs x and y, the algorithm is
sign(clamp(x + 2, 21, 30) - y) | (x < 0 || x >= 30 ? 0 : -1)

sign means numeric sign (-1, 0, or 1)
clamp forces its first argument into the specified half-open interval

Python 2, 47 bytes
lambda a,b:[61>60-a>b<3+max(19,a)for b in-~b,b]

Try it online!
Outputs a list of two Booleans. Thanks to TFeld for writing a test suite in their answer that made it easy to check my solution.
ended: [False, True]
going: [True, True]
invalid: [False, False]

The key insight is that a valid score ends the game exactly if increasing the higher value b makes the score invalid. So, we just code up the validity condition, and check it for (a,b+1) in addition to (a,b) to see if the game has ended.
Validity is checked via three conditions that are chained together:

b<3+max(19,a): Checks that the higher score b isn't past winning, with either b<=21 or b<=a+2 (win by two)
60-a>b: Equivalent to a+b<=59, ensuring the score isn't above (29,30)
61>60-a: Equivalent to a>=0, ensures the lower score is non-negative

Python 2, 44 bytes
lambda a,b:[b-61<~ab/22*b-3for b in-~b,b]

Try it online!
An improved validity check by TFeld saves 3 bytes. The main idea is to branch on  "overtime" b>21 with b/22*b which effectively sets below-21 scores to zero, whereas I'd branched on a>19 with the longer max(19,a).

Python 2, 43 bytes
lambda a,b:a>>99|cmp(2+max(19,a)%30-a/29,b)

Try it online!
Outputs:
ended: 0
going: -1
invalid: 1

Assumes that the inputs are not below \$-2^{99}\$.

Using my newest validity-check (b-61<~ab/22*b-3), you can save 3 bytes.

+1 byte to make your second solution work for all inputs: lambda a,b:-(a<0)|cmp(2+max(19,a)%30-a/29,b)

Python 2, 97 95 75 72 71 70 69 64 55 54 52 51 50 48 bytes
lambda a,b:(b-61<~ab/22*b-3)*~(19<b-(b<30)>a)

Try it online!
Takes input as pre-ordered a,b.
Returns -2, -1, 0 for ended, in play, invalid.
-1 byte, thanks to Kevin Cruijssen

Left part (b-61<~ab/22*b-3) is a validity-check, and right part (19<b-(b<30)>a) is a check for game ended.

JavaScript (ES6),  55 53  48 bytes
Thanks to @KevinCruijssen for noticing that I was not fully assuming \$a\le b\$ (saving 5 bytes)
Takes input as (a)(b) with \$a\le b\$. Returns \$0\$ (valid), \$1\$ (ended) or \$2\$ (invalid).
a=>b=>a<0|a>29|b>30|b>21&b-a>2?2:b>20&b-a>1|b>29

Try it online!

Jelly, 25 bytes
»19«28‘<‘×+2>ɗʋ⁹×,%Ƒ“œþ‘ɗ

Try it online!
Left argument: minimum. Right argument: maximum.
Invalid: 0. Ongoing: 1. Ended: 2.
Mathematically, this works as below (the left argument is \$x\$, the right is \$y\$):
$$[a]=\cases{a\colon1\\\lnot a\colon0}\\\otimes(a,b)=(a\bmod30,b\bmod31)\\x,y\in\mathbb Z\\X:=\min(\max(x+1,20),29)\\p:=(x,y)\\([X<y]+1)[X+2>y][p=\otimes p]$$
Explanation:
»19«28‘<‘×+2>ɗʋ⁹×,%Ƒ“œþ‘ɗ Left argument: x, Right argument: y
»19«28‘                   X := Bound x + 1 in [20, 29]:
»19                         X := max(x, 19).
   «28                      X := min(X, 28).
      ‘                     X := X + 1.
       <‘×+2>ɗʋ⁹          X := If X + 2 <= y, then 0, else if X < y, then 2, else 1:
       <                    t := If X < y, then 1, else 0.
        ‘                   t := t + 1.
          +2>ɗ              u := Check if X + 2 > y:
          +2                  u := X + 2.
            >                 u := If u > y, then 1, else 0.
         ×                  X := t * u.
                 ,%Ƒ“œþ‘ɗ z := If x mod 30 = x and y mod 31 = y, then 1, else 0:
                 ,          z := (x, y).
                  % “œþ‘    m := z mod (30, 31) = (x mod 30, y mod 31).
                   Ƒ        z := If z = m, then 1, else 0.
                ×         X * z.

C# (Visual C# Interactive Compiler), 53 52 bytes
a=>b=>b<0|a-b>2&a>21|b>29|a>30?3:a>20&a-b>1|a>29?1:2

Called as f(max)(min). Returns 3 for invalid, 1 for finished, 2 for ongoing.
Saved 1 byte thanks to Kevin Cruijjsen
Try it online!

APL (Dyalog Unicode), 35 bytesSBCS
Infix tacit function where ended is 2, ongoing is 1, invalid is 0, smaller and larger scores are left.
(,≡30 31|,)×(⊢<2+X)×1+⊢>X←29⌊20⌈1+⊣

Try it online!
Implements Erik the Outgolfer's mathematical formulas combined into
$$X:=\min(\max(x+1,20),29)\\\ ([X< y]+1)[X+2>y][(x,y)=(x\bmod30,y\bmod31)]$$
rearranged (as if traditional mathematical notation had vectorisation and inline assignments) to
$$[(x,y)=(x,y)\bmod(30,31)]×[y<2+X]×(1+[y< (X:=\min(29,\max(20,1+x)))])$$
and translated directly to APL (which is strictly right-associative, so we avoid some parentheses):
$$((x,y)≡30\ 31|x,y)×(y<2+X)×1+y>X←29⌊20⌈1 +x$$
This can be converted into a tacit function simply by substituting \$⊣\$ for \$x\$ and \$⊢\$ for \$y\$, symbolising the left and right arguments rather than the two variables:
$$((⊣,⊢)≡30\ 31|⊣,⊢)×(⊣<2+X)×1+⊢>X←29⌊20⌈1+⊣$$
Now \$⊣⎕⊢\$ is equivalent to \$⎕\$ for any infix function \$⎕\$, so we can simplify to
$$(,≡30\ 31|,)×(⊣<2+X)×1+⊢>X←29⌊20⌈1+⊣$$
which is our solution; (,≡30 31|,)×(⊢<2+X)×1+⊢>X←29⌊20⌈1+⊣:
⊣ the left argument; \$x\$
1+ one plus that; \$1+x\$
20⌈ maximum of 20 and that; \$\max(20,…)\$
29⌊ minimum of 29 and that; \$\min(29,…)\$
X← assign that to X; \$X:=…\$
⊢> is the right argument greater (0/1)?; \$[y>…]\$
1+ add one; \$1+…\$
(…)× multiply the following by that; \$(…)×…\$
 2+X two plus X; \$2+X\$
 ⊢< is the right argument less than that (0/1); \$[y<…]\$
(…)× multiply the following by that; \$(…)×…\$
 , concatenate the arguments; \$(x,y)\$
 30 31| remainders when divided by these numbers; \$…\mod(30,31)\$
 ,≡ are the concatenated arguments identical to that (0/1)?; \$[(x,y)=…]\$

VDM-SL, 80 bytes
f(i,j)==if(j-i>2and j>21)or(i<0or i=30or j>30)then{}else{(j>20and j-i>1or j=30)}

This function takes the scores ordered in ascending order and returns the empty set if the score is invalid or the set containing whether the set is complete (so {true} if the set is complete and valid and {false} if the set is incomplete and valid)
A full program to run might look like this:
functions
f:int*int+>set of bool
f(i,j)==if(j-i>2and j>21)or(i<0or i=30or j>30)then{}else{(j>20and j-i>1or j=30)}

Explanation:
if(j-i>2 and j>21)             /*if scores are too far apart*/
or(i<0 or i=30 or j>30)        /*or scores not in a valid range*/
then {}                        /*return the empty set*/
else{                       }  /*else return the set containing...*/
     (j>20 and j-i>1 or j=30)  /*if the set is complete*/

Java (JDK), 59 48 bytes
a->b->b<0|b>29|a>b+2&a>21|a>30?0:a<21|a<30&a                      // Curried: Target type IntFunction<IntFunction<Object>>
    b->                  // Target type IntFunction<Object>
                         // Invalid if:
            b<0          //    Any score is negative
          | b > 29       //    Both scores above 29
          |   a > b + 2  //    Lead too big
            & a > 21     //        and leader has at least 21 points
          | a > 30       //    Anyone has 31 points
        ? 0              // If invalid, return 0 (autoboxed to Integer)
                         // If valid, return whether the game is ongoing (autoboxed to Boolean)
                         // Ongoing if:
        :   a < 21       //    Nobody has 21 points
          |   a < 30     //    Leader has fewer than 30 points
            & a < b + 2  //        and lead is small

x86 Assembly, 42 Bytes
Takes input in ECX and EDX registers. Note that ECX must be greater than EDX.
Outputs into EAX, where 0 means the game's still on, 1 representing the game being over and -1 (aka FFFFFFFF) representing an invalid score.
31 C0 83 F9 1E 77 1F 83 FA 1D 77 1A 83 F9 15 7C
18 83 F9 1E 74 12 89 CB 29 D3 83 FB 02 74 09 7C
08 83 F9 15 74 02 48 C3 40 C3

Or, more readable in Intel Syntax:
check:
    XOR EAX, EAX
    CMP ECX, 30     ; check i_1 against 30
    JA .invalid     ; if >, invalid.
    CMP EDX, 29     ; check i_2 against 29
    JA .invalid     ; if >, invalid.
    CMP ECX, 21     ; check i_1 against 21
    JL .runi        ; if <, running.
    CMP ECX, 30     ; check i_1 against 30
    JE .over        ; if ==, over.
    MOV EBX, ECX
    SUB EBX, EDX    ; EBX = i_1 - i_2
    CMP EBX, 2      ; check EBX against 2
    JE .over        ; if ==, over.
    JL .runi        ; if <, running.
                    ; if >, keep executing!
    CMP ECX, 21     ; check i_1 against 21
    JE .over        ; if ==, over.
                    ; otherwise, it's invalid.
    ; fallthrough!
    .invalid:
        DEC EAX     ; EAX = -1
        RETN
    .over:
        INC EAX     ; EAX = 1
    ; fallthrough!
    .runi:
        RETN        ; EAX = 0 or 1

Fun fact: this function almost follows the C Calling Convention's rules on which registers to preserve, except I had to clobber EBX to save some bytes on stack usage.

Optional (not included in byte-count)
By adding the following 6 bytes directly before start of the code above, you can pass ECX and EDX unordered:
39 D1 7D 02 87 CA

Which is the following in readable Intel Syntax:
CMP ECX, EDX
JGE check
XCHG ECX, EDX

Retina 0.8.2, 92 bytes
\d+
$*
^(1{0,19},1{21}|(1{20,28}),11\2|1{29},1{30})$|^(1*,1{0,20}|(1{0,28}),1?\4)$|.+
$#1$#3

Try it online! Link includes test cases. Takes input in ascending order. Explanation: The first stage simply converts from decimal to unary so that the scores can be properly compared. The second stage contains six alternate patterns, grouped into three groups so that three distinct values can be output, which are 10 for win, 01 for ongoing and 00 for illegal. The patterns are:

Against 0-19, a score of 21 is a win
Against 20-28, a score of +2 is a win
Against 29, a score of 30 is a win
Against any (lower) score, a score of 0-20 is ongoing
Against a score of up to 28, a score of +1 is ongoing
Anything else (including negative scores) is illegal

Bash 4+, 97 89 91 88 bytes
Assume that inputs are ascending. Used concepts from VDM-SL answer. Try it Online

z==0 - game in progress
z==1 - game completed
z==2 - invalid
-8 by bracket cleanup from (( & | )) conditions
+2 fixing a bug, thanks to Kevin Cruijssen
-3 logic improvements by Kevin Cruijssen
i=$1 j=$2 z=0
((j-i>2&j>21|i<0|i>29|j>30?z=2:0))
((z<1&(j>20&j-i>1|j>29)?z=1:0))
echo $z

Your 89 bytes version seems to output 1 instead of 2 for 0 30. Your 97 bytes version was working correctly, so if you're unable to fix it, you can always rollback. Upvoted for that 97 version. :)

This should fix it, and golf a byte at the same time. :)

I fixed it, but yours was better! Hard to keep up :P

Bug at 29 30 :( it should be "completed"

Ah oops.. the i>29 should be j>29 in the second ternary to fix it.

APL (Dyalog Unicode), 33 32 bytesSBCS
{h⍵+1 0}+h←(⊢≡31 30|⊢)×21 2∨.≥-\

Try it online!
in: a pair in descending order
out: 2=ongoing, 1=ended, 0=invalid
tests stolen from Adám's answer


text:
Return the Closest Prime Number
Challenge
This is a simple one: Given a positive integer up to 1,000,000, return the closest prime number.
If the number itself is prime, then you should return that number; if there are two primes equally close to the provided number, return the lower of the two.
Input is in the form of a single integer, and output should be in the form of an integer as well.
I don't care how you take in the input (function, STDIN, etc.) or display the output (function, STDOUT, etc.), as long as it works.
This is code golf, so standard rules apply—the program with the least bytes wins!
Test Cases
Input  =>  Output
------    -------
80     =>      79
100    =>     101
5      =>       5
9      =>       7
532    =>     523
1      =>       2

Hi and welcome to PPCG!. To avoid down voting due to lack of quality I suggest you to post it to the sandbox first and after a couple of days post it here

This is one of the outputs requested in this challenge.

Very closely related but not quite identical.

@Arnauld I saw that one, but I thought that they were different enough to warrant a new question.

@Giuseppe Yeah, I found out about that one after already posting...

@Arnauld Good idea! Added.

@Arnauld Oh! That’s really good!

Welcome to PPCG. Nice challenge and +1 for your opening note. Sandbox, as suggested by others, is a great place to start.

See also OEIS A051697.

@EricTowers Oh wow... That's really convenient! How should I reference that in my question?

@Bobawob just add it in and say something like "This is OEIS A051697" with a link. Simple enough :-)

Can anyone get this working with JS generators? I haven't had much luck here

Gaia, 3 bytes
ṅD⌡

Try it online!
Rather slow for large inputs, but works given enough memory/time.
I'm not sure why D⌡ implicitly pushes z again, but it makes this a remarkably short answer!
ṅ	| implicit input z: push first z prime numbers, call it P
 D⌡	| take the absolute difference between P and (implicit) z,
	| returning the smallest value in P with the minimum absolute difference

JavaScript (ES6), 53 bytes
n=>(g=(o,d=N=n+o)=>N%--d?g(o,d):d-1?g(o<0?-o:~o):N)``

Try it online!
Commented
n => (            // n = input
  g = (           // g = recursive function taking:
    o,            //   o = offset
    d =           //   d = current divisor, initialized to N
    N = n + o     //   N = input + offset
  ) =>            //
    N % --d ?     // decrement d; if d is not a divisor of N:
      g(o, d)     //   do recursive calls until it is
    :             // else:
      d - 1 ?     //   if d is not equal to 1 (either N is composite or N = 1):
        g(        //     do a recursive call with the next offset:
          o < 0 ? //       if o is negative:
            -o    //         make it positive (e.g. -1 -> +1)
          :       //       else:
            ~o    //         use -(o + 1) (e.g. +1 -> -2)
        )         //     end of recursive call
      :           //   else (N is prime):
        N         //     stop recursion and return N
)``               // initial call to g with o = [''] (zero-ish)

05AB1E, 5 bytes
Åps.x

Try it online!
or as a Test Suite
Inefficient for big numbers

Too bad Ån is "In case of a tie, the higher prime is pushed" Didn't even knew we had this builtin, tbh.

@KevinCruijssen: Neither did I until now :)

Octave, 40 bytes
@(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

Try it online!
This uses the fact that there is always a prime between n and 2*n (Bertrand–Chebyshev theorem).
How it works
@(n)p([~,k]=min(abs(n-(p=primes(2*n)))))

@(n)                                      % Define anonymous function with input n
                       p=primes(2*n)      % Vector of primes up to 2*n. Assign to p
                abs(n-(             ))    % Absolute difference between n and each prime
      [~,k]=min(                      )   % Index of first minimum (assign to k; not used)
    p(                                 )  % Apply that index to p

Japt, 5 bytes
_j}cU

Try it or run all test cases
_j}cU     :Implicit input of integer U
_         :Function taking an integer as an argument
 j        :  Test if integer is prime
  }       :End function
   cU     :Return the first integer in [U,U-1,U+1,U-2,...] that returns true

Wolfram Language (Mathematica), 31 bytes
Nearest[Prime~Array~78499,#,1]&

Try it online!
                              & (*pure function*)
        Prime~Array~78499       (*among the (ascending) first 78499 primes*)
                            1   (*select one*)
Nearest[                 ,#, ]  (*which is nearest to the argument*)

1000003 is the 78499th prime. Nearest prioritizes values which appear earlier in the list (which are lower).

Nearest[Prime@Range@#,#,1]& for 27

Jelly, 9 7 bytes
ḤÆRạÞµḢ

Try it online!
Slow for larger input, but works ok for the requested range.  Thanks to @EriktheOutgolfer for saving 2 bytes!

Hey, that's clever! Save two by substituting _A¥ with ạ (absolute difference). Oh, and Ḥ can really be ‘.

@EriktheOutgolfer thanks. Surely using ‘ won’t always work? It means that only primes up to n+1 will be found, while the closest might be n+2.

Hm, that's a concern.

Python 2, 71 bytes
f=lambda n,k=1,p=1:k<n*3and min(k+n-p%k*2*n,f(n,k+1,p*k*k)-n,key=abs)+n

Try it online!
A recursive function that uses the Wilson's Theorem prime generator. The product p tracks \$(k-1)!^2\$, and p%k is 1 for primes and 0 for non-primes. To make it easy to compare abs(k-n) for different primes k, we store k-n and compare via abs, adding back n to get the result k.
The expression k+n-p%k*2*n is designed to give k-n on primes (where p%k=1), and otherwise a "bad" value of k+n that's always bigger in absolute value and so doesn't affect the minimum, so that non-primes are passed over.

05AB1E, 4 bytes
z-Ån

Try it online!

Brachylog, 7 5 bytes
;I≜-ṗ

Try it online!
Saved 2 bytes thanks to @DLosc.
Explanation
;I≜      Label an unknown integer I (tries 0, then 1, then -1, then 2, etc.)
   -     Subtract I from the input
    ṗ    The result must be prime

@DLosc Mostly because I am stupid. Thanks.

I think we just approached it from different directions. You were thinking about ≜ from the start, I assume, whereas I was thinking about pairing and subtracting and only later realized I'd need ≜ to make it work. :)

C (gcc), 87 76 74 72 bytes
Optimization of innat3's C# (Visual C# Interactive Compiler), 100 bytes

f(n,i,t,r,m){for(t=0,m=n;r-2;t++)for(r=i=1,n+=n<m?t:-t;i<n;n%++i||r++);}

Try it online!

Hello and welcome to PPCG. A few tips: r!=2 is equivalent to r-2, n%++i?0:r++ can most likely be n%++i||r++.

I didn't immediately see that. Thanks.

Pyth, 10 bytes
haDQfP_TSy

Try it online here, or verify all the test cases at once here.
haDQfP_TSyQ   Implicit: Q=eval(input())
              Trailing Q inferred
         yQ   2 * Q
        S     Range from 1 to the above
    f         Filter keep the elements of the above, as T, where:
     P_T        Is T prime?
  D           Order the above by...
 a Q          ... absolute difference between each element and Q
                This is a stable sort, so smaller primes will be sorted before larger ones if difference is the same
h             Take the first element of the above, implicit print

C, 122 121 104 bytes
p(a,i){for(i=1;++i<a;)if(a%i<1)return 0;return a>1;}c(a,b){for(b=a;;b++)if(p(--a)|p(b))return p(b)?b:a;}

Use it calling function c() and passing as argument the number; it should return the closest prime.
Thanks to Embodiment of Ignorance for 1 byte saved a big improvement.
Try it online!

But c() receives two parameters... Also, you can probably shorten the while(1) to for(;;) (untested, since I don't get how to run your code

@EmbodimentofIgnorance I wrote it and tested it all on an online c compiler, I could call c() passing only the first parameter. And you are right, for(;;) saves me a byte, only 117 left to get first place :)

110 bytes: #define r return p(a,i){i=1;while(++i<a)if(a%i<1)r 0;r a>1;}c(a,b){b=a;for(;;b++){if(p(--a))r a;if(p(b))r b;}}. Here is a TIO link: https://tio.run/##TU5BTsQwDLznFdaiSomaSi0IBHK7F54Be3DaBCwtoUqLOFR5e3HKZX0Ye@wZ22MzXil@7Pvd5ANHDwmSX39SVLMmy2bjocPfT756Xdfck@GgqeK@MwlaTEDnDvMoUmc2NxCG76QRXV2LM@hZNw0ZkRIezJXaYc674rjCF3HURm0KJEpj9cv6Sotf3i4wwAbPrYWuFXi08CL4cC8cMqrDUW4VF4u2RUk9PCHIm@YY/68tMSeRBX2qJmjOUE3v8WRvbvHFwqhvuTF4mLPK@x8

106: https://tio.run/##TY7NToRADMfv8xTNJiRtGBLQaHQL68HH0D10WNAmuyMBjAecZ8cZ1GR76Of/17Yt2rP4t3UdUKzSok3FX@967jDPtRbSHiXTuqKxmz9HDyX/JXKoOLQRcrS4Rrj/GJHZ5XlCBiwKoe8BHf2DKX9ye@GwGvUzXEQ9klkMREuNuZvmZ5m66eUIDSzwUFqoyujuLDxGf3sTawhsNiKdS5RGbckx1HDPEH@mbfy7NtkwRlmPu@wExQGy06vf2atberTQ4nVNxBscTFh/AA

101: https://tio.run/##TY7NTsMwDMfveQozqShWUqkFDQ3cjgOPATu4TcssjVC1RRxKnr0khcN88Of/Z7vN2wv793UdNFuxDhepS/o@y6XTxkjF6EzNmVQljd38NXrgY3l74yi0EWhw6T9H3dRM1BiD0utB5znjz6AbxH8i5c/NE1NYlfgZPli8RrUoiJYaczfNLzx10@sJaljgUFgoi@j2Fh6jv7@LNQRSG5EuJkqitqAYKnggiM/iNv5bm2wYo6zXu8xBfoTMvfmdvbolJwutvq4RaYODCusv

The 101 bytes version doesn't seem to be working, according to the test cases. And I couldn't get my head around the new p() function to try and fix it.

102 bytes

Factor, 91 bytes
: p ( x -- x ) [ nprimes ] keep dupd [ - abs ] curry map swap zip natural-sort first last ;

Try it online!

Perl 6, 35 bytes
{$_+=($*=-1)*$++until .is-prime;$_}

Try it online!
This uses Veitcel's technique for generating the list of 0, -1, 2, -3 but simplifies it greatly to ($*=-1)*$++ using the anonymous state variables available in P6 (I originally had -1 ** $++ * $++, but when golfed the negative loses precedence).  There's a built in prime checker but unfortunately the until prevents the automagically returned value so there's an extra $_ hanging around.

I'd usually use a sequence operator approach to something like this, but comes out to one byte longer, so nice work finding a shorter method

@JoKing good catch.  The things that happen when I golf too quickly after getting a working solution.  I had a similar one but the damned lack of [-1] haha

Wolfram Language (Mathematica), 52 bytes
If[PrimeQ[s=#],s,#&@@Nearest[s~NextPrime~{-1,1},s]]&

Try it online!

You have an extra space that can be removed to save a byte.

@Ben you are right. thanx

Python 2 (Cython), 96 bytes
l=lambda p:min(filter(lambda p:all(p%n for n in range(2,p)),range(2,p*3)),key=lambda x:abs(x-p))

Try it online!

Might be able to save a couple bytes via r=range;...

@Arnauld, it now works for x=1

APL (Dyalog Extended), 20 15 bytesSBCS
Tacit prefix function inspired by Galen Ivanov's J answer.
⊢(⊃⍋⍤|⍤-⊇⊢)¯2⍭⍳

Try it online!
⍳ ɩndices one through the argument.
¯2⍭ nth primes of that
⊢(…) apply the following tacit function to that, with the original argument as left argument:
 ⊢ the primes
 ⊇ indexed by:
  ⍋ the ascending grade (indices which would sort ascending)
  ⍤ of
  | the magnitude (absolute value)
  ⍤ of
  - the differences
 ⊃ pick the first one (i.e. the one with smallest difference)

Tidy, 43 bytes
{x:(prime↦splice(]x,-1,-∞],[x,∞]))@0}

Try it online!
Explanation
This is a lambda with parameter x. This works by creating the following sequence:
[x - 1, x, x - 2, x + 1, x - 3, x + 2, x - 4, x + 3, ...]

This is splicing together the two sequences ]x, -1, -∞] (left-closed, right-open) and [x, ∞] (both open).
For x = 80, this looks like:
[79, 80, 78, 81, 77, 82, 76, 83, 75, 84, 74, 85, ...]

Then, we use f↦s to select all elements from s satisfying f. In this case, we filter out all composite numbers, leaving only the prime ones. For the same x, this becomes:
[79, 83, 73, 71, 89, 67, 97, 61, 59, 101, 103, 53, ...]

Then, we use (...)@0 to select the first member of this sequence. Since the lower of the two needs to be selected, the sequence which starts with x - 1 is spliced in first.
Note: Only one of x and x - 1 can be prime, so it is okay that the spliced sequence starts with x - 1. Though the sequence could be open on both sides ([x,-1,-∞]), this would needlessly include x twice in the sequence. So, for sake of "efficiency", I chose the left-closed version (also because I like to show off Tidy).

C# (Visual C# Interactive Compiler), 104 100 bytes
n=>{int r=0,t=0,m=n;while(r!=2){n+=(n<m)?t:-t;t++;r=0;for(int i=1;i<=n;i++)if(n%i==0)r++;}return n;}

Try it online!
Explanation:
int f(int n)
{
    int r = 0; //stores the amount of factors of "n"
    int t = 0; //increment used to cover all the integers surrounding "n"
    int m = n; //placeholder to toggle between adding or substracting "t" to "n"

    while (r != 2) //while the amount of factors found for "n" is different to 2 ("1" + itself)
    {
        n += (n < m) ? t : -t; //increment/decrement "n" by "t" (-0, -1, +2, -3, +4, -5,...)
        t++;
        r = 0;
        for (int i = 1; i <= n; i++) //foreach number between "1" and "n" increment "r" if the remainder of its division with "n" is 0 (thus being a factor)
            if (n % i == 0) r++;
    }
    return n;
}

Console.WriteLine(f(80)); //79

88 bytes

VDM-SL, 161 bytes
f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})

A full program to run might look like this - it's worth noting that the bounds of the set of primes used should probably be changed if you actually want to run this, since it will take a long time to run for 1 million:
functions
f:nat1+>nat1
f(i)==(lambda p:set of nat1&let z in set p be st forall m in set p&abs(m-i)>=abs(z-i)in z)({x|x in set{1,...,9**7}&forall y in set{2,...,1003}&y<>x=>x mod y<>0})

Explanation:
f(i)==                                        /* f is a function which takes a nat1 (natural number not including 0)*/
(lambda p:set of nat1                         /* define a lambda which takes a set of nat1*/
&let z in set p be st                         /* which has an element z in the set such that */
forall m in set p                             /* for every element in the set*/
&abs(m-i)                                     /* the difference between the element m and the input*/
>=abs(z-i)                                    /* is greater than or equal to the difference between the element z and the input */
in z)                                         /* and return z from the lambda */
(                                             /* apply this lambda to... */
{                                             /* a set defined by comprehension as.. */
x|                                            /* all elements x such that.. */
x in set{1,...,9**7}                          /* x is between 1 and 9^7 */
&forall y in set{2,...,1003}                  /* and for all values between 2 and 1003*/
&y<>x=>x mod y<>0                             /* y is not x implies x is not divisible by y*/
}
)

APL(NARS), 38 chars, 76 bytes
{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}

0π is the test for prime, ¯1π the prev prime, 1π is the next prime; test:
  f←{⍵≤1:2⋄0π⍵:⍵⋄d←1π⍵⋄(d-⍵)≥⍵-s←¯1π⍵:s⋄d}
  f¨80 100 5 9 532 1
79 101 5 7 523 2

J, 19 15  bytes
(0{]/:|@-)p:@i.

Try it online!

Perl 5, 57 bytes
$a=0;while((1x$_)=~/^.?$|^(..+?)\1+$/){$_+=(-1)**$a*++$a}

Try it online!
/^.?$|^(..+?)\1+$/ is tricky regexp to check prime
(-1)**$a*++$a generate sequence 0,-1, 2,-3 ...

MathGolf, 10 bytes
∞╒g¶áÅ-±├Þ

Try it online.
Explanation:
∞            # Double the (implicit) input-integer
 ╒           # Create a list in the range [1, 2*n]
  g¶         # Filter so only the prime numbers remain
    áÅ       # Sort this list using the next two character:
      -±     #  The absolute difference with the (implicit) input-integer
        ├    # Push the first item of the list
             # (unfortunately without popping the list itself, so:)
         Þ   # Discard everything from the stack except for the top
             # (which is output implicitly as result)

@JoKing Thanks! I knew Max thought about changing it, but didn't knew he actually did. The docs still state the old one.

Ah, I use the mathgolf.txt file as reference, since it seems to be more up to date

@JoKing Yeah, he told me yesterday about that file as well. Will use it from now on. :)

Haskell, 79 74 bytes (thanks to Laikoni)
72 bytes as annonymus function (the initial "f=" could be removed in this case).
f=(!)(-1);n!x|x>1,all((>0).mod x)[2..x-1]=x|y<-x+n=last(-n+1:[-n-1|n>0])!y

Try it online!

original code:
f=(!)(-1);n!x|x>1&&all((>0).mod x)[2..x-1]=x|1>0=(last$(-n+1):[-n-1|n>0])!(x+n)

Try it online!
Explanation:
f x = (-1)!x

isPrime x = x > 1 && all (\k -> x `mod` k /= 0)[2..x-1]
n!x | isPrime x = x            -- return the first prime found
    | n>0       = (-n-1)!(x+n) -- x is no prime, continue with x+n where n takes the
    | otherwise = (-n+1)!(x+n) -- values -1,2,-3,4 .. in subsequent calls of (!)

Inside a guard you can use , instead of &&. (last$ ...) can be last(...), and the second guard 1>0 can be used for a binding to save parenthesis, e.g. y<-x+n.

Anonymous functions are generally allowed, so the initial f= does not need to be counted. Also the parenthesis enclosing (-1+n) can be dropped.

Thanks for the suggestions. I didn't know "," and bindings are allowed in function guards! But i don't really like the idea of an annonymous function as an answer. It doesn't feel right in my opinion.

You can find more tips in our collection of tips for golfing in Haskell. There is also a Guide to Golfing Rules in Haskell and dedicated chat room: Of Monads and Men.

Java (JDK), 103 bytes
n->{int p=0,x=0,z=n,d;for(;p<1;p=p>0?z:0,z=z==n+x?n-++x:z+1)for(p=z/2,d=1;++d<z;)p=z%d<1?0:p;return p;}

Try it online!

Umm.. I had already create a port of his answer.. ;) Although yours is 1 byte shorter, so something is different. EDIT: Ah, I have a result-integer outside the loop, and you modify the input inside the loop, hence the -1 byte for ;. :) Do you want me to delete my answer?.. Feel free to copy the explanation.

@KevinCruijssen Oops, rollbacked!

Sorry about that (and thanks for the -1 byte). I like your version as well, though. Already upvoted before I saw NaturalNumberGuy's answer.

Java 8, 88 87 bytes
n->{for(int c=0,s=0,d,N=n;c!=2;s++)for(c=d=1,n+=n<N?s:-s;d<n;)if(n%++d<1)c++;return n;}

Port of @NaturalNumberGuy's (first) C answer, so make sure to upvote him!!
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{               // Method with integer as both parameter and return-type
  for(int c=0,     //  Counter-integer, starting at 0
          s=0,     //  Step-integer, starting at 0 as well
          d,       //  Divisor-integer, uninitialized
          N=n;     //  Copy of the input-integer
      c!=2;        //  Loop as long as the counter is not exactly 2 yet:
      s++)         //    After every iteration: increase the step-integer by 1
    for(c=d=1,     //   (Re)set both the counter and divisor to 1
        n+=n<N?    //   If the input is smaller than the input-copy:
            s      //    Increase the input by the step-integer
           :       //   Else:
            -s;    //    Decrease the input by the step-integer
        d<n;)      //   Inner loop as long as the divisor is smaller than the input
      if(n%++d     //    Increase the divisor by 1 first with `++d`
              <1)  //    And if the input is evenly divisible by the divisor:
        c++;       //     Increase the counter-integer by 1
  return n;}       //  Return the now modified input-integer as result

MATL, 6 bytes
t:YqYk

Try it online!
List the first n primes and find the one closest to n.

C# (Visual C# Interactive Compiler), 112 bytes
g=>Enumerable.Range(2,2<<20).Where(x=>Enumerable.Range(1,x).Count(y=>x%y<1)<3).OrderBy(x=>Math.Abs(x-g)).First()

Try it online!
Left shifts by 20 in submission but 10 in TIO so that TIO terminates for test cases.

Swift, 186 bytes
func p(a:Int){let b=q(a:a,b:-1),c=q(a:a,b:1);print(a-b<=c-a ? b:c)}
func q(a:Int,b:Int)->Int{var k=max(a,2),c=2;while k>c && c != a/2{if k%c==0{k+=b;c=2}else{c=c==2 ? c+1:c+2}};return k}

Try it online!

Jelly, 14 bytes
ÆpæRÆnạÞƲ2>?2Ḣ

Try it online!

C# (Visual C# Interactive Compiler), 87 bytes
n=>{int i=0;for(;n<2||Enumerable.Range(2,n-2).Any(x=>n%x<1);n+=++i%2<1?-i:i);return n;}

Try it online!

Python 2, 93 bytes
lambda n:sorted(range(1,3*n),key=lambda x:abs(x-n)if all(x%k for k in range(2,x))else 2*n)[0]

You don't need the f= in the start

@EmbodimentofIgnorance Thanks, fixed that along with the range and non-prime penalty criteria that was causing n=1 to fail

The primality check doesn't work for Fermat pseudoprimes such as 341=31*11 which it calls prime.

Zsh, 101 92 91 90 bytes
-9 by collapsing the body into the head of p's loop, -1 from using i=j instead of i=$1 in main loop, -1 by replacing a && with a ,.
p(){for ((n=2;n<$1&&$1%n++;)):
(($1==n))&&<<<$1}
j=$1
for ((i=j;;++j,--i))p $i||p $j&&exit

Try it online!
Try it online!
Try it online!
57 48 bytes to the prime testing function, 43 41 bytes to the main loop (1 byte to the newline between them):
p(){  # prime function: takes one input, outputs via return code
for (( n = 2; n < $1 && $1 % n++; ))   # divisibility check in loop header
    :                 # no-op loop body
(( $1 == n )) &&      # if we looped up to $1:
    <<< $1            #     echo out $1. Otherwise, this will return false
}

For the last condition, we can't use the shorter (($1-n))||, because we need to return false to the main loop if we didn't find a prime. We print in the function to avoid complexity in the main loop.
j=$1                          # set i = j = $1. Doing one in and one out is smallest
for (( i = j; ; ++j , --i )) # loop indefinitely, increment and decrement
    p $i || p $j && exit      # if either $i or $j was a prime, exit

Conditionals are left-associative, which we take advantage of here. We do test the starting number twice to make the decrement logic simpler.

TSQL query, 155 bytes
USE master
DECLARE @ INT=1000000;

WITH C as(SELECT abs(number-500+@)r,abs(number)+2s
FROM spt_values)SELECT top 1r FROM c
WHERE 0not in(SELECT c.r%s FROM c d
WHERE c.r>s)ORDER BY abs(r-@),r

Try it online

@TobySpeight thanks for improving my answer. Can you please explain what this  does? Is it something I should include in all my answers ?

That's a prettify hint; you can find out about it near the end of Editing Help.

Ruby, 67 bytes
def p n;n.prime?;end;def a b,c=0;p(b-c)?b-c:p(b+c)?b+c:a(b,c+1);end

Try it online!

C (gcc), 78 65 bytes
f(n,i,j){for(i=j=0;j-1;i++)for(j=n+=i%2?-i:i;--j,n-1&&n%j;);i=n;}

Try it online!
f(n,i,j){
    for(i=j=0;j-1;i++)      //while j!=1
        for(j=n+=i%2?-i:i;  // step to next closest value to original input n
            --j,n-1&&n%j;); // find greatest factor which is less than j
    i=n;                    //return
}

@ceilingcat division by 0 when n=1

Ruby -rprime, 39 bytes
Relies on the idea that for any positive integer \$n\$, the \$n\$th prime is always larger than \$n\$.
->n{Prime.take(n).min_by{|i|(i-n).abs}}

Try it online!

Wolfram Language (Mathematica), 22 bytes
RiemannR/*Round/*Prime

Try it online!
This is an approximate solution that by chance works for all of the given test cases, but gives a slightly wrong result for other inputs. The Riemann R function is an approximation of the prime-counting function, which we round to the nearest integer and then request the prime number of that index.

TI-BASIC (TI-84+), 74 Bytes
Ans→A:{2,3→A:For(P,5,2A,2:If min(remainder(P,seq(X,X,3,1+√(P),2:P→∟A(1+dim(∟A:End:abs(A-∟A:∟A(1+sum(not(cumSum(Ans=min(Ans

Hexdump:
(Token hex-values found here.)
72 04 41 3E 08 32 2B 33 04 41 3E D3 50 2B 35 2B | Ans→A:{2,3→A:For(P,5,
32 41 2B 32 3E CE 1A EF 32 50 2B 23 58 2B 58 2B | 2A,2:If min(remainder(P,seq(X,X,
33 2B 31 70 BC 50 11 2B 32 3E 50 04 EB 41 10 31 | 3,1+√(P),2:P→∟A(1
70 B5 EB 41 3E D4 EE B2 41 71 EB 41 3E EB 41 10 | +dim(∟A:End:abs(A-∟A:∟A(
31 70 B6 B8 BB 29 72 6A 1A 72                   | 1+sum(not(cumSum(Ans=min(Ans

Input is an integer in Ans.  Output is printed implicitly.
Note:  due to limitations on how large lists can be, \$A\$ is limited to \$0 \le A \le 3953\$
Explanation:
Ans→A                                  ;store the input in a variable called "A"
{2,3→A                                 ;store the list {2 3} into a list called "A"
For(P,5,2A,2                           ;loop from 5 to two times the input using a step
                                       ; of 2
                   seq(X,X,3,1+√(P),2  ;generate a list of integers from 3 to 1 + the
                                       ; square root of the loop counter using a step of 2
                                       ; (e.g. P=21, list={3 5})
       remainder(P,                    ;then take the loop counter modulo each element
                                       ; (e.g. P=21, list={0 1})
If min(                                ;if all of the resulting elements are non-zero,
                                       ; then
P→∟A(1+dim(∟A                          ;add the loop counter's value to the list "A", the
                                       ; list of primes
End
abs(A-∟A                               ;subtract the input from the primes list and take
                                       ; the absolute value of each element (distance to
                                       ; each prime)
   1+sum(not(cumSum(Ans=min(Ans        ;find the first index of the minimum value
∟A(                                    ;then use that index to get the value in the primes
                                       ; list at that index
                                       ;implicit output

Examples:
100:prgmCDGF1F
             101
5:prgmCDGF1F
               5
80:prgmCDGF1F
              79

Thunno 2 h, 4 bytes
Æpþṛ

Try it online!
Explanation
Æpþṛ  # Implicit input
Æp    # First n primes
  þṛ  # Sort by absolute difference
      # (Lower numbers will appear
      #  first in case of a tie)
      # Implicit output of first item

Nekomata + -1, 3 bytes
Ž-Q

Attempt This Online!
Ž-Q
Ž       Find an integer (in the order of 0, 1, -1, 2, -2, 3, -3, ...)
 -      Input minus that integer
  Q     Check if the result is a prime

-1 prints the first solution.

source: Stack Exchange

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

sort: votes


text:
Terrain Reachability
Turn-based tactics games like Advance Wars, Wargroove, and Fire Emblem are made up of a square grid of varying terrain with units of differing movement classes requiring different costs for each terrain type. We'll be investigating a subset of that problem.
Challenge
Your task is to determine if one location is reachable from another given a grid of terrain costs and a movement speed.
Units can only move orthogonally where the cost of moving onto a square is the value of the corresponding cell on the grid (moving off is free). For instance, moving from a cell valued 3 onto a cell valued 1 costs 1 movement, but going the other way requires 3. Some squares may be inaccessible.
Example
1 [1] 1  1  1
1  2  2  3  1
2  3  3  3  4
1  3 <1> 3  4

Moving from [1] to <1> requires a minimum of 7 movement points by moving right one square and then down three. Thus, if given 6 or less as the movement speed, you should output a falsy answer.
Example Test Cases
These will use top-left-origin zero-indexed (row, column) coordinates rather than bracketed cells for start and end to make parsing easier. Unreachable cells will be represented with X
Case 1a
1 1 2 1 X
1 2 2 1 1
2 1 1 2 1
X X X 1 2
Speed: 5
From (2, 3) to (0, 1)

Output: True

Case 1b
1 1 2 1 X
1 2 2 1 1
2 1 1 2 1
X X X 1 2
Speed: 4
From (2, 3) to (0, 1)

Output: False

Case 1c
1 1 2 1 X
1 2 2 1 1
2 1 1 2 1
X X X 1 2
Speed: 5
From (0, 1) to (2, 3)

Output: False

Case 2a
3 6 1 1 X 4 1 2 1 X
5 1 2 2 1 1 1 X 1 5
2 1 1 1 2 1 1 1 X 1
2 1 1 3 1 2 3 4 1 2
1 1 2 1 1 4 1 1 1 2
3 2 3 5 6 1 1 X 1 4
Speed: 7
From (3, 4) to (2, 1)

Output: True

Case 2b
3 6 1 1 X 4 1 2 1 X
5 1 2 2 1 1 1 X 1 5
2 1 1 1 2 1 1 1 X 1
2 1 1 3 1 2 3 4 1 2
1 1 2 1 1 4 1 1 1 2
3 2 3 5 6 1 1 X 1 4
Speed: 4
From (3, 4) to (2, 1)

Output: False

Case 2c
3 6 1 1 X 4 1 2 1 X
5 1 2 2 1 1 1 X 1 5
2 1 1 1 2 1 1 1 X 1
2 1 1 3 1 2 3 4 1 2
1 1 2 1 1 4 1 1 1 2
3 2 3 5 6 1 1 X 1 4
Speed: 7
From (1, 8) to (2, 7)

Output: True

Case 3a
2 1 1 2
2 3 3 1
Speed: 3
From (0, 0) to (1, 1)

Output: False

Case 3b
2 1 1 2
2 3 3 1
Speed: 3
From (1, 1) to (0, 0)

Output: True

Rules, Assumptions, and Notes

Standard loopholes are banned, I/O can be in any convenient format
You may assume coordinates are all on the grid
Movement speed will never be over 100
Inaccessible cells may be represented with very large numbers (e.g. 420, 9001, 1 million) or with 0 or null, whichever is most convenient for you.
All inputs will consist of positive integers (unless using null or 0 to represent unreachable cells)

@LuisfelipeDejesusMunoz "These will use top-left-origin zero-indexed (row, column) coordinates"

You say I/O can be in any convenient format. Does that include, for example, a list/array with dimensions? I believe that's typically permitted, but it definitely saves a lot of bytes over parsing a string.

@dfeuer, yes of course

I downloaded advanced wars on my phone emulator... I am so sad that it forces you to do the 13 tutorial levels... I wanted to replay it very badly but my patience is paper thin for tutorial pandering on old systems.

TSQL query, 205 191 bytes
Input is a table variable @t
@x=start xpos, @y=start ypos
@i=end xpos  , @j=end ypos
@ =speed
DECLARE @t table(x int,y int,v int)
INSERT @t
values
(0,0,1),(0,1,1),(0,2,2),(0,3,1),(0,4,null),
(1,0,1),(1,1,2),(1,2,2),(1,3,1),(1,4,1),
(2,0,2),(2,1,1),(2,2,1),(2,3,2),(2,4,1),
(3,0,null),(2,1,null),(2,2,null),(2,3,1),(2,4,2)

DECLARE @x INT=2,@y INT=3,@i INT=0,@j INT=1,@ INT=5;

WITH C as(SELECT @y f,@x r,@ s
UNION ALL
SELECT f+a,r+b,s-v FROM C
JOIN(values(1,0),(0,1),(-1,0),(0,-1))x(a,b)ON
s>0JOIN @t
ON f+a=x and r+b=y)SELECT
max(iif(S>=0and f=@j and r=@i,1,0))FROM c

Try it online ungolfed version

Python 2, 220 bytes
def f(m,a,w,h,r,c,R,C):
 T=[w*[999]for _ in' '*h];T[r][c]=0;P=[(r,c)];j,k=1,0
 for u,v in P:exec"U,V=u+j,v+k;j,k=-k,j\nif h>U>-1<V<w:q=T[U][V];T[U][V]=min(T[u][v]+m[U][V],q);P+=[(U,V)]*(q>T[U][V])\n"*4
 return a>=T[R][C]

Try it online!
Takes an array m of integers, with 'X' as a larger-than-100 value;, a speed a, m having width w and height h; and returns whteher we can start at the zero-indexed row/column cell (r,c) and get to the final cell (R,C).
The algorithm is a modified flood-fill.
Slightly ungolfed code:
def f(m,a,w,h,r,c,R,C):
 T = [w*[999]for _ in ' '*h] # make an array same size as m, with all
                             #   values 999, whose values will represent
                             #   the cost of getting to each cell.
 T[r][c] = 0                 # set the starting location to a cost of 0
 P = [(r,c)]                 # initialize a set of cells whose neighbors'
                             #   cost might need to be be updated
 j,k = 1,0                   # and also j,k which will take on values:
                             #  (1,0), (0,1), (-1,0), (0,1), used to
                             #  probe orthogonal neighbors
 for u,v in P:               # scan the cells in P
    for _ in '1234':         # look at each of 4 orthogonal positions
        U,V = u+j,v+k        # U and V get the indexes of a neighbor
                             #   of the current cell.
        j,k = -k,j           # this 'rotates' the j,k pairing.
        if h>U>-1<V<w:       # if the coordinates are in bounds...
            q = T[U][V]      # save the current 'cost' of getting to cell (U,V)
                             # see if we can reduce that cost, which is calculated
                             #   by taking the cost of the currently scanned cell
                             #   + the value from m for the neighbor cell.
            T[U][V] = min(T[u][v]+m[U][V] ,q)
                             # if we can reduce the cost, add the neighbor
                             #   to P because **it's** neighbors might,
                             #   in turn, need updating.
            P += [(U,V)]*(q>T[U][V])
 return a>=T[R][C]           # return if speed is enough for the cost.

JavaScript (ES7),  116  113 bytes
Takes input as (matrix)([endRow, endCol])(speed, startRow, startCol). Expects large values for unreachable squares. Returns \$0\$ or \$1\$.
m=>e=>o=g=(s,y,x)=>m.map((r,Y)=>r.map((v,X)=>r[s<v|(x-X)**2+(y-Y)**2-1||g(s-v,Y,X,r[X]=1/0),X]=v),o|=y+[,x]==e)|o

Try it online!
Commented
m =>                        // m[] = matrix
e =>                        // e[] = target coordinates
  o =                       // o   = success flag, initialized to a non-numeric value
  g = (                     // g   = recursive depth-first search function taking:
    s,                      //   s    = speed
    y, x                    //   y, x = starting coordinates
  ) =>                      //
    m.map((r, Y) =>         // for each row r[] at position Y in m[]:
      r.map((v, X) =>       //   for each value v at position X in r[]:
        r[                  //     this statement ultimately updates r[X]:
          s < v |           //       abort if s is less than v
          (x - X) ** 2 +    //       or the quadrance between (x, y)
          (y - Y) ** 2 - 1  //       and (X, Y) is not equal to 1
          || g(             //       otherwise, do a recursive call to g:
               s - v,       //         subtract v from s
               Y, X,        //         pass (Y, X) as the new coordinates
               r[X] = 1 / 0 //         temporarily make this cell unreachable
             ),             //       end of recursive call
          X                 //       restore r[X] ...
        ] = v               //     ... to its original value
      ),                    //   end of inner map()
      o |= y + [, x] == e   //   set the flag o if (y + ',' + x) matches (e + '')
    ) | o                   // end of outer map(); return o

Jelly, 59 bytes
+2¦µ_2ịæ.Ø½œị$Ʋ+5ịƲ$4¦01Ñḣ3Ḋ⁼/Ɗ?ḣ2=/ẸƊoF<0ẸƊƊ?
çⱮØ.,U$;N$¤Ẹ

Try it online!
Not terribly fast; tries all paths until the speed units are exhausted, even retracing its steps. However, this avoids the need to check whether spaces are visited. Input is provided as [nrows, ncols],[start_row, start_col],[end_row, end_col],speed,flattened matrix column-major
Explanation
Helper link
+2¦                                       | add the right argument to the second item in the left argument (current location)
   µ                                      | start a new monadic chain with the modified left argument
                    4¦                    | for the fourth item (speed)...
    _                                     |   subtract...
                 ịƲ$                      |     the item located at...
     2ịæ.Ø½œị$Ʋ                           |       the dot product of the current position and (number of columns,
                                          |       right-padded with 1)
               +5                         |       plus five
                                        ? | Now, if...
                                       Ɗ  |   next three as a monad
                           ḣ2=/ẸƊ         |   either current row or current column are equal to nrows/ncolumns respectively
                                 o        | or
                                  F<0ẸƊ   |   any value is negative
                 0                        | return zero
                          ?               | else if...
                   ḣ3Ḋ⁼/Ɗ                 | the second and third items (current and end pos) are equal
                  1                       | return 1
                   Ñ                      | else pass the current list back to the main link

Main link
ç             | call the helper link with the current list...
 Ɱ            |   and each of
  Ø.,U$;N$¤   |   [0,1],[1,0],[0,-1],[-1,0]
           Ẹ  | Check if any are true

Jelly, 38 bytes
ạƝṢ€Ḅ’¬Ạ
ŒṪ’ḟŒPŒ!€ẎW€j¥@€ÇƇḊ€‘œị⁸§Ṃ’<⁵

An extremely inefficient full program accepting the terrain (with unvisitables as 101) then the start and end co-ordinates then the speed.
Try it online! (not much point trying most of the test cases!)
How?
Creates a list of all permutations of each of the power-set of "all terrain locations except the start & end", surrounds each of these with the start & end, filters to those which make only orthogonal moves of distance one, drops the start from each, indexes back into the terrain, sums each, takes the minimum, subtracts one and tests that this is less than the speed.

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


text:
BF Last binary digit
Task
Your task is to write as short as possible program preferably in Brainf**k which determines the last digit of given number after it's conversion from decimal to binary system.
Input
An integer in decimal system consisting of up to 200 digits. There is a newline character (ASCII 10) after the given number
Output
One digit (1 or 0) which is the last digit of given number after it's conversion to binary system.
Example
4372667135165131576213 -> 1

Are you looking for https://codegolf.stackexchange.com/a/113513/17602 ?

Output has to be last digit of given number after its conversion to binary

...Which is the parity of the number (i.e. whether it is odd or even)

A bf answer from the parity question is here. It should work for decimal-encoded strings too, since the last bit will be 1 iff the number is odd.

Since you wanted a brainfuck answer on your last question I'd suspect that these are homework questions... except that this is brainfuck lol

+[>,+]<<<,+>[[>]+<[-<]>]++++++[->++++++++<]>. since you like EOF as -1

Wolfram Language (Mathematica), 13 bytes
Boole@OddQ@#&

Try it online!


text:
New Order #3: 5 8 6
Introduction (may be ignored)
Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the third challenge in this series (links to the first and second challenges).
In this challenge, we will arrange the natural numbers in rows of increasing length in such a way that the sum of each row is a prime. What I find really amazing about this, is that every natural number has a place in this arrangement. No numbers are skipped!
This visualisation of this arrangement looks like this:
row             numbers             sum
1                  1                  1
2                2   3                5
3              4   5   8             17
4            6   7   9  15           37
5          10 11  12  13  21         67
6        14  16 17  18  19  23      107
etc.

We can read the elements from the rows in this triangle. The first 20 elements are: 1, 2, 3, 4, 5, 8, 6, 7, 9, 15, 10, 11, 12, 13, 21, 14, 16, 17, 18, 19 (yes, there is a New Order song hidden in this sequence).
Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is A162371.
Task
Given an integer input \$n\$, output \$a(n)\$ in integer format.
\$a(n)\$ is defined as the \$n\$th element of the lexicographically earliest permutation of the natural numbers such that, when seen as a triangle read by rows, for n>1 the sums of rows are prime numbers. Since the first lexicographical permutation of natural numbers starts with 1, \$a(1)\$ is 1. Note that by this definition \$a(1) = 1\$ and \$a(1)\$ is not required to be prime. This is OEIS sequence A162371.
Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.
Test cases
Input | Output
---------------
1     |  1
5     |  5
20    |  19
50    |  50
78    |  87
123   |  123
1234  |  1233
3000  |  3000
9999  |  9999
29890 |  29913

Rules

Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
Default I/O rules apply.
Default loopholes are forbidden.
This is code-golf, so the shortest answers in bytes wins

Can we output the sequence infinitely, or return a generator instead?

Err, 1 is not a prime

@JoKing about a(1)=1: I'll add that. That is indeed the exception. This is stated clearly in the OEIS entry, buy I failed tot mention it explicitly. I'll add it to the question. Thanks.

@JoKing note that the definition of the sequence only requires the sum of the row to be prime for n>1. Since the sequence is the first lexicographical permutation of the natural numbers, a(1) comes out as 1. So indeed, 1 is not prime but the challenge or the definition of the sequence doesn't say or require 1 to be prime...

@JoKing this is a "pure sequence" challenge. So I won't allow to output the entire sequence. For a given n, you need to output a(n) and a(n) alone.

Related sequence: A075348.

@jimmy23013 Nice find! Ik would have chosen that sequence if I found it earlier. It's more elegant in my opinion. A big issue is of couse that the New Order song "5 8 6" is not part of this sequence... ;-)

Husk, 22 bytes
!¡§ḟ(ΛoṗΣtü¤≤LCN:)`-Nø

Try it online! I was honestly somewhat surprised that CN worked as intended here. Heavily inspired by Jo King's answer.
Explanation
!¡λḟ(ΛoṗΣtü¤≤LCN:⁰)-⁰N)ø  (Expanded; let X denote the argument.)
!                         Take element X of
 ¡                         the list created by repeatedly applying this function
                           to the prior list and appending its output,
                       ø    starting with an empty list:
                   -⁰N      Take the list of natural numbers not contained in the
                            argument,
   ḟ                         and find the first element such that
     ΛoṗΣ                     all sums are prime of
                :⁰                the element appended to the argument,
              CN                 cut into lengths of 1, 2, 3, etc.,
          ü¤≤L                  filtered for increasing length,
         t                     with its first element dropped.

A late, but relatively short answer. The sortest to be exactly. Well done! You win!

Jelly, 32 bytes
;®»ṀƊSÆn_S
ẎṀ©+LRḟẎḣL;Ç$ṭ
1Ç¡Fị@

Try it online! - very slow as it builds n rows first, for a faster version which doesn't, at 37 bytes, try this.

Perl 6, 80 77 bytes
{({$!=@_;+(1...{$_∉$!&&(|$!,$_).rotor(1..*).one.sum.is-prime-1})}...*)[$_]}

Try it online!
Explanation:
{                                  }  # Anonymous code block
 (                        ...*)[$_]   # Index into the infinite sequence
  {                      }   # Where each element is
   $!=@_;  # Save the list of previous elements into $!
   +(1...{             })    # Return the first number that
          $_∉$!         # Has not appeared in the list so far
          &&            # And
          (|$!,$_)      # The new sequence
          .rotor(1..*)  # Split into rows of increasing length
                        # And ignoring incomplete rows
          .one          # Have exactly one row
          .sum          # Where the sum
          .is-prime-1   # Is not prime (i.e. just the first row)

Haskell, 122 120 bytes
import Data.Numbers.Primes
l%a|(p,q)<-splitAt l a,(s,k:t)<-span(not.isPrime.(+sum p))q=p++k:(l+1)%(s++t)
((1:1%[2..])!!)

Try it online! (has an extra 2 bytes for f=)
EDIT: Now uses 0-based indexing to save 2 bytes. Thanks @wastl for pointing that out, I must have missed it in the OP.
This was very fun to write! The helper function % takes a length l and a list of values it can use a. It returns an infinite list of values for the sequence. The length is one less than the length of the current triangle row and the list is infinite and pre-sorted. First we just yield the first l values from a and then look through the rest of a until we find the first (smallest) value that makes the sum prime. We break up the list around that value using span and some pattern matching. Now all we have to do is yield that new value and recur with the next line length l+1 and the remaining values in a. For the final result we prepend 1 (special case for n=0) and index into it with !!.

I think you can remove the 0: as the challenge states you can use 0-based indexing.

JavaScript (ES6),  111  110 bytes
n=>{for(g=n=>{for(d=n;n%--d;);},i=l=0;i--||(k=s=0,i=l++),n--;g[k]=s+=r=k)for(;g[++k]|g(!i*++s)|d>1;);return r}

Try it online!

Jelly, 46 bytes
S©‘æR®Ḥ‘¤_®ḟ;F¥Ṃ
FLḤRḟFḣ0ịLƊ;ç¥µW
1;Ç$⁸½Ḥ¤¡Fị@

Try it online!
Times out for large n on tio, but works there for all but the last two examples.

Lua, 242 228 226 211 bytes
s={}u={}i=0 n=0+...while i<n do
n=n-i
x,S=1,0
for j=1,i do
while u[x]do x=x+1 end
s[j]=x
S=S+x
u[x]=0
end
while u[x]or p do
x=x+1
d=S+x
p=F
for c=2,d-1 do
p=p or d%c<1
end
end
i=i+1
s[i]=x
u[x]=0
end
print(s[n])

Try it online!


text:
Rotate a column
Given an integer k and either a block of text, or a 2d array that the inner arrays may have unequal lengths (that resembles a block of text), rotate every character or element in the k-th column up or down to the next position that exists.
Example
Rotate the 20th column of the following text (1-based):
A line with more than k characters.
A longer line with more than k character.
A short line.
Rotate here: ------v--
This is long enough.

This is not enough.
Wrapping around to the first line.

Output:
A line with more thtn k characters.
A longer line with aore than k character.
A short line.
Rotate here: ------m--
This is long enoughv

This is not enough.
Wrapping around to .he first line.

Rotating the k-th column of the same input where 35 < k < 42 would yield the input text unchanged.
Rules

You may use raw text, an array of lines, a 2d array of characters, or any reasonable format to represent the data. You may also use data types other than characters.
The number of possible values of the data type of the elements must be at least 20 if your code length depends on it, otherwise at least 2. This could be a subset of the characters or other values supported in the native type.
Spaces and any kind of null values are just normal values, if you allow them in the input. You may also simply exclude them in the element type.
Rule change: You are allowed to pad the shorter arrays with a generic default value (such as spaces), if you prefer using arrays with equal lengths to store the data.
k could be 0-based or 1-based. It is guaranteed to be inside the longest line in the input (implying the input has at least one non-empty line).
You may choose whether it rotates up or down.
Either just rotate one position, or rotate n positions where n is a positive integer given in the input.
Shortest code wins.

APL (Dyalog Extended), 9 bytesSBCS
Full program. Prompts stdin for 2D block of text, then k (0-based or 1-based, depending on APL's current setting), then n. Positive n rotate up, negative n rotate down.
The domain consists of either one of the following:

all Unicode characters, except spaces, leaving 1114111 allowed values, which is more than the required 20.
all numbers, except 0, leaving approximately 2129 allowed values, which is more than the required 20.

Since APL requires 2D blocks to be rectangular, the input must be padded with spaces/zeros. This can be done automatically by entering ↑ to the left of a list of strings/numerical lists.
⎕⌽@≠@⎕⍢⍉⎕

Try it online! (the apparent spaces are actually non-breaking spaces)
⎕ prompt for text block
⍢⍉ while transposed:
 @⎕ apply the following on the input'th row:
  @≠ at elements different from their prototype (space for characters, zero for numbers):
   ⎕⌽ rotate "input" steps left
APL (Dyalog Unicode), 22+ bytesSBCS
This version allows the full character set by using zeros as identifiable fill element.
0~¨⍨↓⍉⎕⌽@(0≠⊢)@⎕⍉↑0,¨⎕

Try it online!
This of course means that zeros are not allowed in numeric arguments. The corresponding program for all numbers would have the three occurrences of 0 replaced by ' ' and thus use space as fill:
' '~¨⍨↓⍉⎕⌽@(' '≠⊢)@⎕⍉↑' ',¨⎕

If we truly want the full ranges of (even a mixture of) both characters and numbers, we could use null as fill:
n~¨⍨↓⍉⎕⌽@(n≠⊢)@⎕⍉↑⎕,¨⍨n←⎕NULL

And finally, if we wanted to include nulls and objects in the input domain, we could define a fill class and use instances of this as fills:
~∘I¨⍨↓⍉⎕⌽@(~⊢∊I←⎕INSTANCES⊢∘C)@⎕⍉↑⎕,¨⍨⎕NEW⎕FIX':Class C' ':EndClass'

Now officially declare this (and the new answers like this) as a valid answer. Sorry if this has bothered you too much.

Shorter than your null version: n~¨⍨↓⍉⎕⌽@(≢¨)@⎕⍉↑⎕,¨⍨n←⊂⊂⍬. Maybe you could add modded ↑ ↓ in your extension to help further golfing (but I'm not exactly sure how useful they are).

@jimmy23013 Yeah, I thought of that, but then it can't take lists of arbitrarily nested stuff. The last one is the ultimate solution, especially if C and I are localised so they don't pollute: {~∘I¨⍨↓⍉⎕⌽@(~⊢∊I←⎕INSTANCES⊢∘C)@⎕⍉↑⎕,¨⍨⎕NEW⎕FIX I←C←':Class C' ':EndClass'}

Python 2, 111 110 109 99 98 96 94 bytes
lambda a,n:[l[:n]+(l[n:]and[L[n]for L in a[i:]+a if L[n:]][1]+l[n+1:])for i,l in enumerate(a)]

Try it online!
Takes input as a list of lines and 0-index column, and returns a list of strings.
Column is rotated up 1.
-11 bytes, thanks to Jo King

Zsh, 94 87 78 74 69 68 bytes
-7 bytes by changing to an arithmetic ternary, -9 bytes by changing the character in-place (TIL), -4 bytes by inputting the index on stdin and the strings as arguments, -5 bytes by using a string instead of an array to store the rotating characters, -1 byte thanks to @pxeger letting me know ${c[]) allows arithmetic ternary.
read i
for s;c+=$s[i]
c=$c[-1]$c
for s;s[i]=${c[$#s<i?0:++j]}&&<<<$s

Old
Old
Old
Old
Old
Try it online!
Here are the keys to making this answer work:

$array[0] or $string[0] is always empty
$array[n] or $string[n] is empty if n is larger than the length of the array/string
array[i]=c or string[i]=c will replace the element/character.
In $[$#s<i?0:++j], j is not incremented if $#s<i.

In the original 94 byte answer, there was an interesting issue I came across involving using <<< to print. I had to use echo to get around it:
for s;echo $s[0,i-1]$c[$[$#s<i?0:++j]]${s:$i}

The reason for this can be seen here:
echo $ZSH_SUBSHELL   # prints 0
<<< $ZSH_SUBSHELL    # prints 1

Here-strings are run in subshells because they are given as stdin to another program.
If there is no program given, it is implicitly given to cat.
You can see this with <<< $_.
<<< $ZSH_SUBSHELL is similar to echo $ZSH_SUBSHELL | cat.
Since we need to increment j, we can't be in a subshell.

-1 byte by changing $c[$[...]] to ${c[...]}: https://ato.pxeger.com/run?1=LY5NTsMwEIX3PsVTGtWt2kjNohKiiWDBgh0bJBZVFyZ2akNiV7bT8iNuwY5NJeAC3Ka3wU46sqyZNzPfvK_vNyePP_VkOvntfJ1dnG6sYByK1MbCrapZmbq12pCqTKt1lm_S6tyJapm-V-t05Ap1tbiczZ42H-NxURSpO7M-p-QgVSPQMxulxQrcEEDsWQMnPLIMSRobSVCV5uKlTNI8Fk6q2pOQjAYdRsN5rvS8Bzmw8Oy2a4X2LozVAXSdIJwPSb8RKbGk5Tko4UaLwdvx9JcDYHgEpeAkX4LeCrTsOaLRChbOsYZxCvoghRVQDq-ms9gaDm0OQXetaXozNDLonZzDS-bjJINnTQNjubCULBeg97Gju_YxCKBhxBsDzloNqbaSkuCGDj92Vjhh9yLm1O1YFSyFoGSw_g8

Ah, so ${ } works as well, thanks.

Java 8, 107 106 135 107 bytes
k->m->{int s=m.length,i=-1;for(char p=0,t;i<s;t=m[i%s][k],m[i%s][k]=p<1?t:p,p=t)for(;m[++i%s].length<=k;);}

+29 bytes for a bug-fix..
0-indexed; rotates down like the example.
Input as a character-matrix; modifies the char-matrix instead of returning a new one to save bytes.
Try it online.
Explanation:
k->m->{                 // Method with integer and char-matrix parameters and no return-type
  int s=m.length,       //  Amount of lines in the matrix `s`
      i=-1;             //  Index-integer `i`, starting at -1
  for(char p=0,         //  Previous-character, starting at 0
           t;           //  Temp-char, uninitialized
      i<s               //  Loop as long as `i` is smaller than `s`:
      ;                 //    After every iteration:
       t=m[i%s][k],     //     Set the temp to the `k`th character of the `i`'th line
       m[i%s][k]=       //     Replace the `k`'th character of the `i`'th line with:
         p<1?           //      If `p` is still 0:
          t             //       Set it to the temp we just set
         :              //      Else:
          p,            //       Set it to the previous-character instead
       p=t)             //     And then replace `p` with the temp for the next iteration
    for(;m[++i          //   Increase `i` by 1 before every iteration with `++i`,
             %s].length //   And continue this loop until the length of the `i`'th line
           <=k;);}      //   is smaller than or equal to the input `k`

One thing I noticed is that you make an assumption that the first line has enough characters -  char p=m[0][k] - if it doesn't, won't this throw an exception? Nice job btw. You are beating my C# attempt by a large margin :)

@dana Ah, shit, you're right.. I'm probably beating you by this large of a margin because I accidentally make that assumption.. Will try to fix it.

@dana Fixed, thanks for noticing.

@dana And back to 107 again. ;)

Can't you do int p=0,t? Since the question says you can use any datatype. Also, in your explanation, the parameter is named n but the comments say k

@EmbodimentofIgnorance Ah, forgot to change that n to k. I usually use n for integer-inputs, but since the question uses $k$ I later on changed it (but apparently not everywhere). As for int p=0,t; then I will need a cast to char when assigning p to a cell (m[i%s][k]=(char)(p<1?t:p)). And although I could take the input as an integer-matrix, I personally think int-matrix =/= string/string-list/char-matrix..

R, 62 bytes
function(L,n){L[A,n]<-rep(L[A<-L[,n]!=' ',n],2)[1+1:sum(A)];L}

Try it online!
Takes input as a space-padded matrix of characters. Rotates upwards. All thanks to Kirill L.!
R, 74 bytes
function(L,n){substr(L[A],n,n)=rep(substr(L[A<-nchar(L)>=n],n,n),2)[-1]
L}

Try it online!
This submission predates the allowance of padded lines.
Aliasing substr here won't work because we're calling substr and substr<- in the first line.
I/O as a list of non-padded lines; rotates upwards.

Since consensus allows modifying inputs, we can do this crazy thing

Also, OP relaxed the rules, so that it is now possible to work with space-padded matrices, something like this

@KirillL. I don't think that R passes by reference so we probably aren't allowed to do that; it strikes me that this only works if the argument is named L in the parent environment. I'll happily update to the space-padding, though!

Ah, I see, you're right. I came up with this idea looking at my Ruby answer (which saves a whole 1 byte this way :)), but the languages indeed behave differently in this situation.

C# (Visual C# Interactive Compiler), 82 bytes
k=>a=>{var c='0';a.Where(b=>b.Count>k&&((b[k],c)=(c,b[k])).c>0).ToList()[0][k]=c;}

Try it online!
Credit to @ASCIIOnly for suggesting foreach which led to a 12 byte savings!
-8 bytes thanks to @someone!
-1 byte thanks to @EmbodimentofIgnorance!

184 bytes

Maybe 183 if using ints instead of chars

@ExpiredData ew int instead of char

too bad you can't use a foreach since it's the opposite order :(

@ASCIIOnly - you can rotate either direction. I was able to save a byte by iterating in that direction, but the foreach direction would be ok as well. The problem is I track the first swapped index, so I can fix it at the end. So using for seems like the way to go using this approach?

Actually, you may be onto something...

Can you simplify "char[]d=null" to "var d=a[0]" to save 2 chars?

@OliverHallam - I think that causes an error if the first line is too short? - link

Use dynamic to merge declarations and save 2 bytes (I've never seen this before!)Try it online!

@someone - nice :) now we are tied with the Python answer (for now ;)

Replace the foreach loop with something truly horrible for 91 bytes.

Get rid of d (might be possible to golf slightly more!) for 88 bytes. Try it online!

@someone - you say horrible, I say 6 bytes shorter than the Python answer ;)

I think this works? 80 bytes

@EmbodimentofIgnorance - Thanks, I switched from array to list. Declaring c without a value means the scope has changed which seems a little off to me, so I left that the way I had it. I like the thought though.

Ruby, 57 bytes
->a,k{b=a.map{|i|i[k]}-[p];c=-2;a.map{|i|i[k]&&=b[c+=1]}}

Try it online!
Takes input as an array of lines a. Rotates the text down at 0-based position k. Returns by modifying the input a.

K4, 22 41 bytes
New Rules:
Solution:
{+@[+x;y;.q.rotate 1]}

If the input is already padded to the maximum length, then this becomes much shorter.
Old Rules:
Solution:
{.[x;i;:;.q.rotate[1;x . i:(&y<#:'x;y)]]}

Explanation:
Not sure if I'm missing something... 0 index, rotates up (change the 1 to -1 for rotate down)
{.[x;i;:;.q.rotate[1;x . i:(&y<#:'x;y)]]} / the solution
{                                       } / lambda taking implicit x and y
 .[x; ;:;                              ]  / index apply assignment back into x
         .q.rotate[1;                 ]   / left rotate 1 character
                           (       ; )    / two item list
                                    y     / index to rotate
                               #:'x       / count (#:) each (') input
                             y<           / index less than ?
                            &             / indexes where true
                         i:               / assign to variable w
                     x .                  / index into x
     i                                    / indexes we saved as i earlier

05AB1E, 21 bytes
ʒg‹}U¹εXyk©diX®<èIèIǝ

Can definitely be golfed some more..
0-indexed; input and output both as a list of strings.
It rotates down like the example, but < can be replaced with > to rotate up instead.
Try it online (footer joins the list by newlines, remove it to see the actual list output).
Explanation:
ʒ  }             # Filter the (implicit) input-list by:
 g               #  Where length of the current string
  ‹              #  is larger than the (implicit) input-integer
    U            # Pop and store this filtered list in variable `X`
¹ε               # Map over the first input-list again:
  Xyk            #  Get the index of the current string in variable `X`
     ©           #  Store it in the register (without popping)
      di         #  If the index is not -1, so the current string is present in variable `X`
        X®<è     #   Get the (index-1)'th string in variable `X`
            Iè   #   Get the character at the index of the input-integer
              Iǝ #   And insert it at the index of the input-integer in the current string

Japt v2.0a0, 18 bytes
0-based with input & output as a multi-line string. Rotates up by 1.
There's gotta be a shorter method!
yÈr\S_Y¦V?Z:°TgXrS

Try it
yÈr\S_Y¦V?Z:°TgXrS     :Implicit input of string U & integer V
y                      :Transpose
 È                     :Pass each line X at 0-based index Y through the following function & transpose back
  r                    :  Replace
   \S                  :  RegEx /\S/g
     _                 :  Pass each match Z through the following function
      Y¦V              :    Test Y for inequality with V
         ?Z:           :    If true, return Z, else
            °T         :    Increment T (initially 0)
              g        :    Index into
               XrS     :    X with spaces removed

I haven't looked closely at the comments and new rules (so perhaps it's somewhere mentioned it's allowed now, while it wasn't before), but is it allowed to skip spaces of the initial input? Let's say you change the input-index to 6, your answer would skip the space at line with in the first line and at Rotate here in the fourth line, whereas most of the other answers would rotate that space as well.

@KevinCruijssen, I'm a bit confused by all the additional rules & allowances but, if it is an issue, it looks like I can get around that by not allowing spaces in the input. I think.

"I think" This part is indeed how I would also respond, haha. I have no idea what is mandatory and optional anymore, but I think you can indeed choose to omit spaces in the in- and output; I think you can choose to count spaces or not; and I think you can use trialing spaces in the output or not; etc. All on all rather confusing. Ah well..

Jelly, 16 bytes
z⁷⁹ịỴFṙ-ṁƲY⁸ṛ⁹¦"

A dyadic Link accepting a list of lines (lists of characters containing no newline characters) on the left and an integer on the right which returns a list of lines.
Try it online! (footer splits on newlines, calls the Link, and joins by newlines again)
How?
z⁷⁹ịỴFṙ-ṁƲY⁸ṛ⁹¦" - Link: lines L; index I        e.g. example in question; 20
z⁷               - transpose L with filler '\n'       ['AAART\nTW', '   oh\nhr', ...]
  ⁹ị             - Ith item                           'am\nv.\n\nt'
    Ỵ            - split at newlines                  ['am', 'v.', '', 't']
         Ʋ       - last four links as a monad - i.e. f(X):
     F           -   flatten                          'amv.t'
       -         -   -1
      ṙ          -   rotate left by                   'tamv.'
        ṁ        -   mould like X                     ['ta', 'mv', '', '.']
          Y      - join with newlines                 'ta\nmv\n\n.'
                 -   -- call this C
           ⁸     - chain's left argument, L
               " - zip with - i.e. [f(L1,C1), f(L2,C2), ...]:
              ¦  -   sparse application...
             ⁹   -   ...to indices: chain's right argument, I
            ṛ    -   ...of: right argument, Cn

Charcoal, 34 28 21 bytes
θＪη⁰≔ΦＫＤＬθ↓℅ιζＵＭζ§ζ⊖κ

Try it online! Link is to verbose version of code. Takes an array of strings as input. 0-indexed. Edit: Now that PeekDirection has been fixed, I can manipulate it directly. Explanation:
θ

Print the input strings.
Ｊη⁰

Jump to the top of the column to be rotated.
≔ΦＫＤＬθ↓℅ιζ

Extract the cells that have been printed in.
ＵＭζ§ζ⊖κ

Replace each printed cell with the value of the previous cell (cyclically). Conveniently the cell values are read at the time of the PeekDirection call so the fact that the MapCommand call writes new values into the cells doesn't matter.

perl 5 (-p), 75 bytes
k is 0-indexed, rotate down
s/.*//;$r="^.{$&}";s/
//;/$r(.)/;$c=$1;s/$r\K.(?=(?s:.)*?$r(.)|)/$1||$c/gme

TIO

Perl 6, 38 33 bytes
Modifies the array in place (rules don't disallow)
{@^a.grep(*>$^b+1)[*;$b].=rotate}

Try it online!

@joking At first I thought storing it rather than outputting it would be a bit cheating, but rereading the rules, there's no actual stipulation to output so … hooray.  Doing a (…)(…) to get 31 like you have definitely seems to be cheating though, since it's effectively hoisting a call out of the block, but it can still be done with 33 passing them simultaneously with a single call so I'm going go with that.

ah oops, i pasted the wrong link. you got what I mean to comment though. Currying input is perfectly fine though (though it doesn't work in this case), and modifying an argument passed by reference is a standard forn of allowed input

JavaScript (Node.js), 52 bytes
k=>a=>a.filter(b=>b[k]&&([b[k],a]=[a,b[k]]))[0][k]=a

Try it online!
-7 bytes thanks to Shaggy!
Didn't see a JavaScript answer yet! Port of my C# answer.

63 bytes. Can probably be golfed further.

@Shaggy - nice :) most of the time I see JS answers doing all sorts of crazy things. Figured this time I'd give it a shot since I had a strategy.

Oh, nicely golfed! :)

Pip -rn, 32 bytes
POgY#(g@_)>aFI,#gFiyAE@ySsg@i@ag

0-indexed, rotates down. Try it online!
Filters to find the indices of all rows that are long enough to participate in the rotation. Then loops over those rows, swapping the appropriate character on each row with a temp variable s. Visiting the first row again at the end swaps the dummy value back out again.

Jelly, 19 bytes
ZnÄ×$ịḟ¹ṙ-;ɗɗʋ€⁹¦⁶Z

Try it online!
1-indexed. Rotates down. A monadic link that takes a right-padded list of Jelly strings (a list of lists of characters) as the first argument and k as the second. Spaces are forbidden in the input except as right padding, but all other characters are permitted.
As implemented on TIO, the footer splits a single string input into a list of strings and right-pads it, but this is for convenience; as I understand it, the result of that step is permitted input for the main link per the rules.

GFortran, 182 bytes
Requires user to input k and n on the first line, where k is the column to rotate, and n is the number of rows of text. Subsequent inputs are the lines of text to be rotated. This was a pain to write! Fortran is so pedantic! Try it Online.
character(99),allocatable::A(:);character(1)r,s
read*,k,n;allocate(A(n))
do i=1,n;read'(A)',A(i);r=A(i)(k:k)
if(r.ne.' ')then;A(i)(k:k)=s;s=r;endif;enddo
A(1)(k:k)=s;print'(A)',A;end

Original, ungolfed program here, with comments and compilation notes: rotcol.f
Saved 20B by reading from stdin rather than a file. Saved 14B by using implicit integers for i k n. Saved 4B by cleanup of spaces and ::. Saved 17B by simplfying logic, and cutting i/o formatting guff.
203 bytes
199 bytes

APL (Dyalog Unicode), 19 chars
{⍉¯1⌽@{' '≠⍵}@⍺⍉↑⍵}

{                  ↑⍵} ⍝ from nested vector of char vectors to char matrix (padding=space)
{                ⍉   } ⍝ transpose
{              @⍺     } ⍝ apply on row ⍺ (left argument)
{  ¯1⌽@{' '≠⍵}       } ⍝ rotation towards the right only elements that are note spaces
{⍉                   } ⍝ transpose back

Try it online!

T-SQL, 195 bytes
WITH C as(SELECT rank()over(order by i)r,sum(1)over()c,*FROM @t
WHERE len(x)>=@)SELECT
isnull(stuff(c.x,@,1,substring(e.x,@,1)),t.x)FROM @t t
LEFT JOIN c ON t.i=c.i
LEFT JOIN c e ON e.r%c.c+1=c.r

Try it online ungolfed version