text:
Golf a Custom Fibonacci Sequence
The Fibonacci sequence is a fairly well known thing around here. Heck, it even has its own tag. However, for all that, we sure like to stick to our roots of 1, 1, ... (or is it 0, 1, ...? We may never know...). In this challenge, the rules are the same, but instead of getting the nth item in the Fibonacci sequence, you will get the nth item in the Fibonacci-esque sequence starting with x, y, ....
Input
Three integers, in whatever order you want. n is the index (0 or 1 indexed) of term in the sequence for your output. x and y are the first two items in your current program run's Fibonacci sequence.
Output
The nth term in the Fibonacci sequence starting with x, y.
Test Cases
(0-indexed)
n   x     y     out
5   0     0     0
6   0     1     8
6   1     1     13
2   5     5     10
10  2     2     178
3   3     10    23
13  2308  4261  1325165
0   0     1     0
1   0     1     1

(1-indexed)
n   x     y     out
6   0     0     0
7   0     1     8
7   1     1     13
3   5     5     10
11  2     2     178
4   3     10    23
14  2308  4261  1325165
1   0     1     0
2   0     1     1

Caveats
Assume 0 <= x <= y.
Please note your input order (must be constant).

Can we take a list as input?

@BusinessCat you mean like [1, 2, 3]? Yes. Whatever you need to accept 3 integers.

@StephenS How about taking an input as n,[x,y] where n is a number and x and y are numbers in a list? That's probably being a little too flexible though ;)

@Tom as long as all you are doing is accepting 3 integers, I don't care how you format your input (so yes, that would be acceptable. You only can't use anything in the input besides the 3 integers as information).

Related (Numberphile), Related (OEIS) (I was hoping the Brady Numbers would be a test case...)

@CAD97 I'll add them, I had forgotten about them :)

I honestly don't understand why this isn't being considered as a dupe. In most languages, surely, it's simply going to be a case of replacing the 2 initial values of x & y with input values? I've seen the dupe hammer swung on questions that differ a lot more than these two.

@Shaggy it was dupe hammered (not 5 votes) then undupe hammered (not 5 votes). Dunno who unduped it.

Related

There are currently no testcases for n=1 (or 0 if indexed as such), do we need to be able to handle this?

@JarkoDubbeldam yes, editing in, thank you

Quite related. The only difference in that challenge is that you have to first work backwards until you find the "first item" in the custom sequence.

Can I -1-index? Return y for n == 0, x+y for n == 1, and so on?

@Scrooble As long as you return x for n = -1

Jelly, 3 bytes
+¡ạ

Takes x, y, and n (0-indexed) as separate command-line arguments, in that order.
Try it online!
How it works
+¡ạ  Main link. Left argument: x. Right argument: y. Third argument: n

  ạ  Yield abs(x - y) = y - x, the (-1)-th value of the Lucas sequence.
+¡   Add the quicklink's left and right argument (initially x and y-x), replacing
     the right argument with the left one and the left argument with the result.
     Do this n times and return the final value of the left argument.

CJam, 14  9 bytes
l~{_@+}*;

Try it online!
Input format is "x y n".
I'm still a noob at this, so I'm 100% sure there are better ways to do this, but please instead of telling me "do this" try to only give me hints so that I can find the answer myself and get better. Thanks!

ririri can be shortened to 2 bytes. fI can be shortened to 1 byte.

Welcome to PPCG!

@Dennis improved! Thank you! And thanks for the welcome.

JavaScript (ES6), 27 26 bytes
Nothing fancy here, just a standard JS Fibonacci function with the initial values of 0 & 1 removed.
n=>g=(x,y)=>n--?g(y,x+y):x

Try it

f=
n=>g=(x,y)=>n--?g(y,x+y):x
o.value=f(i.value=13)(j.value=2308,k.value=4261)
oninput=_=>o.value=f(+i.value)(+j.value,+k.value)
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
#o{width:75px;}
<label for=i>n: </label><input id=i type=number><label for=j>x: </label><input id=j type=number><label for=k>y: </label><input id=k type=number><label for=o>= </label><input id=o>

Python 2, 37 bytes
f=lambda x,y,n:n and f(y,x+y,n-1)or x

Try it online!
0-indexed, you may need to adjust the recursion limit for n≥999

Python 2, 40 bytes
0-indexed
Try it online
n,a,b=input()
exec'a,b=b,a+b;'*n
print a

Haha not subject to a recursion/stack limit unlike some other answers. Nice trick.

@ShreevatsaR Thanks! But recursive lambda beats me anyway :D

Haskell, 30 bytes
x#y=(f!!)where f=x:scanl(+)y f

Try it online! 0-indexed. Use as (x#y)n, e.g. (0#1)5 for the fifth element of the original sequence.
The most likely shortest way to get the Fibonacci sequence in Haskell is f=0:scanl(+)1f, which defines an infinite list f=[0,1,1,2,3,5,8,...] containing the sequence. Replacing 0 and 1 with arguments x and y yields the custom sequence. (f!!) is then a function returning the nth element of f.

Mathematica, 36 bytes
LinearRecurrence[{1,1},{##2},{#+1}]&

input

[n,x,y]

You can use ##2 instead of #2,#3.

very nice! fixed!

PowerShell, 40 bytes
$n,$x,$y=$args;2..$n|%{$y=$x+($x=$y)};$y

Try it online!

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

Try it online!
{({}[()]<                      >)}     # For n .. 0
         (({}<>)<>            )        # Copy TOS to the other stack and add it to...
                  {}                   # The second value
                    <(<>{}<>)>         # Copy what was TOS back
                                  {}{} # Pop the counter and the n+1th result

Ruby, 27 bytes
->a,b,n{n.times{b=a+a=b};a}

TAESGL, 4 bytes
ēB)Ė

1-indexed
Interpreter
Explanation
Input taken as n,[x,y]
 ēB)Ė
AēB)     get implicit input "A" Fibonacci numbers where "B" is [x,y]
    Ė    pop the last item in the array

Jelly, 6 bytes
;SḊµ¡I

Try it online!
Explanation
   µ¡  - repeat n times (computes the n+1th and n+2th element):
 S     -  take the sum of the elements of the previous iteration (starting at (x,y))
;      -  append to the end of the previous iteration
  Ḋ    -  remove the first element
     I - Take the difference of the n+1th and n+2th to get the n-th.

Prolog (SWI), 85 bytes
l(0,X,Y,X).
l(1,X,Y,Y).
l(N,X,Y,C):-M is N-1,P is N-2,l(M,X,Y,A),l(P,X,Y,B),C is A+B.

Try it online!
0-indexed.

Could you edit this answer? I seem to have accidentally downvoted it the day you posted it.

@EsolangingFruit done

Prolog (SWI), 77 bytes
f(N,Y,Z):-M is N-1,f(M,X,Y),Z is X+Y.
l(N,A,B,X):-asserta(f(0,A,B)),f(N,X,_).

Try it online!
Started off golfing Leaky Nun's answer and arrived at something completely different.
This one has a rule for (Nᵗʰ, (N+1)ᵗʰ) in terms of ((N-1)ᵗʰ, Nᵗʰ) and uses database management to assert 0ᵗʰ and 1ˢᵗ elements at runtime.
f(N,X,Y) means Nᵗʰ element is X and (N+1)ᵗʰ element is Y.

R, 39 bytes
f=function(x,y,n)'if'(n,f(y,x+y,n-1),x)

A simple recursive function. Funnily enough this is shorter than anything I can come up with for the regular Fibonacci sequence (without built-ins), because this doesn't have to assign 1 to both x and y =P
Calculates n+1 numbers of the sequence, including the initial values. Each recursion is calculates with n-1 and stopped when n==0. The lowest of the two numbers is then returned, giving back the n-th value.

Octave, 24 bytes
@(n,x)(x*[0,1;1,1]^n)(1)

Input format: n,[x,y].
Try it online!

x86 machine code, 7 bytes
EDX = x = fib[1], EAX = y = fib[2], RCX = n (1-indexed)
returns in EAX.  Works in all 3 modes (16, 32, and 64).
Try it online!
(64-bit NASM source with a _start that parses 3 integers from argv strings)
0000000000401070 <cfib>:
  401070:       eb                      .byte 0xeb      # jmp rel8 consuming the 01 add opcode as a rel8
0000000000401071 <cfib.loop>:
  401071:       01 d0                   add    eax,edx
# loop entry point on first iteration, jumping over the ModRM byte of the ADD
  401073:       92                      xchg   edx,eax
  401074:       e2 fb                   loop   401071 <cfib.loop>
  401076:       c3                      ret

This "jumps" into the loop with machine code that decodes 2 different ways: with a jmp +1 when falling into the loop from the top of the function, or with that 01 byte being an ADD opcode when the loop instruction jumps backwards.  Equivalent to jmp .entry but with only 1 byte outside the loop instead of 2.
(Credit to @Ira Baxter for pointing out the general idea of falling into a loop with 1 byte outside that consumes some loop bytes to do something different on the first iteration, e.g. the opcode for cmp al, imm8 as a 1-byte encoding for a jump forward by 1.  I got lucky that 01 add could be consumed by jmp rel8 to skip a total of 2 bytes without needing a 66 prefix for cmp ax, imm16 or being in 16-bit mode.  01 or 03 add didn't work well as a modrm for anything like add r/m32, imm8; we need to avoid a memory operand.  Note that this trick is not good for performance on some modern CPUs, e.g. AMD that caches instruction boundaries in L1i tags, and probably not newer Intel/AMD with uop caches.)
Stripping labels lets objdump decode as the CPU would on the first pass:
cfib:
  401070:       eb 01                   jmp    0x401073   # jmp rel8 = +1
  401072:       d0                      .byte 0xd0        # jumped over
  401073:       92                      xchg   edx,eax
  401074:       e2 fb                   loop   0x401071
  401076:       c3                      ret

It's easy to see that the EDX input will be the EAX return value for ECX=1 (exit right away, loop is never taken so add never runs).
Use strace ./custom-fib 14  2308  4261 to see the full integer value passed to the exit() system call before truncation to an 8-bit exit status.
In 32-bit mode, the same machine code is callable with GCC regparm(3) calling convention as __attribute__((regparm(3))) unsigned custom_fib(unsigned y /*eax*/, unsigned x /*edx*/, unsigned n /*ecx*/);, returning in EAX as usual.

Without the 2-way decode hack: x86 machine code, 8 bytes
0-indexed n in RCX,  x (fib[0]) in EAX, y (fib[1]) in EDX - note opposite arg order
0000000000401070 <cfib>:
  401070:       e3 05                   jrcxz  401077 <cfib.done>
0000000000401072 <cfib.loop>:
  401072:       0f c1 c2                xadd   edx,eax
  401075:       e2 fb                   loop   401072 <cfib.loop>
0000000000401077 <cfib.done>:
  401077:       c3                      ret

This way shows off x86's xadd instruction, normally only used with a memory destination and a lock prefix to implement fetch_add.
The reg,reg form of xadd decodes to only 3 uops on Intel Skylake, same as xchg reg,reg (https://uops.info/).  (The loop instruction is slow on Intel so this is hardly optimized for speed.  If you want a speed-efficient asm implementation, unroll by 2 to remove the xchg as shown in my SO answer using clever loop setup to avoid excess branching for odd vs. even n for standard 0,1 Fibonacci.)

While it is a neat trick to re-use the 01h as a jump displacement, am I missing anything or could you equally well drop the EBh byte by defining the entrypoint to be within the loop as in https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/218097#218097 ?

@ecm: actually yeah, good point, that would get us down to 6 bytes.  I often forget about putting the function entry point somewhere after the first byte.  I think in this case I'll leave this answer as-is, because I've linked it from a few places as an example of this trick, which is useful if you need something else before the loop, or as part of a larger function.

Vyxal, 5 bytes
⁽+dḞi

Takes input as [x, y] then n.
Try it online!
Explanation:
   Ḟ   # Create an infinite list from the initial vector [x, y] from:
  d    # a dyadic,
⁽      # single element lambda
 +     # which adds its two arguments.
    i  # Index into that list with the second input (n).

Braingolf, 15 bytes
VR<2-M[R!+v]R_;

_; is no longer needed on the latest version of Braingolf, however that's as of ~5 minutes ago. This could be 13 bytes by removing that.

Python 2, 112 bytes
1-indexed.
import itertools
def f(x,y):
 while 1:yield x;x,y=y,x+y
def g(x,y,n):return next(itertools.islice(f(x,y),n-1,n))

Try it online!

Erp, too late and too big.

PHP>=7.1, 55 Bytes
for([,$n,$x,$y]=$argv;$n--;$x=$y,$y=$t)$t=$x+$y;echo$x;

Online Version
PHP>=7.1, 73 Bytes
for([,$n,$x,$y]=$argv,$r=[$x,$y];$i<$n;)$r[]=$r[+$i]+$r[++$i];echo$r[$n];

Online Version

Taking advantage of strange PHP's evaluation order: $y=+$x+$x=$y. Also, you can use just $n-- instead of $i++<$n.

MATL, 7 bytes
:"wy+]x

Output is 0-based.
Try it at MATL Online!
Explanation
Let the inputs be denoted n (index), a, b (initial terms).
:"     % Implicitly input n. Do this n times
       %   At this point in each iteration, the stack contains the two most
       %   recently computed terms of the sequence, say s, t. In the first
       %   iteration the stack is empty, but a, b will be implicitly input
       %   by the next statement
  w    %   Swap. The stack contains t, s
  y    %   Duplicate from below. The stack contains t, s, t
  +    %   Add. The stack contains t, s+t. These are now the new two most
       %   recently comnputed terms
]      % End
x      % Delete (we have computed one term too many). Implicitly display

dc, 36 bytes
?sdsbsa[lddlb+sdsbla1-dsa1<c]dscxldp

Try it online!
0-indexed. Input must be in the format n x y.

Common Lisp, 49 Bytes, 0-indexed
(defun fib(n x y)(if(= 0 n)x(fib(1- n)y(+ x y))))

I'm a Lisp noob so any tips would be appreciated ;)
Explanation:
(defun fib(n x y)                                  | Define a function taking 3 arguments
                 (if(= 0 n)x                       | If n = 0, return x
                            (fib(1- n)y(+ x y))))  | Otherwise, call fib with n-1, y, and x+y

br**nfuck, 39 29 bytes
Thanks to @JoKing for -10!
,<,<,[>[>+>+<<-]<[>+<-]>-]>>.

TIO won't work particularly well for this (or for any BF solution to a problem involving numbers). I strongly suggest @Timwi's EsotericIDE (or implementing BF yourself).
Takes x, then y, then n. 0-indexed. Assumes an unbounded or wrapping tape.
Explanation
,<,<,            Take inputs. Tape: [n, y, x]
[                While n:
  > [->+>+<<]      Add y to x, copying it to the next cell along as well. Tape: [n, 0, x+y, y]
  < [>+<-]         Move n over. Tape: [0, n, x+y, y]
  >-               Decrement n.
] >>.            End loop. Print cell 2 to the right (x for n == 0).

Why do you bother moving x and y when you can just move n? Try It Online

@JoKing Considered that (but longer on my own), but it doesn't quite work, unless OP allows "-1-indexing".

Oh, just add a > to the end or swap x and y order

@JoKing My palm hit my face quite hard just now. Thanks!

Why did you bother to censor "brain" but not the second word in the programming language's name?

C (gcc), 29 bytes
f(n,x,y){n=n?f(n-1,y,x+y):x;}

Try it online!
This implementation is 0-based.

Nice, and welcome! Here's a prettier TIO setup for testing, should you choose to use it.

05AB1E, 9 bytes
`©GDŠ+}®@

Try it online!
Explanation
`           # split inputs as separate to stack
 ©          # store n in register
  G         # n-1 times do
   D        # duplicate top of stack
    Š       # move down 2 places on stack
     +      # add top 2 values of stack
      }     # end loop
       ®@   # get the value nth value from the bottom of stack

Japt, 11 bytes
?ß´UWV+W :V

Try it online

Explanation
(Inputs U, V & W line up with n, x & y in the challenge.)
     :Implicit input of integer U.
?    :Ternary to check if U is currently >0.
ß    :If not, call the function again, with the arguments...
´U   :U-1,
W    :W,
V+W  :and V+W.
:    :Ternary "else", i.e. if U=0
V    :Return V

Java, 58 bytes
int f(int n,int x,int y){return n<3?n<2?x:y:f(n-1,y,x+y);}

This function is 1-indexed.
Alternatively, one could write the following lambda with recursion, for 55 bytes:
interface B{F f=(n,x,y)->n<3?n<2?x:y:B.f.f(n-1,y,x+y);}

This requires the following description, which isn't usually counted in Java Lambdas:
interface F{int f(int n,int x,int y);}

Test
public class Main {

  static
  int f(int n,int x,int y){return n<3?n<2?x:y:f(n-1,y,x+y);}

  public static void main(String[] args) {
    int[][] tests = {
      {6, 0, 0, 0},
      {7, 0, 1, 8},
      {7, 1, 1, 13},
      {3, 5, 5, 10},
      {11, 2, 2, 178},
      {4, 3, 10, 23},
      {14, 2308, 4261, 1325165},
      {1, 0, 1, 0},
      {2, 0, 1, 1}
    };

    for (int[] test: tests) {
      System.out.printf("%2d %4d %4d %7d%n", test[0], test[1], test[2], f(test[0],test[1],test[2]));
    }
  }
}

Lua, 44 bytes
0-Indexed
n,x,y=...for i=1,n do
x,y=y,x+y
end
print(x)

Try it online!

Axiom, 88 57 bytes
f(k,x,y)==(repeat(k<=0=>break;c:=y;y:=x+y;x:=c;k:=k-1);x)

this would pass the test proposed (0 indexed)
(14) -> f(5,0,0)
   (14)  0
                                                 Type: NonNegativeInteger
(15) -> f(6,0,1)
   (15)  8
                                                    Type: PositiveInteger
(16) -> f(2,5,5)
   (16)  10
                                                    Type: PositiveInteger
(17) -> f(10,2,2)
   (17)  178
                                                    Type: PositiveInteger
(18) -> f(3,3,10)
   (18)  23
                                                    Type: PositiveInteger
(19) -> f(13,2308,4261)
   (19)  1325165
                                                    Type: PositiveInteger

Klein, 18 + 3 bytes
This uses the 000 topology
:?\(:(+)$)1-+
((/@

Pass input in the form x y n.

Retina, 37 bytes
\d+
$*1
+`(1*) (1*) 1
$2 $1$2
 .*

1

Try it online!
0-based, takes x y n separated by space. Calculates in unary.

TI-Basic, 32 bytes
Prompt N,X,Y
While N
X+Y➡Z
Y➡X
Z➡Y
DS<(N,0
End
X

k, 15 bytes
{*x(|+\)/y,z-y}

Try it online!

Pari/GP, 24 bytes
n->x->(x*[0,1;1,1]^n)[1]

Input format: (n)([x,y]).
Try it online!

AWK, 39 bytes
{for(n=3;n<$1+2;)$++n=$n+$(n-1);$0=$n}1

Try it online!
Takes inputs as n x y 0-indexed

Mathematica, 25 bytes
Although this is quite old, and there has already been a Mathematica answer using LinearRecurrence built-in, mine solution is shorter.
{##2}.Fibonacci/@{#-1,#}&

Forth (gforth), 30 bytes
: f 1- 0 ?do tuck + loop nip ;

Try it online!
Input Order is x y n

Perl 6, 24 bytes
{($^x,$^y,*+*...*)[$^n]}

Try it online!

SmileBASIC, 44 39 bytes
crossed out 44 is still regular 44 ;(
DEF F N,X,Y
IF!N THEN?X
F N-1,Y,X+Y
END

Recursive function; prints the result once N reaches 0, ends with a stack overflow.

Pyth, 23 bytes
J.)QWgJlQ=aQ+@Q_2eQ)@QJ

Test suite
0-indexed, input format: [x,y,n].

GolfScript, 8 bytes
~{.@+}*;

Try it online!
Takes input in order x y n. Actually generates first n+1 values and pops last.
Explanation:
~{.@+}*; Full program, implicit input
~        Evaluate
 {   }*  Pop n and repeat:    Stack: x y
  .        Duplicate y               x y y
   @       Get x                     y y x
    +      Add                       y x+y
       ; Pop last

Rockstar, 110 105 bytes
listen to N
listen to X
listen to Y
cast Y
while N
let Z be X-0+Y
let X be Y
let Y be Z
let N be-1

say X

Try it here (Code will need to be pasted in, with each input on an individual line in the order n, x, y)

APL (Dyalog Extended), 16 15 13 bytes
⊃(1↓⊢,+/)⍣⎕⊢⎕

Takes input in the form f x y n
1 fewer byte thanks to TessellatingHeckler
2 fewer bytes thanks to Adám
Try it online!
Old answer
{⊃(1↓⊢,+/)⍣⍺⊢⍵}

Takes input in the form n f x y

Add++, 27 bytes
n:?
y:?
+?
Fn,z:y,y:x,z+
Oy

Try it online!
Just implements the standard Fibonacci algorithm of x, y = y, x+y but with x and y set by the input rather than as \$0, 1\$ or \$1, 1\$

Arn, 9 bytes
á‹-²À-'Z"

Try it!
Takes input in order n, x, y separated by spaces
Explained
Unpacked: [?1_?2{+]?
  [       Begin sequence
      _   Variable initialized to STDIN; implied
    ?     Indexed
      1   Second entry
      _
    ?
      2   Third entry
    {     Block (calculates all other entries)
      +   Last two entries added
    }     End block; implied
  ]       End sequence
?
  _       Implied

Perl 5 -pl, 38 bytes
($a,$n)=<>;($_,$a)=($a,$a+$_)while$n--

Try it online!
Output is 0-indexed.  Input format is:
x
y
n

><>, 16 bytes
:?!v1-}:@+{
{n;>

Try it online
Explanation
:?!v        # if n is 0 move to next row
    1-}     # decrement n and move it to bottom of stack
       :@   # save the largest number for next iteration
         +  # add the current numbers
          { # move n to top of stack
{n;>        # print bottom of stack (smaller number) and exit

Nibbles, 5 bytes (10 nibbles)
=@.~~$+<2

Input is [x,y] n.
=@.~~$+<2
  .~~       # append until null (here this means forever)
     $      # starting with first arg
      +     #   sum of
       <2   #   take 2 elements
=@          # finally, get the second-arg-th element

If we prefer to input x, y and n as individual numbers, instead of combining [x,y] as an array, add 1 byte (2 nibbles):
either =_.~~:$@+<2 (:$@ combines arg1 and arg2)

or =+$~.~~_+<2 (_ treats all args in STDIN as an array, but now we need to add one to the index (+$~) since we've prepended a useless value to the start of the sequence)

cQuents, 8 bytes
=A,B:z+y

Try it online!
Takes input as x y n, where n is 1-indexed.
Explanation
=A,B      Set sequence start to first two inputs
    :     Mode: Sequence
     z+y  Each item in the sequence is the previous two added together

          If there is a third input, that input is `n`. Get the `n`th (1-indexed) item in the sequence
          If there is not a third input, output the whole sequence.

Note current version uses Z and Y instead of z and y

source: Stack Exchange

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

sort: votes


text:
Reversing of Words
Sona is in her house with her 10 year old daughter. She needs to go to school to bring back another child from school, as school is over at 2 pm. It's hot outside, so she wants to leave her younger child at home.
She gave a bunch of strings to her child to keep her busy while she is gone. She asked her to reverse the words in the string. There are lot of strings, so you need to help her daughter in solving this huge task.
So, given a string that contains words separated by single space, reverse the words in the string. You can assume that no leading or trailing spaces are there.
The string will only contain [a-zA-z ], so you don't need to handle punctuation.
You will be given a string as an input, and you should output a string.
Sample Test Cases:
Input:
Man bites dog

Output:
dog bites Man

Input:
The quick brown fox jumps over the lazy dog

Output:
dog lazy the over jumps fox brown quick The

Input:
Hello world

Output:
world Hello

Scoring
This is code-golf. Shortest answer in bytes wins.

Related.

Can we take the input as a list of words? (i.e. ['man', 'bites', 'dog'])

Can the output have trailing whitespace?

misleading title, we're actually reversing a sentence, not the words...

Retina, 7 bytes
O$^`\w+

Try it online!
Match all words (\w+) sort them with sort key empty string (O$) which means they won't get sorted at all, and then reverse their order (^).

Never used Retina but why do you need the 0$? Can't you just reverse it?

@RandomUser sort mode (O) is currently the only mode that has this reverse option.

Haskell, 21 bytes
unwords.reverse.words

Try it online!

Python 3, 29 bytes
print(*input().split()[::-1])

Try it online!

What does the * do?

@OldBunny2800 unpack the list

Ahh. Makes sense.

Bash + common Linux utilities, 21
printf "$1 "|tac -s\

Leaves a trailing space in the output string - not sure if that's OK or not.

Congrats on 50k!! Your turn today :-)

@LuisMendo Thanks!

JavaScript (ES6), 31 bytes
s=>s.split` `.reverse().join` `

Try it

f=
s=>s.split` `.reverse().join` `
o.innerText=f(i.value="Man bites dog")
oninput=_=>o.innerText=f(i.value)
<input id=i><pre id=o>

It's answers like this, that is essentially the same as my C# answer that makes me hate C# for golfing. All the extra fluff in my answer nearly doubles the byte count... +1

Side note: In C# if you pass nothing to Split it splits on whitespace by default, can you do the same here?

Unfortunately not, @TheLethalCoder, if you don't supply a string/regex to split in JS, it will either split on each individual character or create an array with a single element containing the original string, depending on the syntax used.

Brachylog, 6 bytes
ṇ₁↔~ṇ₁

Try it online!
Explanation
ṇ₁        Split on spaces
  ↔       Reverse
   ~ṇ₁    Join with spaces

Note that both "split on spaces" and "join wth spaces" use the same built-in, that is ṇ₁, just used in different "directions".

Jelly, 3 bytes
ḲṚK

Try it online!
Explanation:
Ḳ     Splits the input at spaces
Ṛ     Reverses the array
K     Joins the array, using spaces

https://en.wikipedia.org/wiki/Krk

R, 19 bytes
cat(rev(scan(,'')))

reads the string from stdin. By default, scan reads tokens separated by spaces/newlines, so it reads the words in as a vector. rev reverses, and cat prints the elements with spaces.
Try it online!

C#, 58 bytes
using System.Linq;s=>string.Join(" ",s.Split().Reverse());

C, 54 48 bytes

Using arguments as input, 48 bytes
main(c,v)char**v;{while(--c)printf("%s ",v[c]);}

Try Online
> ./a.out man bites dog

Using pointers, 84 bytes
f(char*s){char*t=s;while(*t)t++;while(t-s){while(*t>32)t--;*t=0;printf("%s ",t+1);}}

Use
main(){ f("man bites dog"); }

That's sneaky, using the shell to do the word-splitting for you!  Clever abuse of the rules.

Second one only works if your compiler puts strings into writable storage and has non-printing character immediately preceding.  It segfaults here.

05AB1E, 4 bytes
#Rðý

Note: Will only work for 2 or more words. +1 byte if this is not OK.
Try it online!

I see unicode, is it reallly 4 bytes?

Yes, 05AB1E uses a custom codepage

#R¸» alternate 4-byte solution :P.

GNU Make, 62 bytes
$(if $1,$(call $0,$(wordlist 2,$(words $1),$1)) $(word 1,$1),)

brainfuck, 74 bytes
,[>++++[<-------->-],]<[>++++[->--------<]+>[[<]>[+>]<]<-[<]>[.>]<[[-]<]<]

Try it online!
This code creates the number -32 in two different places, but that seems to be fewer bytes than trying to maintain a single -32.
Explanation
,[                        input first character
  >++++[<-------->-]      subtract 32 from current character (so space becomes zero)
,]                        repeat for all characters in input
<                         go to last character of last word
[                         while there are more words to display:
 >++++[->--------<]       create -32 two cells right of last letter
 +>                       increment trailing space cell (1 right of last letter) so the next loop works
 [[<]>[+>]<]              add 32 to all cells in word and trailing space cell
 <-                       subtract the previously added 1 from the trailing space
 [<]>                     move pointer to beginning of word
 [.>]<                    output word (with trailing space)
 [[-]<]                   erase word
 <                        move to last character of previous word
]

Cubix, 48 bytes
Almost gave up on this one, but finally got there.
oU_;SW;@?ABu>):tS-?;\0$q^s.$;;<$|1osU!(;;...<#(1

Try it online!
This maps onto a cube with a side length of three as follows
      o U _
      ; S W
      ; @ ?
A B u > ) : t S - ? ; \
0 $ q ^ s . $ ; ; < $ |
1 o s U ! ( ; ; . . . <
      # ( 1
      . . .
      . . .

The general steps are:

Get all input A and reverse B stack
Move the negative q to the bottom, add a counter 0 to the stack. bit of jumping around in here.
Find space/end loop, also puts stack in correct print order.

Increment counter ) and fetch the counter item from the stack t
Is it a space or EOI S-?
Repeat if not

Print word loop

Decrement counter (
Exit loop if counter !U is 0
Swap s counter with character on stack
Print o character and pop it from the stack ;
Repeat loop

Get the length of the stack # and decrement (
Check ? if 0 and exit @ if it is 0
Otherwise print a space So clean up ;; and go back to the first loop.

I've skipped a number of superfluous steps, but you can see it Step By Step

Japt, 11 10 7 4  bytes
My first attempt at Japt.
¸w ¸

Try it online

Saved 3 bytes thanks to ETHproductions

Explanation
    :Implicit input of string U
¸   :Split on <space>
w   :Reverse
¸   :Join with <space>

Please share your Japt tips here.

Thanks for using Japt :-) You can use ¸ in place of qS , which should save you three bytes here. (See the "Unicode shortcuts" section of the interpreter docs)

Nice! you can save a byte if you use the -S flag.

I count 2 bytes, @obarakon. Unless the flag is included in the byte count, in which case that would be 4 byes, no?

@Shaggy Each flag counts as one byte. So -S would be +1 onto your total byte count.

Ah, I see. Is that a PPCG thing or a Japt thing?

@Shaggy It's a PPCG thing. Source

Python 2, 34 bytes
lambda s:' '.join(s.split()[::-1])

Try it online!

Out-golfed. >_> Well... the other one only works in Python 3...

Pyth, 4 bytes
jd_c

Try it online!

J-uby, 23 bytes
:split|:reverse|~:*&' '

Explanation
:split   # split by spaces
|        # then
:reverse # reverse
|        # then
~:*&' '  # join with spaces

PHP, 47 Bytes
<?=join(" ",array_reverse(explode(" ",$argn)));

Try it online!

Röda, 27 25 bytes
2 bytes saved thanks to @fergusq
{[[split()|reverse]&" "]}

Try it online!
This function takes input from the input stream.
Explanation (outdated)
{[[(_/" ")()|reverse]&" "]}           /* Anonymous function */
   (_/" ")                            /* Pull a value from the stream and split it on spaces */
          ()                          /* Push all the values in the resulting array to the stream */
            |reverse                  /* And reverse it */
  [                 ]                 /* Wrap the result into an array*/
                     &" "             /* Concatenate each of the strings in the array with a space */
 [                       ]            /* And push this result to the output stream */

split uses space as the default separator, so split() is shorter than (_/" ")().

k, 9 bytes
" "/|" "\

Try it in your browser of the web variety!
     " "\ /split on spaces
    |     /reverse
" "/      /join with spaces

Mathematica, 35 bytes
StringRiffle@Reverse@StringSplit@#&

Try it online!

StringSplit[#] splits on whitespace automatically, so you don't need to specify the " ".

correct! -5 bytes!

Ooh, and I think you can save another byte using function composition: StringRiffle@*Reverse@*StringSplit (call it like StringRiffle@*Reverse@*StringSplit@"hello world")

Vim, 20 bytes
:s/ /\r/g|g/^/m0<cr>vGJ

This is shorter than the other vim answer.
Try it online!

Pyth, 3 bytes
_cw

My first Pyth answer, one byte shorter than @notjagan's answer!
Explained:
 cw # Split the input by space (same as Python's string.split())
_   # Reverses the array
    # Pyth prints implicitly.

Zsh, 13 bytes
echo ${(Oa)@}

Try it online!

TAESGL, 7 bytes
ĴS)Ř)ĴS

Interpreter
Explanation
 ĴS)Ř)ĴS
AĴS)        implicit input "A" split at " "
    Ř)      reversed
      ĴS    joined with " "

CJam, 7 bytes
qS/W%S*

Try it online!
Explanation
q        e# Read input
 S/      e# Split on spaces
   W%    e# Reverse
     S*  e# Join with spaces

Ohm, 4 bytes
z]Qù

Try it online!
Explanation
z     Split the input on spaces.
 ]    Dump it onto the stack.
  Q   Reverse the stack.
   ù  Join the stack with spaces. Implicit output.

Perl 6, 14 bytes
{~[R,] .words}

Try it
Expanded:
{              # lambda with implicit param $_

  ~            # stringify following (joins a list using spaces)

   [R,]        # reduce the following using the Reverse meta operator

        .words # call the words method on $_
}

J, 6 bytes
|.&.;:

Try it online! This is reverse (|.) under (&.) words (;:). That is, split sentence into words, reverse it, and join the sentence again.

Java 8, 62 bytes
s->{String r="";for(String x:s.split(" "))r=x+" "+r;return r;}

Try it here.
Java 7, 77 bytes
String c(String s){String r="";for(String x:s.split(" "))r=x+" "+r;return r;}

Try it here.

Gema, 29 characters
<W><s>=@set{o;$1 ${o;}}
\Z=$o

Sample run:
bash-4.4$ gema '<W><s>=@set{o;$1 ${o;}};\Z=$o' <<< 'Man bites dog'
dog bites Man

jq, 27 characters
(23 characters code + 4 characters command line options)
./" "|reverse|join(" ")

Sample run:
bash-4.4$ jq -Rr './" "|reverse|join(" ")' <<< 'Man bites dog'
dog bites Man

On-line test

Java 8, 53 57 bytes
Lambda + Stream API
s->Stream.of(s.split(" ")).reduce("",(a,b)->b+" "+a)

Following Selim suggestion, we just dropped 4 bytes

Save 4 bytes by using Stream.of instead of Arrays.stream :--)

Wren, 40 bytes
Fn.new{|a|a.split(" ")[-1..0].join(" ")}

Try it online!
Explanation
Fn.new{|a|                             } // Anonymous function with the parameter a
          a.split(" ")                   // Split on spaces
                      [-1..0]            // Reverse the array
                             .join(" ")  // Join the array with spaces

GNU sed 4.2.2, 34 bytes
Score includes +1 for -r passed to GNU sed.
:
s/(\w*) ([^:]*)/\2:\1/
t
y/:/ /

Try it online!
Another answer, 38 bytes:
s/^/:/
:
s/:(.*) (.*)/\2 :\1/
t
s/://

Try it online!

Vyxal, 3 bytes
⌈ṘṄ

Try it Online!

Thunno 2 Ṡ, 2 bytes
Or

Try it online!
Explanation
    # Implicit input
O   # Split on spaces
 r  # Reverse
    # Join on spaces
    # Implicit output

Cheddar, 26 bytes
3 bytes thanks to Conor O'Brien
@.split(" ").rev.join(" ")

Try it online!

26 bytes

AWK, 30 28 bytes
{for(;++i<=NF;)s=$i" "s}$0=s

Try it online!
Thanks, manatwork, for catching my needless fluff. :)

Not specified by the challenge, but hopefully there is no need to handle empty input, so {for(;++i<=NF;)s=$i" "s}$0=s.

Trying to remember what was going on 21 hours ago... failing.  Good catch @manatwork .

Lua, 66 42 bytes
for i=#...,1,-1 do
io.write(arg[i],' ')end

Try it online!

Ruby, 23+1 = 24 bytes bytes
Uses the -p flag.
$_=$_.split.reverse*' '

Try it online!

Clojure(script), 57 bytes
#(apply str(interpose" "(reverse(re-seq #"[a-zA-Z]+"%))))

Stacked, 17 bytes
' 'split rev' '#`

Try it online!
#` is "join".

MATL, 5 bytes
YbPZc

Try it at MATL Online!
Explanation
    % Implicitly grab input as a string
Yb  % Split it on all of the spaces, yielding a cell array of words
P   % Flip this array
Zc  % Join these words back together with spaces
    % Implicitly display the result

Scala, 37 bytes
s=>s.split(" ").reverse.mkString(" ")

Try it here.

Vim, 49 42 bytes
:s/.*/\=join(reverse(split(submatch(0))))/

Thank you to @manatwork for feedback

Does this require a specific version? Vim 8.0 gives me “E486: Pattern not found: %V.*%V.”

BTW, it seems to work fine without those \%V things: :s/.*/\=join(reverse(split(submatch(0))))/.

@manatwork it works for vim 8 only I did it with visual select aka %V for no practical reason.. my bad :D
Thank you for the feed back I will update the answer

Ruby, 27 24 bytes
thanks to @manatwork
->a{a.split.reverse*" "}

Same with shorter syntax: ->a{a.split.reverse*" "}

Swift, 116 bytes
var r:(String)->String={return $0.characters.split(separator:" ").map(String.init).reversed().joined(separator:" ")}

You can try it here

tcl, 18
puts [lreverse $S]

demo

tcl, 11
lreverse ""
          ^
          |
          Put the string you want to test here between the ""

Can be tested on http://www.tutorialspoint.com/execute_tcl_online.php starting the tcl interpreter by typing tclsh. Then type
lreverse "Man bites dog"

%
lreverse "The quick brown fox jumps over the lazy dog"

%
lreverse "Hello world"

PowerShell Core, 45 29 bytes
$args|%{$r=,$_+$r}
$r-join' '

Try it online!
-16 bytes thanks to mazzy!

Try it online!? because there is the rule "The string will only contain [a-zA-z ]"

Try it online!?

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

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


text:
What week is it?
The day of the week and month of the year seem to get a lot of attention but no one seems to care about the week of the year. I believe it's time to change that, so your job is to write a program or function that when given a date outputs an integer between 1 and 53 corresponding to the current week of the year.
For the purposes of this challenge we will say that the first Sunday of the year marks the beginning of the year so the only case when January 1st is considered week 1 is when it falls on a Sunday.

Input can be any date format which does not explicitly include the week number (just specify the format in your answer) for dates between 1JAN1900 and 31DEC2100.
Output is an integer between 1 and 53
You may use any standard methods of providing input/output.

Test Cases
17MAY2017 -> 20

3JAN2013 -> 53

1JAN2017 -> 1

17MAY1901 -> 19

31DEC2100 -> 52

7JUL2015 -> 27

This is code-golf so all standard golfing rules apply, and the shortest code (in bytes) wins.

ISO weeks would be more standard; IIRC they're based on the first Thursday in a year.

Can we use other date input formats (i.e., 07/07/2015)? Can 7JUL2015 be 07JUL2015?

@StephenS Yes, that's fine. 7/7/2015, 2015-07-07 are also valid.

Can I take input as a timestamp?

@Neil: Not exactly matching the standard definition is a good thing here, it makes it less likely that the problem can just be solved via a builtin, whilst making it no more difficult to solve without.

@thegreatemu Then that date is technically part of the previous year so either 52 or 53.

Note to people using %U: As @J_Lard points out, you need to take care as to whether week 0 is week 52 or 53 of the previous year. It's week 53 in 2001, 2007, 2013, 2018, 2024, 2029 and repeating in a 28-year cycle. Other years it's week 52.

@Neil - First Thursday? We need to stop giving the ISO free tequila.

@RobertFraser I believe the idea is that weeks are counted as being in the year that most of their days are in.

@J_Lard Thinking of accepting an answer soon?

Ohm, 12 33 bytes
EDIT: Fixed the edge cases for "%U".
IΩDÖ?┼╓y≤s"-12-31"C"%F"╓₧Ω
"%U"╓&

Assumes input can be a timestamp.
Explanation to come.
Try it online!

Week 0 is different in years such as 1995 and 2023.

@Neil That's true, but the challenge says the answer must be in between 1 and 53, and I'm basically doing the same thing as all the other answers.

Sorry, I got my years mixed up. Anyway, it's 52 in some years, and 53 in others.

@Neil There we go.

Indeed, this gives correct answers for e.g. Jan 1 2018 and 2019.

MATL, 50 bytes
Thanks to @Neil and @NickClifford for pointing out a mistake, now corrected
ZO1)TThXJYOXIGYO&:8XO!s310=sJ4B-YOIq&:8XO!s310=sX\

Try it online! Or verify all test cases.
Explanation
This uses the three date/time conversion functions that there are in MATL:

XO: convert date and time to string format;
YO: convert date and time to serial date number;
ZO: convert date and time to vector of components.

Determining if week "0" should become 52 or 53 was costly, because MATL cannot define callable functions to reuse the 8XO!s310=s part. Reusing by means of loop with a branch only saves one byte, and complicates the explanation, so probably not worth it.
Also, something could be gained inputting the date as a [year, month, day] array; but the I would not use all three date functions :-)
Consider input '17MAY2017' as an example.
       % Implicit input
       % STACK: '17MAY2017'
ZO     % Convert to date vector
       % STACK: [2017 5 17]
1)     % Get first entry: year
       % STACK: 2017
TTh    % Append [1 1]
       % STACK: [2017 1 1]
XJ     % Copy to clipboard J
YO     % Convert to date number
       % STACK: 736696
XI     % Copy to clipboard I
GYO    % Push input again. Convert to date number
       % STACK: [736696 736832]
&:     % Binary range
       % STACK: [736696 736697 736698 ... 736832]
8XO    % Convert to date string with format 'ddd': day of week
       % STACK: ['Sun'; 'Mon'; 'Tue'; ... ; 'Wed']
!s     % Sum of each row (chars are interpreted as code points)
       % STACK: [310 298 302 ...  288]
310=   % Compare with 310 (sum of 'Sun')
       % STACK: [1 0 0 ... 0]
s      % Sum of array. If is 0, it needs to be transformed into 52 or 53,
       % depending on the number of Sundays the previous year contains.
       % STACK: 20
J      % Paste from clipboard J
       % STACK: 20, [2017 1 1]
4B-    % Push [1 0 0] and subtract element-wise
       % STACK: 20, [2016 1 1]
YO     % COnvert to date number
       % STACK: 20, 736330
I      % Paste from clipboard I
       % STACK: 20, 736330, 736696
q      % Subtract 1
       % STACK: 20, 736330, 736695
&:     % Binary range
       % STACK: 20, [736330 736331 736332 ... 736695]
8XO    % Convert to date string with format 'ddd': day of week
       % STACK: 20, ['Fri'; 'Sat'; 'Sun'; ... ; 'Sat']
!s     % Sum of each row (chars are interpreted as code points)
       % STACK: 20, [289 296 310 ... 296]
310=   % Compare with 310 (sum of 'Sun')
       % STACK: 20, [0 0 1 ... 0]
s      % Sum of array
       % STACK: 20, 52
X\     % 1-based modulo
       % STACK: 20
       % Implicit display

Congrats on 50k!  I'm right there behind you :)

2 points to go... and boom! Congrats!

Does this work with the edge cases pointed out by Neil? I know it doesn't use %U, but I just want to make sure.

This seems to think 1st Jan 2019 is in Week 53, but it's only in Week 52.

@Neil Yes, you're correct. Interestingly the other test cases are correct.

@NickClifford It was wrong. Thanks for pointing it out. It assumed week 0 should always be transformed into week 53. Corrected now, by a mere 21 bytes :-P

@Neil Workingnow. Thanks for catching that!

JavaScript (ES6), 82 80 bytes
Takes input as (year,month,day).

let f =

(y,m,d)=>-~((((x=new Date(y,m-1,d))-new Date(y,0,1))/864e5+372-x.getDay())/7%53)

console.log(f(2017, 5,17)) // 20
console.log(f(2013, 1, 3)) // 53
console.log(f(2017, 1, 1)) // 1
console.log(f(1901, 5,17)) // 19
console.log(f(2100,12,31)) // 52
console.log(f(2015, 7, 7)) // 27

JavaScript (Firefox 34+), 70 bytes

with(new Date())y.value=getFullYear(),m.value=getMonth()+1,d.value=getDate()+1
f=
(y,m,d)=>new Date(y,--m,d-new Date(y,m,d).getDay()).toLocaleFormat`%U`
<div oninput=w.value=f(y.value,m.value,d.value)><input id=y type=number><input id=m type=number min=1 max=12><input id=d type=number min=1 max=31><input id=w readonly placeholder=Output>

Works by finding the first day of the week containing the given date, then finding that day's week number (which is never zero).

+1 for with. Always +1 for with!

JavaScript (Firefox Only), 77 bytes
Takes date as string: i.e. Jan 1, 2017
s=>+new Date(s)[k='toLocaleFormat']`%U`||new Date(s.slice(-4)-1,11,31)[k]`%U`

Nice try but "week 0" isn't always the same week (1995 and 2023 are different).

Sorry, wrong test cases. I should post a proper comment on the question.

@Neil It should be corrected.

Python 2, 70 64 bytes
Input => (year,month,day)
from datetime import*;lambda*v:int(date(*v).strftime('%U'))or 53

print(f(2017, 5,17)) #20
print(f(2013, 1, 3)) #53
print(f(2017, 1, 1)) #1
print(f(1901, 5,17)) #19
print(f(2100,12,31)) #52
print(f(2015, 7, 7)) #27

-6 bytes, thanks to @ovs

PHP, 125 Bytes
for($w=53,$a=0;($c=date_create)($argn)>=$n=date_modify($c("07JAN1900"),"+$a week");$a++)$w=date_format($n,z)<7?1:$w+1;echo$w;

Try it online!
PHP, 28 Bytes
Version for Monday instead Sunday

<?=date(W,strtotime($argn));

Try it online!

C#, 138 123 121 bytes
namespace System.Globalization{d=>CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d,(CalendarWeekRule)1,(DayOfWeek)0);}

Turns out there's a built in for that, although it is rather large...
namespace System.Globalization
{
    Func<DateTime, int> f = d =>
        CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d, (CalendarWeekRule)1, (DayOfWeek)0);
 }

Powershell, 260 + 8 = 268 bytes
+8 bytes because of the -DateTime flag

Accepts argument as "day month year" format.
function W([datetime]$DateTime = (Get-Date)) {
$cultureInfo = [System.Globalization.CultureInfo]::CurrentCulture
$cultureInfo.Calendar.GetWeekOfYear($DateTime,$cultureInfo.DateTimeFormat.CalendarWeekRule,$cultureInfo.DateTimeFormat.FirstDayOfWeek)
}

Not Powershell expert, can't golf

Test case
>W -DateTime "11 March 2015"
11


text:
Lots of seconds!
OUTPUT:  The number of seconds since midnight on January 1, 1 A.D., as an integer.
INPUT:  None, you must pull the current timestamp yourself.
TASK:  This is code-golf, shortest answer in bytes wins.
Standard loopholes apply.

I suggest allowing solutions to take the current timestamp as input, with the input byte count added to the total.

Midnight on January 1, 1 A.D. on which calendar?

I think it's best if Linux Epoch time is used.

I think there are some things in this challenge that aren't entirely clear. 1) Which calendar? Julian? Gregorian? 2) Should we take leap seconds into account? 3) Would this have to handle hypothetical future leap second changes?

@Okx that started on January 1, 1970 in the Gregorian calendar - there have been many changes between 1AD and then regarding new dates.

I downvoted this because it's likely to be a builtin in a large number of languages (with an offset to change the epoch), and even when it isn't it may be easier to use an FFI to get at the builtin from libc than trying to reverse-engineer it from day/month/year. It would be fairer to either take day/month/year as input and convert it to seconds since the epoch, or else allow the time to be output in any format (although the latter wouldn't be a good question due to being too easy, and the former would still be somewhat unfair).

I have not downvoted but would suggest using the sandbox for your next challenge.

Bash + GNU utilities, 26
date +62135596800\ %s+p|dc

This doesn't attempt to do anything special wrt Julian vs. Gregorian or leap-seconds or timezones - I'm just assuming GNU date is doing the right thing.
The 62135596800 is the output of date -ud 1/1/1 +%s multiplied by -1.  date's %s format specifier gives the number of seconds since the unix epoch (1970), and so is a negative number for 1/1/1.
Try it online.


text:
Correct peoples grammar
(yes, that title was intentional)
Your task is to correct common grammatical mistakes.
You must:

Capitalise the first letter of each sentence, ie the first non-whitespace letter after any of .!? and, additionally, capitalise the first letter of the input
Remove repeating punctuation, such as !!! -> !. Ellipses (...) are not special, and will collapse into ..
Remove repeating whitespace <space><space><space> -> <space>
Remove whitespace directly before any of .,;!? as in: Hello , World ! -> Hello, World!
If there is no space directly after any of .,;!?, add it.
Add a . at the end of the input if there is not any of .!? at the end.
Not use Mathematica's builtins

Examples:
This is a  sentence .Unfortunately, it's not very grammatically correct.can you fix it ???
This is a sentence. Unfortunately, it's not very grammatically correct. Can you fix it?

buffalo, buffalo;buffalo   buffalo? Buffalo.buffalo Buffalo buffalo
Buffalo, buffalo; buffalo buffalo? Buffalo. Buffalo Buffalo buffalo.

i'm not sure what to put for this test case...
I'm not sure what to put for this test case.

!this is a test. .Can ...you . . . 'ear me Ground-Control? ?! 'ere as in what you do with you're [sic] ears !
! This is a test. Can. You. 'ear me Ground-Control?! 'ere as in what you do with you're [sic] ears!

"what about this?", "(or this.)"? (I'm guessing "what about this? ". and (or this. )., which is a shame, but golf be golf...)

What are all the possible characters that can appear in the input?

Your last test case seems wrong, since nothing in the post says we need to remove repeated punctuation with whitespace inbetween.

would rules number 5 and 6 clash and end up having a trailing output of .....

I like this challenge but I guess a better title might be "Correct peoples grammar according to the given rules". The rules are specific enough about what is required for me. If I am not misunderstanding, as long as the test cases are matched then the answer is valid. If my comment is grammatically incorrect then please feel free to use it as a further test case.

Do leading whitespace have to be removed?

@KritixiLithos Not unless there is any of .,;!? after the whitespace at the start.

Retina, 80 74 73 71 74 64 65 62 78 72 bytes
 *([.,;!? ])(\1| )*
$1
T`l`L`[.!?].|^.
([.,;!?])(\w|')
$1 $2
[^.!?]$
$&.

Try it online!
This is my first Retina answer.
-12 bytes thanks to @BusinessCat!
-3 bytes thanks to @Neil.

I think you can replace \s with a literal space. OP said there won't ever be newlines and I'm assuming there won't be tabs either.

There should be a space after punctuation like ;

Also ([^.!?])(?m:$) $1. -> [^.!?]$ $&..

@KritixiLithos Thanks, fixed.

@BusinessCat Thanks, but $ still seems to need a multiline modifier.

Ah. When you run all test cases at once it will. If you do one at a time it would be fine. You could also precede the line with `%`` (which executes the stage on each line separately) instead of using the modifier.

You don't need to count code added solely to run multiple test cases at once. On TIO, normal practice is to put %(G`  in the Header area instead.

@Neil Did just that, thanks.


text:
Tips for golfing in Japt
Now that I'm thoroughly addicted to Code Golf, it's probably about time that I try to pick up a few golfing languages.
Given that I play almost exclusively in JavaScript, Japt seems like the logical language to start with. I'll be diving into the documentation at the next opportunity I get but, in the meantime, please post any tips you have for Japt in the answers below.
As I'm a beginner in Japt and golfing languages in general, if you could "translate" your tips to JavaScript, where possible, that would be a big help in helping me get to grips with things.

Heh, thanks for posting this. I'd been holding off on doing this because I'd like to redesign Japt at some point, but that won't be happening anytime soon, and it probably won't mess up a lot of the tips anyway. Tip for myself: write a tutorial :P

Don't forget to visit the Japt chatroom :)

Moving from JavaScript to Japt
As you may know, Japt is simply a shortened, extended version of JavaScript. I created Japt because I was tired of long property names, like String.fromCharCode(x) and Math.floor(x), and the tediousness of doing things such as creating a range. Here's the bare minimum you need to know when going from JavaScript to Japt:

Japt is a transpiled language; Japt code is transpiled to JavaScript and then run as JS. (I guess you could say compiled, but transpiled sounds more hipster. Disclaimer: I know absolutely nothing about being hipster)
All entries are full programs by default. The input is implicitly parsed, and the first six inputs are put into the variables U, V, W, X, Y, and Z; the full array is stored in N. The result of the last expression is automatically printed.
All uppercase letters are variables, and stay the same when transpiled. Most have preset values, which you can find in the "Variables" section of the Japt docs (at the interpreter).
All lowercase letters are prototype functions, or methods. Japt adds the methods a-z (and à-ÿ) on numbers, strings, and arrays. When you use one of these letters, Japt fills in the . and (; Uc in Japt is equivalent to U.c( in JavaScript, which could mean ceil, charCodeAt, or concat, depending on the type of U. This is where most of Japt's power comes from; you can find full lists of these methods under the "_____ functions" sections of the Japt docs (at the interpreter).
A space represents ), and ) represents )). This is because when I first designed Japt, I wanted to save as many bytes as possible, and that's how I first thought of doing this. (Though Us w n does look better than Us)w)n), IMHO.)
A function is denoted as ABC{...}, where the ABC can be any string of variables. Functions work for the most part as they do in JS, the main difference being the last expression is automatically returned (rather than having to use return or fancy ES6 parentheses).
' denotes a single char string (i.e. 'a is the same as "a"), and # takes the next char-code and becomes that number (#e is the same as 101).
Anything between dollar signs $ stays the same during the transpilation process. You can use this to implement for loops, for example, since Japt doesn't have those, but I would suggest using other methods (such as m on strings and arrays, or o on numbers).
Most other chars commonly used in JS — "", 0-9, (, +, =, etc. — stay the same when transpiled (for the most part, anyway).

And that is all you need to know to write basic Japt code. Achieving maximum golf power in Japt requires more knowledge, but that can be found in other answers.

Here's a basic example. Say you have want to take a string of ASCII characters and replace each with its hexadecimal char code. Here's how you might do that in JavaScript:
U.split("").map(x=>x.charCodeAt(0).toString(16)).join("")

Now to convert to Japt. .split("") in JS is equivalent to q"" in Japt, or even shorter, just q. .join("") is also just q, the difference being that the object is an array instead of a string. .map( is m, .charCodeAt( is c, and .toString( is s. So our Japt code might look like:
Uq mX{Xc0 s16} q

In Japt, though, m works as well on strings as it does on arrays, so we can remove both qs:
UmX{Xc0 s16}

Test it online! As you can see in the "JS code" box, this directly transpiles to:
U.m(function(X){return X.c(0).s(16)})

As you learn to work with Japt, you'll become less and less focused on converting back and forth from JavaScript and be able to code in Japt as its own language. Here's an explanation leaving out the JavaScript portion entirely:
UmX{Xc0 s16}
               // Implicit: U = input string
UmX{       }   // Take U, and replace each character X with the result of this function:
    Xc0        //   Take the char-code at index 0 in X (the first and only one).
        s16    //   Convert this to a hexadecimal string.
               // Implicit: output result of last expression

It might be better to show another step: the unicode shortcuts. In this case, we coould save 2B with them. Also, you might want to add that you can leave out certain things at the end. That would save another byte.

An excellent primer, thanks, ETH. There's enough there, I think, to get me started on a few simple challenges.

Combining this with what I've gleaned from the README so far, would I be correct that the example above could be further shortened to Um_c s16?

Or, shorter still: ¡Xc s16?

@Shaggy You're correct! Man, you've figured this out quick ;-) I'll add some basic Japt golfing tips (like Unicode shortcuts and such), probably as other answers though.

It's tricky in parts, but overall it's been easy to pick up so far. I just need to work on better golfing and not being so reliant on the documentation (that'll come in time). I've been working on porting some of my existing JS answers to help me get to grips with things; would you mind throwing an eye over them for me, when you have a minute? Here's one (JS) and here's the other (JS).

The second one in particular needs some work as I had to work around the fact that array indexing wraps in Japt.

Wow! I am definitely going to use Japt somewhere near in future! Thanks for this post!

I'm going to accept this purely to keep it pinned to the top of the list of answers as it's probably going to be where most people will need to start.

I think this would work now: c_sGÃò

@EmbodimentofIgnorance In fact it can now be simply csG!

Compressing String Arrays

UPDATE: The tools featured in this tip have since be rewritten, improved and integrated into my Japt interpreter. For the best results it is recommended that you use that compressor over any of those linked below. I'll revisit this tip when I have some more time and rewrite it with the new compressor in mind.

Introduction
If you have an array of strings in your code, the most obvious way to compress it would be to run each string through Oc individually. For the purposes of this tip, we'll be working with the array ["lollipop","marshmallow","nougat","oreo"], which weighs in at 42 bytes initially. Running each string through Oc gives us:
[`lo¥ipop`,`Ú\hÚaow`,`Í`,`eo`]
That's now 33 bytes, a decent saving.

Step 1
But, we can do better. If we join the array to a newline separated string, we can get rid of the brackets, commas, and extraneous backticks and split on newline to get our array. Applying that to our example array gives us the following:
`lo¥ipop
Ú\hÚaow
Í
eo`·
Down to 26 bytes now.

Step 2
But, we can do better still! We could use a lowercase letter to delimit the strings instead of a newline, which might get included in the compression. z isn't used in any of our strings so let's drop that in, and see how we get on.
`lo¥ipopzÚ\hÚaowzÍzeo`qz
Ah, nuts - no improvement there; our byte count has gone up by one! There might be another letter you could use but, depending on your strings, there could be quite a few to try - in our example there are 11: b,c,d,f,j,k,q,v,x,y,z. Trying each would be pretty tedious, which is where this handy tool comes in; feed it your newline separated strings and it will try to delimit the strings with each letter that's not contained in any of them and output:

the shortest compressed string,
the delimiter it uses, and
its length.

Running our sample strings through it shows that b gives the best results:
`lo¥ipáæqrÚaowbÍÞo`qb
And there you have it, we're down to just 24 bytes.

Step 3
But, we can do even better! If the order of strings in your array doesn't matter, maybe there's a different permutation combined with a different delimiter that could work out even shorter. Trying each possibility is going to be much more tedious, though. With our 4 strings, there are 24 different permutations to try. With each of the 11 possible letters that becomes 264! That's where this tool comes into play. Again, feed it your newline separated strings and it will try every combination of every permutation and every delimiting letter, outputting:

the order of the strings in the shortest compressed string,
the compressed string,
the delimiter it uses, and,
its length.

Running our sample strings through it shows that "nougat","oreo","lollipop","marshmallow" with b as a delimiter gives the best results, with a final byte count of just 23:
`ÍÞo½o¥ipáæqrÚaow`qb

Bonus Tip: Integer Array Compression
You can apply the same principle to arrays of integers by first converting each to a higher base. Using this sample, 36 byte array:
[588181,156859,595676,475330,680474]
We can get that down to 29 bytes by first converting it to an array of base 32 strings and then running it through the first compression programme:
`huclt4p5r5ÛÊg62tkogq`qt mnH
Or as low as 27 bytes using the second programme:
`4p5Ïcl5ÛÊg62tkogq`qt mnH
You might be able to save another byte or 2 on top of that by moving the integer conversion into a method you're already running on the array.

Notes

Don't forget to factor in the 1 or 2 extra bytes q<letter>(<space>) costs over ·. Although, you may be able to use one of the Unicode shortcuts to get a byte back, depending on your delimiter (qÊ is the same as ql<space>, for example).
A word of caution when using the last tool: the more strings you have, the more permutations there will be and the slower the programme will run, until it eventually craps out. As detailed above, with our 4 sample strings and 11 possible letters to try, there are 264 possible combinations, increase the number of strings by just 1 with the same 11 letters and we already have 1320 combinations to try. (You can use this tool to count the number of combinations, if you want).

Credits

Oliver for the inspiration to create the tools found in this tip.
ETHproductions for proofreading.

Compressing strings
Japt (currently) uses the shoco library for string compression.  You can compress an arbitrary string using Oc, as long as it contains runs of lowercase letters:
Oc"Hello, World!"

This outputs HÁM, WŽld! (well, the Ž is technically an unprintable character). You can decompress this by wrapping it in backticks:
`HÁM, WŽld!`
Test it online!
Alternatively, you can use the Od function to decompress an arbitrary string. This isn't usually useful, but it has its purposes...

So, if I were answering the "Hello, World!" challenge, would I use just HÁM, WŽld! or would it need to be enclosed in backticks? I'm guessing the latter.

@Shaggy When answering a question you'd need to include all the code, so that would be `HÁM, WŽld! in this case

Quick tip: Empty array []
Japt has a constant for an empty array: A. But, in order to access it, you must prepend a semicolon ; to your programme to use Japt's alternative constants, otherwise A will be 10. So using ;A actually offers a 0 byte saving over [], but will save you bytes if you need to assign your array to a variable (e.g., A=[]).
However, if (and only if) your programme is not taking any input, you can access the empty array with just 1 byte by using the N variable, which is the array of inputs - with no inputs, it would be empty. Try it out here.
This has also has the added benefit of allowing you to use the default constant values in your programme and, in some cases, can still save you bytes over using ;A even when your programme is taking input thanks to the shortcuts for s1 and s2.

Wow, I hadn't thought about using N, nice idea.

Nice one, @Shaggy!

Shortening Numbers With Char-Codes
In Japt, you can use #, followed by a character to create a char-code. This comes in handy when shortening longer numbers.
As @ETHproductions mentioned, this only works on three-digit runs in the range 100-255, unless you are willing to switch to UTF-8.
Examples:
123 can be shortened to #{
101 can be shortened to #e
You can even chain these together:
123101 can be shortened to #{#e
You can use String.fromCharCode(123) in JavaScript, or 123d in Japt to find the appropriate character.
String.fromCharCode(123) returns {

Thanks, @obarakon, great tip to get the ball rolling with; String.fromCharCode() is one of those (many!) nastily long JS methods that can tank your byte count. Presumably, these would be considered to be integers? i.e., if I have need of the integer 123 in a solution, I could use #{ to save a byte.

Yes, these are integers. If you add the -Q flag into your input window, you can better view the output type: quotes around strings, arrays, etc.

You should mention that String.fromCharCode(123) works in JavaScript, but you can do 123d in Japt to get the same result ;-) Also, this only works on three-digit runs in the range 100-255 (unless you're willing to switch to UTF-8)

@ETHproductions Good call, updated!

Evaluating JavaScript
Japt allows you to execute raw JavaScript by wrapping it around $...$.
For example, $alert("hello world")$
This can be shortened by taking advantage of Japt's auto-closing $ and ).
$alert("hello world")$ can be shortened to $alert("hello world"
Compressing JavaScript
You can also compress JavaScript using Ox.
If there is a JavaScript function that you want to use, say screen.width, you can compress the string "screen.width" using Oc, then inserting the result in between Ox`...`
Note that you do not need closing quotes in Japt when it is not followed by anything else.

@Shaggy You need the Ox to evaluate the string. Otherwise, you would just output the text "screen.width". Example

Know the flags
As per the latest meta consensus (Dec 2017), command-line flags are no longer counted towards bytes. It's really a great news for Japt since it has many flags for extra treatment on input/output.
All available flags in Japt are described below, in the order of evaluation. The flags in the same group are exclusive to each other. Note that the flags in different groups can be used in combination, resulting in something like this :)
mdefæ
The whole program is mapped over the first argument (U).
If more arguments are present, they are passed as-is (i.e. not pairwise mapped). Otherwise, the second argument is the index, and the third is the whole array, just like U.m. If U is a number, it is converted to range; if string, it's converted to array of chars and the results are joined together.

-m: Applies the above and nothing else.
-d: Returns true if some result is truthy, false otherwise.
-e: Returns true if all results are truthy, false otherwise.
-f: Returns the array of elements of U whose results are truthy.
-æ: Applies -f and returns its first element.

gh
Takes an element at the specified index.

-g: Takes first element (index 0).
-gX: Takes the element at index X (can be any positive integer).
-h: Takes last element.

!¡
Convert the result to boolean.

-!: Apply boolean not.
-¡: Apply boolean not twice (returns the truthiness).

N
Convert the result to number. The unary plus is used.
PRSQ
Convert to string of some sort.

-P: Join the array with "".
-R: Join the array with "\n".
-S: Join the array with " ".
-Q: Apply JSON.stringify (can be any object, not only an array). Example.

x
Applies the function x to the output. (It's literally x, not "any single lowercase alphabet function".)

Array: Sum.
String: Trim from both ends.
Number: Round to integer.

Note that using flags doesn't count as a Japt submission though, it counts as a Japt-with-those-specific-flags-language submission.

Take advantage of preset variables
Variables A-S are preset to common values that take more than one byte to represent in Japt:

A-G are 10-16.
H is 32, I is 64, J is -1, L is 100.
K is defined as new Date(), which you can manipulate in various ways.
M and O are objects with various useful functions. You can learn more in the docs.
P is the empty string, Q is a quote mark, R is a newlines, and S is a space.
T is set to 0, so you can use it as an accumulator if necessary.

If the first character in the program is a semicolon ;, A-L are reset as follows:

A is the empty array [].
B is "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
C is "abcdefghijklmnopqrstuvwxyz".
D is "QWERTYUIOP\nASDFGHJKL\nZXCVBNM".
E is "[a-z]", and F is "[A-Za-z]" (useful before I added these as regex features)
G is 36, H is 65, and I is 91 (useful for alphabet ranges).
J is a single comma; L, a single period.

Nowadays only A, B, C, and D from this list are really useful. I'm planning to add a better system which allows up to 256 two-byte variables, which will be preset to these values and a whole lot more.

Unicode shortcuts
There are many common structures in Japt that just can't be stored in a single ASCII char, such as qS , p2 , mX{, } , etc. So to get around this, Japt has "Unicode shortcuts", which are characters in the range \xA1-\xDE (¡-Þ) which expand to these common structures. You can find a full list of these in the interpreter docs.
Additionally, @ stands for XYZ{, and _ stands for Z{Z, to help build functions. So let's golf our example program from another answer:
UmX{Xc0 s16}

Firstly, we can replace X{X with _, which gives us:
Um_c0 s16}

Then we can replace m_ with ® saving another byte:
U®c0 s16}

Or we could replace X{ with @, which gives us:
Um@Xc0 s16}

This then allows us to use the ¡ shortcut to save two bytes:
¡Xc0 s16}

One of these two paths can be shortened 1 byte more than the other. Can you figure out which?

®c s16 for 6 bytes - do I win a cookie?!

@Shaggy You can save 1 more byte if you look hard enough... ;)

Would it be ®c sG?

Yep! I think that's as low as you can go. Well done! :-)

Amazing looking back on these, seeing the progression of Japt in a few short months. This can now be achieved with csG.

With the addition of Ë, another byte can be saved at the start now.

Use auto-functions
You most likely already know that @ and _ are shortcuts for XYZ{ and Z{Z, respectively (covered in the Unicode shortcuts answer). But sometimes you can make functions even shorter.
Suppose you had an array of characters and you wanted to map each character to its char-code. You could do this with either of these:
mX{Xc}
m_c}

But there's a better way. If a method or operator is the first item after another method or a (, it gets turned into a string. So these two lines are equivalent:
r'a'b  // Replace all "a"s with "b"s; transpiles to .r("a","b")
ra'b   // Does the same thing, 1 byte less; transpiles to the same thing

But how does that help with our functions? Well, most methods that accept functions, if given a string representing a method or operator, will interpret it as a function. Which means you can also do this:
m_c}  // Map each item to its char code
m'c   // Does the same thing, 1 byte less
mc    // Also does the same thing, 2 bytes less

I call these "auto-functions". There are several different varieties:

m@Xc} → mc
m@Xc1} → mc1
m@X+1} → m+1
m@1+X} → m!+1
m@2pX} → m!p2

Hopefully you get the idea. To swap the arguments, just prefix the method or operator with !.

Would it be worth noting here that using auto-functions can also allow for further savings through the use of shortcuts? e.g., m@2pXÃ → m!p2<space> → m!².

Woah! I didn't thought about using a string in map, didn't even know it's possible. Maybe I'll save few bytes thanks to this in the future.

Hey @Soaku, I somehow missed that you've been answering with Japt, so allow me to extend you a late Welcome! Hope you've enjoyed using it so far. If you have any questions, suggestions, or just want to talk, feel free to join us in the Japt chatroom (Github usually works as well for the first two ;) )

Implicit Variable Assignment
Whenever you start a new line in Japt the result of the previous line is automatically assigned to one of the input variables (U-Z), with the first line being U, the second V, and so on.
Let's take an example: say you wanted to create 2 arrays to work with, one containing the numbers 1-10 and the other containing their squares. The long way to do this would be like so:
U=Aõ V=Um² [do something with the arrays]

Using automatic variable assignment, though, that can be shortened to:
Aõ
Um²
[do something with the arrays]

We've saved 4 bytes there. But, in this instance, we can save one more byte because the array of 1-10 is assigned to U and U can be omitted in certain scenarios:
Aõ
m²
[do something with the arrays]

Caution
One thing to be careful of with this tip is that you don't overwrite any input variables you might need later on in your programme. This can be avoided by leaving one or more empty lines at the start of it. In the following example, the 2 arrays will be assigned to the variables V & W, instead of U & V:

Aõ
Vm²
[do something with the arrays]

Know the Javascript
Since any Japt code runs as transpiled JS, good understanding of JS operators and built-in methods helps a lot in golfing pieces of Japt code.
Relevant JS tips

Implicit casting, increment/decrement operators
Some arithmetic/bitwise operator recipes

This doesn't necessarily save bytes in Japt (due to shortcuts), but it's always good to keep in mind how the operators work.

Know the comma and assignment-anywhere

The comma (usually implicitly inserted in Japt) is especially useful when you want to initialize a variable and then do some work on it. The following code assigns empty array to U and then evaluates V.m. (Having a newline activates implicit assignment to U on the first line.)

[]Vm@...
...

Short-circuiting
Splitting with numbers

This can be generalized to any method that accepts strings but not numbers. A number passed there will implicitly cast to a string, often saving a byte (e.g. 0 over '0).

Relevant JS built-in functions
Closely look at what parameters are passed to function arguments.

Array.prototype.map

Related Japt methods: Array.a/b/m/x/y/í, Number.o/õ, String.m/y/í

Array.prototype.reduce

Related Japt methods: Array.r/å, String.å; for å, 4th argument is not passed.

Array.prototype.some

Related Japt method: Array.d

Array.prototype.every

Related Japt method: Array.e

For string methods, it's good to know how the behaviors differ between passing a string or regex with or without g flag.

String.prototype.match

Related Japt methods: String.f/o

String.prototype.search

Related Japt method: String.â

String.prototype.replace

Related Japt methods: String.e/k/r
For e/r, passing functions as 2nd argument is OK, and understanding the function parameters is highly encouraged.

Use multiple lines when necessary
For most not-too-hard challenges, you can express the solution in just one line of Japt, as a sequence of applying built-in functions. But more complex ones will require to use looping constructs, recursion, or reusing large chunks of code. This is where multi-line programming comes in.
Remove closing parens
Task: Given an array of numbers, pair each element with the index squared, and sort it by the sum.
[5,1,17,9,3] => [[5,0],[1,1],[17,4],[9,9],[3,16]] => [[1,1],[5,0],[9,9],[3,16],[17,4]]
One-line solution is íUm@Yp2})ñx, but }) costs two bytes (and there is no one-byte shortcut). You can remove }) by simply moving the trailing ñx to the next line, so the code looks like this:
íUm@Yp2
ñx

and the transpiled JS becomes:
U = U.í(U.m(function(X, Y, Z) { return Y.p(2) })); U.ñ("x")

You can clearly see this does the same thing as the one-line solution, just assigning the intermediate result back to U.
Recurse with implicit arguments
The recursion function ß takes all of UVWXYZ as implicit parameter, if not specified. U is obviously the main input, but you can use any of VWXYZ to keep track of other values you need. For example, you can do something like the following:
(modify input and implicit assign to U)
(modify V and implicit assign to V)
(test something and call ß without arguments; U and V are passed automatically)

Alternatively, if all you want is a temporary variable, you can use inline assignment, like (T=...), as the variable T (0) is rarely used as-is.
Reuse a long function
For this, I don't think I can come up with a good example task, so I'll reference the only solution this tip was used, and just outline some general ideas.

In order to reuse a function, you need to store it in a variable. Starting a line with the function-opener {, @ or _ does the job. Alternatively, you can also do something like (T=@...}) to embed the function assignment inside a more complex line.
It's actually not trivial to call the stored function. Suppose V is a function and we want to call V(U) in JS. VU does not work since it simply means V,U. V(U doesn't either; it's V,(U). Even the function methods aren't helpful very much. The best way we found is:

[U]xV (map and sum) if the result is number
UmV if U is a single char and V returns a string, or
$V($U or [U]mV g in general.

However, mapping or looping with it is rather easy. To map over an array, use UmV. To find the first integer that satisfies V, use Va.

Fun with Auto-Functions
As a follow-up to ETH's general tip on auto-functions, this tip will provide a few specific examples of byte saving tricks you can achieve with them, which I'll add to as I think of more.

Get the largest integer in an array.
Assume we have the array [3,1,4,2] assigned to variable U and we ant to retrieve the largest number from it. We could do it in 4 bytes by sorting the array and then popping the last element:
Un o

The downside to that is that we've modified the original array; U is now [1,2,3] which may not always be desirable. Luckily, there's a way of doing it without modifying the array that's also one byte shorter:
Urw

What we've done there is reduced the array using the w method, which, when used on an integer returns the larger of the integer and the method's argument (e.g., 2w5 returns 5). So the above is the equivalent of UrÈwY or UrXY{XwY}. Note, though, that this tip won't work in the case of all the integers in the array being negative.

Side note: I'm planning to add functions to get the min and max of an array, though probably only in v2.

When not to use í
í is a useful built-in that pairs (or zips) two arrays or strings, and optionally maps each pair through a function. However, it currently has a few minor issues when given uneven arrays or strings:

If the first array has more items than the second, the non-existent items in the second will be given as undefined.
If the second array has more items than the first, it will stop processing at the end of the first array.

This can make it difficult to, say, compare two uneven strings and take the char with the higher code point from each pair. Even if you know that U is going to be the longer one, it still takes far to many bytes to solve this simple task:
UíUç hV @[XY]n o

What you could do instead would be to take input as an array of two strings, transpose the array with y, and then map each row to the correct result:
Uy m_q n o

This has the advantage of always padding the shorter string with spaces, making it a piece of cake to go through the entirety of both strings.
Real-life examples: 1, 2

Generate the ASCII Range

Update: Japt now has a constant for the ASCII range; the alternative value for E, accessible with ;. See this tip for more on Japt's constants.

While Japt doesn't (yet) have a built-in for the ASCII range, you can generate an array of characters in just 5 bytes:
95odH

Try it

How It Works
95o creates the range [0,95) with each element being passed through the auto-function d which, when used on a number, returns the character at that codepoint. Pass a number as an argument to the d method, in this case H, the Japt constant for 32, and it will be added to the original number before being converted.
An equivalent solution in JavaScript would be:
[...Array(95)].map((_,x)=>String.fromCharCode(x+32))

Random Characters
To get a random character in the ASCII range, use ö instead, which returns a random number from the range [0,X), where X is the number it is run on.
95ö dH

Or, to get an array of multiple random characters, pass the number of characters you need as an argument of ö. The following will return 10 characters:
95öA mdH

Remove unnecessary structural chars
By structural chars, I mean {}, (), $, even " and `. You can typically remove these chars whenever they occur right at the end of a program (e.g. UmX{Xc +"; "} -> UmX{Xc +"; ).
Additionally, you can remove parens or spaces whenever they appear in the following places:

Up against a semicolon ; (or the end of the program);
To the right of { (and by extension, @) or [, or the left of ] or }.

Also, commas are very rarely needed to separate arguments. If you write AB, for example, Japt knows you mean A and B separately. You only really need a comma to separate two numerical literals, such as Us2,5.
Finally, if there's a U at the start of a program or after a { or ;, followed by a method call (lowercase letter or related Unicode shortcut) or any binary operator excluding + and - (*, &, ==, etc.), you can remove the U to save a byte and Japt will insert it for you.

I've found a few other instances where U can be ommited even when it's not at the start of the programme.

@Shaggy Oh right, it also works after a { or ;. Are there any others that you are aware of? (It's been a while since I coded this feature :P)

Can't think of them off the top of my head; I'll check it out again when I get back to my computer tomorrow.

Modify the Last Element in An Array
Sometimes you may need to modify the last element in an array so here's an explanation of a short way of doing that. We'll be working with the array [2,4,8,32] assigned to input variable U and dividing the last integer (32) by 2.
The obvious way to achieve this would be with this 9 byte solution (Demo):
UhJUgJ /2

hnx sets the element at index n to x.
gn returns the the element at index n.
J is the Japt constant for -1, which, thanks to Japt's support for negative index, allows us to work with the last element in an array; handy when you don't know the size of the array.
And /2 is simply division by 2.

So the above sets the element at index -1 in the array to the element at index -1 in the array divided by 2. Or in JavaScript: U[3]=U[3]/2. When you write it out like that, it seems a far too long-winded way of going about it. Luckily, there is a shorter way; we could pop the last element from the array, modify it and push it back to the array. Performing each of those operations individually would take more than 9 bytes but we can do them all at once for just 7 bytes, a 2 bytes saving (Demo)
UpUo /2

Translated to JS, it's the equivalent of:
U.push(U.pop()/2)&&U

What does the "&&U" part do?


text:
Binary Tetris in tweets
There was recently (a few years back) some buzz on programming websites about an implementation of Tetris in 140 Bytes.
...
It turns out that although it is small, it is a simplified version of Tetris, and not even a complete implementation. Only the core logic function fits in 140 bytes of Javascript. To actually run it, you need another ~840 characters of HTML.
We can do better!
This challenge is to implement a complete version of "Binary Tetris" in as few tweets as possible.
Binary Tetris Rules:

The program must display a playing field containing at least 5 columns and 6 rows of cells.

Any method of display may be used, as long as the blocks and the edges of the field are clearly marked.

There must be at least two types of blocks:  # and ##. Additional block support such as ### or angle blocks shaped like an L will get upvoted by me :P and the most complete game of binary tetris (the most blocks like the original and rotation features) will win my happiness and a possible bounty up 50 rep.
New blocks are added to the field in the top row, and one block cell must occupy the center column.
Blocks descend towards the bottom row at a fixed rate.  Blocks must descend even without user input.
When blocks touch the bottom of the field or a lower block, they stop falling and are fixed in place.  A new block is added.
When all the columns in the row are filled with blocks, the row is emptied, and all the fixed blocks above drop down one row.
The program must respond to keypresses.  There must be 3 unique keys that perform the following functions

shift current block left 1 column
shift current block right 1 column
shift current block down 1 row

Each tweet may only have 140 characters. Using multi-byte characters that can be put in tweets is allowed.
The rules for what can be in a tweet is simple. If you can tweet it you can use it.
Interpreted languages follow the same rules. Each section must follow the specs. As long as no run time errors occur (and the rest is valid following the specs) your answer is valid
Golfing Rules:
Because the original implementation was "tweetable", this challenge requires the same.  Entries must be able to be transmitted as a series of tweets (lines of 140 characters or less).
The first tweet must contain the name of the compiler/interpreter, the name of the program, and any command line arguments

it will be saved as file "P0"

The following N tweets must contain the program as a series of lines.

Each tweet will be stored in a file with the name T<n>, where n is 1..N

Each line will be added to the previous lines and compiled or interpreted.  It must produce a valid object file or program.
The program does not need to be functional until the last line is added.
The program will be run in the following manner (pseudo-bash)
interp,prog,args = split P0 /\s/
touch $prog
for file in ./T* do
  cat $prog file > $prog
  $interp $prog $args
  die("FAIL") if $? #detect error
done

The interpreter must be a commonly available executable program that does not already implement Tetris.

Scoring:
Fewest Tweets, including P0.  Ties broken by largest number of spare characters (140 * num tweets - total character count).
Example Entries
chrome a.htm

Score = 3 (334 spare)
cc a.c ;a.out
main(){/*cool prog here*/}

Score = 2 (241 spare)
tetris

Score = 1 (134 spare)    if it were legal, which it's not
Special thanks
I was allowed to post this by Ashelly's consent here

Tweets may contain UTF-8 characters. Is that true here as well (for example, can we stuff 400ish bytes into a single tweet using CJK characters?)

@RobertFraser if you can type it into a tweet and send it then yes

If anything that can fit in a tweet is game, can we have newlines within each of our "tweets?" Line breaks are allowed within tweets.

@notjagan yes. It you can tweet it you can have it

If the challenge is going to be that way, you need to include an exact specification of which character sequences are allowed in a tweet.

With JavaScript, can the output be written with console.clear(), console.log(...) , or must it be injected into HTML as per the 1st example?

@Bumpy if it works it can be done like that

"Each line will be added to the previous lines and compiled or interpreted. It must produce a valid object file or program." - What exactly does that mean for interpreted languages? That it doesn't throw a syntax error, or that it throws no exception at all?

@JanDvorak running correctly. You get tetris when run and can play it

Does that rule only apply to the final program then, not the partial ones? You can't expect the partial programs to be playable... (plus, your clarification contradicts the following rule)

@JanDvorak only the final program

So... is there no requirement for the partial programs? Is it just code golf except the score is rounded up to a multiple of 140?

@JanDvorak pretty much. It changes the dynamic a bit. "The program does not need to be functional until the last line is added."

Please edit to clarify that... your rule suggests that the partial programs have to compile. It looks like you're trying to deceive us ... and both answerers so far fell for it...

If there is no requirement for the partial programs, why mention them at all? Also, your bash code has that magical #detect error formula that suggest you do care about partial programs...

@JanDvorak I changed my mind. I fixed it :P didn't mean to do that.

I'm sorry... what did you change your mind from and into? If this just a regular code golf now, you have invalidated both answers.

Let us continue this discussion in chat.

Python 3, Score of 5 Tweets (242 spare, counting P0)

-19 bytes thanks to Jonathan Allan!
The spare count does not take into account newlines from between tweets.
Tweet 1 (Declaration, 12 bytes)
python3 t.py

Tweet 2 (70 bytes)
import msvcrt as m,os;f=c=s=0;a=34636833;r=range;p=1<<32;t=30
while 1:

Tweet 3 (129 bytes)
 if m.kbhit()and b"\xe0"==m.getch():p=[p>>(not(a|f<<1)&p),p,p<<(not(a<<4|f>>1)&p),p>>5-5*(bool(f&p>>5)or p<t)][ord(m.getch())-77]

Tweet 4 (113 bytes)
 c+=1;print("\n".join("".join(".#"[1&(f|p)>>i*5+j]for j in r(5))for i in r(6))[::-1]);os.system("cls")
 if c%t<1:

Tweet 5 (134 bytes)
  if f&p>>5or p<t:s=~s;f|=p;p=2-s<<26
  else:p>>=5
 for i in r(0,t,5):
  if f|31<<i==f:b=bin(f)[2:].zfill(t);f=int(b[:-i-5]+b[t-i:],2)

Full Program (449 bytes)
import msvcrt as m,os;f=c=s=0;a=34636833;r=range;p=1<<32;t=30
while 1:
 if m.kbhit()and b"\xe0"==m.getch():p=[p>>(not(a|f<<1)&p),p,p<<(not(a<<4|f>>1)&p),p>>5-5*(bool(f&p>>5)or p<t)][ord(m.getch())-77]
 c+=1;print("\n".join("".join(".#"[1&(f|p)>>i*5+j]for j in r(5))for i in r(6))[::-1]);os.system("cls")
 if c%t<1:
  if f&p>>5or p<t:s=~s;f|=p;p=2-s<<26
  else:p>>=5
 for i in r(0,t,5):
  if f|31<<i==f:b=bin(f)[2:].zfill(t);f=int(b[:-i-5]+b[t-i:],2)

Does some evil bit point hacking and stores the field and piece in two integers. I'll try and post an explanation soon.
Note: This only runs on Windows, but it could be switched to Linux through msvcrt → getch and "cls" → "clear". Additionally, character input doesn't work on Python's IDLE, so I'd recommend running it elsewhere.

Wow well done! This short

Good work. \xe0 is four bytes not one so tweet 3 should be 130. You seem to have missed time.sleep(.1);c+=1 from tweet 4 and changed the order (I don't know if the order change is intentional) and again \n is two bytes not one, so it should be 134.

...mind you it seems playable without the sleep on my machine.

You could also test c%10<1 and remove c=0.

@JonathanAllan Thanks for the suggestions! I was in a bit of a hurry when posting this so it seems I was somewhat careless with splitting the tweets.

JavaScript (4 Tweets / 343 317 bytes / 243 spare)
Not quite sure about the requirements of the header & Tweets format, so please advise if it needs correcting.  Still a bit more can be shaved off I'm certain.
Tweet 1 - P0 (11 bytes)
chrome a.js

Tweet 2 (82 bytes)
a=y=z=j=0,onkeyup=b=>R((k=b.keyCode-40)?z*2*(d=k+3?k+1?1:.5:2)&65|j*d&a||(z*=d):0)

Tweet 3 (126 bytes)
R=d=>{d||(!(!y||a&j>>5)||(y>25?a=0:(31^31&(a|=j)>>y||(a=a>>y+5<<y|a&-1>>>-y-5>>5),y=0)),y-=5),y>=0||(y=30,z=12/(new Date%3+1))

Tweet 4 (98 bytes)
j=z<<y;for(o="",i=30;i--;)o+=1<<i&(a|j)?"#":"_",o+=i%5?"":"
";O.innerHTML=o},setInterval(R,300)

Run it in JSFiddle: https://jsfiddle.net/CookieJon/7Lenhcge/
(Click on the output pane to provide focus for keyboard events)

Please do not post partially completed or invalid answers to the question.  As per this meta discussion this answer should be deleted until it complies with the spec outlined in the question

@PunPun1000 My apologies.  It's now completed and undeleted.

No problem, I'll remove my downvote.  Welcome to PPCG.


text:
How to simplify ternary expressions in Javascript
I have an expression that could be expressed as either of :
a += (A ? B ? x : C ? y : D : D);

a += (A && B ? x : A && C ? y : D);

where A,B,C are expressions of 5-10 bytes each, and x and y are single character literals (3-4 bytes). D is another chain of ternaries (without the branching problem).
I'm getting stuck trying to eliminate the duplication of D or A. If I was using if, it would be something like this:
if (A)
    if (B)
        x
    else if (C)
        y
else D

Obviously I could do ((z=A) && B ? x : z && C ? y : D)...but any other more creative suggestions?
The actual code looks something like:
if (r%4<2&&r>3&&c<22&&c>1)
    if ((i-r)%8==6)
        '\\'
    else if ((i+r)%8==1)
        '/'
else

D is something like:
(i+r) % 8 == 3 ? '/' :
    (c-r+16) % 8 == 4 ? '\\' :

It would help to know what those expressions are.

yup, updated. try not to distracted by golfing them :)

Well, (i-r)%8 can become i-r&7 :p

I still can't see what your D is.

Updated again...

You're still hiding part of your D.

If you know that x and y cannot contain falsy values, as your code examples suggest, you can do the following to eliminate duplicate evaluation of A or D:
a += A && (B && x || C && y) || D;

Demo code and test cases in the following snippet:

// return x
test(1,1,0); // A and B
test(1,1,1); // A and B (and C)

// return y
test(1,0,1); // A and C

// return D
test(0,0,0); //
test(0,0,1); // C
test(0,1,0); // B
test(0,1,1); // B and C
test(1,0,0); // A

function test(A, B, C) {
  var x = 'x', y = 'y', D = 'D';
  a = A && (B && x || C && y) || D;
  expected = (A && B ? x : A && C ? y : D);
  var ws = ' ';
  console.log(
    [
      A && 'A' || ws,
      B && 'B' || ws,
      C && 'C' || ws
    ].join(ws),
    ' ==> a = ' + a,
    a === expected ?
      'Passed' :
      'Failed, expected ' + expected
  );
}

Otherwise, if falsy values are possible, you could do this:
a += [D, x, y][A && (B && 1 || C && 2) || 0];

Demo code and test cases in the following snippet:

// return x
test(1,1,0); // A and B
test(1,1,1); // A and B (and C)

// return y
test(1,0,1); // A and C

// return D
test(0,0,0); //
test(0,0,1); // C
test(0,1,0); // B
test(0,1,1); // B and C
test(1,0,0); // A

function test(A, B, C) {
  var x = false, y = 0, D = '';
  A = !!A; B = !!B; C = !!C;
  a = [D, x, y][A && (B && 1 || C && 2) || 0];
  expected = (A && B ? x : A && C ? y : D);
  var ws = ' ';
  console.log(
    [
      A && 'A' || ws,
      B && 'B' || ws,
      C && 'C' || ws
    ].join(ws),
    ' ==> a = ' + xyD(a, x, y, D),
    a === expected ?
      'Passed' :
      'Failed, expected ' + xyD(expected, x, y, D)
  );
}

function xyD(result, x, y, D) {
  return result === x ? 'x' :
         result === y ? 'y' :
         result === D ? 'D' : '<error>' ;
}

Thanks, that's very helpful. So, probably I should just stop thinking in terms of ternaries altogether.

Since short-circuiting is not required here, you can also do:
d=D;a+=A?B?x:C?y:d:d;

If short-circuiting were required, since your B and C are truthy values, you can do:
a+=(A?B?x:C?y:0:0)||D;

If short-circuiting were required and your B and C are not truthy values:
d=_=>D;a+=A?B?x:C?y:d():d();

Ah, that second one is an interesting way to "fall through" a ternary operator.