text:
Draw a bowling formation
Your goal is to display ASCII art of a formation in ten-pin bowling where only some of the pins remain. Fewest bytes wins.
The tens pins are in a triangular formation:
O O O O
 O O O
  O O
   O

Pins are labelled from 1 to 10 as:
7 8 9 10
 4 5 6
  2 3
   1

Drawing pins as O and missing pins as ., the formation 1 3 5 6 9 10 is:
. . O O
 . O O
  . O
   O

Input:
A space-separated string that lists a nonempty subset of the numbers 1 though 10 in order.
Output:
Print the corresponding formation or output it as a string with linebreaks.
The formation should be flush with the left of the screen. Any whitespace is fine as long as the visible image is correct. Empty lines before and after are fine too.
Test cases:
>> 1 2 3 4 5 6 7 8 9 10

O O O O
 O O O
  O O
   O

>> 7 10

O . . O
 . . .
  . .
   .

>> 3 5 7 9 10

O . O O
 . O .
  . O
   .

>> 1

. . . .
 . . .
  . .
   O

Can you guarantee that there will be at least one pin? It will save characters for me if I can choke on empty input.

@undergroundmonorail It's already guaranteed: "nonempty subset"

I totally missed that, thanks :)

[code-bowling]? :P

brainfuck - 617 616 604 bytes
+>>>>,[>++++[<-------->-]<[>>>>],]<<<<[>+<<+<+>>-]<[>+<-]+<+<<[>+>-<<-]>[<+>-]>[,+++++[>+++++<-]>>[<->-]<[>>>>>[>>>>]+[<<<<]<-]>>[<+>-]<<<]>[>>[,<]<<+++++++++<]<<<[-[+>>-<]>[>>[<+<+>>-]<<<<[>+>-<<-]>[<+>-]>[<<[<<<<]>>>>[[<<<<+>>>>-]>>>>]<<<<+>>-]>[>+<-]]<<<[-[+>]+<<<<]>>>>-<<<<<]>>>>>+++++[>----<-]>->[<+>>+<-]<[<<<[<<<<]+[>>>>]<-]>>[<+>-]<[<<<<]>>>++++[<-------->-]>[-[,+++>]+>>>[<<<->>]>]<<<<<[>-]>[>>]>>+[<++++[<++++++++>-]<]>>[+++++++++++++>>>>]<<<<----<+++[<<+<<[<<+<<]+[>>>>]<<<<-]<<<<[-<<<<]>[.,>>]<<<<<[<<<<]<++++++++++<<.<+<<+<<+<<+<<+<[.,>>]<<<<<[<<]>++++++++++<+<<+<<+<..<+<[.,>>]<[<<]<...<<.

This took me the better part of two days. I think it was worth it. There's probably parts that can be golfed more by changing what cell something is stored in or whatever, but right now I'm just happy I got it working.
This program would have to be completely different if the question didn't specify that the input would be sorted. The way this works is by constructing a list of 10 pins around the ones that are input. That's kind of confusing but maybe this will explain it better:
If you input these pins:           [2, 3, 6, 8, 9]
First, the program does this:      [2, 3, 6, 8, 9] + [10]
Then this:                         [2, 3, 6] + [7] + [8, 9, 10]
Then this:                         [2, 3] + [4, 5] + [6, 7, 8, 9, 10]
Finally, this:                     [1] + [2, 3, 4, 5, 6, 7, 8, 9, 10]
To build this:                     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

While it's doing that, it remembers which of the pins the user put there and which ones it put there. This strategy would be very difficult to use if the input wasn't sorted.
Another thing that the sorting make easier is detection of the number 10. Since brainfuck deals with individual bytes, not "numbers" per se, it could have been a pain in the ass, but the sorted input made it much easier for me to deal with. The reason for that has to do with how I stored data in the program. I take the input one character at time and subtract 32 from the result. If the cell is non-zero after that, I move forward 4 cells. before repeating. This means that I get a non-space byte of input every 4 cells, and I effectively store pins as their number + 16. However, 10 takes two bytes to type, so I had to special case it. If the input wasn't sorted, I'd have to look through the pins, but since it is sorted it will always be the last pin if it appears. I check if the (last byte of input + 1) == (the second last byte of input) and if so, it must be 10. I get rid of the last byte and set the second last one to what my system understands as "10". The characters '1' and '0' don't fit in a single byte, but the number 26 sure does!
Coming up with tricks just to make something work at all is my favourite part of using this language. :)
If you're interested in how this program works in more detail, you can see the program with the comments I used while writing it to make sure I remembered what everything did. Even writing comments in brainfuck is hard, since there's no comment syntax. Instead, every character except those in <[+.,-]> are no-ops. It's easy to introduce bugs by accidentally including . or , in your comments! That's why the grammar is so wonky and semicolons are everywhere.
EDIT: As an example of how easy this is to screw up: I used "non-space" in one of the comments! When I stripped all the non-bf characters from the source, the program I used to do that kept in the -. Luckily it didn't break anything, but now I've removed it to save a byte. :)
EDIT II: It's been a while since I touched this one, haha. In another brainfuck answer on this site, I noticed that I accidentally used a comma in the commented version. Since the input had already been exhausted, it set the current cell to 0 (this is implementation dependant, but in my experience it's the most common behaviour). I fixed the bug, but it got me thinking. The idiomatic way to set a cell to 0 is [-] (roughly while (*p) { *p--; }), which is two bytes longer. Any time all the input has been read, I can use , instead. This saved me 2 bytes in that answer, and 12 in this one!
one flag at the very left; will be important later
+>>>>

all nonspace bytes of input separated by 3 empty cells; pin number `n` stored with value `n` plus 16
,[>++++[<-------->-]<[>>>>],]<<<<

test if last pin is 10
[>+<<+<+>>-]<[>+<-]+<+<<[>+>-<<-]>[<+>-]>

[
    if not: find 10 minus the number it is; put that many placeholder pins (cells with value 1) at the end
    ,+++++[>+++++<-]>>[<->-]<[>>>>>[>>>>]+[<<<<]<-]>>[<+>-]<<<
]>

[
    if so: get rid of '0' byte; convert '1' byte to 26 (10 plus 16)
    >>[,<]<<+++++++++<
]<<<

pointer now sitting on the cell with the second greatest pin that was inputted (ie not a placeholder)

;;;;;;;

[
    check for flag placed at the very beginning of the program; if present: break
    -[+>>-<]>
    [
        find ((pin to our right) minus 1) minus pin to our left
        move all pins left of us 4*(that value) cells and insert placeholder pins
        >>[<+<+>>-]<<<<[>+>-<<-]>[<+>-]>[<<[<<<<]>>>>[[<<<<+>>>>-]>>>>]<<<<+>>-]>[>+<-]
    ]

    find first non placeholder pin to our left
    there has to be one because we haven't hit the flag yet
    <<<[-[+>]+<<<<]>>>>-<<<<<
]>>>>>+

we have now added placeholder pins at the end and in the middle; all that's left is the beginning

subtract 17 from lowest pin and put that many placeholders to the left
++++[>----<-]>->[<+>>+<-]<[<<<[<<<<]+[>>>>]<-]>>[<+>-]

subtract 32 from an empty cell 2 to the left of the lowest pin; will be useful later
<[<<<<]>>>++++[<-------->-]>

placeholder pins have the value 1; real pins have a value somewhere between 17 and 26
normalize it by stepping through and setting every pin with value != 1 to 3 (0's ascii code is 2 higher than period so this will make it easier to print later)
[-[,+++>]+>>>[<<<->>]>]<<<<<[>-]>[>>]>>

start writing 32s across the board; hitting every second cell
that's every pin and the cell 2 to the right of each pin
this is done in such a way that it will only halt if adding 32 to a cell sets it to 0; which is why we subtracted 0 from an empty cell earlier
it will catch us and prevent an infinite loop
+[<++++[<++++++++>-]<]

now write 13 to each pin; this adds up to 46 or 48; which are exactly the ascii values we want
>>[+++++++++++++>>>>]

we happen to have made a 14; turn it into a 10 for a newline
<<<<----

we're so close now; i can taste it
we have a list of 10 pins; each one with the ascii value that needs to be written
we have 32 everywhere because we'll need spaces
we even have a newline

the only problem now is that our list looks like this:
;;;;;;;;;;;;;;;;;;;;;;;;
;;1 2 3 4 5 6 7 8 9 10;;
;;;;;;;;;;;;;;;;;;;;;;;;

and we need to print in this order:
;;;;;;;;;;;;;;;;;;;;;;;;
;;7 8 9 10 4 5 6 2 3 1;;
;;;;;;;;;;;;;;;;;;;;;;;;

it's a pretty simple fix
once we print a pin we obviously don't need to remember it any more
so we simply print the last 4 pins on the list; destroying them on the way
then we print the last 3; which have become the ones we want
then two; then one
<+++[<<+<<[<<+<<]+[>>>>]<<<<-]<<<<[-<<<<]

print pins 7 8 9 10
>[.,>>]

print pins 4 5 6
<<<<<[<<<<]<++++++++++<<.<+<<+<<+<<+<<+<[.,>>]

print pins 3 2
<<<<<[<<]>++++++++++<+<<+<<+<..<+<[.,>>]

print the final pin!! :)
<[<<]<...<<.

Python 2, 108 bytes
def f(x):
 for i in 4,3,2,1:print" "*(4-i)+" ".join(".O"[i*~-i/2-~z in map(int,x.split())]for z in range(i))

Call with f("3 5 7 9 10").
i is the row number, with 4 being the first row and 1 being the last. z is the nth pin on that row, with 0 meaning it's the first pin in the row and i-1 meaning it's the last pin in the row.
The main hack is i*~-i/2-~z, which converts (i, z) -> pin number. For example, (4, 0) -> 7 as pin 7 is the first pin on row 4 (the first row). The derivation goes like this:

We want a function taking i to the first pin on row i, i.e. 4 -> 7, 3 -> 4, 2 -> 2, 1 -> 1. This is satisfied by (i**2-i)/2 + 1, and thus (i**2-i)/2 + 1 + z gives the correct pin number for input (i, z)

Then simplify:

(i**2-i)/2 + 1 + z
  = (i*(i-1))/2 + 1 + z
  = i*~-i/2 + 1 + z
  = i*~-i/2-~z

Pyth, 33 bytes
V4~Z-4N+*dNjdm@".O"}+d-11Zrz7U-4N

Try it online.
The program roughly translates to:
z = input()
Z = 0

for N in range(4):
  Z += 4-N
  print(" "*N + " ".join(".O"[d+11-Z in map(int, z.split())] for d in range(4-N)))

(Thanks to isaacg for tips)

Your Pyth code can be golfed in two ways: V4 is equivalent to FNU4, and rz7 is equivalent to mvkcz\ .

Ahaha thanks. I'm still not used to what there is and isn't in Pyth without having to check the docs all the time.

107 bytes as a full program.

Pyth, 31
V4+*dNjdm?\O}+7+dZrz7\.rN4~Z-N4

Try it here.
V4 sets up a for loop, with N as the variable over [0,1,2,3].
*dN provides the initial spaces, because d is space.
To find the pin locations, it uses +7+dZ - 7 + d + Z.
d is:
0 1 2 3
 1 2 3
  2 3
   3

while Z is 0 in the first line, -4 in the second, -7 in the third and -9 in the forth. This is becasue Z starts as 0, and ~Z-N4 decrements Z by 4, then 3, then 2.
Then, it checks if the pin location is in the input, using }+7+dZrz7. rz7 is the desired pins in list-of-int form.
Then, it creates an O if it was present, and . otherwise. This is space separated, with jd, and printed implicitly.

GNU sed, 75

Saved 6 bytes thanks to @Jordan.

Score includes 1 extra for -r option:
s/^/7 8 9 10\
 4 5 6\
  2 3\
   1 /
:
s/([0-9]+)(.*)\1/O\2/
t
s/[0-9]+/./g

Input via STDIN:
$ echo 3 5 7 9 10 | sed -rf ./bowling.sed
O . O O
 . O .
  . O
   .
$

Try it online.

GNU sed allows empty labels, so you can save two bytes by dropping the ls.

Also if you change 0 to 10 on the line 2, 1/ to 1 / on line 5, and [0-9] to [0-9]+ on lines 7 and 9 you can drop the first line for 4 bytes.

@Jordan Cool - someone already made a tip out of that.  Oh wait ... ;-)

Javascript, 155
First golf, can probably be shorter.
function f(i){q='replace',s='7 8 9 0\n 4 5 6\n  2 3\n   1';alert(s[q](RegExp(i[q]('10','0')[q](/ /g,'|'),'g'),function(a){return a?'O':a})[q](/\d+/g,'.'))}

call with
f('1 2 3 4 5 6 7 8 9 10')
f('1 5 10')
f('')

EDIT
ES6 version, 130
f=i=>{q='replace',s='7 8 9 0\n 4 5 6\n  2 3\n   1';alert(s[q](RegExp(i[q]('10','0')[q](/ /g,'|'),'g'),a=>a?'O':a)[q](/\d+/g,'.'))}

EDIT
ES6 version, 79 fails
f=i=>alert('7890\n 456\n  23\n   1'.replace(/\d/g,a=>i.indexOf(a)<0?'. ':'O '))

ES6 version, 72 77, no alert, just returns
f=i=>'7890\n 456\n  23\n   1'.replace(/\d/g,a=>i.search(a+'\\b')<0?'. ':'O ')

The 79 and 72 are broken, both fail for input 10

@edc65 whoops, thanks, fixed.

Ooh, clever use of word boundary character, I came up with almost the exact same (except using .match). This is the most elegant of them all.

Python 2, 97 94
This uses the translate function, which allows one to make character-for-character substitutions in a string.  Like tr in perl, except much longer to type. I get a list of decimal digits by making a string from 9 to the 99th power.
lambda a:u"7890\n 456\n  23\n   1".translate({ord(n):u'.O'[n+' 'in a+' ']+' 'for n in`9**99`})

Perl 5: 51 (50 + 1 for -p)
Using r flag for s/// which is one of the recent perl 5 additions.
#!perl -p
$_="7890
 456
  23
   1
"=~s!\d!'. '^a
x/$&\b/!egr

CJam, 48 41 bytes
Wow, this got horribly long
"6789345 12  0"S*7/N*[l~]:(s"O"erA,s"."er

Test it here.
Explanation
First we generate the layout:
"6789345 12  0"       "Push this string.";
               S*     "Riffle with spaces.";
                 7/   "Split into substrings of length 7.";
                   N* "Join with newlines.";

This yields
6 7 8 9
 3 4 5
  1 2
   0

And now we replace the digit characters according to the input:
[l~]                 "Read the input and turn it into an array of integers.";
    :(s              "Decrement each number and turn the array into a string of digits.";
       "O"           "Push this string.";
          er         "Character transliteration, replaces the input digits with O.";
            A,s      "Create the string '0123456789'.";
               "."   "Push this string.";
                  er "Character transliteration, replaces all remaining digits with periods.";

"789A456S23SS1":~S*7/N*[l~]'OerB,'.er is a bit shorter.

@Dennis Thanks. I'm not entirely sure if er was autocasting to array back then.

Oh, right. That was implemented in 0.6.4, which is younger than this question. "789A456S23SS1":~S*7/N*[l~]"O"erB,"."er works fine in 0.6.2.

Ruby, 91
x=(1..10).map{|i|i.to_s==$*[0]?($*.shift;?0):?.}
4.times{|i|puts (x.pop(4-i)*' ').center 8}

Simply substitutes the command line arguments with .s and 0s and prints them using a loop of 4 cycles.
Readable version
x = (1..10).map do |i|
  if i.to_s == ARGV[0]
    ARGV.shift
    "0"
  else
    "."
  end
end

4.times do |i|
  row = x.pop(4 - i)
  puts row.join(' ').center 8
end

Pure bash (no coreutils), 85
Simple pattern replacement:
f="7 8 9 0
 4 5 6
  2 3
   1"
a=${@/10/0}
f="${f//[${a// /}]/O}"
echo "${f//[0-9]/.}"

List is input via the command-line args.

CJam, 40 39 bytes
4,Sf*'-A*[q~]{('ot}/3,{)/(\s}%Sf*W%]zN*

I know there is a shorter way, don't have time to figure it out right now.
How it works:
4,Sf*'-A*[q~]{('ot}/3,{)/(\s}%Sf*W%]zN*
4,                                          "Get the array [0,1,2,3]";
  Sf*                                       "Covert each number to that many spaces to";
                                            "get ["", " ", "  ", "   "] array";
     '-A*                                   "String '----------'";
         [q~]                               "Input numbers in an array";
             {    }/                        "For each input number";
              ('ot                          "Put 'o' at the corresponding index";
                    3,                      "Array [0,1,2]";
                      {     }%              "For each of the above number";
                       )                    "Increment the number";
                        /                   "Split the string into pieces of that length";
                         (\s                "Take the first string and join the rest back";
                              Sf*           "Riffle each string in array with space";
                                 W%         "Reverse the array of strings";
                                   ]z       "Zip together the space array and this one";
                                     N*     "Join by new line";

Try it online here

Haskell: 163 160 bytes
This accepts a line of space separated numbers from stdin.
m=map
y?x|x`elem`y="O "|0<1=". "
f y=putStr.unlines.zipWith(++)(m(`replicate`' ')[0..])$m(concat.m(y?))[[7..10],[4..6],[2,3],[1]]
main=getLine>>=f.m read.words

Ungolfed:
layout :: [[Int]]
layout = [[7,8,9,10]
         ,[ 4,5,6  ]
         ,[  2,3   ]
         ,[   1    ]
         ]

indentBy :: Int -> String
indentBy n = replicate n ' '

indentLines :: [String] -> [String]
indentLines
  = zipWith (++)
            (map indentBy [0..])

bowling :: [Int] -> String
bowling pins
  = unlines
  . indentLines
  $ map (concatMap showPlace)
        layout
  where
    showPlace :: Int -> String
    showPlace index
      | index `elem` pins = "O "
      | otherwise         = ". "

parseInput :: String -> [Int]
parseInput = map read . words

main :: IO ()
main = do
  pins <- fmap parseInput getLine
  putStr (bowling pins)

And a bonus:
C: 250 bytes
This version expects its command line arguments to be the list of numbers.
#define w int
main(w
z,char**a){w
b[10]={1,3,2,6,5,4,10,9,8,7};w
q=9;for(w
k=4;k>0;--k){w
i;for(i=0;i<4-k;++i)printf(" ");for(i=0;i<k;++i,--q){w
g=0;w
c;for(w
p=1;p<z;++p){sscanf(a[p],"%d",&c);g|=b[q]==c;}c=g?'O':'.';printf("%c ",c);}printf("\n");}}

APL (35)
⊖4 7⍴'.O'[1+⎕∊⍨⍳10]\⍨17110357⊤⍨28/2

Test:
      ⊖4 7⍴'.O'[1+⎕∊⍨⍳10]\⍨17110357⊤⍨28/2
⎕:
      1 3 5 6 9 10
. . O O
 . O O
  . O
   O

Explanation:

17110357⊤⍨28/2: the 28-bit representation of 17110357:
      4 7⍴17110357⊤⍨28/2
0 0 0 1 0 0 0
0 0 1 0 1 0 0
0 1 0 1 0 1 0
1 0 1 0 1 0 1

\⍨: For every 0, give a space, and for every 1, take an item from the string on the left.
⎕∊⍨⍳10: Read a line from the keyboard and evaluate it (⎕), then check for every number from 1 to 10 (⍳10) whether or not it is contained in the input (∊⍨).
'.O'[1+...]: Add 1 to every value (giving 1s and 2s instead of 0s and 1s), and then replace every 1 by . and every 2 by O.
4 7⍴: turn the generated string into a 4-by-7 matrix
⊖: flip it horizontally

Powershell: 109
Input is in $i
(7..10),(4..6),(2,3),1|%{$c=0}{$_|%{$o=(" "*$c++)}{$o="$o $(if($i.split() -contains $_){'O'}else{'.'})"};$o}

That was fun. Learned a bunch of stuff about how the pipeline works, too.

Mathematica, 109 bytes
Function:
f=(i=0;Reverse@Table[Row@Table[If[MemberQ[ToExpression/@StringSplit@#,++i],O,"."],{n}],{n,4}]~Column~Center&)

Called by:
f@"3 5 7 9 10"

If anonymous functions are allowed, this can be shortened to 105 bytes:
i=0;Reverse@Table[Row@Table[If[MemberQ[ToExpression/@StringSplit@#,++i],O,"."],{n}],{n,4}]~Column~Center&

If the input didn't have to be a space-delimited string, but could be an array of numbers in the form {3,5,7,9,10}, this can be further shortened to 79 bytes:
i=0;Reverse@Table[Row@Table[If[MemberQ[#,++i],O,"."],{n}],{n,4}]~Column~Center&

Rebol - 117
s: array/initial 10"."b:""foreach n to-block input[s/:n:"0"]for n 4 1 -1[prin b print take/last/part s n append b" "]

Ungolfed:
s: array/initial 10 "."
b: ""
foreach n to-block input [s/:n: "0"]
for n 4 1 -1 [prin b print take/last/part s n append b " "]

Perl, 73
$_="7 8 9 10\n 4 5 6\n  2 3\n   1";for$v(<>=~/\d+/g){s/$v/O/g};s/\d+/./g;print

And a goofy bonus approach that didn't pan out, 90 characters:
srand(1488068);$i=<>;print+(($i=~/$_\b/?O:".")." "x rand 5)=~s/  /\n /r for 7..10,4..6,2,3,1

Brainfuck, 179 bytes
++++++++++[-[<<+>>-]+<<]>,[<[-]-[>-<-----]>++[-[>>+<<-]>>]>+++[<<],>,]<[,>>---[>
>]<<+++[<<]]>->>->>>>->>>>>>->[[>>]>,<<+[++[>+++++++++++<-]<+]>>[++.>-.>]>++++++
++++[>>]<<[.[<]<]<]

Formatted:
++++++++++
[
  -[<<+>>-]
  +<<
]
>,
[
  <[-]
  -[>-<-----]
  >++
  [
    -[>>+<<-]
    >>
  ]
  >+++[<<]
  ,>,
]
<
[
  ,>>---[>>]
  <<+++[<<]
]
>->>->>>>->>>>>>->
[
  [>>]
  >,<
  <+
  [
    ++[>+++++++++++<-]
    <+
  ]
  >>[++.>-.>]
  >++++++++++[>>]
  <<[.[<]<]
  <
]

Expects input without a trailing newline.
Try it online.
The tape is initialised with ten nodes, each of which contains a one followed by a zero. The one is the initial value of the pin, and the zero facilitates navigation and acts as a placeholder for the space character. For each number in the input, that pin is incremented by 3; note that ord('O') - ord('.') = 33, and during the printing phase, the pin's value will be multiplied by 11. (This multiplication is also used to generate the space character.) The order of the pins from left to right on the tape is simply 1 up to 10. If the input ends with a 10, a correction is made, since the 10 is initially treated as a 1.
After the input has been processed, a negative one is placed after each row. Then the rows are printed in a loop, with the number of leading spaces determined by the number of rows previously processed.

Powershell, 84 bytes
$p='6789
 345
  12
   0'
-split$args|%{$p=$p-replace($_-1),'O '}
$p-replace'\d','. '

Test script:
$f = {

$p='6789
 345
  12
   0'
-split$args|%{$p=$p-replace($_-1),'O '}
$p-replace'\d','. '

}

# one space at the end of each line with pins
@(
,("1 2 3 4 5 6 7 8 9 10",
@"
O O O O
 O O O
  O O
   O
"@)

,("7 10",
@"
O . . O
 . . .
  . .
   .
"@)

,("3 5 7 9 10",
@"
O . O O
 . O .
  . O
   .
"@)

,("1",
@"
. . . .
 . . .
  . .
   O
"@)
) | % {
    $s, $expected = $_
    $result = &$f $s
    $result-eq$expected
    $result
}

Output:
True
O O O O
 O O O
  O O
   O
True
O . . O
 . . .
  . .
   .
True
O . O O
 . O .
  . O
   .
True
. . . .
 . . .
  . .
   O

AWK: 96 bytes
{gsub(/ /,"");a="6 7 8 9\n 3 4 5\n  1 2\n   0";gsub("["$0"]","O",a);gsub(/[0-9]/,".",a);print a}

Note:

The spaces separators on the input value are optional (but it works also with them as required)
The numbers don't have to be in order
The input is read on STDIN

C# - 192 bytes
Because C#!
I started out trying to build the output with math, but the simple replace-tokens-in-string method seems best for higher-level languages. Linq dependency is longish but still shorter than keeping a counter and doing range checks.
using System.Linq;class A{static void Main(string[]a){var s=@"7 8 9 0
 4 5 6
  2 3
   1";for(int c=11;c-->1;)s=s.Replace((char)(48+c%10),a.Contains(""+c)?'O':'.');System.Console.Write(s);}}

EDIT: unix line returns (-3 bytes)

Scala, 150148
def t(n:Any)=("G H I J D E F   B C     A"/:('A'to'J'))((j,i)=>j.replace(i,(if((n+" ").indexOf((i-64)+" ")>=0)'0'else'.'))).grouped(7).maxBy(println)

Accepts space-delimited set of strings

JavaScript ES6, 78 bytes
F=i=>'7890\n 456\n  23\n   1'.replace(/\d/g,e=>'0.'[+!~i.search(e+'\\b')]+' ')

Use the following snippet to test. It uses prompts and alerts and regular function notation for ease of testing.

i=prompt()
alert('7890\n 456\n  23\n   1'.replace(/\d/g,function(e){return'0.'[+!~i.search(e+'\\b')]+' '}))

Clojure, 216 chars (ugh)
I'm sure this can be golfed further.
(let[s(map #(dec(read-string %))(.split(slurp *in*)" +"))](println(apply str(replace(apply hash-map(interleave(map #(char(+ 48 %))(range 10))(map #(if(some #{%}s)"O"".")(range 10))))"6 7 8 9\n 3 4 5\n  1 2\n   0"))))

Use like this:
echo -n "2 4 9 8 10 5" | clojure a-file-which-contains-this-program.clj

Java - 223 chars
public class Pins {public static void main(String[] args) {String s = "7 8 9 0\n 4 5 6\n  2 3\n   1";for (String arg : args) {s = s.replace(arg.replace("10", "0"), "o");}s = s.replaceAll("\\d", ".");System.out.println(s);}}

I used to like this way of doing it, then I realized I needed a small hack, still kind of like my solution.
public class Pins {
public static void main(String[] args) {
    String s = "7 8 9 0\n 4 5 6\n  2 3\n   1";
    for (String arg : args) {
        s = s.replace(arg.replace("10", "0"), "o");
    }
    s = s.replaceAll("\\d", ".");
    System.out.println(s);
}
}

VB/Basic-229
My goal was to beat java^^
Dim f
Sub m()
f = " 1 2 3 4 5 6 7 8 9 10"
a = l(7, 10) + l(4, 6) + l(2, 3) + l(1, 1)
MsgBox a
End Sub
Function l(b, e)
r = Space(3 - (e - b))
For i = b To e
r = r + IIf(InStr(f, Str(i)), "0 ", ". ")
Next
l = r + vbCr
End Function

edit vbCr instead of chr(13)
r = r + Space(3 - (e - b))
shorthand if
use of function instead of sub
sub MAIN() - > sub m()

Can you please include the code length in bytes in your answer?

I will, but i'm still fiddling a bit with the code

K, 57 bytes
Not very competitive yet, but it's a start:
`0:((!4)#\:" "),',/'|0 1 3 6_(". ";"O ")@|/(1+!10)=/:(),.

Usage example:
  `0:((!4)#\:" "),',/'|0 1 3 6_(". ";"O ")@|/(1+!10)=/:(),."3 5 7 9 10"
O . O O
 . O .
  . O
   .
  `0:((!4)#\:" "),',/'|0 1 3 6_(". ";"O ")@|/(1+!10)=/:(),."1"
. . . .
 . . .
  . .
   O

I begin by evaluating the input string with .- fortunately, space separated numbers are a valid list literal in K. By prepending an empty list to the result of eval I can ensure it's a list even in the case of a single pin. Then I create a boolean vector representing the positions of pins:
  (1+!10)=/:3 5 7 9 10
(0 0 1 0 0 0 0 0 0 0
 0 0 0 0 1 0 0 0 0 0
 0 0 0 0 0 0 1 0 0 0
 0 0 0 0 0 0 0 0 1 0
 0 0 0 0 0 0 0 0 0 1)
  |/(1+!10)=/:3 5 7 9 10
0 0 1 0 1 0 1 0 1 1

Then I index into a list of strings to get space-padded characters for each pin position.
  (". ";"O ")@0 0 1 0 1 0 1 0 1 1
(". "
 ". "
 "O "
 ". "
 "O "
 ". "
 "O "
 ". "
 "O "
 "O ")

I slice that sequence into rows (_), reverse them (|) and join together each fragment (,/'):
  ,/'|0 1 3 6_(". ";"O ")@0 0 1 0 1 0 1 0 1 1
("O . O O "
 ". O . "
 ". O "
 ". ")

Now it's starting to look like the pattern we want. All that's left is to tack on some leading spaces to each row (((!4)#\:" "),') and print the rows to stdout (0:).

Japt -Rx, 29 19 18 17 bytes
5ÇÆ".O"gUø°TÃ¸ÃÔû

Try it

Explanation
                      :Implicit input of integer array U
5Ç                    :Map each Z in the range [0,5)
  Æ                   :  Map the range [0,Z)
          °T          :    Increment T (initially 0)
        Uø            :    Does U contain T? (false=0, true=1)
   ".O"g              :    Get the character in the string ".O" at that index
            Ã         :  End mapping
             ¸        :  Join with spaces
              Ã       :End mapping
               Ô      :Reverse
                û     :Centre pad each element with spaces to the length of the longest
                      :Implicitly join with newlines, trim (not strictly necessary) and output

Pascal (FPC), 165 bytes
var f:string='. . . .'#10' . . .'#10'  . .'#10'   .';i:byte;z:array[1..10]of byte=(25,18,20,10,12,14,1,3,5,7);begin repeat read(i);f[z[i]]:='O'until eof;write(f)end.

Try it online!
Takes numbers from standard input, prints the formation to standard output.
Pascal (FPC), 175 bytes
function f(q:array of byte):string;var i:byte;z:array[1..10]of byte=(25,18,20,10,12,14,1,3,5,7);begin f:='. . . .'#10' . . .'#10'  . .'#10'   .';for i in q do f[z[i]]:='O'end;

Try it online!
A function which does the same thing, taking an array of pin positions and returning a formatted string.

Vyxal, 43 bytes
`7 8 9 0
 4 5 6
  2 3
   1`?⌈(nt\OV)‛\d\.øṙ

Try it Online!
Nothing clever, just a simple substitution.

33 bytes

Haskell, 96 bytes
main=interact$ \a->do
c<-"7 8 9 0\n 4 5 6\n  2 3\n   1"
max['O'|elem c$last<$>words a]$min"."[c]

Try it online!

JavaScript (Node.js), 73 69 bytes
Thanks @l4m2 for saving 4 bytes
s=>`7890
 456
  23
   1`.replace(/\d/g,d=>s.match(d+"\\b")?"0 ":". ")

Attempt This Online!
Explanation:

s=>... Anonymous function taking string argument s
`7890...` Multiline string
.replace(/\d/g,d=>...) Replace each digit d with:
s.match(d+"\\b") Check if s contains d followed by a word boundary
?"0 ":". " If it does, replace with "0 ", else with ". "

(JavaScript (Node.js), 71 bytes: s=>7 8 9 0
4 5 6
2 3
1.replace(/\d/g,d=>s.match(d+"\\b")?0:".")

JavaScript (Node.js), 69 bytes: s=>7890
456
23
1.replace(/\d/g,d=>s.match(d+"\\b")?"0 ":". ")

Java - 371 316 294 chars
public class Bowling{public static void main(String[] a){boolean[] o=new boolean[10];int i;for(String s:a){i=Integer.parseInt(s)-1;o[i]=true;}for(int j=9;j>=0;j--){p((o[j]?"0 ":". "));p(j==6?"\n ":"");p(j==3?"\n  ":"");p(j==1?"\n   ":"");}p("\n");}static void p(String l){System.out.print(l);}}

First time doing this, I'm pretty sure it's shitty, but I'm a novice. It also works when the numbers aren't ordered. The numbering is wrong but I don't have time to find out how to fix it...
public class Bowling {
    public static void main(String[] args) {
        boolean[] ordened = new boolean[10];
        int i;
        for (String s : args) {
            i = Integer.parseInt(s) - 1;
            ordened[i] = true;
        }
        for (int j = 9; j >= 0; j--) {
            p((ordened[j] ? "0 " : ". "));
            p(j == 6 ? "\n " : "");
            p(j == 3 ? "\n  " : "");
            p(j == 1 ? "\n   " : "");
        }
        p("\n");
    }
    static void p(String l){
        System.out.print(l);
    }
}

input is given by java B 1 2 3 5 10 for example. Output will then be:
0 . . .
 . 0 .
  0 0
   0

The numbering is wrong.

I'll try to fix it

05AB1E, 15 bytes
TLå4L£R».cT„O.‡

Input as a list (if input as a space-delimited string is mandatory, a leading # (+1 byte) can be added to split the implicit input-string by spaces to the necessary list).
Try it online or verify all test cases.
Explanation:
                #  (e.g. input = [2,7,10])
TL              # Push a list in the range [1,10]
                #  STACK: [1,2,3,4,5,6,7,8,9,10]
  å             # Check for each whether it's in the (implicit) input-list,
                # resulting in a list of 1s and 0s
                #  STACK: [0,1,0,0,0,0,1,0,0,1]
   4L           # Push a list in the range [1,4]
                #  STACK: [0,1,0,0,0,0,1,0,0,1],[1,2,3,4]
     £          # Split the earlier list into parts of those sizes:
                #  STACK: [[0],[1,0],[0,0,0],[1,0,0,1]]
      R         # Reverse it
                #  STACK: [[1,0,0,1],[0,0,0],[1,0],[0]]
       »        # Join each inner list by spaces, and then each line by newlines
                #  STACK: "1 0 0 1\n
                #          0 0 0\n
                #          1 0\n
                #          0"
        .c      # Centralize it by prepending spaces where necessary
                #  STACK: "1 0 0 1\n
                #           0 0 0\n
                #            1 0\n
                #             0"
              ‡ # Transliterate
          T     # the digits of "10"
           „O.  # to the characters of "O."
                # (which replaces all "1" with "O" and "0" with "." respectively)
                #  STACK: "O . . O\n
                #           . . .\n
                #            O .\n
                #             ."
                # (after which the result is output implicitly)

R 4.2, 159 bytes
f=function(x)cat(sapply(X=4:1,FUN=function(X){i=((X^2-X)/2+1);c(rep(" ",4-X),paste0(ifelse(1:10%in%strsplit(x," ")[[1]],"0",".")[i:(i+X-1)]," "),"\n")}),sep="")

Try it online!
# ungolfed:
f = function(s) {
  nums = strsplit(s, " ")[[1]]  # split input string
  idx = 1:10 %in% nums          # convert 1:10 to logical vector for given pins
  ind01 = ifelse(idx,"0",".")   # convert to ASCII characters
  cat(                          # concatenate rows of output
    sapply(X=4:1,               # iterate through rows
           FUN=function(X){
             i=((X^2-X)/2+1);   # same hack as @Sp3000 (nice!)
               c(rep(x=" ",times=4-X), # add leading spaces
                 paste0(ind01[i:(i+X-1)]," "),  # print ASCII chars separated by space
                 "\n")          # new line after each row
             }
           ),
    sep="")                     # remove default space between elements
}

f("1 2 3 4 5 6 7 8 9")
f("7 10")
f("3 5 7 9 10")
f("1")

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


text:
At least h with at least h
Input
A list of nonnegative integers.
Output
The largest nonnegative integer h such that at least h of the numbers in the list are greater than or equal to h.
Test Cases
[0,0,0,0] -> 0
[12,312,33,12] -> 4
[1,2,3,4,5,6,7] -> 4
[22,33,1,2,4] -> 3
[1000,2,2,2] -> 2
[23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] -> 20

Rules
You can write either a full program or a function, and anonymous functions are allowed too. This is code-golf, so the fewest byte count wins. Standard loopholes are disallowed.
Background
The h-index is a notion used in academia which aims to capture the impact and productivity of a researcher. According to Wikipedia, a researcher has index h, if he or she has published h scientific articles, each of which has been cited in other articles at least h times. Thus, this challenge is about computing the h-index from a list of citation counts.

Update
Wow, great answers all round! I have accepted the shortest one, but if someone else comes up with an even shorter one, I'll update my choice accordingly.
Winners by language
Here's a table of winners by language that I'll also try to keep up to date. I have included all posts with nonnegative score. Please correct me if I have made a mistake here.

APL: 7 bytes by @MorisZucca
Bash + coreutils: 29 bytes by @DigitalTrauma
C#: 103 bytes by @LegionMammal978
C++: 219 bytes by @user9587
CJam: 15 bytes by @nutki
GolfScript: 13 bytes by @IlmariKaronen
Haskell: 40 bytes by @proudhaskeller
J: 12 bytes by @ɐɔıʇǝɥʇuʎs
Java: 107 bytes by @Ypnypn
JavaScript: 48 bytes by @edc65
Mathematica: 38 bytes by @kukac67
Perl: 32 bytes by @nutki
Pyth: 10 bytes by @isaacg
Python: 49 bytes by @feersum
R: 29 bytes by @MickyT
Ruby: 41 bytes by @daniero
Scala: 62 bytes by @ChadRetz
SQL: 83 bytes by @MickyT
TI-BASIC: 22 bytes by @Timtech

APL 7
+/⊢≥⍋∘⍒

Can be tried online on tryapl.org
f←+/⊢≥⍋∘⍒
f¨(4⍴0)(12 312 33 12)(⍳7)(22 33 1 2 4)(1000 2 2 2)(23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42)
0 4 4 3 2 20

Python 2, 49
Input should be typed in the same format as the examples.
i=0
for z in sorted(input())[::-1]:i+=z>i
print i

What an amazing algorithm!

Python, 52
f=lambda s,n=0:n<sum(n<x for x in s)and f(s,n+1)or n

A recursive solution. Run this in Stackless Python if you're worried about overflows.
Starting from n=0, checks whether at least n+1 of the numbers are at least n+1. If so, increments n and starts again. If not, outputs n.
The conditional is done using Python's short-circuiting for Booleans. The expression sum(n<x for x in s) counts the number of values in s that are greater than n by adding the indicator Booleans, which are treated as 0 or 1.
For comparison, the iterative equivalent is 2 chars longer. It requires Python 2.
s=input()
n=0
while n<sum(n<x for x in s):n+=1
print n

Unfortunately, the input need to be saved for a variable before being iterated over or else Python will try to read the input repeatedly.

Pyth, 13 10 bytes
tf<l-QUTT1

Input in a form such as [22,33,1,2,4] on STDIN.
Try it here.
How it works:
-QUT is all of the numbers in the input (Q) at least as large as the number being checked, T.
<l-QUTT is true if the the length of that list is less than T.
f<l-QUTT1 finds the first integer which returns true for the inner check, starting at 1 and going up.
tf<l-QUTT1 decrements that by one, giving the largest value for which the condition is false, which is the h-index.
Starting at 1 ensures that 0 is returned when the test is always true, such as in the first test case.

CJam, 15 bytes
Direct translation of my Perl solution.
l~{~}${W):W>},,

l~$W%{W):W>},, - 14 bytes

@Optimizer Thanks, I expected there should be a short way of reversing a table. I am surprised though that there is no access to iteration count in maps. Anyway if 1 byte is all you can take that is not bad for my first CJam code.

There's are some 12-byte solutions now: {$W%ee::<1b} (ee was added 2015-04-17) and {$W%_,,.>1b} (. was added 2015-02-21).

J (13 12)
[:+/i.@#<\:~

Pretty similar to randomra's solution. Demonstration:
   f=:[:+/i.@:#<\:~
   f 0,0,0,0
0
   f 12,312,33,12
4
   f 1,2,3,4,5,6,7
4
   f 22,33,1,2,4
3
   f 1000,2,2,2
2
   f 23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42
20

Using #\<: instead of i.@#< saves a character.

Mathematica, 44 42 40 38 bytes
Anonymous function:
LengthWhile[i=0;SortBy[#,-#&],#>i++&]&

Run it by tacking the input on to the end like so:
In: LengthWhile[i=0;SortBy[#,-#&],#>i++&]&@{1,2,3,4,5,6,7}
Out: 4

@MartinBüttner You're right, I can use #>i++. I tested some more cases. (And thanks for all the suggestions!)

SQL, 81 94 83
Given a table (I) of values (V), the following query will return h.  Tested in PostgreSQL and will also work in SQL Server.  Edit Make it return 0 rather than NULL.  Made better with a COUNT, thanks @nutki
SELECT COUNT(R)FROM(SELECT ROW_NUMBER()OVER(ORDER BY V DESC)R,V FROM I)A WHERE R<=V

SQLFiddle example
Essentially it numbers the rows on a descending sort of the values.  Then it returns the maximum row number where the row number is greater than equal to the value.

You can use COUNT(R) instead of COALESCE(MAX(R),0) for a shorter fix for the NULL problem.

@nutki of course ... Thank you

R, 39 35 29
s=sort(i);sum(s>=length(s):1)

Given a vector of integers in i and using the logic of a reverse sort then returning the length of the vector where element number is less than s.  Thanks to @plannapus for the nice tip.
> i=c(23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42)
> s=sort(i);length(s[s>=length(s):1])
[1] 20
> i=c(0,0,0,0)
> s=sort(i);length(s[s>=length(s):1])
[1] 0

Nice! You can even shorten to 29 by directly summing the logical vector: s=sort(i);sum(s>=length(s):1)

Japt, 4 bytes
ñÍè>

Try it here
ñÍè>     :Implicit input of array
ñ        :Sort by
 Í       :  Subtracting from 2
  è      :Count the elements that are
   >     :  Greater than their 0-based indices

Python (63)
Basically a direct port of my J solution. Obviously, a lot longer, as one might imagine.
lambda x:sum(a>b for a,b in zip(sorted(x)[::-1],range(len(x))))

You can save some chars by using enumerate.

Haskell, 40
f s=[x-1|x<-[1..],x>sum[1|r<-s,r>=x]]!!0

this searches for the first number to not fit the scheme and returns it's predecessor.

39 bytes with until: Try it online!

Ruby 44 41
Recursive, more or less same strategy as xnor's Python solution:
f=->a,n=0{a.count{|x|x>n}<n+1?n:f[a,n+1]}

Ruby 52
Non-recursive:
f=->a{a.size.downto(0).find{|x|a.count{|y|y>=x}>=x}}

"Stabby" lambda/anonymous functions, require Ruby 1.9 or newer. Call with e.g. f[[22,33,1,2,4]]

Bash + coreutils, 29
sort -nr|nl -s\>|bc|grep -c 0

Input taken from stdin as a newline-separated list.

sort the integers in descending order
nl prefixes each line with its 1-based line number, separating the line number and rest of the line with a greater-than >
Arithmetically evaluate each line with bc.  Integers less than their line number result in 0.  Otherwise 1.
grep counts the number of 0s, i.e. the number of integers greater than or equal to h

Example
$ for i in {23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42}; do echo $i; done | ./atleasth.sh
20
$ for i in {1,2,3,4,5,6,7}; do echo $i; done | ./atleasth.sh
4
$

CJam, 23 bytes
l~:I,),W%{_If>:!:+>}$0=

This takes the list as an array on STDIN, like
[23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42]

Test it here.
You can use this to run all test cases:
[0 0 0 0]
[12 312 33 12]
[1 2 3 4 5 6 7]
[22 33 1 2 4]
[1000 2 2 2]
[23 42 12 92 39 46 23 56 31 12 43 23 54 23 56 73 35 73 42 12 10 15 35 23 12 42]]
{:I,),W%{_If>:!:+>}$0=N}/

Explanation
l~:I,),W%{_If>:!:+>}$0=
l~:I                    "Read input, evaluate, store in I.";
    ,                   "Get length of input N.";
     ),W%               "Create range from 0 to N, reverse.";
         {         }$   "Sort stably.";
          _I            "Duplicate candidate h, push input list.";
            f>          "Map each number to 1 if it's less or 0 otherwise.";
              :!        "Invert all results.";
                :+      "Sum them up.";
                  >     "Check if the sum is less than the candidate h.";
                     0= "Pick the first element.";

The logic is a bit backwards, but it saved a couple of bytes. Basically, the block passed to sort returns 0 for valid candidates and 1 otherwise. So the valid candidates come first in the sorted array. And because the sort is stable, and we begin with a list from N down to 1, this will return the largest valid h.

Perl 5: 32 (30 + 2 for -pa)
#!perl -pa
$_=grep$_>$i++,sort{$b<=>$a}@F

Takes space separated input on STDIN:
perl hidx.pl <<<'1 2 3 4 5 6 7'

sort{$b-$a} saves 2 more

APL, 12 characters
(+/⊢≥⍒)⊂∘⍒⌷⊢

C++ 815 219 from (wc -c main.cpp)
Alright here's some of the worst code I've ever written! :)
#include <iostream>
#include <list>
using namespace std;int main(int c,char** v){list<int>n(--c);int h=c;for(int&m:n)m=atoi(*(v+(h--)));n.sort();for(auto r=n.rbegin();r!=n.rend()&&*r++>++h;);cout<<(h==c?h:--h)<<endl;}

JavaScript (ES6) 48
Recursive solution.
F=(l,h=-1)=>l.filter(v=>v>h).length>h?F(l,h+1):h

Test in FireFox/FireBug console
;[
  [0,0,0,0],
  [12,312,33,12],
  [1,2,3,4,5,6,7],
  [22,33,1,2,4],
  [1000,2,2,2],
  [23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42]
 ].forEach(l=>console.log(l,F(l)))

Output
[0, 0, 0, 0] 0
[12, 312, 33, 12] 4
[1, 2, 3, 4, 5, 6, 7] 4
[22, 33, 1, 2, 4] 3
[1000, 2, 2, 2] 2
[23, 42, 12, 92, 39, 46, 23, 56, 31, 12, 43, 23, 54, 23, 56, 73, 35, 73, 42, 12, 10, 15, 35, 23, 12, 42] 20

47 bytes: f=(l,h=0)=>l.map(v=>x+=v>h,x=0)&&x>h?f(l,h+1):h. However, your solution would be 47 bytes too if you just change the h=-1 to h=0.

Java 8, 116 bytes.
Full class:
import java.util.*;
import java.util.stream.*;

class H{

    public static void main(String[]a){
        System.out.println(new H().f(Stream.of(a[0].split(",")).mapToInt(Integer::parseInt).toArray()));
    }

    int i;

    int f(int[]n){
        Arrays.sort(n);
        i=n.length;
        Arrays.stream(n).forEach(a->i-=a<i?1:0);
        return i;
    }
}

Function:
import java.util.*;int i;int f(int[]n){Arrays.sort(n);i=n.length;Arrays.stream(n).forEach(a->i-=a<i?1:0);return i;}}

Jelly, 6 bytes
NỤỤ<’S

Explanation:
N           Negate (so that repeated elements won't mess up the second grade down)
 Ụ          Grade down
  Ụ         Twice.
   <’       Predicate, check for each element if the new one (after grading) is lower than original array (minus 1 on each element)
     S      Sum

Haskell, 72 59 bytes
My C++ solution looked pretty verbose, and the recursive nature made me think of Haskell, so here's my attempt:
a!i|i<foldr(\x s->s+fromEnum(i<x))0 a=a!(i+1)|1<2=i
H a=a!0

Explanation:
foldr (\x s -> s + fromEnum(i < x)) 0 a

I'm sure there's a shorter way to do this, because I'm pretty new to haskell, but basically it counts how many elements of a are less than x.
If this is greater than i, we can check i+1, otherwise, return i.
And the H function is so that we don't need to pass in 0 to h. It adds 10 8 bytes, so I'm pretty sure there's a better way.
-13 bytes thanks to ovs

Instead of defining a the named function H the main function can be flip a 0, which can be shortened to (`h`0): Try it online! (The -cpp is there to set up TIO in the same way we count the bytes here). Then you might want to have a look at these two tips: 1 and 2

@ovs wdym about flip a 0 and/or \h`0`?

You don't need to name functions if you don't rely on a specific name, just like with Python lambda's. But in Haskell flip h 0 and (`h`0) are functions that do the same as your H, so (!0);a!i|... is a valid submission. (See the TIO link in my previous comment)

C#, 103
Anonymous function.

a=>{try{return a.OrderBy(b=>-b).Select((b,c)=>new{b,c}).First(b=>b.b<b.c+1).c;}catch{return a.Length;}}

Indented:
a =>
{
    try
    {
        return a.OrderBy(b => -b).Select((b, c) => new { b, c }).First(b => b.b < b.c + 1);
    }
    catch
    {
        return a.Length;
    }
}

JAGL Alpha 1.2 - 14
Doesn't count because the 'C' reverse array functionality was added after the question, but am answering for fun anyway.
Assumes that the array is the first item on the stack, and puts the answer at the top of the stack.
0SJC{Sd@>+1}/S

To print, just add P at the end, adding a byte.
Explanation:
0               Push the number 0 (the counter)
 SJC            Swap to array, sort and reverse
    {Sd@>+1}/   For each item in the array, add 1 to counter if counter is less than item
             S  Swap counter to top of stack

GolfScript, 13 bytes
$-1%0\{1$>+}/

Test this code online.1
Takes input as an array on the stack.  Uses the same algorithm as feersum's Python solution, iterating over the numbers in the array and incrementing a counter from 0 until it equals or exceeds the current element of the array.
1) The online GolfScript server seems to be experiencing random timeouts again.  If the program times out for you, try re-running it.

TI-BASIC, 22 bytes
ASCII representation:
Input L1:1:While Ans≤sum(Ans≥L1:Ans+1:End:Ans

Hex dump:
DC 5D 00 3E 31 3E D1 72 6D B6 72 6C 5D 00 3E 72 70 31 3E D4 3E 72

Gets a list as input. Starting from Ans=0, checks whether at least Ans+1 of the numbers are at least Ans+1. If so, increments Ans and loops again. If not, outputs Ans.

J, 15 11 chars
(Current shortest J solution.)
   [:+/#\<:\:~

   ([:+/#\<:\:~) 1 2 3 4 5 6 7
4

Compares <: sorted list \:~ elements with 1..n+1 #\ and counts true comparisons +/.
Testing similarity against other J solution on 100 random test cases:
   */ (([:+/#\<:\:~) = ([:+/i.@#<\:~))"1 ?100 100$100
1

CJam, 22 bytes
q~:Q,),{Q{1$>},,>!},W=

Takes the list as input:
[23 42 12 92 39 46 23 56 31 12 43 23  54 23 56 73 35 73 42 12 10 15 35 23 12 42]

Output:
20

Try it here

Reng v.3.2, 43 bytes
1#xk#yaïí'1ø ~n-1$\
1+)x(%:1,%1ex+y1-?^#y#x

Try it here! This code can be split into three parts: initial, computational, and final.
Initial
1#xk#yaïí'1ø

This stores 1 to x, the length of the input stack k to y, and gets all input (aïí) which is then sorted ('). 1ø goes to the next line, i.e., the next part.
Computational
1+)x(%:1,%1ex+y1-?^#y#x

Reng has no built-in for inequality. Thus, an algorithm must be implemented. The shortest algorithm I found for a < b is %:1,%1e; this looks like this:
Command | Stack
  ---   | a, b
   %    | a/b
   :    | a/b, a/b
   1    | a/b, a/b, 1
   ,    | a/b, (a/b)%1
   e    | (a/b) == ((a/b)%1)

I'm sure that cleared it up! Let me explain further. x % 1, i.e modulus with 1, maps x to (-1,1). We know that (a/b) % 1 is a/b when a < b. Thus, this expression is equal to a < b.
However, this doesn't work quite as well because of problems with modulus with zero. So, we increment every member of the stack and the counter initially.
After we get the inequality Boolean on the stack, x+ adds it to x, but leaves it on the stack for the moment. y1- decrements y, and ?^ goes up iff y == 0 and we proceed to the final phase. Otherwise, we put y-1 into y and the new x into x.
Final
             ~n-1$\

This pops the residual y-1 from the stack, decrements the result, outputs it, and ends the program.

05AB1E, 5 bytes
{Rā@O

Try it online!
or as a Test Suite
Explanation
{R      # sort descending
  ā@    # check each element if it's greater than or equal to its 1-based index
    O   # sum

Scala, 41 39 bytes
_.sorted.:\(0){(n,h)=>h+(n/(h+1)).sign}

Try it online!
In Scala 2.13, signum was changed to sign, so it's 2 bytes extra in TIO, which still uses Scala 2.10.
Scala, 41 bytes
a=>a.max to(0,-1)find(b=>a.count(b<=)>=b)

Try it online!
This isn't mine, it's just a modified version of Chad Retz's answer, but since they're not active anymore, I decided to put it here instead of commenting on it.

Vyxal s, 5 bytes
s₌Ṙż≥

Try it Online!
A port of the 05AB1E answer. I originally had ẏ'?<∑≤ + -G, which I kinda like more.
Explained
s₌Ṙż≥
s     # sort the input list
 ₌Ṙż  # and push reversed(^) and range(1, len(^) + 1)
    ≥ # vectorise >= over ^ and input
      # -s sums that

ẏ'?<∑≤
ẏ       # The range [0, len(input))
 '      # with only elements where: (call each element N)
  ?<∑   #   the sum of all elements of the input greater than N
     ≤  #   is less than or equal to N
        # (this gets all h with at least h)
        # -G gets the biggest h from the possible h's

C++, 81 bytes
int h(std::list<int>a,int i=0){int c=0;for(int x:a)c+=i<x;return i<c?h(a,i+1):i;}

Similar solution to most of the other ones.
Assuming that <list> is included.
Non-recursive solution (85 83 bytes):
int h(std::list<int>a){for(int i=0,c;;i++){c=0;for(int x:a)c+=i<x;if(i>=c)return i;}}

It might be possible to put the c initialization outside the function (because that defaults to 0, and you also don't need the int, but it doesn't seem to work on TIO.

Scala, 62
def h(a:Int*)=Range(a.size,-1,-1).find(b=>a.count(b<=)>=b).get

Java, 107
long f(java.util.ArrayList<Long>l){for(int i=0;;){long x=i++;l.removeIf(j->j<x);if(l.size()<x)return x-1;}}

Explanation:
long f(java.util.ArrayList<Long> l) {
    for(int i = 0;;) {
        long x = i;
        i++;
        l.removeIf(j -> j<x);
        if(l.size() < x)
            return x-1;
    }
}

Mathematica, 57 bytes
FirstCase[Range[Length@#,0,-1],h_/;Count[#,k_/;k>=h]>=h]&

This is an anonymous function taking a list and returning an integer, like
FirstCase[Range[Length@#,0,-1],h_/;Count[#,k_/;k>=h]>=h]&@{1,2,3,4,5,6,7}

Use this to check all test cases:
FirstCase[Range[Length@#,0,-1],h_/;Count[#,k_/;k>=h]>=h]& /@ {
  {0, 0, 0, 0},
  {12, 312, 33, 12},
  {1, 2, 3, 4, 5, 6, 7},
  {22, 33, 1, 2, 4},
  {1000, 2, 2, 2},
  {23, 42, 12, 92, 39, 46, 23, 56, 31, 12, 43, 23, 54, 23, 56, 73, 35,
    73, 42, 12, 10, 15, 35, 23, 12, 42}
}

MATL, 8 7 bytes
SPGf<~s

Try it online!
Explanation
Direct application of the definition:
SP    % Take input array implicitly. Sort in non-increasing order
Gf    % Push array of indices of nonzero entries of the input. This gives
      % [1 2 ... n] where n is input size
<~    % True for values of the sorted input that are >= those in [1 2 ... n]
s     % Sum. Implicitly display

x86 machine code, 24 bytes
Hexdump:
53 8b c2 8b d8 52 39 44 91 fc 72 01 4b 4a 75 f6
5a 48 4b 7d ee 5b 40 c3

A function that takes a pointer to the list and its length; outputs the number.
C-compatible declaration:
int __fastcall hindex(int* list, int size);

Source code:
    // eax = h
    // ebx counts down from h to 0; if it gets to 0, we have found h
    // ecx = list
    // edx = array size
    push ebx;
    mov eax, edx;                   // h = size ... down to 0
h_loop:
    mov ebx, eax;                   // init the countdown
    push edx;
array_loop:
    cmp [ecx + edx * 4 - 4], eax;   // check 1 list element
    jb skip;
    dec ebx;
skip:
    dec edx;                        // go to next element
    jnz array_loop;
    pop edx;
    dec eax;                        // go to next h
    dec ebx;                        // compare the countdown to 0
    jge h_loop;                     // if it was 0 or less, stop
    pop ebx;
    inc eax;                        // undo going to next h
    ret;

It uses a peculiar way to compare a register with 0:
    dec ebx;

Here, if ebx was less or equal to 0, it will be negative now, and then we should stop the outer loop (h_loop). Otherwise, continue:
    jge h_loop;

There is a small price (1 byte) to pay for this trick: the loop control variable h (eax) has already been advanced. So this has to be undone after the loop ends:
    inc eax;

However, even with this price, this trick gives the code the proper do-while structure, which saves 2 bytes when compared to a for structure.

Octave, 41 bytes
@(x)sum(cumprod(-sort(-x)>=(1:numel(x))))

This is an anonymous function.
Try it at Ideone.

Arturo, 43 bytes
$=>[0-1enumerate arrange&=>[2-&]=>[>&<=1+]]

Try it

source: Stack Exchange

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

sort: votes


text:
Meta-atomic code golf
In this meta-challenge, you will score your own atomic-code-golf submissions. More precisely, you will need to write a program P in language L such that the atomic-score of P is produced by P.
Score
The idea behind atomic-code-golf is to count language tokens instead of bytes. However, in practice, it is hard to define a general set of rules for all questions (see Count big-ints/symbols/variables as N tokens in atomic-code-golf). That's why it is recommended to clarify rules for each challenge.
Intuitively, tokens are nodes in the abstract syntax tree of your language, except for strings, where each character count (due to potential abuse).

Things that count as single tokens:

variable/function/type  identifiers
literals, except strings, where each byte counts
built-in keywords and operators
(edit) Empty lists, empty vectors, empty strings

Things that are ignored from counting:

preprocessor/reader macros
include/import statements
separating and grouping symbols used to build tuples, lists, arrays, statements, function parameters, structs are ignored (,;:(){}[]<>|). However, if those symbols are tokens, they count (I am looking at you, CJam (or Brainfuck)). Also, quotes enclosing strings are not counted.

Corner cases

Using identifiers to hold data is a nice hack (see feersum's comment), but it might be considered abusive. So, there should be a penaly of +25 if your answer exploits identifiers' names for computations. This penalty needs not be correctly scored by your program. If you manage to add a penalty to programs which abuse identifiers' names for computation (for a reasonable subset of programs in your language), you deserve -100 points of bonus (this bonus needs not be correctly scored by your program).

Challenge
You should write a program in the language of your choice that scores programs in that language according to the above atomic-score rules. Your own answer will be scored according to that program.

Input may be read from STDIN or given as a function parameter
Output is a number, as a return value or printed to STDOUT
Answer with lowest atomic-score wins
I'll provide an example answer (if it has the lowest score, the next one wins).

So much CJam hate :(

How could a "separating or grouping symbol" not be a token?

the quotes in a string count as 2 tokens ?

Also, many languages allow variable names to be accessed, so they can be abused like strings.

@Optimizer I don't hate CJam, I could have said Perl or Brainfuck ;-)

@feersum They are not token if they are not concretely present in the AST.

@Optimizer no: quotes do not count as 2 tokens

@feersum About variable names: maybe that kind of abuse could be valid. Do you have an example?

@coredump Maybe something like this in Python: def f(s): soaosuOSNTEUHSONETUHTSon50392858209358092386092 = 3; exec locals().keys()[0].decode('base64')

What happens when some characters are no-op in one language ? i.e. their presence does not have any effect to the AST or the code ?

@Optimizer Like whitespace, comments? they are ignored. What do you have in mind?

@feersum maybe I can restrict this usage a little: "user-defined identifiers of length > 5 are counted as strings"?

What about built-in lexers? Are they allowed?

@MartinBüttner Sure

What if () supports IO? It has only grouping symbols.

@user23013 How would you name a function that does the same thing as ()?: "empty-list", "read-from-stdin"? Depending on the meaning of symbols in a particular language, symbols are counted differently.

@coredump the winning condition should be to win in as much (non-eso)languages as possible

For scoring strings, is it number of bytes as typed or as parsed? E.g. do you score "\n" as 1 or 2 points?

What does If you manage to add a penalty to programs which abuse identifiers' names for computation (for a reasonable subset of programs in your language), you deserve -100 points of bonus (this bonus needs not be correctly scored by your program). mean

Unary, 1
The program is a string of 47297560408284 zeroes
i.e.
000000000000000000000000000000000000000000.... 47297560408284 times

A brainfuck quivalent code would be
+[>+<+++++]>--.

which just prints 1
as in unary, the whole program is made up of just 0 which are all a single token.

+1 It works for any program written in Unary, not just itself. That being said, something tells me I should have a rule about very long litterals...

Its not a literal. It is the program.

The whole chain of zero is one (big) integer expressed in base 1, which, converted back to Brainfuck can be decoded as commands. So it is both the program and a big literal, isn't it?

You can say that, but at least here I am not abusing them, but actually using them how they are meant to be used.

I don't think you are abusing them, just that the language is designed to interpret a big unary literal. Even though is doesn't seem fair w.r.t. other languages, I can't prevent it. Let's Unary wins, for a change (atomic-code-golf rules were supposed to level languages, and ironically, they tend to favor this one)

I may be wrong, but I think you only need 47297560408284 zeroes.

The first BF character is +. According to this page, it should be represented by 010 in the binary stream. With a 1 added at the beginning, that means your number should start with 0b1010.... But 3424997280936108 in binary starts with 0b1100... (Or maybe i just read it wrong.)

Ah, you are right. I messed up in binary conversion.

Common Lisp - 23 26
Here is the example answer:
(labels ((sum (s form)
           (if (typep form 'sequence)
               (max (1+ s) (reduce #'sum form :initial-value s))
               (1+ s))))
  (defmacro atomic-count (form) (sum 0 form)))

And here we can see the macro scoring itself:
(atomic-count
 (labels ((sum (s form)
            (if (typep form 'sequence)
                (max (1+ s) (reduce #'sum form :initial-value s))
                (1+ s))))
   (defmacro atomic-count (form) (sum 0 form))))
=> 26

NB. This never terminates (or, badly) with cyclic expressions built with #1= and #1# reader macros.
(edit) Empty sequences should count as 1 token

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


text:
Create a T9 keyboard
This question asks for a T9 dictionary matching functionality which is a very interesting problem. But T9 has another way of typing and that is typing character-by-character. You would NOT need a dictionary to implement this keyboard.
Here is key-map of a T9 keyboard if you forgot:
+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!  |  ABC  |  DEF  |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI  |  JKL  |  MNO  |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS  |  TUV  |  WXYZ |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   | SPACE |   →   |
+-------+-------+-------+

How T9 works
To type a character with T9, you need to press number key representing that character n times. n is order of that character written on that key. Numbers are the last character you can type for each key. For example, to type B I press 2 two times, or to type 5 I press 5 four times. To finish typing this character I press #. * is simply backspace. In our version of keyboard there is no capitalization.
Input and output examples:
8#99999#055#33#999#22#666#2#777#3# → T9 KEYBOARD

Explanation:

8 selects T and # moves to next character
99999 select last character of 9 key which is 9 and # moves to next charachter
0 inserts a space
33 selects second character of  3 key which is K and # moves to next character
And so on...

Rules
Your function or program should accept a string representing T9 keypresses. Output is the resulting text from those keypresses, as outlined above.
This is basic code golf, so the winner is shortest in bytes, and standard rules/loopholes apply.

Bonus does not have any effect on score ? Why would I go for it ?

Also, your example T9 KEYBOARD is completely wrong. That one reads T9 JEYBARD

8#99999#055#33#999#22#666#2#777#3#1

@Optimizer for bonuses I don't know what should I do? Thanks for finding the issue. It's fixed.

@Mohsen usually, bonuses in code golf will subtract a fixed amount from the score. you'll have to figure out how much is reasonable. for the first bonus probably not more than 10 or 20 bytes. the second bonus, I don't even understand. if I give the sequence of keypresses as a string to the function, how would there be any sort of time between keypresses? I think a more reasonable bonus would be to allow omitting # if consecutive buttons are different anyway. that being said: without that bonus what should happen if # is omitted?

You need to add a possible byte count benefit for these bonuses. Bonuses are optional but you seem to ask every answer to implement the bonuses as if they are compulsory. Please clear the tone, if they are mandatory, move them to rules, if they are not, do not ask every answer to implement the bonuses. I will wait for a couple of hours for your reply before voting to close as unclear.

No reply even after 18 hours. Voting to close as unclear.

Does 000 give a sole space or 0+space? I.e. should it rotate or print when the max number of presses for a key is reached?

The exact behaviour of backspace is undefined: Does it reset the current character or does it delete it and we´re back at the previous position to continue typing? Does 9911*9# give XW or Y?

Should 899999055339992266627773 also give T9 KEYBOARD?

CJam, 109 94 bytes (2nd bonus)
A very naive and long solution
q'#/);{__'*-:A-,_g{){;}*A_}*;'0/{_,g{)~".?~1"a'[,65>292994 5b{/(X):X+\s}%+1:Xm>=\,=}*}%S*1/~}%

This is a full program, although a function will be of the same length.
The input goes into STDIN
Example:
8#99999#055#33#999#***22#666#2#777#3#

Output:
T9 BOARD

Try it online here

Can you make it work for the first bonus?

@Mohsen Not until there is an actual benefit of going for bonus! Lets say, a 25% code length reduction in final score.

JavaScript ES6, 220-10=210 178 bytes
As a part of Helka's CMC, I've outgolfed my first challenge.
n=>(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))(n.match(/(\d)\1*|\*/g).map(e=>e<"0"?e:(a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0])[~-e.length%a.length]).join``)

Sample outputs:
> f=n=>(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))(n.match(/(\d)\1*|\*/g).map(e=>e<"0"?e:(a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0])[~-e.length%a.length]).join``)
[Function]
> f("8#99999#055#33#999#***22#666#2#777#3#")
'T9 BOARD'
> f("8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#111#")
'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!'
> f("8#99999#055#33#999#***22#666#2#777#3#")
'T9 BOARD'

Explanation
(g=n=>n==(k=n.replace(/.\*/,""))?n:g(k))

This implements recursive replacement, replacing all characters followed by * until there are no *s left.
n.match(/(\d)\1*|\*/g)

This matches all runs of consecutive digits, or *s.
a=" |.?!|ABC|DEF|GHI|JKL|MNO|PQRS|TUV|WXYZ".split`|`[+e[0]]+e[0]

This creates the desired dictionary, obtaining the encoded part from the large string, then appending the desired digit to it.
a[~-e.length%a.length]

This gets the character, modulo a's length.
.join``

This prepares the string for processing and removal of *s.

Can you make it work with the first bonus?

@Mohsen Yes, and that might actual help it. I'll work on it through today and tomorrow.

Please at least do not advertise a score that is incorrect as the answer is not even up to the spec.

@Mohsen It is now working with the first bonus.

t("2#2"); gives B instead of AA. Try to match any # instead of removing them.

AWK 211 bytes (with the bonuses)
{split(".?!1-ABC2-DEF3-GHI4-JKL5-MNO6-PQRS7-TUV8-WXYZ9- 0",k,"-");split($0"#",a,"");while(1+(b=a[++i])){if(b==p)++c;else{for(g in k)if(p==substr(k[g],l=length(k[g])))printf(substr(k[g],1+((c-1)%l),1));c=1;p=b}}}

This is a full program which read the input from stdin. It would be more efficient to not resplit the keyboard for each line, but it would make the script longer.
Also if the "0" key was anything else than 0, the script would be 4 bytes shorter, but that's part of the game :o)

Python, 167 157 151 bytes
(doesn't support '*')
Nothing special. I use regex to convert the input to a list, then i loop the entries. I use the first character and length of each entry to search it in a lookup list:
def f(i):
  import re
  t9 = [" 0",".?!1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV9","WXYZ9"]
  i = re.findall(r'[1-9]+|0+',i)
  answer = []
  for j in i:
    answer = answer + [t9[int(j[0])][len(j)-1]]
  return ''.join(answer)

After some golfing it looks like this:
import re;m=lambda i:"".join([" 0,.?!1,ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV9,WXYZ9".split(",")[int(j[0])][len(j)-1] for j in re.findall(r'[1-9]+|0+',i)])

No bonuses (yet). I don't know how I would implement the first bonus in regex. The second bonus would add a lot of bytes as the lookup elements are not the same size. Don't really understand the third bonus.

Perl 5: 106 (104 code + 2 flags)
Modified to handle deletes.
#!perl -lp
s/((\d)\2*)#?|./chr$2*5+length$1/ge;y//d 0-3.?!1 ABC2 DEF3 GHI4 JKL5 MNO6 P-S7TUV8 W-Z9/c;1while s/.?d//

Usage:
perl t9.pl <<<'8#99999#055#33#999#22#666#2#777#3#'
perl t9.pl <<<'899999055339992266627773'

Perl 5: 88 (86 code + 2 flags)
Old version without star-delete.
#!perl -lp
s/(\d)(\1*)#?/chr$1*5+length$2/ge;y// 0-3.?!1 ABC2 DEF3 GHI4 JKL5 MNO6 P-S7TUV8 W-Z9/c

@Optimizer tried it, and it indeed doesn't work with *. Is it actually required though? It says: "Note that it can include * for backspace..."

Since its not part of the bonus. Its a mandatory rule.

That being said. the question is very unclear on what's a rule and what's a bonus. I asked OP for clarification several hours ago. If there is no response, I am voting to close this question as unclear.

Sorry, I was misled as current answers in the languages that I can read also do not support *.

If you're referring to my python answer, you're right. I misinterpreted the question.

Ruby 254, 248, 229 bytes
Golfed:
n=->(t){r,m,b=[]," _.?!1_ABC2_DEF3_GHI4_JKL5_MNO6_PQRS7_TUV8_WXYZ9_*_0_#".split("_"),nil;t.scan(/((.)\2*)/){|l,_|(!(l=~/\#/)?(l=~/\*/?(r.pop l.size):(l=="00"?r<<(b ? "0 ":" 0"):(c=m[l[0].to_i];r<<c[l.size%c.size-1]))):b=l)};r*""}

Ungolfed:
def t9totext(t)
  bonq = nil
  numpad = [" ",".?!1","ABC2","DEF3","GHI4","JKL5","MNO6","PQRS7","TUV8","WXYZ9","*","0","#"]

  r = []
  t.scan(/((.)\2*)/) do |l, _|
    if !(l =~ /\#/)
      if l =~ /\*/
        r.pop(l.size)
      elsif l == "00"
        r << (bonq ? "0 " : " 0")
      else
        c = numpad[l[0].to_i]
        r << c[l.size % c.size - 1]
      end
    else
      bonq = l
    end
  end
  r.join
end

All these specs should succeed:
  it "outputs the correct word" do
    expect(n.call('8#99999#055#33#999#22#666#2#777#3#1')).to eq("T9 KEYBOARD.")
    expect(n.call('4433555#55566609666666677755533*3111')).to eq("HELLO WORLD!")
    expect(n.call('7##222#222**7#222#4')).to eq('PPCG')
    expect(n.call('00#0#00')).to eq(' 0 0 ')
  end

The 0 0 answer looks a bit like a hacky solution. Will look into it when I've got the time.

C (245 bytes)
#define M "8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#111#"

#include<stdio.h>
char K[][4]={" ",".?!","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"},I[]=M;int
i,j,k,r;main(){for(;I[i];++i){if(I[i]=='#')I[j++]=K[k][--r],r=k=0;else
if(I[i]=='*')j?--j:0;else if(!r++)k=I[i]-'0';}I[j]=0;printf("%s\n",I);}

Output
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG!

Explanation
The byte count does not include the input string given in the first #define.
I use a two-dimensional array as the lookup table for what character to print. The program reads in characters delimited by '#'.
For each group, the input number determines the first-dimension array index, and the number of repetitions of the input number determines the second-dimension array index. The '*' moves back the index of the array for the output string so as to overwrite the previous letter.
So the input string 44# (1 repetition of '4') is translated to lookup table K[4][1], which is the character H.

Ungolfed Version
#define INPUT "8#44#33#0#999#*77#88#444#222#55#0#22#777#666#9#66#0#333#666#99#0#5#88#6#7#7777#0#666#888#33#777#0#8#44#33#0#555#2#99#*9999#999#0#3#666#4#"

#include<stdio.h>

static const char keyboard[10][4] = {" ", ".?!", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};

int main(void)
{
  char input[] = INPUT;
  char output[256];
  int i, j;
  int key = 0;
  int reps = 0;

  for (i = j = 0; input[i] != '\0'; ++i) {
    switch (input[i]) {
    case '#':
      output[j] = keyboard[key][reps - 1];
      ++j;
      reps = key = 0;
      break;
    case '*':
      if (j > 0) --j;
      break;
    default:
      if (reps == 0)  {
        key = (int)input[i] - '0';
      }
      ++reps;
      break;
    }
  }

  output[j] = '\0';
  printf("%s\n", output);

  return(0);
}

PHP, 183-10=173 bytes
All versions take input from command line argument; call with php -r '<code>' <string>.
Note: All versions throw a warning if input starts with *.
Prepend $o=[]; to the code to remove that flaw.
preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]="- 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)];echo join($o);

does not need hash tags
fails if a key is pressed too often

210-10-??=??? bytes
$a=[" 0",".?!1",ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV8,WXYZ9];preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=$a[$w[0]][strlen($w)%strlen($a[$w[0]])-1];echo join($o);

does not need hash tags
rotates if a key is pressed too often

181 bytes, no bonus
preg_match_all("%\d+#|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=" 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)-2];echo join($o);

breakdown
The "no hash tags" versions split the string to (streak of equal numbers) and (asterisk) and forget everything else. The no-bonus version takes (streak of numbers followed by #) and (asterisk).
Then loop through the matches: If a '*' is found, remove the last element of the result array.
The difference between the versions is in the else part:

no bonus version: offset map string to (key*5), then add (keystrokes=word length-1)-1, add character from that position to result.
simple no-tag version: almost the same, but: (keystrokes=word length); added a character to the map string to get rid of the other -1.
rotating version: take item (key) from map array, add character (keystrokes%item length-1) from that item to result.

JavaScript, 147 bytes
Conor´s answer fixed with the regex from my PHP answer and golfed down.
t=i=>i.match(/(\d)\1*|\*/g).map(w=>(" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length-1]).join``.replace(/.\*/g,"")

breakdown
t=i=>i
    .match(/(\d)\1*|\*/g)   // split input to streaks of equal numbers and single `*`
    .map(w=>                // replace each item with ...
                            // .. take string depending on the digit
        (" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]
        ||"*")              // .. ("*" for not a digit)
        [w.length-1]        // -> the (item length)th character of that string
    )
    .join``                 // join without delimiter
    .replace(/.\*/g,"")     // and recursively remove every (letter,asterisk) combination

rotating version, 158 bytes
added s= to remember the string and %s.length to rotate.
t=i=>i.match(/(\d)\1*|\*/g).map(w=>(s=" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length%s.length-1]).join``.replace(/.\*/g,"")

authors: علیرضا حسنعلی نژاد

authors: مظفر الشوبكي


text:
Draw A Snowflake
Joe lives at the Bahamas. It is winter. His children are disappointed that there is no snow. Joe needs to make snow for his children. Fortunately, he has a 3-d printer. He plans to make snowflakes with it. Unfortunately he has no idea how a snowflake would look like. In fact, he has never seen a snowflake! Let us help him by creating a program that automatically generates a 2d-image of a snowflake for him.
Input
The diameter of the image(in pixels), the percentage of the image that is actually a snowflake.
Output
An image of a snowflake with the required diameter. It can be saved to a file or displayed to the user.
Specifications
Create a wedge that has a 30 degree angle. Create a Brownian Tree with initial seed at the point of the wedge. Reflect the wedge around the center of the image 12 times to generate the rest of the image. The snowflake has the color White. The background has the color Black.
Scoring
Due to the fact there are different ways to generate a Brownian Tree, the score is 10 * number of upvotes - golf score.
Golf score is defined as the number of bytes in the program with the following bonuses:
-20% Can arbitrarily specify the symmetry of the snowflake.
-50% Can specify the shape of the snowflake. (By being able to specify the ratio of the lengths of the sides of the wedge.)
Highest score wins.
Here is a picture what the shape of the wedge would be with the ratio approximately 2:

Scoreboard:
Martin Buttner: 10 * 14 - 409 = -269
Nimi: 10 * 1 - 733 * .5 = -356.5
Optimizer: 10 * 5 - 648 = -598
The winner is Martin with score -269!

Related

Koch snowflake is duplicate of http://codegolf.stackexchange.com/questions/41011/graphical-representation-of-koch-snowflake

@feersum Koch bonus removed.

I cannot understand why, if we're allegedly helping someone who has never seen a snowflake know what they look like, we're supposed to make them have rotational symmetry of order 4. Are we supposed to be trolling the poor guy?

Also, what qualifies for the -20% "Can specify the symmetry of the snowflake"? Any choice between more than one symmetry group? Any choice from an infinite family of symmetry groups?

@PeterTaylor Any choice from an infinite family of symmetry groups.

"Highest score wins"? *makes a 300000000 byte code program to do this*

@Conor "The score is 10 * number of upvotes - golfscore." That program would have a score of -300000000. That is very low.

@TheBestOne ....oh. Right.... ^^"

Does the Brownian tree have to remain within the wedge?

6x60deg wedges! an improvement on what it said at the time of @PeterTaylor 's comment , but actually you need 12x30deg wedges.. 6 for the right hand side of each of the 6 points, and 6 reflected ones for the left hand side of each point. BTW, I don't understand the second bonus

@Martin Yes. It does have to.

@Steverill Thanks will fix symmetry.

@Optimizer Done, should be clearer now.

Mathematica, 409 bytes
{n,p}=Input[];m=999;Clear@f;_~f~_=0;0~f~0=1;r=RandomInteger;For[i=0,i<m,++i,For[x=m;y=0,f[x+1,y]+f[x-1,y]+f[x,y+1]+f[x,y-1]<1,a=b=-m;While[x+a<0||y+b<0||(y+b)/(x+a)>Tan[Pi/6],a=-r@1;b=r@2-1];x+=a;y+=b];x~f~y=1];Graphics[{White,g=Point/@Join@@{c=Cases[Join@@Table[{i,j}-1,{i,m},{j,m}],{i_,j_}/;i~f~j>0],c.{{1,0},{0,-1}}},Array[Rotate[g,Pi#/3,{0,0}]&,6]},Background->Black,ImageSize->n*p,ImageMargins->n(1-p)/2]

Ungolfed:
{n,p}=Input[];
m = 999;
ClearAll@f;
_~f~_ = 0;
0~f~0 = 1;
r = RandomInteger;
For[i = 0, i < m, ++i,
  For[x = m; y = 0,
   f[x + 1, y] + f[x - 1, y] + f[x, y + 1] + f[x, y - 1] < 1,
   a = b = -m;
   While[x + a < 0 || y + b < 0 || (y + b)/(x + a) > Tan[Pi/6],
    a = -r@1;
    b = r@2 - 1
    ];
   x += a;
   y += b
   ];
  x~f~y = 1
  ];
Graphics[
 {White, g =
   Point /@
    Join @@ {c =
       Cases[Join @@ Table[{i, j} - 1, {i, m}, {j, m}], {i_, j_} /;
          i~f~j > 0], c.{{1, 0}, {0, -1}}},
  Array[Rotate[g, Pi #/3, {0, 0}] &, 6]},
 Background -> Black,
 ImageSize -> n*p,
 ImageMargins -> n (1 - p)/2
 ]

This expects input the form {n,p} where n is the image size in pixels, and p is the percentage of the image to be covered by the snowflake.
It takes something like half a minute to generate a snowflake with the given parameters. You can speed it up by changing the value of m from 999 to 99, but then the result looks a bit sparse. Likewise, you can crank up the quality by using larger numbers, but then it'll take very long.
I'm forming the Brownian tree on an integer lattice, placing new particles at {999, 0}, and moving the randomly to the left and up or down (not to the right), until they hit the existing particles. I'm also constraining the motion to the wedge between 0 and 30 degrees. Finally, I reflect that wedge on the x-axis, and display it with its 5 rotations.
Here are some results (click for larger version):

And here are two animations of the Brownian tree growing (10 particles per wedge per frame):

Wow I like... all of them, actually. The results are nice!

JavaScript, ES6, 799 740 695 658 648

I am only counting the two canvas tags and the function f from the snippet below as part of the byte count. Rest of the stuff is for live demo
To watch it in action, just run the snippet below in a latest Firefox giving the size and ratio via the input boxes
Note that you will have to hide the result then show again before a consecutive snowflake

f=(N,P)=>{E.width=E.height=D.width=D.height=N
E.style.background="#000"
C=D.getContext("2d"),F=E.getContext("2d")
C.strokeStyle='#fff'
M=Math,r=M.random,I=0,n=N/2
C.beginPath()
C.rect(n,n,2,2)
C.fill()
B=_=>{x=n*P/100,y=0,w=[]
do{w.push([x,y])
do{X=2*((r()*2)|0)
Y=2*(((r()*3)|0)-1)
}while(x-X<0||y-Y<0||(y-Y)/(x-X)>.577)
x-=X,y-=Y}while(!C.isPointInPath(n+x,n+y))
I++
w=w.slice(-4)
x=w[0]
C.moveTo(x[0]+n,x[1]+n)
w.map(x=>C.lineTo(n+x[0],n+x[1]))
C.stroke()
E.width=E.height=N
for(i=0;i<12;i++){F.translate(n,n)
i||F.rotate(M.PI/6)
i-6?F.rotate(M.PI/3):F.scale(1,-1)
F.translate(-n,-n)
F.drawImage(D,0,0)}
I<(n*n*P*.22/100)&&setTimeout(B,15)}
B()}
<input placeholder="Input N" id=X /><input placeholder="Input percentage" id=Y /><button onclick="f(~~X.value,~~Y.value)">Create snowflake</button><br>
<canvas id=E><canvas id=D>

Here are a few example renders with different size and percentages. The best one is called SkullFlake (first in the list). Click the images to see them in full resolution.

A lot of help and input from Martin and githubphagocyte.

This doesn't take the percentage of the image that is filled as input.

@TheBestOne it takes percentage into account now. Do note that since this is a Brownian tree based snowflake, neither the percentage nor the ratio for wedge lengths can be accurate as a role of randomness is in play.

This qualifies now.

Haskell, 781 733 Bytes
The program features the „specify the ratio of the lengths of the sides of the wedge“ option, so you have to call it with three command line arguments:
./sf 150 50 40

Argument #1 is the size of the image, #2 the % of pixels in the wedge and #3 the length (in %) of the shorter side of the wedge. The image is saved in a file called „o.png“.
150-50-40:
My program produces snowflakes with cut-off spikes, because new pixels start on the middle axis of the wedge (green dot, see below) and tend to stay there, because they move equally random to the left, up or down. As pixels outside the wedge are discarded, straight lines appear on the boundary of the wedge (green arrow). I was too lazy to try out other paths for the pixels.
150-50-40:
When the wedge is big enough (3rd argument 100) the spikes on the middle axis can grow and then there are 12 of them.
150-40-100:
Few pixels make round shapes (left: 150-5-20; right 150-20-90).

The program:
import System.Environment;import System.Random;import Graphics.GD
d=round;e=fromIntegral;h=concatMap;q=0.2588
j a(x,y)=[(x,y),(d$c*e x-s*e y,d$s*e x+c*e y)] where c=cos$pi/a;s=sin$pi/a
go s f w p@(x,y)((m,n):o)|x<1=go s f w(s,0)o|abs(e$y+n)>q*e x=go s f w p o|elem(x-m,y+n)f&&(v*z-z)*(b-q*z)-(-v*q*z-q*z)*(a-z)<0=p:go s(p:f)w(s,0)o|1<2=go s f w(x-m,y+n)o where z=e s;a=e x;b=e y;v=e w/100
main = do
 k<-getArgs;g<-getStdGen;let(s:p:w:_)=map read k
 i<-newImage(2*s,2*s);let t=h(j 3)$h(\(x,y)->[(x,y),(d$0.866*e x+0.5*e y,d$0.5*e x-0.866*e y)])$take(s*d(q*e s)*p`div`100)$go s[(0,0)]w(s,0)$map(\r->((1+r)`mod`2,r))(randomRs(-1,1)g)
 mapM(\(x,y)->setPixel(x+s,y+s)(rgb 255 255 255)i)((h(j(-3/2))t)++(h(j(3/2))t));savePngFile "o.png" i

@Optimizer: the spike is on the middle axis of the wedge. The wedge goes up and down 15 degrees to the x-axis. In a *-*-100 image both of it's sides reach to the left border of the image (see the second image for the position of the wedge). There are pixels on approximately half of the sides - the other halves are empty.

Using this counter your program has length 841 bytes.

@TheBestOne: Tabs vs. Spaces when indenting. I've mixed them up when adding additional 4 spaces for code style. I've edited my post and set Tabs, but they still appear as spaces. Does anyone know how to fix it?

@nimi On the site TheBestOne linked there's a little hash # link which you can click. You can paste your tabbed code there and link it.

You could probably make a link to the code somewhere. You could use spaces instead of tabs to indent. You could manually get code style by indenting every line 4 spaces.

The counter now shows 780 Bytes. I guess the 1 byte difference is because of the missing last NL.

Got rid of the tabs and saved a few bytes

Processing 2 - 575 characters
Takes in a file f whose first line is the image size and the second is the flakes radius.
Every time a new point is placed it is rotated around the center 12 times. This creates a very similar effect as a rotated wedge, but not exactly the same.
  int d,w,h,k,l,o,p,x,y;
  String n[] = loadStrings("f.txt");
  d=Integer.parseInt(n[0]);
  h=Integer.parseInt(n[1]);
  size(d,d);
  w=d/2;
  k=l=(int)random(d);
  background(0);
  loadPixels();
  o=p=0;
  pixels[w*w*2+w]=color(255);
  while(true)
  {
    o=k+(int)random(-2,2);
    p=l+(int)random(-2,2);
    if(p*d+o>d*d-1 || p*d+o<0 || o<0 || o>d){
      k=l=(int)random(d);
    }
    else
    {
      if(pixels[p*d+o]==color(255))
      {
        p=l-w;
        o=k-w;
        if(o*o+p*p>h*h){break;}
        float s,c;
        for(int j=0;j<12;j++)
        {
          s=sin(PI*j/6);
          c=cos(PI*j/6);
          x=(int)((o*c)-(p*s));
          y=(int)(((p*c)+(o*s)));
          pixels[(int)(d*y+x+w+(w*d))]=color(255);
        }
        k=l=(int)random(d);
      }
      else
      {
        k=o;
        l=p;
      }
    }
  }
  updatePixels();

you can get processing here

This doesn't quite fit the specifications. This would qualify if you reflected the point around the center instead of rotating it.

color(255) can become color(-1) to save one byte


text:
Reverse indentation

I've heard that your code can run faster if you indent it in reverse, so that the compiler can process it like a tree design pattern from the very top of the "branches" down. This helps because gravity will speed up the time it takes for your code to be compiled, and the data structure efficiency is improved. Here's an example, in Java scripting:
            function fib(n) {
        var a = 1, b = 1;
        while (--n > 0) {
    var tmp = a;
    a = b;
    b += tmp;
    if (a === Infinity) {
return "Error!";
    }
        }
        return a;
            }

But for some reason Notepad doesn't have a setting to do this automatically, so I need a program to do it for me.
Description
Submissions must take a code snippet as input, reverse the indentation, and output the resulting code.
This is done by the following procedure:

Split the code up into lines. Each line will start with zero or more spaces (there will be no tabs).
Find all unique indentation levels in the code. For example, for the above example, this would be
0
4
8
12

Reverse the order of this list of indentation levels, and map the reversed list to the original list. This is hard to explain in words, but for the example, it would look like
0  — 12
4  — 8
8  — 4
12 — 0

Apply this mapping to the original code. In the example, a line with 0-space-indentation would become indented by 12 spaces, 4 spaces would become 8 spaces, etc.

Input / Output
The input and output can be provided however you would like (STDIN/STDOUT, function parameter/return value, etc.); if your language does not support multiline input (or you just don't want to), you can use the | character to separate lines instead.
The input will consist of only printable ASCII + newlines, and it will not contain empty lines.
Test cases
Input:
function fib(n) {
    var a = 1, b = 1;
        while (--n > 0) {
            var tmp = a;
            a = b;
            b += tmp;
            if (a === Infinity) {
                return "Error!";
            }
        }
    return a;
}

Output: the example code above.
Input:
a
  b
  c
d
   e
        f
  g
   h

Output:
        a
   b
   c
        d
  e
f
   g
  h

Input:
1
 2
  3
 2
1

Output:
  1
 2
3
 2
  1

Input:
  foo

Output:
  foo

Its "JavaScript" not "Java scripting" :/

@Optimizer I see that my goal of infuriating as many people as possible with the first two paragraphs has been achieved. ;)

1 != as many people as possible.

WAT. How could anyone possibly think this is a good idea?

@JanDvorak The same guys that invented MLA style citations think this is a good idea.

Are these the same guys who made the comefrom statement?

Are we allowed to append a single newline?

Supposedly, it's faster. Let's assign a committee to it and wait a few years while we forget the purpose of it.

This explains why Python is so slow...

I literally laughed out loud at "for some reason, Notepad doesn't do this automatically"

Before anything, this made me cringe like hell.

Gravity pulls sideways? coooooool

This is almost as bad as using spaces for indenting

This is infuriating...good job

CJam, 43 39 36 35 bytes
qN/_{_Sm0=#}%___&$_W%er]z{~S*@+>N}%

This looks toooo long. I am sure I am not Optimizing enough!
How it works:
Basic idea is to split the input on newline, calculate the number of leading spaces in each line, sort and get unique numbers, copy that array and reverse the copy, transliterate the original in-order numbers with this two arrays and then finally form the final string using this information.
The lengthiest part is to figure out how many leading spaces are there in each line as CJam does not have an easy way of doing it.
Code expansion:
qN/_                                      "Split the string on newline and take copy";
    {_Sm0=#}%                             "Map this code block on the copy";
     _Sm                                  "Copy the string and remove spaces from the copy";
        0=                                "Get first non space character";
          #                               "Gets its index in original string";
             ___                          "Get 3 copies of the above array";
                &$_W%                     "Get unique elements, sort, copy and reverse";
                     er                   "Transliterate unique sorted elements with";
                                          "the unique reverse sorted in the copy";
                       ]z                 "Get array of [row,
                                          " original number of leading spaces,
                                          " required number of leading spaces]";
                         {~S*@+>N}%       "For each above combination";
                          ~S*             " unwrap and get leading space string";
                             @+           " prepend to the row";
                               >          " remove original spaces";
                                N         " put newline";

And in the spirit of the question. A real expansion of the code:
                                          qN/_                                      "Split the string on newline and take copy";
                                {_Sm0=#}%                             "Map this code block on the copy";
                               _Sm                                  "Copy the string and remove spaces from the copy";
                             0=                                "Get first non space character";
                          #                               "Gets its index in original string";
                         ___                          "Get 3 copies of the above array";
                       &$_W%                     "Get unique elements, sort, copy and reverse";
                     er                   "Transliterate unique sorted elements with";
"the unique reverse sorted in the copy";
                ]z                 "Get array of [row,
" original number of leading spaces,
" required number of leading spaces]";
             {~S*@+>N}%       "For each above combination";
          ~S*             " unwrap and get leading space string";
        @+           " prepend to the row";
     >          " remove original spaces";
    N         " put newline";

7 bytes saved thanks to Martin and 1 byte thanks to Dennis
Try it online here

{}# has a bug: it returns an Integer, but it should return a Long. Ironically, i (cast to integer) fixes this. 2. Since ""# doesn't have the same bug, _Sm0=# is one byte shorter.

@Dennis Yeah, the bug is weird. Thanks for the workaround !

this indentation in the expansion is so easy to read! You should reverse it!

Python 2 - 137 131 bytes
i=raw_input().split('|')
f=lambda s:len(s)-len(s.lstrip())
d=sorted(set(map(f,i)))
for l in i:print' '*d[~d.index(f(l))]+l.lstrip()

Takes input with | instead of \n.
Explanation
The first three lines are fairly straightforward. Make a list of all the lines in the input, define a function that tells you how much leading whitespace a string has, and make a sorted list of values that function spits out for each line of input.
The last line is way more fun.
                                 l               # string with the line
                               f(l)              # amount of leading whitespace
                       d.index(f(l))             # where it is in list of whitespace amounts
                      ~d.index(f(l))             # bitwise NOT (~n == -(n+1))
                    d[~d.index(f(l))]            # index into the list (negative = from end)
           print' '*d[~d.index(f(l))]            # print that many spaces...
           print' '*d[~d.index(f(l))]+l.lstrip() # plus everything after leading whitespace
for l in i:print' '*d[~d.index(f(l))]+l.lstrip() # do the above for every line

Confirmed 137 :)

This all seems fine in python 3 which should save you 2 bytes (pay 2 for () save 4 for raw_)

f(s)for s in i should be map(f,i).

A piece of magic: d=[];d+=set(L) is a shorter version of d=sorted(set(L)).

@fry sure, but I like python2 better ;)

@fee not sure how i missed that, i use map all the time! thanks :)

@xno yeah, i was informed in chat and had't had a chance to play with it yet. thanks :)

@xnor I suggested that, thinking it was a good idea. But then I tried with larger and more numbers and found out that it doesn't actually work...

I have a suspicion that it fails if the largest element is larger than the number of elements there are, e.g. x=[];x+=set(random.randint(0, 10000) for i in range(10))

Now make your "correctly" indented code run!

JavaScript, ES6, 113 103 101 bytes
I am pretty sure this can be golfed at least a little further, but here goes.
Never would have thought that there will be a 101 bytes JS solution, beating Python!
f=a=>(b=c=[...Set(a.match(r=/^ */gm).sort())],c.map((x,i)=>b[x]=c.slice(~i)[0]),a.replace(r,x=>b[x]))

This creates a method named f which can be called with the input string. If you are in a latest Firefox, you have template strings and you can call the method like
f(`a
  b
  c
d
   e
        f
  g
   h`)

Otherwise, you can also call it like
f("a\n\
  b\n\
  c\n\
d\n\
   e\n\
        f\n\
  g\n\
   h")

or, try the snippet below:

g=_=>O.textContent=f(D.value)

f=a=>(b=c=[...Set(a.match(r=/^ */gm).sort())],c.map((x,i)=>b[x]=c.slice(~i)[0]),a.replace(r,x=>b[x]))
<textarea id=D></textarea><button id=B onclick=g()>Inverse!</button>

You can save a coupes bytes by storing the regex as a variable, as it is used twice (you should be able to replace \s with a space character), and removing the parentheses around x in the replace function.

@hsl gee, thanks! I don't even know why I wrote (x) :/

You don't need both b and c do you? They just refer to the same array anyway.

Ruby, 63 bytes
->s{l=s.scan(r=/^ */).uniq.sort;s.gsub r,l.zip(l.reverse).to_h}

This defines an unnamed function which takes and returns a string. You can call it by appending ["string here"] or by assigning it to a variable, and then calling that variable.
How it works: s.scan(r=/^ */) gives a list of all leading spaces and stores that regex in r for later use. uniq eliminates duplicates. sort... sorts.
Now skip to the end, l.zip(l.reverse) gives an array of pairs we want to substitute. to_h turns that into a hash, interpreting the pairs as key-value pairs.
Now s.gsub replaced all matches of the regex (all leading spaces) by using that hash as a look up table to find the replacement.

Pyth 39
L-/bd/rb6dJcz\|KS{mydJFNJ+*d@_KxKyN>NyN

Try it online.
Uses the | delimiter option.

Japt -R, 27 bytes
·
mâ\S
Vâ n
Ëx2 iSpWg~WbVgE

Try it online!
Unpacked & How it works
Input: U = multiline string

qR    Split by newline and implicit assign to U

mâ\S
m     Map over U...
 â\S    .search(/\S/); first index of non-whitespace char
      Implicit assign to V (V = array of indentations)

Vâ n  Take unique elements of V, sort, and implicit assign to W

mDEF{Dx2 iSpWg~WbVgE
mDEF{                 Map over U...
     Dx2                Trim left
         iSp            Indent by this many spaces...
                 VgE      Find the current indentation stored in V
               Wb         Find its index on W
            Wg~           Take the opposite element on W

-R    Join with newline

How it really works
                 Input: U = multiline string

                 qR    Split by newline and implicit assign to U

                 mâ\S
                 m     Map over U...
               â\S    .search(/\S/); first index of non-whitespace char
         Implicit assign to V (V = array of indentations)

                 Vâ n  Take unique elements of V, sort, and implicit assign to W

                 mDEF{Dx2 iSpWg~WbVgE
                 mDEF{                 Map over U...
            Dx2                Trim left
      iSp            Indent by this many spaces...
VgE      Find the current indentation stored in V
 Wb         Find its index on W
     Wg~           Take the opposite element on W

                 -R    Join with newline

Scala, 176171
def g(n:String)={val a=n.split('|').map(a=>a.prefixLength(' '==)->a)
(""/:a){case(s,(l,p))=>val b=a.unzip._1.distinct.sorted
s+" "*b.reverse(b.indexOf(l))+p.drop(l)+'\n'}}

It will add an extra newline at the end. If I did not have to preserve spaces at the end of the line, I can get it to 167:
def t(n:String)={val a=n.split('|').map(a=>a.prefixLength(' '==)->a.trim)
(""/:a){(s,l)=>val b=a.unzip._1.distinct.sorted
s+" "*b.reverse(b.indexOf(l._1))+l._2+'\n'}}

Ungolfed:
      def reverseIndent(inString: String): String = {
    val lines = inString.split('\n')
    val linesByPrefixLength = lines.map { line =>
  line.prefixLength(char => char == ' ') -> line
    }
    val distinctSortedPrefixLengths = linesByPrefixLength.map(_._1).distinct.sorted
    val reversedPrefixes = distinctSortedPrefixLengths.reverse
    linesByPrefixLength.foldLeft("") { case (string, (prefixLength, line)) =>
  val newPrefixLength = reversedPrefixes(distinctSortedPrefixLengths.indexOf(prefixLength))
  val nextLinePrefix = " " * newPrefixLength
  string + nextLinePrefix + line.substring(prefixLength) + '\n'
    }
      }

Haskell, 116
import Data.List
f s|l<-map(span(==' '))$lines s=unlines[k++b|(a,b)<-l,(k,r)<-reverse>>=zip$sort$nub$map fst l,r==a]

PowerShell, 112 bytes
$x=@($args|sls '(?m)^ *'-a|% m*|% v*|sort -u)
[regex]::Replace($args,'(?m)^ *',{$x[-1-$x.IndexOf($args.Value)]})

Try it online!
Less golfed:
$xIdents=@($args|select-string '(?m)^ *'-AllMatches|% matches|% value|sort -unique) # get a sorted set of indentations
[regex]::Replace($args,'(?m)^ *',{$xIdents[-1-$xIdents.IndexOf($args.Value)]})    # replace each indentation with opposite one

JavaScript, 351
var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);

Ungolfed version:
var i = 0;
var a = $("#i").html().split("\n");
var b = [];
for (; i < a.length; i++) {
  j = a[i].match(/\s*/)[0];
  if (b.indexOf(j) < 0) {
    b.push(j);
  }
}
b.sort(function(a, b) {
  return a - b;
});
var c = b.slice().reverse();
var d = "";
for (i = 0; i < a.length; i++) {
  d += a[i].replace(/\s*/, c[b.indexOf(a[i].match(/\s*/)[0])]) + "\n";
  j = a[i].search(/\S/);
  if (b.indexOf(j) < 0) {
    b.push(j);
  }
}
$("#i").html(d);

Testing

var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);

function fib(n) {
    var a = 1, b = 1;
        while (--n > 0) {
            var tmp = a;
            a = b;
            b += tmp;
            if (a === Infinity) {
                return "Error!";
            }
        }
    return a;
}

var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);

a
  b
  c
d
   e
        f
  g
   h

var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);

1
 2
  3
 2
1

var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d);

  foo

PHP - 173 bytes
The unoptimized code should be stored in the $v variable:
<?php $f='preg_replace';$f($p='#^ *#me','$i[]='.$s='strlen("$0")',$v);$a=$b=array_unique($i);sort($a);rsort($b);echo$f($p,'str_repeat(" ",array_combine($a,$b)['.$s.'])',$v);

Here is the ungolfed and commented version:
<?php
// Get the level of indentation for each line
$preg_replace = 'preg_replace';
$pattern = '#^ *#me';
$strlen = 'strlen("$0")';
$preg_replace($pattern, '$indentationLevelsOldList[] = '. $strlen, $value);

// Create an array associating the old level of indentation with the new expected one
$sortedArray = array_unique($indentationLevelsOldList);
$reverseSortedArray = $sortedArray;

sort($sortedArray);
rsort($reverseSortedArray);

$indentationLevelsNewList = array_combine($sortedArray, $reverseSortedArray);

// Print the correctly indented code
echo $preg_replace($pattern, 'str_repeat(" ", $indentationLevelsNewList['. $strlen .'])', $value);

I've probably never written something so dirty. I'm ashamed.

Perl 5, 112
111 + 1 for -n (-E is free)
@{$.[$.]}=/( *)(.*)/;++$_{$1}}{map$_{$_[$#_-$_]}=$_[$_],0..(@_=sort keys%_);say$_{$.[$_][0]}.$.[$_][1]for 0..$.

I'm sure it can be done in fewer strokes, but I don't see how at the moment.