text:
Tips for Golfing in T-SQL
What general tips do you have for golfing in T-SQL? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to T-SQL. Please post one tip per answer.
Thanks to Marcog for the original idea. :)

a tip - use a different language for golfing. Sql answers usually gets very few or no upvotes at all.

My general bag of tricks::

@ is a valid variable in t-sql.
T-sql 2012 added iif a VB style case statement. This is almost always shorter than an equivalent if else.
\ is a useful way to initialize a number as 0 in a money type. You can convert a value to to a float by adding e. e.g. 4e or \k which will set k to the value 0.00 money.
rCTE seem to be the best way to create a number table of less than a 100 entries. Even shorter than using spt_values. If you need more than a 100, cross join and add them.
+= and other compound operators were added in 2008. Use them it saves a few characters.
Literals are usually a good enough delimiter for aliasing purposes. You rarely need a space or a ;.
Use ANSI SQL joins if you need them. Select*from A,B where condition is shorter than select*from A join b on condition
If you can be assured that the your while loop will do the first iteration it's best to rewrite it as a do-while style goto loop.
STR() is the shortest function to turn an int into a string. If you are doing more than one conversion or may need to concat numerous different datatypes consider the concat function.  E.g. 'hello'+str(@) is shorter than concat('hello',@), but hello+str(@)+str(@a) is longer than concat('hello',@,@a)

For example
These two are semantically equivalent.
while @<100begin/*code*/set @+=1 end
s:/*code*/set @+=1if @<100goto s

You can use Values to create a table or subquery. This will only really be a benefit if you need a few constant rows.

For me, $ is a bit more obvious than \ to initialize a number as 0 in a money type. YMMV

Code compression using SQL
SQL is wordy,scores high, and as much as we love'em, SELECT FROM WHERE cost 23 bytes with every use. You can compress these and other repeated words or entire code snippets. Doing this will decrease the marginal cost of repeated code to 1 byte!*
How this works:

A variable is declared and assigned compressed SQL code
A table modifies the variable. Each row deflates the variable.
The modified variable is executed.

The problem:
The upfront cost is close to 100 bytes and each row in the replacement table costs another 6 bytes. This kind of logic won't be very effective unless you're working with a lot of code which you can't trim down or the challenge is compression-based.
Here's an example
The challenge is to get the last 10 multiples of 2,3, and 5 leading up to n.
Let's say this (343 bytes golfed) is the best solution I could come  up with:
WITH x AS(
    SELECT 99 n
UNION ALL
    SELECT n-1
    FROM x
    WHERE n>1
)
SELECT w.n,t.n,f.n
FROM
    (SELECT n, ROW_NUMBER()OVER(ORDER BY n DESC)r
     FROM x WHERE n%2=0
    )w
,
    (SELECT n, ROW_NUMBER()OVER(ORDER BY n DESC)r
     FROM x WHERE n%3=0
    )t
,   (SELECT n, ROW_NUMBER()OVER(ORDER BY n DESC)r
     FROM x WHERE n%5=0
    )f
WHERE w.r=t.r AND w.r=f.r AND w.r<11
ORDER BY 1

Example after code is compressed
This executes the same code as above, is ~302 bytes golfed.
DECLARE @a CHAR(999)='
WITH x AS(!99n UNION ALL !n-1 @x#n>1)
!w.n,t.n,f.n@$2=0)w,$3=0)t,$5=0)f
#w.r=t.r AND w.r=f.r AND w.r<11^1'

SELECT @a=REPLACE(@a,LEFT(i,1),SUBSTRING(i,2,99))
FROM(VALUES
  ('$(!n,ROW_NUMBER()OVER(^n DESC)r@x#n%'),
  ('! SELECT '),
  ('@ FROM '),
  ('# WHERE '),
  ('^ ORDER BY ')
)x(i)

EXEC(@a)

Great strategy, that multi-replace style can be useful in more conventional scenarios as well.

After some testing, I've determined that if your list of replacements has 7 or fewer items, you'd save bytes by doing SELECT @=REPLACE(@,i,j)FROM(VALUES(...)x(i,j) instead of using a single column with LEFT() and SUBSTRING(). If you have 8 or more, then avoiding the extra quotes and commas is a good tradeoff.

Actually for 4 or fewer replacements, you'd save bytes with an old-fashioned SET @=REPLACE(REPLACE(REPLACE(...

Here's a funny one. This will convert the values in a column into a single tuple.
EDIT: Thank you for the comments. It seems like the shortest way of rolling up without the XML tags is:
SELECT (SELECT column1+''
FROM table
ORDER BY column1
FOR XML PATH(''))

Note: if XML is a valid output you can omit the outer select and parens. Also the column1+'', only works for strings. For number types it's best to do column1+0

Actually it will return <column_name>value1</column_name><column_name>value2</column_name>.... In order to have a CSV from a column you can DECLARE @ VARCHAR(MAX)='';SELECT @+=column_name+',' FROM table_name;SELECT @ (thanks for @MichaelB's first tip) which will return value1,value2,... . However, it is actually 9 characters longer than your XML trick :(

Note you can make this shorter. Ltrim isn't necessary as select (select... for xml path('')) returns an nvarchar(max). Also, to solve the column thing just use a non-mutating expression. For numerics you can do v+0, for string add empty string etc. Although I don't really consider this a golfing tip, this is just sadly a reality of how to write queries in sql server.

It is possible to use some bitwise operators in T-SQL.
I don't have a concrete example, but I believe it is a good-to-know fact when golfing in T-SQL.

This is very valid. Instead of writing a condition like x=0 or y=0, you can write that as the logically equivalent x|y=0 which saves quite a few bytes!

Print instead of Select
It's as simple as that! So here's a T-SQL / Python polyglot:
print'Hello, World!'

Try it online

Scientific notation is a shorter method to express very large and very small numbers, e.g. select 1000000000 = select 1E9 and select 0.000001 = select 1E-6.

Use GZIP compression for very long strings!
So I knew that SQL 2016 added a COMPRESS function (and a DECOMPRESS function), which (finally) brings the ability to GZIP a string or binary.
The problem is that it isn't immediately clear how to take advantage of this for golfing; COMPRESS can take a string but returns a VARBINARY, which is shorter in bytes (when stored in a SQL VARBINARY field), but is longer in characters (raw hex).
I've played with this before, but I finally was able to put together a working version, based on this old answer on SO. That post doesn't use the new GZIP functions, but it does convert a VARBINARY to a Base-64 encoded string. We just needed to insert the new functions into the right place, and golf it up a bit.
Here is the code you can use to convert your very long string to the Base-64 encoded compressed string:
DECLARE @s VARCHAR(MAX)='Your really long string goes right here'
SELECT CONVERT(VARCHAR(MAX),(SELECT CONVERT(VARBINARY(MAX),COMPRESS(@s))
       FOR XML PATH(''),BINARY BASE64))

Take the output, and use it in your code in place of the original long string, along with:
--To use your compressed string and return the original:
DECLARE @e VARCHAR(MAX)='H4sIAAAAAAAEAIvMLy1SKEpNzMmpVMjJz0tXKC4pygRS6fmpxQpFmekZJQoZqUWpAGGwW5YnAAAA'
SELECT CAST(DECOMPRESS(CAST(@e as XML).value('.','varbinary(max)'))AS varchar(max))

So instead of your original code (1471 bytes)
SELECT'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate — we can not consecrate — we can not hallow — this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us — that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion — that we here highly resolve that these dead shall not have died in vain — that this nation, under God, shall have a new birth of freedom — and that government of the people, by the people, for the people, shall not perish from the earth.'

you would have this (1034 bytes):
SELECT CAST(DECOMPRESS(CAST('H4sIAAAAAAAEAGVUW47bMAy8Cg/g5hD9aLFA0a8C/aYt2hZWEVNJjpGT5LodinE2i/0JIouPmeFQP3QrVCctQpwDVblKpptwqcSLkt3O3FbBeSy6LWujWUtbSTO1NVaaNLeYJbeBmLLslLlFzYNdTBKvEihm+hVHKe029CZBQpy44aYpighdil60RsvDmRtxSnQGEAasqUiPlX8bpxP91p126TeSF168PtNiYTTFa0y0cxmoSQWwhfZVDL8XPsBpAZLb40hVX9B+QgganCkp6kgOW5ET/fXmZ2mmwdF45NaSfJujpEA6ezfg6PErX8FDz2KEj9pIvUBJ63/E92xoBO3xP3Oi8iBxSTyJKY9ArQJSSiAltFhp8IuFEuBXL/TClc7RhmaXJ3prhJFxarq4KHNsvb6RtikcOkHhuuoGLkH7nE/0fcOIu9SJy4LAKrnKYKGmUdb2Qe3++hXSVpnKl+8rpoxh3t1HC9yVw4n+wA9jMVYwwGC4D3xBGOIY89rKtiwJwzINhkPfow0cAagzY8aj4sZMfFG1n90IKnEIZoEgrfDUvOmuBXT3COulaMM0kCieEdgNUOQsZ9gYEB4K8e0BYNwgbHNm2KBik4LCHgmhbxSigz1mYKPcane/Uxyo9D0bDN8oL0vS5/zYlC3DF7Gu+Ay872gQp9U7mDCzb2jPWN0ZaGJKwOJZx3QD9SvD6uEA4l2feHrvnv9lS93ojeu7ScHAAVFGme3tQOr94eGiZwuHSVeFduKDM70avwscZAtd++er+sqrp068VTf5C63D4HBdRfWtvwxcsYq2Ns8a96dvnTxMD7JYH0093+dQxcFU897DhLgO0V+RK0gdlbopj+cCzoRGPxX+89Se5u/dGPtzOIO5SAD5e3drL7LAfiXDyM13HE+d6CWZY26fjr7ZH+cPgFhJzPspK+FpbuvpP9RXxXK3BQAA'as XML).value('.','varbinary(max)'))AS varchar(max))

See this answer which saved me nearly 200 bytes.
I haven't done the math, but clearly due to the overhead this is only going to be effective for extremely long strings. There are probably other places this can't be used; I've already discovered you have to SELECT it, you can't PRINT it, otherwise you get:
Xml data type methods are not allowed in expressions in this context.

EDIT: Shorter version of the decompress code, courtesy of @digscoop:
Save 10 bytes by changing the outer CAST to an implicit conversion using CONCAT:
SELECT CONCAT('',DECOMPRESS(CAST('encoded_string_here'as XML).value('.','varbinary(max)')))

You can also declare a variable of type XML instead of VARCHAR(MAX), and save on the inner CAST:
DECLARE @ XML='encoded_string_here'
SELECT CONCAT('',DECOMPRESS(@.value('.','varbinary(max)')))

This is slightly longer by itself, but if you need it in a variable for other reasons, then it might help.

Nice, I don't know SQL but this looks cool still

Michael B mentioned using a recursive CTE for a number table, but didn't show an example. Here is a MS-SQL version we worked out in this other thread:
--ungolfed
WITH t AS (
    SELECT 1 n
    UNION ALL
    SELECT n + 1
    FROM t
    WHERE n < 99)
SELECT n FROM t

--golfed
WITH t AS(SELECT 1n UNION ALL SELECT n+1FROM t WHERE n<99)SELECT n FROM t

Note that you can change the starting value (1 n), the interval (n + 1) and the ending value (n < 99).
If you need more than 100 rows, though, you will need to add option (maxrecursion 0):
WITH t AS(SELECT 0n UNION ALL SELECT n+1FROM t WHERE n<9999)
SELECT n FROM t option(maxrecursion 0)

or join the rCTE to itself:
WITH t AS(SELECT 0n UNION ALL SELECT n+1FROM t WHERE n<99)
SELECT 100*z.n+t.n FROM t,t z

Although this last one isn't guaranteed to return in numeric order without an ORDER BY 1

A few thoughts about creating and using tables for challenges:
1. SQL input can be taken via a pre-existing table
Code Golf Input/Output Methods:

SQLs may take input from a named table

Creating and populating this table with input values doesn't count toward your byte total, you can just assume it is already there.
This means your calculations can output via simple SELECT from the input table:
SELECT 2*SQRT(a)FROM t

2. If possible, don't actually create a table at all
Instead of (69 bytes):
CREATE TABLE t(b INT)
INSERT t VALUES(7),(14),(21),(99)
SELECT b FROM t

Just do (43 bytes):
SELECT b FROM(VALUES(7),(14),(21),(99))t(b)

3. If possible, create the table with a SELECT INTO
Instead of (39 bytes):
CREATE TABLE t(p INT)
INSERT t VALUES(2)

Do this (17 bytes):
SELECT 2 p INTO t

4: Consider mashing multiple columns together
Here are two variations that return the same output:
SELECT a,b FROM
(VALUES('W','Bob'),('X','Sam'),('Y','Darla'),('Z','Elizabeth'))t(a,b)

SELECT LEFT(a,1),SUBSTRING(a,2,99)FROM
(VALUES('WBob'),('XSam'),('YDarla'),('ZElizabeth'))t(a)

After some testing, the top version (multiple columns) seems shorter with 7 or fewer rows, the bottom version (due to the LEFT and SUBSTRING) is shorter with 8 or more rows. Your mileage may vary, depending on your exact data.
5: Use REPLACE and EXEC for very long sequences of text
In the vein of comfortablydrei's excellent answer, if you have 15 or more values, use REPLACE on a symbol to get rid of the repeated '),(' separators between elements:
114 characters:
SELECT a FROM(VALUES('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H')
,('I'),('J'),('K'),('L'),('M'),('N'),('O'))t(a)

112 characters:
DECLARE @ CHAR(999)=REPLACE('SELECT a FROM(VALUES(''
 A-B-C-D-E-F-G-H-I-J-K-L-M-N-O''))t(a)','-','''),(''')EXEC(@)

If you're already using dynamic SQL for other reasons (or have multiple replaces), then the threshold where this is worth it is much lower.
6: Use a SELECT with named columns instead of a bunch of variables
Inspired by jmlt's excellent answer here, re-use strings via a SELECT:
SELECT a+b+a+b+d+b+b+a+a+d+a+c+a+c+d+c+c+a+a
FROM(SELECT'Hare 'a,'Krishna 'b,'Rama 'c,'
'd)t

returns
Hare Krishna Hare Krishna
Krishna Krishna Hare Hare
Hare Rama Hare Rama
Rama Rama Hare Hare

(For MS SQL I changed the \t to an in-line return, and changed CONCAT() to + to save bytes).

Tag your code for T-SQL syntax highlighting
Instead of just:
CREATE TABLE t(b INT)
INSERT t VALUES(7),(14),(21),(99)
SELECT b FROM t

Include a language tag like this:
<!-- language: lang-sql -->

    CREATE TABLE t(b INT)
    INSERT t VALUES(7),(14),(21),(99)
    SELECT b FROM t

and the result will be:
CREATE TABLE t(b INT)
INSERT t VALUES(7),(14),(21),(99)
SELECT b FROM t

Take advantage of new features/functions in MS SQL 2016 and SQL 2017
If you don't have local copies to work with, you can play online with the StackExchange Data Explorer
 (SQL 2016) or with dbfiddle.uk (SQL 2016 or SQL "vNext").
STRING_SPLIT (SQL 2016 and later)
SELECT *
FROM STRING_SPLIT('one,two,three,four,five',',')

If you need to alias the table or refer to the column name:
SELECT t.value
FROM STRING_SPLIT('one,two,three,four,five',',')t

TRIM (SQL 2017 or later)
Shorter than RTRIM() and certainly shorter than LTRIM(RTRIM()).
Also has an option to remove other characters or sets of characters from either the beginning or the end:
SELECT TRIM('sq,0' FROM 'SQL Server 2000')

returns L Server 2
TRANSLATE (SQL 2017 or later)
TRANSLATE allows you to replace multiple characters in one step, rather than a bunch of nested REPLACE statements. But don't celebrate too much, it only replaces individual single characters with different single characters.
SELECT TRANSLATE('2*[3+4]/{7-2}', '[]{}', '()()');

Each character in the second string is replaced by the corresponding character in the 3rd string.
Looks like we could eliminate a bunch of characters with something like REPLACE(TRANSLATE('source string','ABCD','XXXX'),'X','')

Some more interesting ones as well, like CONCAT_WS and STRING_AGG that are probably worth a look as well.

Holy cow, I have discovered the wonder of PARSENAME (SQL 2012 or higher).
The function was built to isolate the parts of an object name like servername.dbname.dbo.tablename, but it works for any dot-separated values. Just remember it counts from the right, not the left:
SELECT PARSENAME('a.b.c.d',1),      -- d
       PARSENAME('a.b.c.d',2),      -- c
       PARSENAME('a.b.c.d',3),      -- b
       PARSENAME('a.b.c.d',4)       -- a

If you have less than 4 dot-separated values, it will return NULL for the remainder (but it still counts right to left):
SELECT PARSENAME('a.b',1),      -- b
       PARSENAME('a.b',2),      -- a
       PARSENAME('a.b',3),      -- NULL
       PARSENAME('a.b',4)       -- NULL

Here's where the magic comes in, though: combine it with STRING_SPLIT (2016 or higher) to make in-memory multi-column tables!!
Old and busted:
SELECT a,b,c FROM
(VALUES('Bob','W','Smith'),
       ('Sam','X','Johnson'),
       ('Darla','Y','Anderson'),
       ('Elizabeth','Z','Turner'))t(a,b,c)

New hotness:
SELECT PARSENAME(value,3)a,PARSENAME(value,2)b,PARSENAME(value,1)c
FROM string_split('Bob.W.Smith-Sam.X.Johnson-Darla.Y.Anderson-Elizabeth.Z.Turner','-')

Clearly your actual savings depend on the size and contents of the table, and how exactly you are using it.
Note that if your fields are constant-width, you're probably better off using LEFT and RIGHT to separate them instead of PARSENAME (not only because the function names are shorter, but also because you can eliminate the separators entirely).

I am not sure when PARSENAME came out, but there are articles describing it from 2003

A couple more unrelated tricks I saw and wanted to preserve:

Use GO # to repeat a block a specific number of times.

Saw this clever trick on Paul's excellent answer.
PRINT'**********'
GO 10

This would, of course, reset any counter variables in the block, so you'd have to weigh this against a WHILE loop or a x: ... GOTO x loop.

SELECT TOP ... FROM systypes

From the same question as Paul's above, Anuj Tripathi used the following trick:
SELECT TOP 10 REPLICATE('*',10) FROM systypes

or, as suggested by pinkfloydx33 in the comments:
SELECT TOP 10'**********'FROM systypes

Note this doesn't rely on any of the actual contents of systypes, just that the system view exists (which it does in every MS SQL database), and contains at least 10 rows (it looks to contain 34, for most recent versions of SQL). I couldn't find any system views with shorter names (that didn't require a sys. prefix), so this may be ideal.

See this question on dba.stackexchange for some interesting ideas for adding a number column to a STRING_SPLIT result.
Given a string like 'one,two,three,four,five', we want to get something like:
value   n
------ ---
one     1
two     2
three   3
four    4
five    5

Per Joe Obbish's answer, use ROW_NUMBER() and order by NULL or a constant:
SELECT value, ROW_NUMBER() OVER(ORDER BY (SELECT 1))n
FROM STRING_SPLIT('one,two,three,four,five',',')

Per Paul White's answer, use a SEQUENCE:
CREATE SEQUENCE s START WITH 1
SELECT value, NEXT VALUE FOR s
FROM STRING_SPLIT('one,two,three,four,five', ',')

Sequences are interesting persistent objects; you can define the data type, the min and max value, the interval, and whether it wraps around to the beginning:
    CREATE SEQUENCE s TINYINT;     --Starts at 0
    CREATE SEQUENCE s MINVALUE 1;  --Shorter than START WITH
    SELECT NEXT VALUE FOR s        --Retrieves the next value from the sequence
    ALTER SEQUENCE s RESTART;      --Restarts a sequence to its original start value

Per Biju jose's answer, you can use the IDENTITY() function (which is not the same as the IDENTITY property in conjunction with an INSERT:
SELECT value v,IDENTITY(INT) AS n
INTO t
FROM STRING_SPLIT('one,two,three,four,five',',')

SELECT * FROM t

Note that the last two parameters in IDENTITY(INT,1,1) are optional, and will default to 1 if excluded.

the problem is that STRING_SPLIT doesn't guarantee any return order.  You might think it will always return the rowset in the order of the tokens in the original string.  Indeed it may even do that!  However, there is no guarantee in the docs.  that's fine if you don't care about the order. But if you do (e.g. parsing a row in CSV format), there's a problem.

@user1443098 I ultimately agree with you in the context of recommending code for a business purpose, like we might see on dba.SE. But for challenges on PPCG my standards are a bit different; if in testing my code returns rows in the order I want then I'll save the bytes where I can. Similar to how I'll leave out an ORDER BY if I can get away with it (see my answer to Toasty, Burnt, Brulee, for example).

Just discovered that you can use numerals for a single-character REPLACE to eliminate quotes:
--44 bytes
PRINT REPLACE('Baby Shark******','*',' doo')

--42 bytes
PRINT REPLACE('Baby Shark000000',0,' doo')

This is because REPLACE does an implicit conversion to string.
Both produce the same output:
Baby Shark doo doo doo doo doo doo

_ and # are valid aliases. I use them with CROSS APPLY to make it appear the columns it returns are part of the FROM clause e.g.
SELECT TOP 10 number, n2
FROM master.dbo.spt_values v
CROSS APPLY (SELECT number*2 n2) _

I like this when the only purpose of the CROSS APPLY is to compute an expression.
For that matter, using APPLY for computing sub-expressions is a neat way to make your code DRY-er (and shorter).  From what I've seen in execution plans, there is no added cost to this approach.  The compiler figures out you're just computing something and treats it like any other expression.

I find cross apply to long, it is really hard to find a useful situation using cross apply without  finding another shorter method

OK -- shorten the example given above!

SELECT TOP 10 number, number*2 n2
FROM master.dbo.spt_values v

I mean, keeping the join.  By the way, once you build xml queries, CROSS APPLY can become the only way to do it, since there may be no columns in a subquery do do a join on.

Subselect is shorter than cross apply: SELECT top 10*
FROM(SELECT number n, number*2n2 FROM master..spt_values)x

XML queries doesn't need to contain cross apply. At least I can't think of an example. Besides XML queries are usually not used for golfing

source: Stack Exchange

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

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

sort: votes


text:
Aeroplane sitting plan
An airlines company has several planes of the same type.Each plane has a seating capacity of 24 X 3 rows and 8 seats in each row split has shown.
1 [a] [b] [c] [d] [e] [f] [g] [h]
2 [a] [b] [c] [d] [e] [f] [g] [h]
3 [a] [b] [c] [d] [e] [f] [g] [h]

If 4 people book-allocate 4 seats in middle row.Else 2 on the right
   and 2 on the left.
if 3 people book- id middle section is
   empty,allocate there continuously.Else go to next row middle section.
if 2 people book-allocate the edge seats.
if 1 person has booked -then allocate whatever free seat available.

eg-
input 4
output-1c 1d 1e 1f
input-3
output- 2c 2d 2e
input-2
output-1a 1b.

The "split as shown" doesn't show. The allocation rules seem very incomplete. And the scoring can only be one of code-golf, fastest-code (in which can you need to say how measured, and the problem doesn't scale enough for measurement to really be practical in any case), or code-challenge (which means that you have a fairly unique scoring system, and need to explain it in detail).

This question has potential but it's really confusing at the moment. Plane seats normally have numbers from front to back and letters from left to right. Is this the shortest widebody plane in the world, with only three rows but 8 seats in each? Or does it have "24x3"=72 rows?. From the rules and examples it seems there are aisles in the normal place for an 8 seat wide plane: ab-cdef-gh but they are not shown. The allocation rules need improvement too. I think the rule for 4 people is: allocate 4 seats in middle block. Otherwise 2 on the right and 2 on the left of the aisle.

And what do you do if you can't find room for 4, 3 or 2 people by your rules? Error? Allocate them anywhere? What if there is no room left at all? If I have to put 4 people on the outer seats, do they have to be in the same row? Can I assume that I'll never get any other input than one of the four valid numbers?

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


text:
Calculate cell-phone keypresses
Your task is to calculate the total number of key-presses required to enter a given text on an old cellphone.
The keymaps are:
1:1
2:abcABC2
3:defDEF3
4:ghiGHI4
5:jklJKL5
6:mnoMNO6
7:pqrsPQRS7
8:tuvTUV8
9:wxyzWXYZ9
0:<space><newline>0

To type exaMPle TExt 01 , you would press 33 99 2 6666 77777 555 33 0 8888 33333 99 8 0 <a 1-sec pause here in real life but we'll ignore it>000 1 for a total of 37 keypresses.
The * key brings up a map of special characters:
.,'?!
"-()@
/:_;+
&%*=<
>£€$¥
¤[]{}
\~^¡¿
§#|`

with the first one (.) highlighted. You can move to highlight the required character using rectangular navigation keys and it takes another keypress to select.
So to insert $, you would press *↓↓↓↓→→→<select> i.e. a total of 9 key-presses.

Input will be from a file called source placed in the current directory/directory of your program.
EDIT: Per requests in comments, I'm adding STDIN as a valid input method.  Apologies for changing the spec after receiving answers.
You must output Total key presses <total_keypresses>
If the input file contains any character not in the given keymap, then your program must output Invalid character <character> in source and exit.

In short, the input and output of your program must resemble that of this(ungolfed) python script:
# This Python file uses the following encoding: utf-8
from __future__ import print_function
import sys

general_dict = { '1':1,
                 'a':1, 'b':2, 'c':3, 'A':4, 'B':5, 'C':6, '2':7,
                 'd':1, 'e':2, 'f':3, 'D':4, 'E':5, 'F':6, '3':7,
                 'g':1, 'h':2, 'i':3, 'G':4, 'H':5, 'I':6, '4':7,
                 'j':1, 'k':2, 'l':3, 'J':4, 'K':5, 'L':6, '5':7,
                 'm':1, 'n':2, 'o':3, 'M':4, 'N':5, 'O':6, '6':7,
                 'p':1, 'q':2, 'r':3, 's':4, 'P':5, 'Q':6, 'R':7, 'S':8, '7':9,
                 't':1, 'u':2, 'v':3, 'T':4, 'U':5, 'V':6, '8':7,
                 'w':1, 'x':2, 'y':3, 'z':4, 'W':5, 'X':6, 'Y':7, 'Z':8, '9':9,
                 ' ':1, '\n':2, '0':3
                }

special_chars = ['.',',',"'",'?','!','"','-','(',')','@','/',':','_',';','+','&','%','*','=','<','>','£','€','$','¥','¤','[',']','{','}','\\','~','^','¡','¿','§','#','|','`']
for x in special_chars:
    general_dict[x]=(special_chars.index(x)/5) + (special_chars.index(x)%5) + 2

key_press_total = 0
with open('source') as f: # or # with sys.stdin as f:
    for line in f:
        for character in line:
            if character in general_dict:
                key_press_total+=general_dict[character]
            else:
                print('Invalid character',character,'in source')
                sys.exit(1)

print('Total key presses',key_press_total)

This is code-golf, shortest program in bytes wins.

Shameless disclaimer: I made this challenge to have translations of the above python script in different languages which will be used to score this challenge in the sandbox.

Should we error and exit immediately or when the invalid character is encountered?

@nyuszika7h It's up to you, but you must print what invalid character that was. Suppose there are 10 invalid characters in source, you can select any one of them, print that that character is invalid and exit. It doesn't need to be the first occurrence of an invalid character.

The input requirement is a shame. File I/O is insanely expensive in some languages and entirely impossible in others.

If you were to allow more free-form IO, I have a J solution of 171 chars, who's sha1 hash is 1ce5a2fdd0316e37c0a07d151d02db766a3adbb7.

Does ValueError: invalid literal for int() with base 10: count as exiting with an invalid char?

@Dennis Allowed STDIN

@TheDoctor No, sorry.

@user80551 gives up

@TheDoctor It wasn't much as "giving up" as me seeing open requests to change the spec about 15 mins ago

I suppose it not okay to just ignore invalid characters?

@ɐɔıʇǝɥʇuʎs See third bullet point.

GolfScript, 219 characters
Basic approach using a lookup table:
"Total key presses "0@1/{"1adgjmptw °behknqux\n.°cfilorvy0,\"°ADGJMsTz'-/°BEHKNPUW?(:&°CFILOQVX!)_%>°23456R8Y@;*£¤°SZ+=€[~°79<$]^§°¥{¡#°}¿|°`°".2$?)\1$<"°"/,{"Invalid character  in source"18/*puts'"#{''exit}"'+~}if\;+}/

Try here.

Nicely done :) Delphi sucks at this lol.. just finished mine and im at 459 xD need to improve!

Input needs to be from a file named source , not STDIN

To read from file, borrow from ruby: "#{File.read('source')}"

@Quincunx You can drop the parentheses from that: "#{File.read'source'}"

You can keep this as it is, I allowed STDIN now.

Correct me if I'm wrong, but the backslash seems to be missing from your lookup table, and some characters  are assigned an incorrect value (e.g. ~).

Ruby 2.0, 232
$.-=~(%W[1adgjmptw\s
behknqux.\n
cfilorvy0,"
ADGJMsTz-'/
BEHKNPUW?(:&
CFILOQVX!)_%>
23456R8Y@;*£¤
SZ+=€[\\
79<$]~§
¥{^{#
}¡|
¿`].index{|s|s[$c]}||$><<"Invalid character #$c in source"&exit)while$c=$<.getc
puts"Total key presses #$."

Very simple encoding scheme so far: over 75% of the characters are used for string/array literals ...

PHP, 711 708 676 characters (reading from STDIN now)
<?php $message=iconv("UTF-8","CP1252",fread(STDIN,1024));@$s=str_split;$special=iconv("UTF-8","CP1252",'.,\'?!"-()@/:_;+&%*=<>£€$¥¤[]{}\~^¡¿§#|`');$z=0;foreach($s($message)as$l){$a=ord($l);$b=$a;if($a==13)continue;($a>114||($a>82&&$a<91))&&$a--;$w=$a<58?($a-48):($a<91?($a-64):($a-96));$y=($a<58?1:($w%3?$w%3:3));$a<91&&$y+=3;$a<58&&$y=7;if($a==55||$a==57)$y=9;if($b==115||$b==122)$y=4;if($b==90||$b==83)$y=8;if(($b>79&&$b<83)||($a>85&&$a<89))$y++;($a==32||$a==49)&&$y=1;$a==10&&$y=2;$a==48&&$y=3;$u=array_search($l,$s($special));if($u!==false){$y=2+floor($u/5)+$u%5;}$z+=$y;if(($a<32||$a>127)&&$a!=10){echo"Invalid character $l in source";exit();}}echo"Total key presses $z";

My first golf so far :)
Wanted to try a rather unconventional approach. Instead of having a list of every character and how many clicks are needed to create it, I am using the character's ASCII values and calculate their required keypresses. Thought it would spare me some characters first, now I think it's even longer than an array-approach.
My main problem are the keys 7 and 9, which have 4 letters, instead of 3. Therefore I needed to create a couple of fallbacks, which blew my code up by almost 200 characters.
Ungolfed version
<?php
@$source = source;
$h = fopen($source, @r);
$message = iconv("UTF-8", "CP1252", fread($h, filesize($source)));
@$split = str_split;
$special = iconv("UTF-8", "CP1252", '.,\'?!"-()@/:_;+&%*=<>£€$¥¤[]{}\~^¡¿§#|`');
$count = 0;
foreach ($split ($message) as $character) {
    $ascii = ord($character);
    $helper = $ascii;
    if ($a == 13) continue;
    ($a > 114 || ($a > 82 && $a < 91)) && $ascii--;
    $key = $ascii < 58 ? ($a - 48) : ($a < 91 ? ($a - 64) : ($a - 96));

    $presses = ($a < 58 ? 1 : ($key % 3 ? $key % 3 : 3));

    // This part uses a lot of (probably unnecessary or still optimizable) fallbacks
    // for those characters, that are on "4-letter-keys"
    $ascii < 91 && $presses += 3;
    $ascii < 58 && $presses = 7;
    if ($a == 55 || $a == 57) $presses = 9;
    if ($helper == 115 || $helper == 122) $presses = 4;
    if ($helper == 90 || $helper == 83) $presses = 8;
    if (($helper > 79 && $helper < 83) || ($a > 85 && $a < 89)) $presses++;
    $ascii == 32 && $presses = 1;
    $ascii == 10 && $presses = 2;
    $ascii == 48 && $presses = 3;
    $ascii == 49 && $presses = 1;

    $key = array_search($l, $split($special));
    if ($key !== false){
        $presses = 2 + floor($key/5) + $key % 5;
    }

    $count += $presses;
    if ($a < 32 && $a > 127 && $a != 10) {
        echo "Invalid character $l in source";
        exit();
    }
}
echo "Total key presses $count";

I assume there's still a lot of room for improvement, but I'm pretty happy with this.
Another bad thing is the required use of iconv() for the list of special characters. Some of these (€, ¥, ...) are not natively supported by PHP.

€¥,etc are not ascii characters, that's why my python script declares the utf-8 encoding. That is a special comment interpreted by python.

utf8_decode would work fine for every character except of €. That's why I had to use iconv instead. My code doesn't calculate these special characters like it does with normal characters, as they're not in order and I can't reliably work with their respective ASCII values. It's using a normal list for them.

Python 3, 239 characters
s='1adgjmptw 1behknqux\n.1cfilorvy0,"1ADGJMsTz\'-/1BEHKNPUW?(:&1CFILOQVX!)_%>123456R8Y@;*£¤1SZ+=€[\\179<$]~§1¥{^#1}¡|1¿`'
print('Total key presses',sum(s[:s.find(c)+1].count('1')or exit('Invalid character %c in source'%c)for c in input()))

CJam, 207 bytes
q:Q{" dptgwj1am hxk
.bnequ  ,0flco\"rviy    DT'/GsJz-AM (HP?KW&:BNEU    LXCO_>FV!%)IQ   48@3;*26R¤£5Y   €\+S[Z= $<§7~9] #{^¥ |¡}    `¿"'    /{1$#W>\}%1#)}%_0#){"Invalid character "Q@0#=" in source"}{:+"Total key presses "\}?

This program has 207 characters. With the appropriate encoding (Windows-1252), it fits in 207 bytes.
Note that Stack Exchange converts tabs (which I use as delimiter in the lookup table) into spaces, so you can't copy and paste the above code.
Usage
Windows-1252 encoding
$ base64 -d > keys.cjam <<< cTpReyIgZHB0Z3dqMWFtCWh4awouYm5lcXUJLDBmbGNvXCJydml5CURUJy9Hc0p6LUFNCShIUD9LVyY6Qk5FVQlMWENPXz5GViElKUlRCTQ4QDM7KjI2UqSjNVkJgFwrU1taPQkkPKc3fjldCSN7XqUgfKF9CWC/IicJL3sxJCNXPlx9JTEjKX0lXzAjKXsiSW52YWxpZCBjaGFyYWN0ZXIgIlFAMCM9IiBpbiBzb3VyY2UifXs6KyJUb3RhbCBrZXkgcHJlc3NlcyAiXH0/
$ wc -c keys.cjam
207 keys.cjam
$ echo 'Hello, world!' | LANG=en_US.CP1252 cjam keys.cjam; echo
Total key presses 39
$ echo 'á' | LANG=en_US.CP1252 cjam keys.cjam; echo
Invalid character á in source

UTF-8 encoding
$ base64 -d > keys.cjam <<< cTpRezpDIiBkcHRnd2oxYW0JaHhrCi5ibmVxdQksMGZsY29cInJ2aXkJRFQnL0dzSnotQU0JKEhQP0tXJjpCTkVVCUxYQ09fPkZWISUpSVEJNDhAMzsqMjZSwqTCozVZCeKCrFwrU1taPQkkPMKnN345XQkje17CpSB8wqF9CWDCvyInCS97MSQjVz5cfSUxIyl9JV8wIyl7IkludmFsaWQgY2hhcmFjdGVyICJRQDAjPSIgaW4gc291cmNlIn17OisiVG90YWwga2V5IHByZXNzZXMgIlx9Pw==
$ wc -cm keys.cjam
209 217 keys.cjam
$ echo 'Hello, world!' | LANG=en_US.UTF8 cjam keys.cjam; echo
Total key presses 39
$ echo 'á' | LANG=en_US.UTF8 cjam keys.cjam; echo
Invalid character á in source

JavaScript (E6) 291
Edit
Shell version, using spydermonkey shell. Read from a 'source' file, write to sdtout
z=t=0,[...read('source')].map(c=>t-=~((i=".\"/&>Â¤\\Â§,-:%Â£[~#'(_*â‚¬]^|?);=${Â¡`!@+<Â¥}Â¿".indexOf(c))<0?(p="0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])?p.search(/\d/):z="Invalid character "+c+" in source":i%8-~(i>>3))),print(z||"Total key presses "+t)

First try, works in FireFox console using popup for input and output
P=m=>(z=t=0,[...m].map(c=>t-=~((i=".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c))<0
?(p="0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])
?p.search(/\d/):z="Invalid character "+c+" in source":i%8-~(i>>3))),z||"Total key presses "+t);
alert(P(prompt()))

Readable
P=m=>(
  z=t=0,
  [...m].map(
    c=>t-=~(
      (i = ".\"/&>¤\\§,-:%£[~#'(_*€]^|?);=${¡`!@+<¥}¿".indexOf(c)) < 0
      ? (p = "0\n 9ZYXWzyxw8VUTvut7SRQPsrqp6ONMonm5LKJlkj4IHGihg3FEDfed2CBAcba10".split(c)[1])
        ? p.search(/\d/)
        : z="Invalid character "+c+" in source"
      : i%8 - ~(i>>3)
    )
  ),
  z||"Total key presses "+t
);

VBScript 435
Does not support non-ASCII chars. I was pretty far along with my code so I thought I'd post it for reference. I don't think anyone else used this approach.
i=inputbox(i)
a=SPLIT("1 abcABC2 defDEF3 ghiGHI4 jklJKL5 mnoMNO6 pqrsPQRS7 tuvTUV8 wxyzWXYZ9 0")
a(9)=" "+vbLf+"0"
b=SPLIT(".,'?! ""-()@ /:_;+ &%*=< >£€$¥ ¤[]{} \~^¡¿ §#|` x x")

for o=1 to len(i)
n=0
    for x=0 to 9
        for c=1 to 10
            d=mid(i,o,1)
            IF n=0 AND mid(b(x),c,1)=d THEN n=c+x
            IF mid(a(x),c,1)=d THEN n=c
        next
    next
    z=n+z
    IF n=0 THEN EXIT FOR
next
o="Total key presses "+cstr(z)
IF n=0 THEN o="Invalid character "+d+" in source"
msgbox o


text:
Detect the newest file and pass it to a process
Challenge
Detect the newest file in a specific folder and pass it as an argument to another process. The first argument to your program will be the folder, and the second argument will be the full path to the process.
Please specify the platform(s) your code works on.
Examples
Windows
newestfile "C:\Public_domain_movies\" "C:\Mplayer\mplayer.exe"

Linux
./newestfile /home/user /bin/ls

@Geobits I expect the most recent timestamp no matter what, I removed the misleading part.

Actually I think it could have added a very interesting twist to have to figure out when the program was last run.

@Ventero Yes, no recursive scanning just the specified folder

The most recently modified file or the most recently created file?

@Joey
The most recently modified

Zsh - 15
Only tested on Linux, but it should work on other platforms too.
$2 $1/*(.om[1])

Windows, PowerShell, 35
&$args[1](ls $args[0]|sort *w*)[-1]

Linux, Ruby, 52 characters
exec$*[1],Dir[$*[0]+"/*"].sort_by{|a|test(?M,a)}[-1]

I'm not sure if I undestood the specifications correctly, so if this doesn't work as intended, please let me know. I only tested this on Linux, but in  theory it should run on Windows, too.

linux - bash+sed - 18 bytes
$2 `ls -t $1|sed q`

Does not work if the arguments contain blanks.

Windows, cmd, 54
for /f "delims=" %%A in ('dir/b/o-d %1')do %2 %%A&exit

Caveats:

Closes the current shell session
Will consider directories (as do most other solutions)

You don't need the options string "delims="

Well, have fun with file names with spaces, then.

This doesn't work if the file has spaces in it

What if you add /x parameter for short names? FOOBAR~1.TXT

@nderscore: Not every file has to have a short name.


text:
Rotate 2D Array
Given an input of a 2 dimensional array of integers, rotate the array 90 degrees clockwise.
It should work for rectangular arrays of all sizes and proportions.
The rotated array should be printed at the end of the program.
Example:
Input:
[[0,1,2,3,4,5],

 [6,7,8,9,0,1],

 [2,3,4,5,6,7],

 [8,9,0,1,2,3]]

Output:
[[8,2,6,0],
 [9,3,7,1],
 [0,4,8,2],
 [1,5,9,3],
 [2,6,0,4],
 [3,7,1,5]]

Do not rely on the patterns in the arrays above, they were used just for explanation purposes. Expect the arrays to be randomly generated.
Scoring
Every character in the program counts as 1 point.
The first line of the program can store the array as a variable for 0 points. The array must be stored as-is without any changes made to it until after this first line.
If your code can rotate other multiples of 90 degrees, -15 points from your score. If this value must be stored, it can be done so at the beginning of the program for 0 points. It can be supplied in the same way that the array is supplied.
Lowest score wins!

Will the arrays only hold numbers? Will every line in the array have the same length? Should we print the result, or output it by some other method?

@xnor edited the post

Can "user input" be stored in a variable? Otherwise for Python, simply taking input() takes 7 characters, so there's no reasonable way to benefit from the bonus.

@xnor Edited the rules. It can be created like the array now, and does not necessarily require it as input.

related: http://codegolf.stackexchange.com/questions/32626/simulate-rotating-a-board

Another very closely related question: http://codegolf.stackexchange.com/questions/26541/rotate-a-two-dimensional-list-by-45-degrees

Python 2 (17=32-15) (19)
No input (19):
s = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]
print zip(*s[::-1])

Taking input in t, the number of rotations (17=32-15)
s = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]
t=3
exec"s=zip(*s[::-1]);"*t
print s

J 11 9 7 -10 = -3
|:&|.^:

Edit: Changing argument order gets rid of the parentheses.
Edit 2: Reducing by 2 characters by swapping rows instead of columns, and inverting the order of operations.
Adverb taking the multiple of 90 degrees, then the array to rotate.
NB. needs assigning to a variable or parentheses to separate from the arguments.
rot =: |:&|.^:
]a =: i. 4 4
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

    |:&|.^: 1 a
12  8 4 0
13  9 5 1
14 10 6 2
15 11 7 3
   |:&|.^: 2 a
15 14 13 12
11 10  9  8
 7  6  5  4
 3  2  1  0
   |:&|.^: 3 a
3 7 11 15
2 6 10 14
1 5  9 13
0 4  8 12
   |:&|.^: 4 a
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

Try it yourself at tryj.tk
As a little extra, this extends to any rank at the cost of 1 char, when slightly changed to
rot =: (|:|.)^:

This way it takes the permutation order for the transpose to the left, and the number of flips and the array to the right. Depending on the axis permutation requested, you get back after a number of flips: flipping two axis makes you come back after 4 turns, shifting the axis makes you come back after 2 times the rank of the array.
       ]b=:i.2 3 4
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23
   0 2 1 (|:|.)^: 1 b
12 16 20
13 17 21
14 18 22
15 19 23

 0  4  8
 1  5  9
 2  6 10
 3  7 11
   1 2 0 (|:|.)^: 6 b
 0  1  2  3
 4  5  6  7
 8  9 10 11

12 13 14 15
16 17 18 19
20 21 22 23

The scoring for this one might be a little off. rot=:|."1&|:^: and 1 rot a would come out to 20-10 = 10, no?

The function itself is just the |."1&|:^: and could be used in verb frazes as such. Since it's not specified, I figured the function alone needs counting. I'll be fair and include the parens.

I was going to post this exact same answer. +1

Javascript (ES6) 51 48 45
Alerts each row of the new rotated array in sequence.
a = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]

for(i in a[0])alert(a.map(j=>j[i]).reverse())

You can use a.map(j=>j[i]) instead of [j[i]for(j of a)] to save 3 more characters ;)

@core1024 good call!

Ruby — 34 - 15 = 19
m = [[0,1,2,3,4,5],
     [6,7,8,9,0,1],
     [2,3,4,5,6,7],
     [8,9,0,1,2,3]]
n = 1

n.times{m=m.reverse.transpose};p m

Haskell — 55 - 15 = 40
let m = [[0,1,2,3,4,5],[6,7,8,9,0,1],[2,3,4,5,6,7],[8,9,0,1,2,3]]
let n = 1 :: Int

import Data.List
print$(iterate(transpose.reverse)m)!!n


text:
Control Your Computer's Fan Speed
The objective of this question is to create a program that pushes your computer's internal fan speed to its maximum RPM.  Upon exiting the program, your fan should return to the normal operating RPM.
Rules:

You may not perform a CPU intensive task in order to modify the
fan's speed.
Exiting the program may be via user input, a timeout period, or a response to a SIGTERM or SIGEXIT signal.
Avoid the standard loopholes.

How should the program exit? Timeout? User input? Signal?

@GregHewgill No requirement is put in place on that, whatever takes the fewest number of characters would make an optimal solution however.

Then probably the fewest number of characters would be a program that never exits, since exiting is not actually required.

@GregHewgill The program can run infinitely, sure.  But if I kill the program from outside the sandbox in which it runs, then the fan should return to the normal operating RPM.

See, that's what I was asking about. :) So is responding to signals a requirement? Which signals? Signal 9 on a POSIX platform might be challenging to react to.

@GregHewgill It is not a requirement.  Let your execution environment manage the handling of SIGTERM, SIGSTOP and the like.

Now, I'm not an expert on this, never actually implemented code to control your own hardware, but wouldn't "Max" fan speed differ from person to person?  If I write code to max my own fan speed, but your fan can do better, have I still won?

Do you have good reason to believe that this is possible?

@PeterTaylor I mean, it's possible given a pre-installment of lm_sensors, and then to run a bash script, but I don't know the rules about installing anything to help your program :/

@user3334871, controlling the fan speed is possible. The bit I'm dubious about is resetting it to normal when the program is killed without any opportunity to react.

huge side-effect as a primary target - not a pure programming puzzle.

I suspect very strongly that in order to meet this requirement, the program would need to be closed in a controlled manner. As far as I'm aware, this is no way to capture an unmanaged process termination.

"computer's internal fan speed", which fan?

Wouldn't a signal handler help?  Or a process that monitors the original process?

OSX + Bash + smcFanControl, 91 bytes
This relies on the third-party smcFanControl suite to do the hard work and is therefore more of a proof-of-concept than a serious answer.  Real answers could pick apart the smcFanControl source code and do this without third-party help.
smcFanControl.app is assumed to be installed in /Applications.
p=/Ap*/smcFan*/C*/R*/smc\ -k # Path to CLI utility
f()($p'FS! ' -w000$1)        # function to set fan mode
f 3                          # Set fan speeds to "forced" mode
eval $p\ F{0,1}"Tg -w5DC0;"  # Set fan 1 and 2 to 6000 RPM target speed
read                         # wait for keyboard input
f 0                          # Return fans to "auto" mode

Comments added for explanation, but not included in score.

depending on your entry the whole point of this contest is to find an utility that has the shortest name and then control the fan with it. how clever one must have to be...
and this doesn't mean i don't like your answer. i belive it's already a winner. but the whole challenge is pointless.

DigitalTrauma found a program that can be controlled like that. What if i find (or make but okay, its a loophole) an utility that does the same if I type maxfan?

@bebe All good points.  See my edit.

basically Outsourcing the answer

GLXGEARS - 8bytes
First thing I thought of was yes, or yes in parallel. As we are not allowed to use the CPU to control the speed, let's use the GPU:
glxgears

Reboot, 6 bytes
reboot

Just after a boot, the fans start spinning at max rpm because the power is turned on to the fan, before the BIOS loads any real time controllers that will base the speed of the fan on the temperature of the processor. This also keeps the processor from getting excessively hot if you were to try the alternative... which would be to keep the fan off until those controllers were loaded and basing the fan speed on processor temp. More of a safeguard than anything. The processor is starting to work the moment you turn the computer on, but the BIOS still needs time to load. https://superuser.com/a/427723/246895
(Does not work on every pc, but is confirm the OP)

The program exits before the reboot actually occurs, so the fan spin-up happens after program exit. This is not at all in line with the spec.

@PeterTaylor Completely true.


text:
Give me the Gray Code list of bit width n
The Gray Code is a sequence of binary numbers of bitwidth n where successive numbers differ only in one bit (see example output).
Reference
Example input:
3

Example output:
000
001
011
010
110
111
101
100

Notes:

This question seems to have a dupe but it's not, for that question is not a code-golf, and it demands different output. It will help to check out it's answers, though.
You may assume a variable n which contains the input.

Considering that the other question is a fastest-code code-challenge without an objective winning criterion (fastest measured how?), I propose closing the other and reopening this one.

I agree with @dennis and therefore I have upvoted the following unpopular answer on the original question. "If the answer you are looking for is strictly a fast result, then if you declare an array (of the gray codes)..." However the original question aready has a 7-character and a 4-character answer so I don´t see much room for improvement. Therefore I am not casting a reopen vote at present.

It's awfully similar to Traverse all numbers with only one bit flip per step though...

The earliest Gray code question isn't great, but it already has answers which are fundamentally the same as the answers which this question wants, and which are not likely to be improved. I think it would have made more sense to leave this one closed and change the other one to a code golf.

JavaScript (77)
for(i=0;i<1<<n;)alert((Array(n*n).join(0)+(i>>1^i++).toString(2)).substr(-n))

More browser-friendly version (console.log and prompt()):
n=prompt();for(i=0;i<1<<n;)console.log((Array(n*n).join(0)+(i>>1^i++).toString(2)).substr(-n))

Maybe this array...join is overkill for(i=0;i<(l=1<<n);i++)console.log((i^(i>>1)|l).toString(2).slice(1));

Python 2 (47)
for i in range(2**n):print bin(2**n+i/2^i)[3:]

The expression i/2^i for the i'th gray code number is from the this answer. To add leading zeroes that pad to length n, I add 2**n before converting to a binary string, creating a string of length n+1. Then, I truncate the leading 1 and number type prefix 0b with [3:].

APL (Dyalog Classic), 11 bytes
2≠/0,↑,⍳n⍴2

Try it online!
n⍴2 is 2 2...2 - a vector of n twos
⍳ is the indices of an n-dimensional array with shape 2 2...2 - that is, a 2×2×...×2 array of nested vectors. As we use 0-indexing (⎕IO←0), those are all binary vectors of length n.
, flatten the 2×2×...×2 shape, so we get a vector of 2n nested binary vectors
↑ "mix" - convert the vector of vectors to a solid 2n×n matrix. It looks like this:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

0, prepends zeroes to the left of the matrix
2≠/ computes the pairwise (2) xor (≠) along the last dimension (/ as opposed to ⌿); in other words, every element gets xor-ed with its right neighbour, and the last column disappears
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0

would you mind adding a quick explanation?

@Jonah sure, added

very clever, thx

K (ngn/k), 10 bytes
+~0=':!n#2

Try it online!

the odometer overload of ! took me by surprise. very cool !

Japt, 14 12 bytes
2pU Ç^z)¤ùTU

Shaved off two bytes thanks to ETHproductions.
Try it online!

Perfect example of how ù is used. Since N.z(n) is integer division with default arg = 2, you can save two bytes with 2pU Ç^z)¤ùTU: Try it online!

@ETHproductions Thanks, I still miss the default args every now and then. Very handy, thanks a lot.

F# (86) (84) (80)
for i in 0..(1<<<n)-1 do printfn"%s"(Convert.ToString(i^^^i/2,2).PadLeft(n,'0'))

This could probably be improved further.
Also note, if run in FSI, you'd need to open System;; first. If you'd like to avoid importing that, (and if you don't care about the order in which the values are printed) you can use this 82-character version:
for i in 0..(1<<<n)-1 do(for j in 0..n-1 do printf"%i"((i^^^i/2>>>j)%2));printfn""

PowerShell(168)
Amateur PowerShell'r back with another attempt at golF! Hope you don't mind! At the very least these questions are fun, and a learning experience to boot. Assuming n has been inputted, we have:
$x=@('0','1');for($a=1;$a-lt$n;$a++){$x+=$x[($x.length-1)..0];$i=[Math]::Floor(($x.length-1)/2);0..$i|%{$x[$_]='0'+$x[$_]};($i+1)..($x.length-1)|%{$x[$_]='1'+$x[$_]}}$x

Because the PowerShell I'm working with is only 2.0, I can't use any bit shifting cmdlets which might make for shorter code. So I took advantage of a different method described in the question source, flipping the array and adding it to itself, appending a 0 to the front of the top half, and a 1 to the bottom half.

Python - 54
Based off of an algorithm from the reference given in the challenge:
for i in range(2**n):print'{1:0{0}b}'.format(n,i>>1^i)

Ungolfed:
# For each of the possible 2**n numbers...
for num in range(2**n):
    gray = num>>1 ^ num

    # Print in binary and pad with n zeros.
    print '{1:0{0}b}'.format(grey)

Ruby — 42 39
Same algorithm, different language:
(2**n).times{|b|puts"%0#{n}b"%(b>>1^b)}

Switching from #map to #times as @voidpigeon suggests saves 3 characters.

Instead of [*0...2**n].map you can use (2**n).times.

J, 24 bytes
[:#:@(22 b.<.@-:)[:i.2^]

Try it online!
Straightforward implementation of the "XOR with it's own floored half" algorithm.  Note that 22 b. is XOR.

MATL, 10 bytes
W:qt2/kZ~B

Try it online!
The good old "XOR n with n>>2" method.
W - compute 2^(input) (gets input implicitly)
:q - create range of numbers from 0 to 2^n - 1
t  - duplicate that range
2/k - MATL doesn't have bitshift, so divide (each number) by 2 and floor
Z~  - elementwise XOR that result with the original 0 to 2^n - 1 array
B   - convert each number in the result to binary
(Implicitly display output.)

K (ngn/k), 25 bytes
{(x-1){,/0 1,''|:\x}/0 1}

Try it online!

|:\xis "reverse scan x". applies reverse to x until the output equals the input, and shows each iteration. returns (0 1; 1 0) on first pass.
0 1,'' is "0 1 join each each". joins a 0 to each value of 1st elem, and 1 to each value of 2nd elem, giving ((0 0; 0 1);(1 1; 1 0)) on first pass
,/ is "join over", and flattens to list.
(x-1){...}/0 1is "apply {func} over 0 1 x-1 times". takes the output of the last iteration as input

APL (22)
{(0,⍵)⍪1,⊖⍵}⍣(n-1)⍪0 1

This outputs a n-by-2^n matrix containing the bits as its rows:
      n←3
      {(0,⍵)⍪1,⊖⍵}⍣(n-1)⍪0 1
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0

Explanation:

{...}⍣(n-1)⍪0 1: run the function n-1 times with initial input the matrix (0 1)T (which is the 1-bit gray code)

(0,⍵): each row of ⍵ with a 0 prefixed,
⍪: on top of,
1,⊖⍵: each row of ⍵ with an 1 prefixed, in reversed order

Jq 1.5, 105 100 bytes
def g(n):if n<2then. else map([0]+.)+(reverse|map([1]+.))|g(n-1)end;[[0],[1]]|g(N)[]|map("\(.)")|add

Assumes N provides input.  e.g.
def N: 3 ;

Expanded
def g(n):  # recursively compute gray code
  if n < 2
  then .
  else map([0]+.) + (reverse|map([1]+.)) | g(n-1)
  end;

  [[0],[1]]                 # initial state
| g(N)[]                    # for each element in array of gray codes
| map("\(.)")|add           # covert to a string

Try it online!

Japt, 10 bytes
³Ç¤ÅÃf_Ê¥U

Try it online!

T-SQL 134
This challenge is asking to return the Cartesian power of {(0),(1)}. This snippet builds the code which would execute the Cartesian product of {(0),(1)} n times.
DECLARE @ int=4,@s varchar(max)='SELECT*FROM's:set @s+='(VALUES(0),(1))t'+ltrim(@)+'(b)'if @>1set @s+=','set @-=1if @>0goto s exec(@s)

It's asking for the cartesian power in a specific order. Does your code account for that?

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