text:
Counter-Fibonacci Sequences
Given three numbers m,n and p, your task is to print a list/array of length p starting with m and n and each element after p represents the difference of the 2 numbers before it, m-n (Counter-Fibonacci Sequence)
For this challenge you can either use a function to return or print the result or a full program.
Input
Three integers, m,n and p, separated by newlines/spaces/commas, whatever your language supports, but you should specify your input format. Code insertion is disallowed.
Output
The numbers contained by the Counter-Fibonacci Sequence, in any of the following formats (this example: m = 50, n = 40, p = 6):

50,40,10,30,-20,50 (or with spacing after commas)
[50,40,10,30,-20,50] (or with spacing after commas)
50 40 10 30 -20 50 (or with \n(newlines) instead of spaces)
{50,40,10,30,-20,50} (or with spaces instead of commas)

Examples
Input => Output

50,40,10 => 50,40,10,30,-20,50,-70,120,-190,310
-100,-90,7 => -100,-90,-10,-80,70,-150,220
250,10,8 => 250,10,240,-230,470,-700,1170,-1870

Rules

You are guaranteed that p is higher than 1
You should provide a way to test your program, if possible
Take note that this loopholes are forbidden and code insertion is disallowed, as mentioned above

Scoring & Leaderboard
Your code must be as short as possible, since this is code-golf. No answer will be accepted, because this challenge is meant to find the shortest answer by language, avoiding an unfair advantage to golfing languages.

var QUESTION_ID=113051,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Related Question by ETHproductions: Monday Mini-Golf #1: Reverse Fibonacci Solver

Related, possible duplicate. It's basically the same challenge as this one, but outputting in reverse order from a specific spot in the sequence.

@ETHproductions might be considered a dupe, but this is a bit different, trying to see the shortest solution in each language

Yeah, there wasn't as much worry about language inequality back then ;-) I don't think it makes a big difference though. The main difference here is that you can pretty much leave out the first step of the algorithm you would have used to solve that challenge (working backwards to find the starting point)

@ETHproductions indeed there are small differences. If you wish this challenge to be removed, I'll totally do it.

I personally think it's fine. Aside, are we allowed to have a trailing separator?

@ETHproductions yes, trailing separators are allowed

Would p, [m,n] be an okay input format?

Yes @Emigna, it would.

Do we have to handle p=1?

No, p=1 or 0 is excluded

Haskell, 29 bytes
a#b=a:b#(a-b)
(.(#)).(.).take

Length p is the first parameter. Usage example: ( (.(#)).(.).take ) 10 50 40 -> [50,40,10,30,-20,50,-70,120,-190,310]. Try it online!.
Shortening the list to p elements takes more bytes than producing it.

Python 2, 39 bytes
-2 bytes thanks to ETHproductions
-1 byte thanks to Dennis
f=lambda m,n,p:p*[0]and[m]+f(n,m-n,p-1)

Try it Online!

Jelly, 6 bytes
_@Ð¡+Ṗ

Try it online!
How it works
_@Ð¡+Ṗ  Main link. Left argument: m. Right argument: n. Third argument: p

    +   Yield (m + n), the term that comes before m.
  Ð¡    Execute the link to the left p times, starting with left argument m and
        right argument (m + n). After each execution, replace the right argument
        with the left one and the left argument with the previous return value.
        Yield all intermediate values of the left argument, starting with m.
_@          Subtract the left argument from the right one.
        This yields the first (p + 1) terms of the sequence, starting with m.
    Ṗ   Pop; discard the last term.

JavaScript (ES6), 33 bytes
f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

Returns a string of the format 1,2,3, — without using strings!
Test snippet

f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

console.log(f(50,40,10))
console.log(f(-100,-90,7))
console.log(f(250,10,8))

CJam, 15 bytes
q~2-{1$1$-}*]S*

1 extra byte because CJam doesn't naturally use one of the allowed output formats >_<
Try it online!
Explanation
q~               e# Read and eval the input
  2-             e# Subtract 2 from p (to account for m and n being in the list)
    {            e# Run this block p-2 times:
     1$1$-       e#   Copy the top values and subtract
          }*     e# (end of block)
            ]    e# Wrap the stack in an array
             S*  e# Join with spaces

Perl 6, 25 bytes
{($^m,$^n,*-*...*)[^$^p]}

Try it
Expanded:
{  # bare block lambda with placeholder parameters ｢$m｣ ｢$n｣ ｢$p｣
  (
    $^m, $^n,  # declare first two params, and use them

    * - *      # WhateverCode lambda which subtracts two values

    ...        # keep using that to generate values

    *          # never stop (instance of type Whatever)

  )[ ^ $^p ]   # declare last param, and use it to grab the wanted values
               # ｢^ $^p｣ is short form of range op
               # ｢0 ..^ $^p｣ which excludes the ｢$p｣
}

05AB1E, 9 7 bytes
ÍFÂ2£¥«

Try it online!
Explanation
ÍF          # p-2 times do
  Â         # create a reversed copy of the current list
   2£       # take the first 2 elements of the list
     ¥      # calculate delta
      «     # append to the list

Röda, 38 bytes
f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}

Try it online!
Explained:
f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}
f i,a,b{                             } /* Function declaration */
        seq 1,i                        /* Push numbers 1..i to the stream */
               |{|_|               }_  /* For each number in the stream: */
                    [a];               /*   Push the current value of a */
                        b=a-b;         /*   Set b = the next number */
                              a=a-b    /*   Set a = the previous value of b */

Haskell, 33 bytes
(m!n)0=[]
(m!n)p=m:(n!(m-n))(p-1)

Call using (m!n)p. Works by defining ! as an infix function that takes in m and n and returns a function that takes p and returns the desired result.

Nice! I didn't think of making the function infix, so my best try with haskell was 34. BTW you can replace the newline with ; to make it single-line, so it looks a little more codegolfy.

PHP, 76 Bytes
[,$a,$b,$c]=$argv;for($r=[$a,$b];$c---2;)$r[]=-end($r)+prev($r);print_r($r);

PHP, 84 Bytes
[,$a,$b,$c]=$argv;for($r=[$a,$b];$c>$d=count($r);)$r[]=$r[$d-2]-end($r);print_r($r);

Ruby, 31 bytes
->m,n,p{p.times{m,n=n,(p m)-n}}

The straightforward solution

Pyth, 18 bytes
JEKEVEJ=N-JK=JK=KN

Try it online!
Input and output are both delimited by newlines.
How it works:
JEKE                Read two lines of input to J and K
    VE              Read another line and loop that many times:
      J               Print J
       =N-JK          Set N to J - K (Pyth uses prefix notation)
            =JK       Set J to K
               =KN    Set K to N

Mathematica, 26 bytes
{-1,1}~LinearRecurrence~##

Lovin' the builtin. Takes input in the form {{m, n}, p}. LinearRecurrence wants the know the coefficients of the linear combination of previous elements to use to generate new elements, which in this case is {-1,1}.

QBIC, 35 33 bytes
:::?'a;b;`[c-2|e=a-b?e';`┘a=b┘b=e

Saved 2 bytes by placing the first PRINT into one code literal.
Explanation (35 byte version):
:::         Get parameters a, b, c from the cmd-line
  ';`       This suppresses a newline when printing
?a   b';`   PRINT a and b
[c-2|       FOR x=1; x<=(c-2); x++
  e=a-b       calculate the next term of the sequence
  ?e';`       Print it, suppressing newline
  ┘a=b        ┘ denotes a syntactic linebreak; shove the numbers one over
  ┘b=e        dito
            FOR-loop is auto-closed

Have any idea of an online interpreter to test this?

@Mr.Xcoder no online interpreter yet, sorry. I've added a link to the interpreter, which is a DOSBOX project running QBasic, running QBIC.

The explanation is worth more than the interpreter @steenbergh, thanks for responding!

C, 128 bytes
m,n,p,z;main(c,v)char**v;{m=atoi(v[1]);n=atoi(v[2]);p=atoi(v[3])-2;printf("%d,%d",m,n);while(p--)z=m,m=n,n=z-m,printf(",%d",n);}

This program parses the three arguments m, n and p from the command-line, and prints the output as specified.
Modern C compilers allow you to omit basic imports, and thus we can use printf and atoi without the #includes.
Global variables are int by default when declared without a type - this saves a lot of space.

Java, 66 bytes
For once, lambdas are the inefficient approach to golfing due to the very roundabout way of applying recursion to them that requires a lot of extra bytes.
Golfed:
String f(int m,int n,int p){return""+m+(p>1?","+f(n,m-n,p-1):"");}

Ungolfed:
public class CounterFibonacciSequences {

  private static final int[][] INPUTS = new int[][] { //
      { 50, 40, 10 }, //
      { -100, -90, 7 }, //
      { 250, 10, 8 } };

  private static final String[] OUTPUTS = new String[] { //
      "50,40,10,30,-20,50,-70,120,-190,310", //
      "-100,-90,-10,-80,70,-150,220", //
      "250,10,240,-230,470,-700,1170,-1870" };

  public static void main(String[] args) {
    for (int i = 0; i < INPUTS.length; ++i) {
      final int m = INPUTS[i][0];
      final int n = INPUTS[i][1];
      final int p = INPUTS[i][2];
      System.out.println("M: " + m);
      System.out.println("N: " + n);
      System.out.println("P: " + p);
      System.out.println("Expected: " + OUTPUTS[i]);
      System.out.println("Actual:   " + new CounterFibonacciSequences().f(m, n, p));
      System.out.println();
    }
  }

  String f(int m, int n, int p) {
    return "" + m + (p > 1 ? "," + f(n, m - n, p - 1) : "");
  }
}

AHK, 68 bytes
m=%1%
n=%2%
3-=2
Send %m%`n%n%`n
Loop,%3%
{
n:=m-n
m-=n
Send %n%`n
}

Getting' really tired of not knowing how / being able to use passed arguments (%1%, %2%, ...) directly in any math functions

Python 2, 93 90 bytes
u,t=int,input;m,n,p=u(t()),u(t()),u(t());l=[m,n]
for i in range(p-2):l.append(l[-2]-l[-1])

Try it online!
Saved 3 bytes thanks to @Mr.Xcoder
It works by taking the numbers as input and formatting them correctly, then using a for loop to generate a list based on the inputted numbers.

You can remove the space after comma in that range to save 1 byte

And it may be shorter if you map your input with ints and input.split

@Mr.Xcoder I tried the split, but it ended up being longer.

Ok, I couldn't test it. It's good anyway.

And the range does not need the first argument

Husk, 7 bytes
↑¡o→Ẋ`-

Try it online!
Explanation
↑¡o→Ẋ`-
 ¡o     create an infinite list using the array:
        the next element is:
   →    the last element of
    Ẋ`- overlapping pairs reduced by subtraction.
↑       take n elements

Swift - 85 bytes
func y(x:Int,y:Int,z:Int){var m=x,n=y,p=z,c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

Usage: y(x:50,y:40,x:6)
Swift - 84 bytes
func z(l:[Int]){var m=l[0],n=l[1],p=l[2],c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

Usage: z(l: [50,40,6])

Output:
50
40
10
30
-20
50

Python - 55 bytes
def s(m,n,p):
 for i in range(p):print(m);c=m;m=n;n=c-n

Try it online! & Usage: s(50,40,6)
Note: Solution without lambda


text:
Escape a chessboard
You find yourself on a chessboard, as one does.  You can see the exit but it is awfully far away and you would rather not walk all the way.  Luckily some locals have offered you a ride. A Knight, a Rook, a Bishop and a King are all willing to take you to your destination, but seeing how this is a chessboard they must each abide by the rules of chess on the way to your destination.  You would like to get out of here as soon as possible, whose offer do you accept?
Task
Given a arbitrarily shaped and sized chessboard and two points on the chess board, output the chess piece that can move between the two locations in as few moves as possible.  Boards will not necessarily be continuous meaning that there could be gaps between sections of the board.  Each of the four pieces (King, Rook, Knight, and Bishop) can move according to their standard rules in chess.  The Queen and pawn pieces have been intentionally left out of this challenge.
I/O
You may take input in any reasonable format and you may output in whatever format you choose as well.  Your input and output must be self-consistent.  If multiple pieces can make it to the destination in the same number of moves you must output all of the pieces that can get there in the minimum amount of time.  If none of the four pieces can make it to the end you may output anything as long as it is distinct from all other possible outputs.  This could include outputting nothing or throwing an error.
Test Cases
A square indicates the starting point and a circle indicates the ending point.

Bishop

Knight

King

Rook

King, Knight

None

Nice. I like this but isn't an "arbitrarily shaped and size chessboard" a single entity? I don't really see how examples 2 and 6 fit in with this as it looks like they are two separate boards which only the knight can jump between. Maybe I am missing something?

@ElPedro They are still a single board, its just not a continuous board.  Part of arbitrary shape is that the boards can be non-continuous.

For example 3, shouldn't it be "king, queen"?

Thanks @Wheat. Not sure that was clear from the question but I understand now.

@KritixiLithos To keep things interesting there is no Queen or Pawn.

Haskell, 447 439 437 432 bytes
t=[1,2]
p=[(+),(-)]
f=filter
a=abs
(#)=elem
x?y=[min x y..max x y]
f&g=(\x->g x>>=f)
(b!1)(c,r)=f(#b)[(c!d,r#s)|(!)<-p,(#)<-p,d<-t,s<-t,d/=s]
(b!2)(c,r)=f(\(d,s)->(c==d&&all(#b)[(c,z)|z<-r?s])||r==s&&all(#b)[(z,r)|z<-c?d])b
(b!3)(c,r)=f(\(d,s)->a(c-d)==a(r-s)&&all(#b)(zip(c?d)$r?s))b
(b!4)(c,r)=f(\(d,s)->a(c-d)<2&&a(r-s)<2)b
(b%p)n s=[s]>>=foldr(&)(:[])(replicate n$b!p)
g b s e=head$f(not.null)[[p|p<-[1..4],e#(b%p)n s]|n<-[0..]]

Call using g <board> <start> <end> where <board> :: [(Int, Int)], <start> :: (Int, Int) and <end> :: (Int, Int). Returns a list containing 1 for Knight, 2 for Rook, 3 for Bishop, and 4 for King. If no solutions are found, it consistently overflows the stack (that counts as throwing an error, right?).
Inspiration taken from LYAH's chapters on Monads—(%) is just a generalized and golfed inMany, with (&) equivalent to (Control.Monad.<=<). Everything else should be more-or-less self-explanatory.
This can probably be golfed a lot more, but I've had enough fun for now.
Ungolfed:
data Piece = Knight | Rook | Bishop | King deriving (Show)
type Place = (Int, Int)
type Board = [Place]

x `to` y = [min x y..max x y]

f <=< g = (\x -> g x >>= f)

moves
    :: Board    -- available spaces
    -> Piece    -- type of piece
    -> Place    -- starting place
    -> [Place]  -- places available in one move
moves b Knight (c,r) =
    filter (`elem` b) [(c!d, r#s) |
                       (!) <- [(+),(-)], (#) <- [(+),(-)],
                       d <- [1,2], s <- [1,2], d/=s]
moves b Rook   (c,r) =
    filter (\(d,s) -> (c == d && all (`elem` b) [(c,z) | z <- r `to` s])
                    || r == s && all (`elem` b) [(z,r) | z <- c `to` d]) b
moves b Bishop (c,r) =
    filter (\(d,s) -> abs(c-d) == abs(r-s)
                && all (`elem` b) (zip (c `to` d) (r `to` s))) b
moves b King   (c,r) =
    filter (\(d,s) -> abs(c-d) <= 1 && abs(r-s) <= 1) b

canGoIn
    :: Board    -- available spaces
    -> Piece    -- type of piece
    -> Int      -- number of moves
    -> Place    -- starting place
    -> [Place]  -- places available in the specified number of moves
canGoIn b p n s =
    return s >>= foldr (<=<) return (replicate n (moves b p))

quickestPieces
    :: Board    -- available spaces
    -> Place    -- starting place
    -> Place    -- ending place
    -> [Piece]  -- quickest pieces
quickestPieces b s e =
        head $ filter (not.null)
            [[p | p <- [Knight, Rook, Bishop, King], elem e (canGoIn b p n s)] |
                n<-[0..]]

Nice use of functional programming!

Mathematica, 326 325 bytes
Thanks to masterX224 for pointing out a byte savings!
f[g_,w_,x_]:=(c={{1,1},{-1,1}};s=c.c/2;e=#<->#2&@@@#&;j=Join;h=FindShortestPath;t=#~Tuples~2&;a@d_:=e@Select[t@g,#-#2&@@#==d&];y@k=j@@(a/@j[s,c]);y@n=j@@(a/@{{1,2},{2,1},{-2,1},{-1,2}});v=Flatten[e@t@#&/@ConnectedComponents@a@#&/@#]&;y@r=v@s;y@b=v@c;Pick[p={b,k,n,r},z=Length[h[y@#,w,x]/.h@__->0]&/@p,Min[z~Complement~{0}]]);

Defines a function f taking three arguments: g is a list of ordered pairs of integers representing the board, and w and x ordered pairs representing the start and end squares. The output is the subset of {b, k, n, r} (representing bishop, king, knight, and rook, respectively) which have a minimal-moves path between the two squares. For example, the third test case is invoked by f[{{0, 0}, {1, 1}, {1, 2}, {0, 3}}, {0, 0}, {0, 3}] and returns {k}; the last two test cases return {k, n} and {}, respectively.
The strategy is to translate the squares of the board into vertices of a graph, where the edges are determined by each piece's moves, and then use built-in graph routines.
More user-friendly version of the code:
 1  f[g_, w_, x_] := ( c = {{1, 1}, {-1, 1}}; s = c.c/2;
 2    e = # <-> #2 & @@@ # &; j = Join; h = FindShortestPath; t = #~Tuples~2 &;
 3    a@d_ := e@Select[t@g, # - #2 & @@ # == d &];
 4    y@k = j @@ (a /@ j[s, c]);
 5    y@n = j @@ (a /@ {{1, 2}, {2, 1}, {-2, 1}, {-1, 2}});
 6    v = Flatten[e@t@# & /@
 7         ConnectedComponents@a@# & /@ #] &;
 8    y@r = v@s; y@b = v@c;
 9    Pick[p = {b, k, n, r},
10      z = Length[h[y@#, w, x] /. h@__ -> 0] & /@ p,
11      Min[z~Complement~{0}]]
12  );

In line 3, Select[g~Tuples~2, # - #2 & @@ # == d finds all ordered pairs of vertices whose difference is the vector d; e then transforms each such ordered pair into an undirected graph edge. So a is a function that creates edges between all vertices that differ by a fixed vector.
That's enough to define, in lines 4 and 5, the king's graph y@k (which takes the union of edges generated by the vectors {1, 1}, {-1, 1}, {0, 1}, and {-1, 0}) and the knight's graph y@n (which does the same with {1, 2}, {2, 1}, {-2, 1}, and {-1, 2}).
In line 7, ConnectedComponents@a@# takes one of these neighbor graphs and then finds its connected components; this corresponds to grouping all line segments of vertices in the given direction (so that a rook or bishop doesn't have to move through them one by one). Then e@t@# on line 6 puts edges between every pair of vertices in the same connected component, which are then Flattened into a single graph. Thus lines 6 through 8 define the rook's graph y@r and the bishop's graph y@b.
Finally, lines 9 through 11 choose the elements of {b, k, n, r} that yield the shortest path between the two target vertices. FindShortestPath will throw an error and return unevaluated if a target vertex doesn't appear in the graph (which will happen if no edges emanate from it), so we use h@__ -> 0 to return 0 in those cases instead. And the lack of a path between valid vertices returns a list of length 0, so Min[z~Complement~{0}] calculates the length of the smallest path that actually exists, ignoring the bad cases above.

any reason for double f in the function name? or is it a mathematica limit?

oh, haha, no it's a mental limit on my part :) I had an f in that session already, but I should have changed it before submission!

source: Stack Exchange

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

sort: votes


text:
Bowl a rectangular quine
Code-Bowling Quine Challenge
You must bowl a quine following the rules of code bowling and quines but the source code must be in the shape of a rectangle (details specified below)

Quine
Quines returned must be returned via the ways defined in the standard I/O rules.

Rules
Code-Bowling Rules

Character : Byte Ratio  In Code-Bowling a character-count is
preferred over a byte-count. The obvious reasoning for this is that
multi-byte unicode characters (e.g. ) can be used in place of
single-byte unicode characters to fluff up byte count and will make
bowling more about who renames the most variables with high-byte
unicode characters rather than who most strategically creates
meaningful complex code. (See Useful tools section at end for
character-counting widget)

Variable/Function/Object Names  All variable names (or object pointers, function names, etc) should be 1 character long. The only
acceptable time to use 2-character variables names is after all
possible 1-character variables have been used. The only acceptable
time to use 3-character variables names is after all possible
2-character variables have been used. Etc.

Non-simplified Arithmetic  All arithmetic should be in simplified form unless there is a justifiable reason for doing otherwise (e.g.
circumventing penalties defined in the scoring system of the
challenge (In which case you still must use the smallest possible
alternative form)). Finding the simplified form of any equation (as
well as a list of small alternative forms) is easy to do using
Wolfram|Alpha. (See Useful tools section at end)

Un-used Code  All code must be used. Meaning the program must fail to always properly complete the task if any individual character (or
varying set(s) of characters) is/are removed. Naturally, a subset of
the program should not be able complete the task on its own without
the rest of the program.

Line-breaks and White-space  Unless necessary for code function or otherwise specified by the challenge, all line-breaks and
white-space should be removed from code before scoring by counting
characters.

Comments  Comments are not permitted towards character-count, unless somehow utilized by your program/function.

Rectangle Rules
Your code must be in the shape of a rectangle, i.e. every line has the same number of characters. Your code must have at least 2 lines, with at least 3 chars on each line.
Also, each line of code must be distinct to a certain threshold. Distinctness is calculated using the Levenshtein distance. The threshold is 85%, meaning the Levenshtein distance between any two lines must be greater than or equal to 0.85*w, where w is the number of characters used in a line of your rectangle.
And for convenience, here is a Levenshtein distance calculator and a character length calculator.

Scoring
This is a code-bowling variant. The program with the highest number of characters wins!

Just want to clarify, do all common rules apply; and for the rectangle scoring system is the Levenshtein distance threshold for this challenge 85%?

@AlbertRenshaw yes

"Meaning the program must fail to always properly complete the task if any individual character (or varying set(s) of characters) is/are removed." Can fail also mean that removing characters prevents the code from being a rectangle?

Possibly related: Hello world with the shape of hello world

I'd be disappointed if you couldn't score infinity in the limit on this one (the only difficult part would be creating a checksum operation that can handle having arbitrary subsets of bytes deleted from it).

@ais523 it would fail un needed bytes

@DownChristopher: All the bytes are needed because the checksum wouldn't match otherwise, thus causing the code to fail to work. This is a common trick used in "all the bytes must matter" [tag:restricted-source] questions.

@ais523 It's possible that the checksum part of the code itself could be removed as well. No subset of the program should be able to complete the task. Granted I dont know exactly how the check sum code works, need an example to tell

A trick that would probably work would be to make the checksum executable code, and eval it. Removing the checksum would mean that part of the code doesn't run, and thus the program fails. Removing any of the part of the code that gets checksummed would cause the wrong code to run. The only really hard part is designing the checksum in such a way that you can't find a subset of the code that would sum to the same value.

Python 3, 89 bytes
a='a=%r;b=%r;p=\\';b='print;p(a%(a,b));';p=\
print;p(a%(a,b));c='c=%r;p(b+c%%c)';p(b+c%c)

Try it online
The Levenshtein distance is 38, which is 86.36% of 44.
Explanation:
This is similar to the standard quine s='s=%r;print s%%s';print s%s. I had to try a lot of combinations and modifications in order to find my program. Creating the function p was used to make the second line shorter. The \ on the end of the first line is a line-continuation character.
a
a='a=%r;b=%r;p=\\'

A string template that results in the first line

b
b='print;p(a%(a,b));'

String that represents the first part of the 2nd line

p
p=\
print

Shorten stuff, change lengths

line 1
p(a%(a,b))

Print the first line

c
c='c=%r;p(b+c%%c)'

String representing itself plus the part after that prints b

line 2
p(b+c%c)

Outputs the second line

Dang. That is impressive, good job!

If you want to make me smile (I would offer a upvote but you already got it) add a explanation

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


text:
Big base, small digits
The J language has a very silly syntax for specifying constants. I want to focus on one cool feature in particular: the ability to write in arbitrary bases.
If you write XbY for X any number and Y any string of alphanumerics, then J will interpret Y as a base X number, where 0 through 9 have their usual meaning and a through z represent 10 through 35.
And when I say X any number, I mean any number. For the purposes of this question, I'll constrain X to be a positive integer, but in J you can use anything: negative numbers, fractions, complex numbers, whatever.
The thing that's weird is that you can only use the numbers from 0 to 35 as your base-whatever digits, because your collection of usable symbols consists only of 0-9 and a-z.
The problem
I want a program to help me golf magic numbers like 2,933,774,030,998 using this method. Well, okay, maybe not that big, I'll go easy on you. So...

Your task is to write a program or function which takes a (usually large) decimal number N between 1 and 4,294,967,295 (= 232-1) as input, and outputs/returns the shortest representation of the form XbY, where X is a positive integer, Y is a string consisting of alphanumerics (0-9 and a-z, case insensitive), and Y interpreted in base X equals N.
If the length of every representation XbY representation is greater than or equal to the number of digits of N, then output N instead. In all other ties, you may output any nonempty subset of the shortest representations.

This is code golf, so shorter is better.
Test cases
      Input | Acceptable outputs (case-insensitive)
------------+-------------------------------------------------------
          5 | 5
            |
   10000000 | 79bkmom  82bibhi  85bgo75  99bauua  577buld
            | 620bq9k  999baka
            |
   10000030 | 85bgo7z
            |
   10000031 | 10000031
            |
   12345678 | 76bs9va  79bp3cw  82bmw54  86bjzky  641buui
            |
   34307000 | 99bzzzz
            |
   34307001 | 34307001
            |
 1557626714 | 84bvo07e  87brgzpt  99bglush  420blaze
            |
 1892332260 | 35bzzzzzz  36bvan8x0  37brapre5  38bnxkbfe  40bij7rqk
            | 41bgdrm7f  42bek5su0  45bablf30  49b6ycriz  56b3onmfs
            | 57b38f9gx  62b244244  69b1expkf  71b13xbj3
            |
 2147483647 | 36bzik0zj  38br3y91l  39bnvabca  42bgi5of1  48b8kq3qv
 (= 2^31-1) | 53b578t6k  63b2akka1  1022b2cof  1023b2661  10922bio7
            | 16382b8wv  16383b8g7  32764b2gv  32765b2ch  32766b287
            | 32767b241
            |
 2147483648 | 512bg000  8192bw00
            |
 4294967295 | 45bnchvmu  60b5vo6sf  71b2r1708  84b12mxf3  112brx8iv
 (= 2^32-1) | 126bh5aa3  254b18owf  255b14640  1023b4cc3  13107bpa0
            | 16383bgwf  21844b9of  21845b960  32765b4oz  32766b4gf
            | 32767b483  65530b1cz  65531b1ao  65532b18f  65533b168
            | 65534b143  65535b120

If you're ever unsure about whether some representation is equal to some number, you can use any J interpreter, like the one on Try It Online. Just type in stdout 0":87brgzpt and J will spit back out 1557626714. Note that J only accepts lowercase, even though this problem is case-insensitive.
Some possibly helpful theory

For all N less than 10,000,000, the decimal representation is as short as any other and hence is the only acceptable output. To save anything you would need to be at least four digits shorter in the new base, and even more if the base is greater than 99.
It suffices to check bases up to the ceiling of the square root of N. For any larger base B, N will be at most two digits in base B, so the first time you'll get something with a valid first digit is at around B ≈ N/35. But at that size you will always be at least as large as the decimal representation, so there's no point in trying. That in mind, ceil(sqrt(largest number I'll ask you to solve this problem for)) = 65536.
If you have any representation in a base less than 36, then the base 36 representation will be at least as short. So you don't have to worry about accidentally short solutions in bases less than 36. For example, the representation 35bzzzzzz for 1,892,332,260 uses an unusual digit for that base, but 36bvan8x0 has the same length.

Lol, 1557626714  = 420blaze ^_^

JavaScript (ES6), 103 101 bytes
Takes input as a string.
n=>[...Array(7e4)].reduce(p=>p[(r=++b+(g=x=>x?g(x/b|0)+(x%b).toString(36):'b')(n)).length]?r:p,n,b=2)

Test cases
NB: The number of iterations in the snippet function is limited to 600 so that the test cases complete faster. (It would take a few seconds otherwise.)

let f =

n=>[...Array(6e2)].reduce(p=>p[(r=++b+(g=x=>x?g(x/b|0)+(x%b).toString(36):'b')(n)).length]?r:p,n,b=2)

console.log(f("5"))
console.log(f("10000000"))
console.log(f("10000030"))
console.log(f("10000031"))
console.log(f("12345678"))
console.log(f("34307000"))
console.log(f("34307001"))
console.log(f("1557626714"))
console.log(f("1892332260"))
console.log(f("2147483647"))
console.log(f("2147483648"))
console.log(f("4294967295"))

If my number is too large to work with this, how would I fix it? Increasing the iterations doesn't seem to help.

@FrownyFrog Which number are you trying to process? This code is supposed to work for $N<2^{32}$, as per the challenge rules.

"Pernicious numbers" lookup, 2136894800297704.

@FrownyFrog You may be able to process it by increasing the number of iterations and using Math.floor(x/b) instead of x/b|0. (But I didn't test it.)

it worked! Thank you.

Ruby, 118 bytes
This was linked in another question and I noticed there aren't many answers here, so I decided to give it a shot.
Walk through all bases up to and including the input to construct all valid J number constructions. It skips 1-8 though, because there's no way those will be shorter than the base-10 representation anyways. It's a pretty naive solution, all things considered, since it calls the digits builtin to get the digits, but since that starts with the least significant digit first we have to reverse it to get the actual number, so it could possibly be improved.
It's slow. So, soooooo incredibly slow. TIO times out on 34307000, for example. We could go with the square root or even Arnauld's choice of 7e4 to save time, but that costs extra bytes, so why bother?
->n{([n.to_s]+(9..n).map{|b|d=n.digits b;"#{b}b"+d.reverse.map{|i|i.to_s 36}*''if d.all?{|i|i<36}}-[p]).min_by &:size}

Try it online!
Try it online w/ sqrt so everything finishes on time

05AB1E, 37 bytes
[¼35Ý¾ãvtîEyNβQižhA«yèJ'bìNìDgIg@i\}q

Should work in theory, but times out for all non-trivial test cases, even 10000000. The cartesian product builtin ã is extremely slow for \$\geq4\$..
Without the final if-statement DgIg@i\} it can still be tested for lower values, to verify that it does in fact work: Try it online.
Will see if I can come up with a (probably much longer but) more efficient solution later on.
Explanation:
[              # Start an infinite loop:
 ¼             #  Increase the counter variable by 1 (0 by default)
 35Ý           #  Push a list in the range [0, 35]
 ¾ã            #  Take the cartesian product of this list with itself,
               #  with chunks-sizes equal to the counter variable
 v             #  Loop `y` over each of these lists:
  t            #   Take the square-root of the (implicit) input-integer
   î           #   Ceil it
  E            #   Loop `N` in the range [1, ceil(square(input))]:
   yNβ         #    Convert list `y` to base-`N`
   Qi          #    If it's equal to the (implicit) input-integer:
     žh        #     Push string "0123456789"
       A«      #     Append the lowercase alphabet
     yè        #     Index each value in list `y` into this string
     J         #     Join the characters to a single string
     'bì      '#     Prepend a "b"
        Nì     #     Prepend the number `N`
     D         #     Duplicate it
      g        #     And pop and push the length of this string
       Ig      #     Also push the length of the input
         @i }  #     If the length of the string is >= the input-length:
           \   #      Discard the duplicated string
     q         #     Stop the program
               #     (after which the result is output implicitly;
               #      or if the string was discarded and the stack is empty, it will
               #      implicitly output the implicit input as result instead)

Impressive answer! I think you're missing a rule, though: "If the length of every representation XbY representation is greater than or equal to the number of digits of N, then output N instead." While you do have the first 10 million numbers covered, I suspect that an input of 10000031 will give back something like 26blmoof. The number is valid, but the length is the same as the input, so it should be returning the input instead.

@ValueInk Ah oops. Thanks for noticing! Should be fixed now at the cost of a few bytes.

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


text:
Chemistry 101 - Introduction to the Periodic Table
Question
Given the atomic number of an element in the range [1-118] output the group and period, of that element as given by the following Periodic Table Of Elements.
For elements in the Lanthanide and Actinide series, (ranges [57-71] and [89-103]), you should instead return L for the Lanthanides and A for the Actinides

You may write a program or a function and use any of the our standard methods of receiving input and providing output.
You may use any programming language, but note that these loopholes are forbidden by default.

[Source]
Test Cases
Since there are only 118 possible inputs, a full list of the expected inputs and outputs is given below.
Created by hand, let me know if there's a mistake!

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

Scoring
Simple code-golf. Shortest number of bytes wins

I just know that Mathematica will have a built-in for this...

@Okx, I'm hoping that the Lanthanides and Actinides mess up any built-ins :)

Are you allowed to return "6,L" and "7,A" for the Lanthanides and Actinides?

@Neil, No. Just "L" and "A" please.

can't comment (yet) but sometimes Hydrogen is placed in group 17 - but I acknowledge that you've used an image to justify why group 1 and don't know if this makes things harder or easier?

I assume trailing whitespace is fine?

can it be L? or it has to be L,

L is fine. That's actually what I intended. But since the CSV outputted L, I'll accept both

Why not L,# for lanthanides (and analogous for actinides), where # is the element's position within the Ln/An group?

@hBy2Py, because I came up with an arbitrary way to note those elements :P

@James "Just because." Fair enough! :-)

Is the comma as delimiter mandatory, or could we use (example) an underscore as delim?

@sjb-2812 who is putting H in group 17? That's just wrong.

@OrangeDog, with just one electron, is it the first electron in its shell? Or is it missing one from a complete shell?

@JamesWebster does its chemical properties most closely resemble Na or Cl? Hint: H-Cl and Na-Cl are a lot more common than H-H and Na-H. You can (and Mendeleev did) construct the table with no knowledge of atomic structure at all.

From what I remember of my high school chemistry, since it has properties of both the alkali metals and the halogens, it is both, yet neither. The books we had placed it in neither group but on its own. This might be better argued on Chemistry SE!

CJam, 64 59 58 56 54 bytes
Thanks to Dennis for saving 2 bytes.
{_80-zG-z8<{80>"LA"=}{_"X8"f>[-14_AAGH].*+:+Imd)}?}

Try it online!
Leaves either period and group or a single character on the stack.
Explanation
There are two main ideas here:

First, we deal with the Lanthanides and Actinides. We have the condition 56 < x < 72 for Lanthanides and 88 < x < 104 for Actinides. Both of these can be expressed as a single comparison by taking an absolute difference to the centre of the range: the inequalities become |x - 64| < 8 and |x - 96| < 8, respectively. But these are still very similar, and doing the two comparisons separately is expensive. So we apply the same idea of checking a symmetric range, by taking another absolute difference with the centre between the two ranges, 80, first: ||x-80| - 16| < 8. This condition indicates that the atom is either a Lanthanide or an Actinide, but distinguishing between these two cases is then as trivial as comparing against 80 (or some other value between the ranges).
Since the output is really an index in a table of width 18, an obvious approach is to try base-converting the value to base 18, so that the two digits give group and period. To do that, we need to shift some values around though. All the we really need to do is to add the gaps in periods 1, 2 and 3 and close the gaps in periods 6 and 7. It's easiest to do this from the end, so that the values of the other gaps aren't affected (and keep their values).

_            e# Make a copy of the input, to figure out whether the output
             e# should be L or A.
80-z         e# Absolute difference from 80.
G-z          e# Absolute difference from 16.
8<           e# Check whether the result is less than 8.
{            e# If so...
  80>        e#   Check whether the input is greater than 80.
  "LA"=      e#   Select 'L or 'A accordingly.
}{           e# ...otherwise...
  _          e#   Duplicate input again.
  "X8"    e#   Push a string with character codes [88 56 12 4 1].
             e#   These are the values just before the gaps.
  f>         e#   Compare the input to each of these.
  [-14_AAGH] e#   Push [-14 -14 10 10 16 17]. These are the changes we need to
             e#   make to remove or insert the gaps corresponding to the above
             e#   positions. Note that the 17 doesn't get paired with an offset.
             e#   It's a constant offset to itself, which is equivalent to
             e#   decrementing the input (to make it zero based) and adding 18
             e#   to make the increment the period and make it 1-based.
  .*         e#   Multiply each gap by whether it's before the input value.
  +:+        e#   Add all of the applicable gaps to the input value.
  Imd        e#   Divmod 18, gives 1-based period and 0-based group.
  )          e#   Increment the group to make it one-based.
}?

05AB1E, 113 102 99 bytes
X18©XY‚Dˆ13®Ÿ¯13®Ÿ®LD¯15'L×S15L3+©¯15'A×S®)˜¹<è,XXY8×SD>4 18×SD>S66Sð14×S6 15×S77Sð15×S7 15×S)˜¹<è,

Explanation:
(start to construct the period part)
X18 ~ push 1 and 18
© ~ store 18 in register_c without p-opping
XY ~ push 1 and 2
13® ~ push 13 and the top element in register_c (18)
Ÿ ~ range - pop 2 values and push [a .. b]
XY ~ push 1 and 2
13®Ÿ ~ range - 13 to 18
XY ~ push 1, 2
13®Ÿ ~ range - 13 to 18
®LD ~ range - 1 to 18 (twice)
2L ~ range - 1 to 2
15'L×S ~ push 'L' 15 times
15L ~ range - 1 to 15
3+ ~ add 3 to each value in topmost element in stack
© ~ store in register-c without popping
2L ~ range - 1 to 2
15'A×S ~ push 'A' 15 times
® ~ push topmost value in register_c
) ~ wrap stack to array
˜ ~ deep flatten
¹<è ~ 1-indexed value of input in array
, ~ print & pop
(start to construct the group part)
XX ~ push 1 twice
Y8×SD ~ push 2 eight times (twice)
> ~ increment each value by 1
4 18×S ~ push 4 eighteen times (twice)
> ~ increment each value by one
66S ~ push 6 twice
ð15×S ~ push a space character 15 times
6 15×S ~ push 6 fifteen times
77S ~ push 7 two times
ð15×S ~ push a space character 15 times
7 15×S ~ push 7 fifteen times
)˜ ~ wrap stack to array and deep flatten
¹<è, ~ get 1-indexed value of input in array, then pop & print

Try it online!

Using a mask like 1000000000000000000000000000000001 1100000000000000000000000000111111 1100000000000000000000000000111111 1112222222222222221111111111111111 1113333333333333331111111111111111 may reduce bytecount, otherwise nice!

Mathematica, 77 bytes
e=ElementData;Which[56<#<72,"L",88<#<104,"A",1>0,{#~e~"Group",#~e~"Period"}]&

It would also be quite easy to use ElementData to determine whether the input is a Lanthanide or Actinide, but it would take about 20 more bytes.

Seriously, builtins again?

@MatthewRoh I'm sure a well-golfed arithmetic solution in a golfing language will easily beat this.

@MartinEnder Well, I'm actually sure of the exact opposite.

@EriktheOutgolfer Well, there you go. I'm sure Jelly could cut off another 30-50%.

@MartinEnder I'll most probably leave that up to Dennis, I can't do such a thing in exam period.

Python 2, 205 136 bytes
-26 bytes thanks to @Dead Possum
def f(x):a=(x>71)+(x>99);print((((x-2*(x>1)-8*(x>4)-8*(x>12)+4*a-1)%18+1,(x-(x>17)-14*a)/18+(x>2)+(x>10)+1),'L'),'A')[88<x<104][56<x<72]

Try it online!

PHP, 144 bytes
Note: uses IBM-850 encoding
$x=($a=$argn-1)<57|$a>70?$a>88&$a<103?A:0:L;foreach([16,19=>10,37=>10,92=>-14,110=>-14]as$l=>$m)$a>$l&&$a+=$m;echo$x?:$a%18+1 .~Ë.ceil(++$a/18);

Run like this:
echo 118 | php -nR '$x=($a=$argn-1)<57|$a>70?$a>88&$a<103?A:0:L;foreach([16,19=>10,37=>10,92=>-14,110=>-14]as$l=>$m)$a>$l&&$a+=$m;echo$x?:$a%18+1 .~Ë.ceil(++$a/18);';echo
> 18,7

Explanation
Check whether input is within the ranges for L or A; the "exception" ranges. Then modify the input to fill the missing cells in the grid (or get rid of the extra cells). Finally, print the exception (unless that is falsy 0) or convert the position to grid coordinates.

Running your example, the output I receive is 18<t7. Is this something I'm doing wrong? (running on Mac El Capitan)

@JamesWebster that's because of the encoding I used for the comma. If you can't switch your terminal's encoding, you can replace the thing between the 2 dots (just before ceil) with "," for 1 extra byte

Jelly, 57 bytes
“9Ḳ*!}ḣE’ṃ“¢£Æ¥Ø‘r2/;€"“ⱮḶıð’ḃ7¤µ⁵,12Ṭœṗ;"⁾LAṁ€15¤j“”$⁺³ị

Full program that prints the desired output.
Try it online! (A slightly modified program which prints all input : output may be seen here).
How?
Builds a list of the 118 possible outputs and then picks the entry at the index of the input.
Some prep:
“9Ḳ*!}ḣE’ - base 250 number: 14334152882934570 (call this A)

“¢£Æ¥Ø‘   - a list using Jelly's code page: [1, 2, 13, 4, 18] (call this B)

“ⱮḶıð’    - base 250 number: 2354944025 (call this C)

The program (shortened by substituting A, B, and C) :
AṃBr2/;€"Cḃ7¤µ⁵,12Ṭœṗ;"⁾LAṁ€15¤j“”$⁺³ị - Main link: atomicNumber
AṃB                                    - number A with digits B: [1,1,18,18,1,2,13,18,1,2,13,18,1,18,1,18,1,2,4,18,1,2,4,18]
    2/                                 - pair-wise reduce with
   r                                   -     inclusive range: [[1],[18],[1,2],[13,14,15,16,17,18],[1,2],[13,14,15,16,17,18],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],[1,2],[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],[1,2],[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]]
            ¤                          - nilad followed by link(s) as a nilad:
         C                             -     number C
          ḃ7                           -     converted to bijective base 7: [1,1,2,2,3,3,4,5,6,6,7,7]
        "                              - zip with:
      ,€                               -     pair each: [[1,1],[18,1],[[1,2],[2,2]],[[13,2],[14,2],[15,2],[16,2],[17,2],[18,2]],[[1,3],[2,3]],[[13,3],[14,3],[15,3],[16,3],[17,3],[18,3]],[[1,4],[2,4],[3,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]],[[1,5],[2,5],[3,5],[4,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]],[[1,6],[2,6]],[[4,6],[5,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]],[[1,7],[2,7]],[[4,7],[5,7],[6,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]]]
             µ                         - monadic chain separation (call the result x)
              ⁵                        - 10
               ,12                     - pair with 12: [10,12]            10↓ 12↓
                  Ṭ                    - truthy indexes: [0,0,0,0,0,0,0,0,0,1,0,1]
                   œṗ                  - partition x at the truthy indexes
                                       -     (the locations of the runs of L's and A's)
                              ¤        - nilad followed by link(s) as a nilad:

                       ⁾LA             -     ['L','A']
                          ṁ€15         -     mould each like 15: [['L','L','L','L','L','L','L','L','L','L','L','L','L','L','L'],['A','A','A','A','A','A','A','A','A','A','A','A','A','A','A']]
                      "                - zip with:
                     ;                 -     concatenation: [[[1,1],[18,1],[[1,2],[2,2]],[[13,2],[14,2],[15,2],[16,2],[17,2],[18,2]],[[1,3],[2,3]],[[13,3],[14,3],[15,3],[16,3],[17,3],[18,3]],[[1,4],[2,4],[3,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]],[[1,5],[2,5],[3,5],[4,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]],[[1,6],[2,6]],'L','L','L','L','L','L','L','L','L','L','L','L','L','L','L'],[[[4,6],[5,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]],[[1,7],[2,7]],'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A'],[[4,7],[5,7],[6,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]]]

             µ⁵,12Ṭœṗ;"⁾LAṁ€15¤j“”$⁺³ị
                                  $    - last two links as a monad:
                               j“”     -     join with [''] (a workaround for no "flatten by 1")
                                   ⁺   - repeat last link (flatten once more): [[1,1],[18,1],[1,2],[2,2],[13,2],[14,2],[15,2],[16,2],[17,2],[18,2],[1,3],[2,3],[13,3],[14,3],[15,3],[16,3],[17,3],[18,3],[1,4],[2,4],[3,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],[1,5],[2,5],[3,5],[4,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],[1,6],[2,6],'L','L','L','L','L','L','L','L','L','L','L','L','L','L','L',[4,6],[5,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],[1,7],[2,7],'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A',[4,7],[5,7],[6,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]]
                                    ³  - program's first input
                                     ị - index into the list

Perl5, 202 bytes
$x=substr(" !2ABMNOPQRabmnopqr\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\301\302LLLLLLLLLLLLLLL\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\341\342KKKKKKKKKKKKKKK\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362",$ARGV[0],1);print$x=~/K/?"A":$x=~/L/?$x:(ord($x)&31).",".(ord($x)>>5)

I would recommend shortening the '\201\202\203...\362' part of the string. Seriously, its long as heck.

Curious how @MatthewRoh measured heck.

Ruby, 130 bytes
->a{(w=32767)[a-57]>0??L:w[a-89]>0??A:([[1,2],[20,8],[38,8],[107,32],[125,32]].map{|x,y|a>x&&a+=18-y};[(b=a%18)>0?b:18,~-a/18+1])}

First get the 'A' and 'L' with the bitmask trick, then try to fit into a 18*7 rectangle and use a div/mod.

Python 2, 137 bytes
lambda x:[(1+(x>2)+(x>10)+min((~-x/18),3)+(x>86),(x+(x>1)*15+((x>4)+(x>12))*10-((x>71)+(x>103))*14)%18+1),"AL"[89<x]][57<x<72or 89<x<104]

Try it online!

Python 2, 115 bytes
def f(n):n+=([0,17]+[33]*3+[43]*8+[53]*45+[200]*14+[39]*18+[400]*14+[25]*15)[n];print[(n%18+1,n/18),'L','A'][n/200]

Try it online!
The idea is to div-mod the grid position to get the group and period. The grid position is the input n adjusted by a displacement to account for gaps and the L/A contraction. These are extracted from a list.
The Lanthanide and Actinide handling is ugly. These are assigned large displacements 200 and 400 that can be detected with /200. I'd like to put the characters L and A here, but then n+=... will add a char to a number, giving an error even if n is not used. If not for the 1-indexing, divmod could be used to refer to n only once, and then it could be replaced with its expression,

JavaScript (ES7), 100 98 bytes

f=(n,p=1,x=0,y=x+2*(p+2>>1)**2)=>(n-57&95)<15?n>71?'A':'L':n>y?f(n,p+1,y):[n-x-1>p/2?n-y+18:n-x,p]
<input type=number min=1 max=118 oninput=o.textContent=f(this.value)>

Explanation: The 'L' and 'A' series are special-cased, using some bitwise logic that saved me 3 bytes over direct comparisons. Otherwise the function recursively finds the period p containing the desired atomic number, the number of the last element in the previous period x, and the number of the last element in the period y which is computed each time by noting that the differences are 2, 2, 8, 8, 18, 18 i.e. repeated doubled square numbers. The group is then found by offsetting from the left or right of the table depending on whether the element lies under the Beryllium-Scandium diagonal or not.

Python 2, 264 227 217 bytes
lambda x:((((((((((((((1,1),(18,1))[x>1],(x-2,2))[x>2],(x+8,2))[x>4],(x-10,3))[x>10],(x,3))[x>12],(x-18,4))[x>18],(x-36,5))[x>36],(x-54,6))[x>54],'L')[x>56],(x-68,6))[x>71],(x-86,7))[x>86],'A')[x>88],(x-100,7))[x>103]

Try it online!
Way too many brackets. It looks more like Brain-Flak.

can't you place that while outside the function? it would save a byte (space)

@FelipeNardiBatista - Managed to get rid of the while loop altogether :)

JavaScript (ES6), 136 bytes
n=>[...'112626ii2ff2fff'].reduce((p,i,j)=>(n-=parseInt(i,36))>0?n:+p?+(x='112233456L67A7'[j])?[p+(9258>>j&1?j>5?3:j>2?12:17:0),x]:x:p,n)

Test

let f =

n=>[...'112626ii2ff2fff'].reduce((p,i,j)=>(n-=parseInt(i,36))>0?n:+p?+(x='112233456L67A7'[j])?[p+(9258>>j&1?j>5?3:j>2?12:17:0),x]:x:p,n)
<input oninput="o.innerHTML=f(+value)" type="number" min=1 max=118/>

Excel, 192 bytes
Far from pretty.  Borrows from existing Python answers
=SUBSTITUTE(SUBSTITUTE(IF(ABS(ABS(A1-80)-16)<8,IF(A1<80,"L","A"),MOD(A1-2*(A1>1)-8*(A1>4)-8*(A1>12)+4*((A1>71)+(A1>99)),18)&" ,"&1+(A1>2)+(A1>10)+(A1>18)+(A1>36)+(A1>54)+(A1>86)),0,18),118,10)

Struggling to handle the case where MOD(x,18)=0 for Group value gracefully.

I think I've found a mistake. Should the IF for determining lanthanides and actinides read IF(A1<80?

@JamesWebster, well spotted.  Have corrected.

Ruby, 116 bytes
->n{a=(17..143).map{|i|"#{[i%18+1,i/18]}"}
a[2..17]=a[21..30]=a[39..48]=[]
a[57]=[?L]*15
a[75]=[?A]*15
a.flatten[n]}

Commented in test program
f=->n{
a=(17..143).map{|i|"#{[i%18+1,i/18]}"} #Make an array with strings "[18,0]" to "[18,7]" (first value required as input is 1 indexed.)
a[2..17]=a[21..30]=a[39..48]=[]        #Delete "missing" elements from first three periods.
a[57]=[?L]*15                          #Replace position 57 in the table with a 15-element array ["L".."L"]
a[75]=[?A]*15                          #Replace the correct position in the table with a 15-element array ["A".."A"]
a.flatten[n]}                          #Flatten the array (break the two above elements into 15) and output element n of the array.

1.upto(118){|n|print n,f[n],$/}

PHP, 120 bytes
echo(($n=--$argn)-56&95)<15?LA[$n>70]:(($n-=14*($n>88)+14*($n>56)-10*($n>11)-10*($n>3)-16*!!$n)%18+1).",".(($n/18|0)+1);

takes input from STDIN, run with -nR.
some bitwise magic for the Lanthanides and Actinides,
the $n-= part adds and subtracts offsets for the gaps and Lanthanides/Actinides,
the rest is simple mod/div.
An iterative port of Neil´s answer takes 108 bytes:
for(;(95&71+$n=$argn)>14&&$n>$y+=2*(++$p+2>>1)**2;)$x=$y;
echo$p?$n-$x>$p/2+1?$n-$y+18:$n-$x:LA[$n>70],",$p";

Perl, 169 bytes
90>($n-=14)&&($g=A)if($n=$v=pop)>88;58>($n-=14)&&($g=L)if$n>56;if(!$g){$c+=vec"\1\0\xe\xc0?\0".("\xff"x9)."?",$i++,1
while$c<$n;$p=1+($i-($g=$i%18||18))/18}say"$v,$g,$p"

Using:
perl -E '90>($n-=14)&&($g=A)if($n=$v=pop)>88;58>($n-=14)&&($g=L)if$n>56;if(!$g){$c+=vec"\1\0\xe\xc0?\0".("\xff"x9)."?",$i++,1 while$c<$n;$p=1+($i-($g=$i%18||18))/18}say"$v,$g,$p"' 103

Jelly, 49 43 42 41 39 bytes
45“ÞØ\€a€⁶;l;i‘bx/€F’ḣ¹Sḃ18µV=“?I‘⁾LAxȯ

Try it online!
Background
With the exception of lanthanides and actinides, the output will consist of an integer expressed in bijective base 18. For example, hydrogen corresponds to 1910 = 11b18, helium to 3610 = 1Ib18, and eka-radon/ununoctium/oganesson to 11410 = 7Ib18.
We start by mapping all atomic numbers we can to the corresponding integers, while mapping lanthanides and actinides to those that correspond to lanthanum (11110 = 63b18) and actinium (12910 = 73b18).
To do this, we record the forward differences of the integers that represent the atoms. For example, the first is 1Ib18 - 11b18 = Hb18 = 1710, the second is 1 (as are all differences between consecutive elements of the unexpanded periodic table), the fourth (B to Be) is 2Db18 - 22b18 = Bb18 = 1110, and so on. To map all lanthanides and all actinides, we'll consider all differences between two lanthanides or to actinides (e.g., La to Ce) to be 0.
To get the desired integer for an atomic number n, all we have to do is prepend 19 (hydrogen) to the differences and compute the sum of the first n elements of the resulting vector. The output is then simply displayed in bijective base 18, unless this would display 6 3 (lanthanides) or 7 3 (actinides). In the latter case, we simply replace the computed result with L or A.
Wrapped for horizontal sanity, the vector we have to encode looks as follows.
19 17  1  1 11  1  1  1  1  1  1  1 11  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
 1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  1  1  1  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  1  1  1  1  1  1  1  1
 1  1  1  1  1  1

After run-length encoding, we get the following.
19 1    17 1    1 2    11 1    1 7    11 1    1 44    0 14    1 18    0 14    1 15

To reduce the space required to encode the vector even more, we strip rightmost 1's (lengths) and add 1 to the runs.
20      18      2 2    12      2 7    12      2 44    1 14    2 18    1 14    2 15

Now we can reversibly convert these digit arrays from base 45 to integers.
20      18      92     12      97     12      134     59      108     59      105

All of these are smaller than 250, so we can represent them with characters from Jelly's code page. Surrounded with “ (literal start) and ‘ (interpret as integer array), we get the Jelly literal
“ÞØ\€a€⁶;l;i‘

which appears verbatim in the code.
How it works
45“…‘bx/€F’ḣ¹Sḃ18µV=“?I‘⁾LAxȯ  Main link. Argument: n (atomic number)

45                             Set the return value to 45.
  “…‘                          Yield [20,18,92,12,97,12,134,59,108,59,105].
     b                         Convert the integers in the array to base 45.
      x/€                      Reduce each resulting digit array (length 1 or 2)
                               by repetition, mapping [z] -> [z] and
                               [y,z] -> [y,…,y] (z times).
         F                     Flatten the result.
          ’                    Decrement, yielding the vector of length 118 from
                               the previous section.
           ḣ¹                  Head; take the first n elements of the vector.
             S                 Compute their sum.
              ḃ18              Convert to bijective base 18, yielding [p, g].
                 µ             Begin a new chain with argument [p,g].
                  V            Eval. The atom casts to string first, so [6,3]
                               , e.g., is mapped to 63, [7,18] to 718, etc.
                   =“?I‘       Compare the result with [63,73], yielding
                               [1,0] for lanthanides, [0,1] for actinides, and
                               [0,0] otherwise.
                        ⁾LAx   Repeat 'L' and 'A' that many times, yielding "L" for
                               lanthanides, "A" for actinides, and "" otherwise.
                            ȯ  Flat logical OR; replace "" with [p,g].

While this is an interesting answer, I'm afraid I think it falls down on the output. Instead of outputting the group and the period for the input, it appears to output the atomic number, group and period for the full table. Consider if I'd asked you for a dictionary definition of a word and you just outputted a dictionary.

The footer provides a test suite for easy verification. If you remove it and provide the input as an argument, it will just print yhe information the spec asks for. https://tio.run/nexus/jelly#@29i@qhhzuF5h2fEPGpakwjEjxq3WedYZz5qmJFUoQ/kuz1qmPlwx@JDO4Mf7mg2tDi0NcwWqMPeE6jgUeM@H8eKE@v///9vbgkA


text:
Round the string
Some decimal numbers cannot be precisely represented as binary floats due to the internal representation of the binary floats. For example: rounding 14.225 to two decimal digits does not result in 14.23 as one might expect but in 14.22.
Python:
In: round(14.225, 2)
Out: 14.22

Assume, however, that we have a string representation of 14.225 as '14.225', we should be able to achieve our desired rounding '14.23' as a string representation.
This approach can be generalized to arbitrary precision.
Possible Python 2/3 Solution
import sys

def round_string(string, precision):
    assert(int(precision) >= 0)
    float(string)

    decimal_point = string.find('.')
    if decimal_point == -1:
        if precision == 0:
            return string
        return string + '.' + '0' * precision

    all_decimals = string[decimal_point+1:]
    nb_missing_decimals = precision - len(all_decimals)
    if nb_missing_decimals >= 0:
        if precision == 0:
            return string[:decimal_point]
        return string + '0' * nb_missing_decimals

    if int(all_decimals[precision]) < 5:
        if precision == 0:
            return string[:decimal_point]
        return string[:decimal_point+precision+1]

    sign = '-' if string[0] == '-' else ''
    integer_part = abs(int(string[:decimal_point]))
    if precision == 0:
        return sign + str(integer_part + 1)
    decimals = str(int(all_decimals[:precision]) + 1)
    nb_missing_decimals = precision - len(decimals)
    if nb_missing_decimals >= 0:
        return sign + str(integer_part) + '.' + '0' * nb_missing_decimals + decimals
    return sign + str(integer_part + 1) + '.' + '0' * precision

Try it online!
Usage:
     # No IEEE 754 format rounding
In:  round_string('14.225',2)
Out: '14.23'

     # Trailing zeros
In:  round_string('123.4',5)
Out: '123.40000'

In: round_string('99.9',0)
Out: '100'

    # Negative values
In: round_string('-99.9',0)
Out: '-100'

In: round_string('1',0)
Out: '1'

    # No unnecessary decimal point
In: round_string('1.',0)
Out: '1'

    # No unnecessary decimal point
In: round_string('1.0',0)
Out: '1'

In:  for i in range(8):
         print(round_string('123456789.987654321',i))
Out: 123456790
     123456790.0
     123456789.99
     123456789.988
     123456789.9877
     123456789.98765
     123456789.987654
     123456789.9876543

Task
Input argument 1: a string containing

at least one digit (0, 1, 2, 3, 4, 5,6, 7, 8, 9),
at most one decimal point (.) which must be preceded by at least one digit,
an optional minus (-) as first character.

Input argument 2: a non-negative integer
Output: the correctly rounded (base 10) string
rounding = Round half away from zero
This is a code-golf. The lowest number of bytes wins!

@KevinCruijssen 1) You do not need to stick to strings in the body of your implementation and are allowed to use built-in rounding. Unfortunately (for the question) the IEEE 754 standard is a widely used standard and thus built-in rounding will not result in the desired behavior. 2) Ok, wasn't aware of the sandbox.

TI-Basic: round(A,B 5 bytes

@JulianLachniet Actually no, the input number is a string so maybe round(expr(Str0,B but then you need to convert that back into a string representation for output.

Regarding the second input argument: 0 is not a positive integer, it is "non-negative".

@Timtech toString(round(expr(Str0),B

I assume we add trailing zeros if needed? Could you perhaps add a test case for 123.4 & 5 --> 123.40000? Or can we assume the second input will never be larger than the amount of decimals after the point in the first input?

@KevinCruijssen Added the example (trailing zeros). Is it possible to make the Python code interactive like Javascript on StackExchange?

@Matthias Unless you can integrate the Python with the JavaScript (I've never programmed Python, and barely JS, so I honestly don't know if it's possible) no. But you could always add a Try it online link with your test code. EDIT: Also, it's usually better to wait at least a couple of days until you accept an answer.

@KevinCruijssen Thanks never used TIO before, but very handy.

@JonathanAllan Edit: added rounding explicitly

Related: Round to n Sig Figs

Several answers seem to use printf and doubles, but they'll all fail with enough digits before or after the decimal dot. Can we assume any size/precision limits for the input?

@Dennis: No limitations are specified, so all sizes (Input argument 1) and precision (Input argument 2) sould be supported (as long as your underlying memory system does not become a bottleneck).

Can the inputs be taken in any order?

For the record, base 10! is an exceedingly odd base to choose.

@BasicSunset order is as specified and fixed

@Jules it is base 10. Since the initial solutions just used the default rounding without paying attention to the underlying binary implementation, I added an exclamation mark. But since this is confusing, I will remove it.

Interesting, thanks for the tip @JulianLachniet, didn't notice they added that to the CE calcs.

@Timtech Funny, because I don't have a CE myself ;). This drives my crazy. Also, what is "IEEE"

@JulianLachniet https://en.wikipedia.org/wiki/IEEE_floating_point

@JulianLachniet IEEE is an organization which specifies a.o. standards such as the IEEE 754 standard for floating points which has a huge impact on hardware and software. Basically it deals with the tradeoff between the number of bits for the mantissa (impacts the precision of the floating point numbers) and exponent (impacts the range of the floating point numbers)

Is 123.4 valid output for round_string('123.4',5)? Is 123456790. valid output for round_string('123456789.987654321',0)?

@Dennis 1) round_string('123.4',5) = '123.40000' 2) round_string('123456789.987654321',0) = '123456790'

You should clarify that in your post. Examples do not count as part of the specification.

Also, since we have to support negative numbers, there should be negative number in the test cases, preferably ones that check for correct implementation of round half away from zero.

@Dennis updated

Were you not a bit quick on the accept trigger?

@Adám indeed. First thought I needed to manually verify the Wonder version and now there is the APL one which is even shorter. I guess we now reached the limit unless some language has a one byte built-in.

@Matthias APL has a built-in ⍕, if you allow numeric input. Takes number as right argument and precision as left argument.

May I suggest you add some test cases? Currently my code works correctly for every single one of your test cases. But it fails on test cases like 987654321.666666666; 7, 987654321.666666666; 8, 987654321.666666666; 9.

@Matthias Can we take input as a number?

@Adám only the second argument

APL (Dyalog), 4 bytes
Dyalog APL uses enough internal precision.
⎕⍕⍎⍞

Try it online!
⍎⍞ execute string input
⎕⍕ get numeric input and use that as precision for formatting

Why is this 4 instead of 8 bytes?

@Matthias Because Dyalog APL has a SBCS

Perl, 22 20 bytes
printf"%.*f",pop,pop

Using:
perl -e 'printf"%.*f",pop,pop' 123456789.987654321 3

It is Dada’s version of code. Previous:
printf"%*2\$.*f",@ARGV

printf"%.*f",pop,pop should work

PHP, 33 31 bytes
PHP rounds correctly too (at least on 64 bit):
printf("%.$argv[2]f",$argv[1]);

takes input from command line arguments. Run with -r.
PHP, no built-ins, 133 bytes
[,$n,$r]=$argv;if($p=strpos(_.$n,46))for($d=$n[$p+=$r],$n=substr($n,0,$p-!$r);$d>4;$n[$p]=(5+$d=$n[$p]-4)%10)$p-=$n[--$p]<"/";echo$n;

Run with -nr or test it online.
breakdown
[,$n,$r]=$argv;             // import arguments
if($p=strpos(_.$n,46))      // if number contains dot
    for($d=$n[$p+=$r],          // 1. $d= ($r+1)-th decimal
        $n=substr($n,0,$p-!$r); // 2. cut everything behind $r-th decimal
        $d>4;                   // 3. loop while previous decimal needs increment
        $n[$p]=(5+$d=$n[$p]-4)%10   // B. $d=current digit-4, increment current digit
    )
        $p-=$n[--$p]<"/";           // A. move cursor left, skip dot
echo$n;

A null byte doesn´t work; so I have to use substr.

You can write "%.$argv[2]f" instead of "%.{$argv[2]}f", saving 2 bytes.

Python, 114  105 103 96 91 89 bytes
Saved 5 bytes thanks to Kevin Cruijssen
Saved 2 bytes thanks to Krazor
from decimal import*
d=Decimal
lambda x,y:d(x).quantize(d('0.'[y>0]+'1'*y),ROUND_HALF_UP)

Try it online!

from decimal import * and removing the three d. is 4 bytes shorter.

You could also do d=Decimal and d() , which would save another 5. (Might be wrong, very sleepy)

@Krazor: Unless I did it wrong it saved me 2 bytes. Thanks!

Woops, that's what I've meant. Will leave my sleepy thoughts up anyways.

REXX, 24 bytes
arg n p
say format(n,,p)

Since REXX always uses text representation of numbers, correct rounding of numbers is free.
Try it online!

Wow. nice abuse of the language.

Does REXX have an online compiler?

It's (mainly) an interpreted language.

Try it online!

Ruby 2.3, 12 + 45 = 57
Uses the BigDecimal built-in, but it needs to be required before use, which is cheaper to do as a flag.
the flag: -rbigdecimal
the function:
->(s,i){BigDecimal.new(s).round(i).to_s('f')}

Ruby 2.3 by default uses ROUND_HALF_UP

Javascript (ES6), 44 bytes
n=>p=>(Math.round(n*10**p)/10**p).toFixed(p)

Try it online:

const f = n=>p=>(Math.round(n*10**p)/10**p).toFixed(p)

console.log(f('14.225')(2));

[...Array(8).keys()].map(i=>console.log(f('123456789.987654321')(i)))

console.log(f('123.4')(5))

TI-Basic, 53 16 bytes
TI-Basic does not use IEEE and the below method works for 0-9 (inclusive) decimal positions.
Prompt Str1,N
toString(round(expr(Str1),N

Thanks to @JulianLachniet for showing that CE calcs have the toString( command which I was not aware of (Color Edition calcs OS 5.2 or higher are required).
P.S. I did have a second line with sub(Str1,1,N+inString(Str1,". but then I realized it was useless.

How is N used?

@Matthias Thanks for catching that typo! I accidentally removed the last three bytes with my previous edit

Java 7, 77 72 71 bytes
<T>T c(T n,int d){return(T)"".format("%."+d+"f",new Double(n+""));}

-1 byte thanks to @cliffroot
72-byte answer:
String c(String n,int d){return n.format("%."+d+"f",new Double(n));}

Unlike Python, Java already rounds correctly and already returns a String when you use String.format("%.2f", aDouble) with the 2 replaced with the amount of decimals you want.
EDIT/NOTE: Yes, I'm aware new Float(n) is 1 byte shorter than new Double(n), but apparently it fails for the test cases with 123456789.987654321. See this test code regarding Double vs Float.
Explanation:
<T> T c(T n, int d){               // Method with generic-T & integer parameters and generic-T return-type (generic-T will be String in this case)
  return (T)"".format("%."+d+"f",  //  Return the correctly rounded output as String
    new Double(n+""));             //  After we've converted the input String to a decimal
}                                  // End of method

Test code:
Try it here.
class M{
  static <T>T c(T n,int d){return(T)"".format("%."+d+"f",new Double(n+""));}

  public static void main(String[] a){
    System.out.println(c("14.225", 2));
    System.out.println(c("123.4", 5));
    System.out.println(c("99.9", 0));
    System.out.println(c("-99.9", 0));
    System.out.println(c("1", 0));
    System.out.println(c("1.", 0));
    System.out.println(c("1.0", 0));
    for(int i = 0; i < 8; i++){
      System.out.println(c("123456789.987654321", i));
    }
  }
}

Output:
14.23
123.40000
100
-100
1
1
1
123456790
123456790.0
123456789.99
123456789.988
123456789.9877
123456789.98765
123456789.987654
123456789.9876543

One byte shorter:
<T>T c(T n,int d){return(T)"".format("%."+d+"f",new Double(n+""));}

This solution doesn't work. Though the example is potentially a round half-even/away-0 issue, floating point errors do occur and OP has since clarified that arbitrary precision should be supported.

In fact, you fail the example cases in the question which you reproduced here: 123456789.987654321, 4 should be 123456789.9877, not 123456789.9876

BASH, 26 23 21 bytes
bc<<<"scale=$2;$1/1"

usage
save to round_string.sh, chmod +x round_string.sh
./round_string.sh 23456789.987654321 3

edit:no need to load library

Explanation: bc uses arbitrary precission, create a here doc with '<<<' contaning the value of scale as the second parameter and the first parameter divided by 1 to force scale interpretation.

This gives 14.22 for the input 14.225 2, and not 14.23

AHK, 25 bytes
a=%1%
Send % Round(a,%2%)

Again I am foiled by the inability of AHK to use passed in parameters directly in functions that accept either a variable name or a number. If I replace a with 1 in the Round function, it uses the value 1. If I try %1%, it tries to use the first argument's contents as a variable name, which doesn't work. Having to set it as another variable first cost me 6 bytes.

Batch, 390 bytes
@echo off
set s=%1
set m=
if %s:~,1%==- set m=-&set s=%s:~1%
set d=%s:*.=%
if %d%==%s% (set d=)else call set s=%%s:.%d%=%%
for /l %%i in (0,1,%2)do call set d=%%d%%0
call set/ac=%%d:~%2,1%%/5
call set d=00%s%%%d:~,%2%%
set z=
:l
set/ac+=%d:~-1%
set d=%d:~,-1%
if %c%==10 set c=1&set z=%z%0&goto l
set d=%m%%d:~2%%c%%z%
if %2==0 (echo %d%)else call echo %%d:~,-%2%%.%%d:~-%2%%

Explanation. Starts by extracting the sign, if applicable. Then, splits the number into integer and fraction digits. The fraction is padded with n+1 zeros to ensure it has more than n digits. The nth (zero-indexed) digit is divided by 5, and this is the initial carry. The integer and n fraction digits are concatenated, and the carry added character by character. (The extra zeros guard against carry ripple.) After the carry stops rippling the number is reconstructed and any decimal point inserted.

Python (2/3), 394 bytes
def rnd(s,p):
    m=s[0]=='-'and'-'or''
    if m:s=s[1:]
    d=s.find('.')
    l=len(s)
    if d<0:
        if p>0:d=l;l+=1;s+='.'
        else:return m+s
    e=(d+p+1)-l
    if e>0:return m+s+'0'*e
    o=''
    c=0
    for i in range(l-1,-1,-1):
        x=s[i]
        if i<=d+p:
            if i!=d:
                n=int(x)+c
                if n>9:n=0;c=1
                else:c=0
                o+=str(n)
            else:
                if p>0:o+=x
        if i==d+p+1:c=int(x)>4
    if c:o+='1'
    return m+''.join(reversed(o))

Works for arbitrary precision numbers.

Hey, and welcome to PPCG! However, this isn't golfed. There's a lot of whitespace you can remove. Answers on this site are required to be golfed, sorry.

Just some things (there is likely a lot more)... The function name can be one byte. The first line can use s[0]<'0' and could also use string multiplication, m='-'*(s[0]<'0'). Lines without any block statement spans can be joined together with ; (e.g. o='';c=0). Some if statements could be probably be replaced by list indexing to further reduce the need for line breaks and tabs. The final line could use a slice, o[::-1], instead of reversed(o) and the ''.join is redundant. You may well also be able to rewrite it to avoid the need for multiple return statements.

... if you're interested there are tips for golfing in Python here.

JavaScript (ES6), 155 bytes
(s,n)=>s.replace(/(-?\d+).?(.*)/,(m,i,d)=>i+'.'+(d+'0'.repeat(++n)).slice(0,n)).replace(/([0-8]?)([.9]*?)\.?(.)$/,(m,n,c,r)=>r>4?-~n+c.replace(/9/g,0):n+c)

Explanation: The string is first normalised to contain a . and n+1 decimal digits. The trailing digit, any preceding 9s or .s, and any preceding digit, are then considered. If the last digit is less than 5 then it and any immediately preceding . are simply removed but if it is greater than 5 then the 9s are changed to 0s and the previous digit incremented (or 1 prefixed if there was no previous digit).

Python 3 + SymPy, 54 bytes
from sympy import*
lambda s,p:'%.*f'%(p,S(s).round(p))

Try it online!

J, 22 17 bytes
((10 j.[)]@:":".)

NB.    2    ((10 j.[)]@:":".)   '12.45678'
NB.    12.46

Thanks to @Conor O'Brien for correcting my understanding of the rules.
t=:4 :'(10 j.x)":".y'

    NB.    Examples
    NB.    4 t'12.45678'
    NB.    12.4568
    NB.    4 t'12.456780'
    NB.    12.4568
    NB.    4 t'12.4567801'
    NB.    12.4568
    NB.    2 t'12.45678'
    NB.      12.46
    NB.    2 t'12.4567801'
    NB.      12.46
    NB.    2 (10 j.[)":". '_12.4567801'
    NB.     _12.46

format
    x t y
where x is a digit number of decimal places required and y
is the character string containing the value to be rounded.

The challenge requires you to take the number of digits after the decimal point to round to N decimals, not N points of precision. As such, 2 t '1234.456' should give 1234.46 instead of 6 t '1234.456'

Scala, 44 bytes
(s:String,p:Int)=>s"%.${p}f"format s.toFloat

Test:
scala> var x = (s:String,p:Int)=>s"%.${p}f"format s.toFloat
x: (String, Int) => String = <function2>

scala> x("14.225",2)
res13: String = 14.23

Wonder, 10 bytes
@@fix#1E#0

Usage:
@@fix#1E#0

Set decimal precision and add trailing zeros if necessary.

Is there a TIO for this one?

No there isn't, but the installation is pretty easy. Make sure you have Node.js (v6+), and npm i -g wonderlang. Use the wonder command to fire up the REPL, and paste the code in.


text:
Uni-Dimensional String Golf
Introduction
You have to simulate playing golf over an input string that represents the green. The 2-character substring () represents the hole, and is guaranteed to appear only once in the string.
This is a sample green:
ABCDEFGHIJKLM()NOPQRSTUVWXYZ

The simulation consists of outputting the characters that the ball falls on after a series of hits that are also passed to your function.
Each hit is represented by a positive integer indicating how many characters the ball will travel, relative to previous position.
Example
The following input results in the output G(o).
7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ

Explanation
The input represents two hits of length 7. The output is a string of characters, showing the intermediate positions of the ball. The ball starts to the left of the string, and travels 7 characters to the right, landing on the G. As such, that character is the first part of the output.
Then the ball is hit for the second time, and it lands in the hole. In this case, the hole is output with the ball inside, like this: (o).
9,7,1,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
I(o)N

The output represents the characters the ball has landed on in the same order as in the string.
Notes

The width of the hole is 2. If the ball lands on either parenthesis, the hole is hit.
The direction of the hit is always towards the hole, so when the ball ends up to the right of the hole, the next hit will cause the ball to move to the left (and vice versa).
The ball might not reach the hole, in which case the position of the ball after the last hit must be output next to the character (in the direction of the hole) the ball is on at the end of the hits. The hole is still included in the output.

example:
28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
B12()Z

First 28 hit lands on Z at the right of the hole , next 26 hit is as
  always thowards the hole (left) and lands on B. No more hits left so
  the distance to the hole (12 characters) is shown next to B

If the hits cause the ball to leave the green at some point, discard all remaining hits, and prepend ^ if the ball exits the green to the left, and append $ if the ball leaves the green via the right side.
There might be hits after the putt, in which case those should be discarded, and the hole in the output should not contain an o, but an X.

Test cases
15,10,3,TOURING()MACHINE
I(o)N

7,HOLEIN()NE
(o)

9,7,1,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
I(o)N

7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
G(o)

28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
B12()Z

2,25,26,27,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
AB()Y13Z

1,1,6,SH()RT
SH()$

2,4,6,TOO()HARD
^O()H

4,8,1,3,3,3,3,3,TAKEIT()ASITCOMES
E(X)IT

You have to write a program or function wich accepts a series of positive numbres representing the hits and a [A..Z] string with one hole "()" representig the green. Make clear if your input format is different form 7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
This is code golf, so the submission with the smallest amount of bytes per language wins!

Python 2 - 380 bytes
Try it online
Shorter answer, thanks to @ovs. This one requires list of integers and string as input. Example: 28,26,"ABCDEFGHIJKLM()NOPQRSTUVWXYZ".
Check edits for older version, that accepts plain string like "28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ"
I=input()
c=-1
G=I[c]
I=map(int,I[:c])
u=r=""
L=[u]*len(G)
H=len(G.split('(')[0])
L[H:H+1]='()'
d=1
s=0
f="".join
for h in I:
 s+=1;c+=h*d;d=(1,-1)[H-c<0];T=f(L)
 if H<=c<H+2:u='o'if s==len(I)else'X';break
 if c<0:r="^"+T;break
 if c>len(G):r=T+"$";break
 L[c]=G[c]
else:
 m=H-c if~d else c-H-1
 if d>0:c+=1
 L=L[:c]+[str(m)]+L[c:];r=f(L)
print r or("%s)"%u).join(f(L).split(')'))

Explanation (for older version, but approach is same):
I=input().split(',')             # split input
G=I[-1]                          # last element - Green
I=map(int,I[:-1])                # convert all other (hits) to int
L=[""]*len(G)                    # empty list of same length as Green, used to ouput
H=len(G.split('(')[0])           # index of hole
L[H]='('                         # hole is always printed
L[H+1]=')'
c=-1                             # current index on Green
d=1                              # direction of hit
u=r=""                           # strings for output and in-hole marker (X)/(o)
s=0                              # number of current hit
for h in I:
    s+=1
    c+=h*d                       # move current by hit * direction
    d=(1,-1)[H-c<0]              # calculate new direction
    T="".join(L)                 # used to remove code duplication
    if H<=c<H+2:                 # if in hole
        u='o'if s==len(I)else'X' # check whether it is last hit or not
        break
    if c<0:                      # if out of Green on the left
        r="^"+T                  # add '^' and join all visited indices
        break
    if c>len(G):                 # if out of Green on the right
        r=T+"$"                  # add '&' after join all visited indices
        break
    L[c]=G[c]                    # mark visited index
else:                            # rare occasion of for-else construction - executes if never break out of loop
                                 # which means, that we are out of hits and not in hole
    m=H-c if~d else c-H-1        # calculate distance to hole
    if d>0:
        c+=1
    L=L[:c]+[str(m)]+L[c:]       # expand L list with distance
    r="".join(L)                 # join list
t="".join(L).split(')')
if r:
    print r                      # ouput r in all cases exept in-hole
else:
    print t[0]+"%s)"%u+t[1]      # output for in-hole cases

some minor improvements

even more

@ovs Thanks! Clever golfing, also I managed to cut another 5 bytes from your last improvement: here
But this approach requires list as input. It's not clear, if it is accepted

@ovs and -1 more byte, since x is not really needed

Röda, 308 299 bytes
f g{a=indexOf("()",g)g=g[:a].."oo"..g[a+2:]o=[""]*#g
s=""e=""i=-1{|j|o[i]="X"if[i>=a,i<=a+1]else{i+=j if[i<a]else i-=j if[i>a+1]
{s="^";[]_}if[i<0]else{e="$";[]_}if[i>=#g]else o[i]=g[i:i+1]}}_
o[i].=s..a-i if[i<a,i>=0]
o[i]=i-a-1..o[i]if[i>a+1,i<#g]
[s..o[:a]&""..`(${o[a:a+2]&""})`..o[a+2:]&""..e]}

Try it online!
Saved 8 bytes thanks to Kritixi Lithos!
Ungolfed:
function f(green) {
    /* find the hole */
    hole := indexOf("()", green)
    /* replace () with oo in the green string */
    green := green[:hole].."oo"..green[hole+2:]
    /* initializes the output array: contains an empty string for each yet unvisited place on the green */
    out := [""]*#green
    start := ""
    end := ""
    i := -1
    /* for each number in the stream */
    for j do
        /* if the ball is in the hole, change the output to X */
        if [ i=hole or i=hole+1 ] do
            out[i]="X"
        else
            /* add or subtract the number */
            i+=j if [ i < hole ] else i-=j if [ i > hole+1 ]
            /* if the ball has left the green, stop looping */
            if [ i < 0 ] do
                start = "^"
                break
            done
            if [ i >= #green ] do
                end = "$"
                break
            done
            /* add the visited character to the output array */
            out[i] = green[i:i+1]
        done
    done
    /* add a number next to the last character visited */
    out[i] .= ""..hole-i if [ i < hole and i >= 0 ]
    out[i] = i-hole-1..o[i] if [ i > hole+1 and i < #green ]

    /* return the output */
    return start..out[:hole]&""..`(${out[hole:hole+2]&""})`..out[hole+2:]&""..end
}

I think you can replace and with ,

@KritixiLithos You are right! Thanks.


text:
True and false and true
Challenge is to write a function/program which outputs a truthy or falsey value alternately each time you call it. No input.
It can start with either true or false.

I would recommend posting your challenges to the sandbox first for feedback next time.

Can it be a full program instead of a function?

Yes, full programs are allowed

So if I open an entirely clean environment to run the program, it should print  "False" instead of "True" (or vice versa)? Or can you require it be repeatedly run in the same context? (i.e. "f()\nf()" prints "True\nFalse")

Same context, not a clean environment

Allowing programs may be problematic. What can be assumed between program executions? Can it be assumed that any variables created by the program will be seen by the next execution? More generally, to which extent is "state" preserve between executions?

By allowing full programs I meant for calling the function multiple times

May I assume that nothing is happening between subsequent calls?

Yes, nothing in between calls

I think you're starting to give people too much liberty. Nothing between calls is a bit iffy for tacit languages (including stack-based ones), as you can operate on the previous return value for free. If full programs are valid or not is also unclear at this point. You should clarify these things in the question.

Most answers here rely on externals or globals which could change between calls.

Curiously, on the day this challenge was posted, Mathematica released, in v. 11.1, the function, PersistentValue, which supports values that persist between sessions.  (http://reference.wolfram.com/language/ref/PersistentValue.html)

Jelly, 3 bytes
®¬©

Try it online!
How it works
®¬©  Main link. No arguments.

®    Retrieve the value stored in the register.
 ¬   Negate it.
  ©  Copy the result to the register.

This looks like a distraught frog and I can't stop laughing about it.

According to this comment, ¬ might be valid as well. Dibs on the 1-byte solution in case this turns out to be allowed.

JavaScript ES6, 11 bytes
f=i=_=>i=!i

f=i=_=>i=!i

console.log(f());
console.log(f());
console.log(f());

This doesn't work. If I run it again with a clean environment, it fails.

Uh... wow, ok, that works. That's really clever, actually :D

Python 2, 30 bytes
def f():f.n^=1;print f.n
f.n=0

Try it online!

Python 2, 34 33 32 bytes
-1 byte thanks to Cyoce

def f(x=[]):x+=0,;print len(x)%2

Try it online!
This works because the list used as (optional) argument is kept between function calls.
It's not a bug, it's a feature

Does def f(x=[0]):x[0]^=1;print x[0] work?

@Neil yep, it works

Java 7, 36 35 bytes
int f=0;boolean c(){return++f%2<1;}
// OR
boolean f;boolean c(){return f=!f;}     // Thanks to @Poke

Old answer: int f=0;boolean c(){return(f^=1)<1;}
Extremely short for a Java 7 answer. :D (Although still the longest of all submissions of course)
Explanation:
int f=0;              // Integer flag on class level
boolean c(){          // Method with no parameters and a boolean return-type
  return ++f % 2 < 1  //  return whether `f` modulo 2 is 0 (but increase `f` first)
}                     // End of method

Test code:
Try it here.
class M{
  int f=0;boolean c(){return++f%2<1;}

  public static void main(String[] a){
    M m = new M();
    System.out.println(m.c());
    System.out.println(m.c());
    System.out.println(m.c());
    System.out.println(m.c());
    System.out.println(m.c());
  }
}

Output:
false
true
false
true
false

boolean f;boolean c(){return f=!f;} is also 35 bytes

@Poke Oops, I've been overthinking it apparently..

Your answer works nicely too :] The bytecount of boolean is enough to dissuade me in a lot of cases, haha

@Poke Exactly, that's why I had rejected boolean from a possible solution right away for this challenge. ;)

CJam, 6 bytes
{T!:T}

Try it online!
Pushes T (initially 0, falsy), negates it (toggling between 1, truthy, and 0), stores the result in T for the next invocation and leaves it on the stack.

Octave, 4 bytes
i=~i

i is initially sqrt(-1). Everything that's not 0 is considered true in Octave (note, this doesn't work in MATLAB).
i=~i assigns not(true) to i, making it false, The next iteration it will be false again.
This is a full program, that can be called using the file name. Example from octave-online with a file name called inverter.m:
octave:1> source("inverter.m")
i = 0
octave:1> source("inverter.m")
i =  1
octave:1> source("inverter.m")
i = 0
octave:1> source("inverter.m")
i =  1

Python 3, 31 bytes
def f(x=[]):x+=print(len(x)&1),

Try it online!

C, 39 30 26 19 18 Bytes
Using a Macro now
i;
#define f i++%2

Thanks for the help i=!i
i;f(){return i=!i;}
i;f(){return i++?i=0,1:0;}
i;f(){putchar(i++?i=0,70:84);}
f(){static i=0;putchar(i++?i=0,70:84);}
main()
{
    putchar(48+f);puts("");
    putchar(48+f);puts("");
    putchar(48+f);puts("");
    putchar(48+f);puts("");
}

Output
0
1
0
1

You could change the return to i=!i Try it Online!

i;f(){return++i%2;} is shorter [19 bytes] (based on my Java 7 answer). Try it here.

Mathematica, 12 bytes
Either of these works:
(x=x=!=1>0)&
(x=x===0>1)&

I would love to express the True or False at the end using only x and = or maybe ! as well, but unfortunately, that gets longer.
In the notebook environment we can also use this 8-byte solution:
%=!=1>0&

But it only works if the call to the function is the only thing on its line and there are no other function calls in between, so I won't count this one.

Ruby, 15 14 12 bytes
->{0>$.^=-1}

PHP, 31 25 bytes
Thanks to user63956 for golfing 6 bytes
function(){echo$_GET^=1;}

Try it online!
This is an anonymous function.

You can use superglobal variables: function(){echo$_GET^=1;}.

@user63956 Weird, I tried it with $argv and $argc and it didn't work so I didn't even try $_GET. Thanks.

Bash, 11 bytes
f()((n^=1))

Output is via the function's status code.
Try it online!

Bash, 25 bytes
sed -i y/TF/FT/ $0
echo T

Try it online!
This is a full program. You must have write access to the file in addition to execute.

Java, 32 bytes
Not competing because ints aren't truth and false values in Java and an  answer like that already exists.
int a;int f(){return a=a>0?0:1;}

Ungolfed(barely anything to ungolf):
int a;
int f() {
    return a = a > 0 ? 0 : 1;
}

Unfortunately, returning 0 or 1 isn't considered a truthy/falsey value in Java. Also, if it would have been, this would be shorter: int a;int f(){return++f%2;} (27 bytes)

Instead of making it non-completing, can you edit to output truthy and falsy values?

@Riker An answer like this already exists

You're allowed to post an identical answer.

Applescript, 25
property i:0
set i to 1-i

Applescript properties are persistent.  The result of the last assignment is implicitly given as the program result.

Haskell, 52 bytes
import Control.Monad.State
execState(modify not)True

This uses the State monad to store a boolean value which is initially set to True. Additional calls must also run within the State monad, e.g.
 execState(modify not>>modify not>>modify not)True

which evaluates to False.

Scala, 25 bytes
var b=8<9
def f={b= !b;b}

Explanation:
var b = 8 < 9 // define a variable b as false
def f = {     // define a function f wothout parameters
  b = !b      // invert the state of b
  b           // return b
}

There needs to be a space in b= !b, so scala doesn't want to invoke the method =! on b, which doesn't exists.