text:
1/N probability
Because there are not enough simple code-golf challenges:
Create an optionally unnamed program or function that, given (by any means) an integer 1 ≤ N ≤ 10000, outputs your language's True value with a pseudo-random probability of 1/N, False otherwise.
Please note that the requirement for naming has been removed. Feel free to edit answers and scores accordingly.
Some languages use 1 (or -1) and 0 for True and False, that is fine too.
Example:
Example input tests:
4 -> True
4 -> False
4 -> False
4 -> False
4 -> False
4 -> True
4 -> False
4 -> False

I.e. given 4; it returns True with a 25% chance and False with a 75% chance.

Relevant meta post

Also relevant meta post.

As not all languages have built in "pseudorandomness" is it possible to get a seed as second argument? (E.g. Brainfuck)

@flawr use current millisecond...

@NBZ Brainf*** doesn't have that either

@SuperJedi224 Right. OK then; have a seed and optionally return a new seed. But only for languages that really don't have other options.

What's the largest N we have to accept?

@TobySpeight 10000.

MediaWiki templates with ParserFunctions, 48 bytes
{{#ifexpr:1>{{#time:U}} mod {{{n}}}|true|false}}

Interesting choice of language :-)

Who the heck thought it would be sensible to add non-deterministic functions to MediaWiki templates!?

@immibis: well the non-determinism occurs from #time, probably to update the age of living people, etc.

Pyth, 3 bytes
!OQ

Try it online
Simple inversion of random choice from 0 to input
Amusingly in Pyth it is not possible to make a function that does this without $ because Pyth functions are automatically memoized.

It is possible.

@LeakyNun Ah right, I had forgotten about using the time for a random function, that's rather clever.

No, I just used time to de-memoize it.

I'm aware, I guess I just didn't word it well :P That said I don't think it would really work as a workaround for most submissions, if it were ever better than a full program for some reason. Taking the time as an argument probably isn't just allowed by default.

another one: qhO :p

@LeakyNun I believe this question predates the Q filling in at the end, as otherwise I would have answered !O ;)

CJam, 5 bytes
Gotta be quick with these ones...
rimr!

Test it here.
Explanation
ri e# Read input and convert to integer N.
mr e# Get a uniformly random value in [0 1 ... N-1].
!  e# Logical NOT, turns 0 into 1 and everything else into 0.

"Gotta be quick with these ones..." which is a reason to disagree with OP that "there are not enough simple [tag:code-golf] challenges". If FGITW is an issue, IMO it's too simple.

TI-BASIC, 4 bytes using one byte tokens
not(int(Ansrand

Determines if the integer part of the input times a random number in [0,1) is zero. Ansrand<1 also works.

How... Is that four bytes?

@JanDvorak The first bytes is not(, the next is int(, the next is Ans, the next is rand. In general, graphing calculators do not use ASCII as their internal representation for programs.

@immibis In general, computers don't use ASCII either. This might be questionable, is there a meta discussion about that?

@Kroltan Yes; this is the meta discussion, and this is the list of tokens that are one byte, which includes all four that I used.

@ThomasKwa thanks!

MATL, 5 bytes
Three different versions of this one, all length 5.
iYr1=

which takes an input (i), generates a random integer between 1 and that number (Yr), and sees if it it is equal to 1 (1=). Alternatively,
li/r>

make a 1 (l, a workaround because there is a bug with doing 1i at the moment), take an input (i), divide to get 1/N (/), make a random number between 0 and 1 (r), and see if the random number is smaller than 1/N. Or,
ir*1<

take and input (i), and multiply by a random number between 0 and 1 (r*), and see if the result is smaller than 1 (1<).
In Matlab, not MATL, you can do this anonymous function
@(n)n*rand<1

for 12 bytes, which is used by doing ans(5), for example.

Julia, 17 16 15 bytes
n->2>rand(1:n)

This is a function that generates a random integer between 1 and n and tests whether it's less than 2. There will be a 1/n chance of this happening, and thus a 1/n chance of returning true.
Saved 1 byte thanks to Thomas Kwa!

JavaScript ES6, 15 bytes
-5 bytes thanks to Downgoat.
x=>1>new Date%x

Based off (uses) of this answer's technique.

new Date can also work and might save a few bytes

@Downgoat Ah, right, Date randomness!

Microscript II, 3 bytes
NR!

Reads an integer n, generates a random integer between 0 and n-1 (inclusive), then applies a boolean negation to that value.

Candy, 2 bytes
Hn

H stands for Heisen-double
n stands for not
The 'n' is passed with the -i flag as numeric input.  Values left on the stack are printed on exit.
"Long" form:
rand   # number between 0 and pop()
not    # cast to int, invert non-zero to zero, and zero to one

I think you'd need to count -i as one byte.

basically the only way to pass numeric input is with the -i flag.  I guess only languages that read from stdin suffer no input specification penalty?

Well, if there were a generic input flag, or you just used regular CLAs to pass arguments, that would definitely be fine. It seems unfair that the datatype is being specified for free, though.

@ThomasKwa Should a function written in a dynamic language have to count the bytes to specify that the argument is an integer in the documentation? In lambda x: random.random()<1/x (ungolfed) it's also "specified for free" that the argument is a number.

@immibis Hmm, that's a good point. I guess trying to keep the rules for programs and functions the same should allow this, then. I'll make a post on meta.

R, 30 22 bytes
code
cat(runif(1)<1/scan())          #new
f=function(N)cat(runif(1)<1/N)  #old

It generates a number from a uniform distribution (0 to 1) and should evaluate to true 1/n of the times.

Seriously, 3 bytes
,JY

0 is falsey and 1 is truthy. Try it online
Explanation:
,JY
,    get input
 J   push a random integer in range(0, input) ([0, ..., input-1])
  Y  logical not: push 0 if truthy else 1

APL, 6 3 bytes
+=?

This is a function train that takes an integer and returns 1 or 0 (APL's true/false). We generate a random integer from 1 to the input using ?, then check whether the input is equal to that integer. That results in a 1/input chance of true.
Saved 3 bytes thanks to Thomas Kwa!

@ThomasKwa I thought about some kind of train, but does that really count as a "named function" if assigned? I guess the "named" part is throwing me here since it's atypical.

@ThomasKwa Assignment of trains (and derived functions) is completely parallel to all other assignments.

@NBZ what do you mean by parallel?

@ThomasKwa Equivalent; behaving like any other function assignment.

I would use ⊢ instead of '+' because + means Conjugate for complex numbers. Of course it doesn't matter here, and + is the traditional identity (no-op) function, but now we have ⊢ (same). Other no-ops for scalars are: ⌷ (materialize), ⊃ (pick), ⊂ (enclose), ↑ (split), ↓ (mix), ∪ (unique), ∊ (enlist), , (ravel), ⍪ (table), ⌽ (reverse), ⊖ (reverse first), and ⍉ (transpose). Some change the scalar into a vector or matrix.

Japt, 6 bytes
1>U*Mr

Try it online!
Mr is equivalent to JS's Math.random. The rest is pretty obvious. I could probably add a number function that generates a random float between 0 and the number. When this happens, two bytes will be saved:
1>Ur    // Doesn't currently work

Alternate version:
1>Ð %U

Ð is equivalent to new Date(, and the Date object, when asked to convert to a number, becomes the current timestamp in milliseconds. Thus, this is entirely random, unless it is run multiple times per ms.

PlatyPar, 3 bytes
#?!

#? gets a random number [0,n) where n is input.
! returns true if the number before it is 0, else it returns false.
Using more recent features that were implemented (but unfortunately for me not committed) before this question was asked I can get it down to 2 with ~!
Try it online!

Marbelous, 21 bytes
}0    # takes one input n
--    # decrements n
??    # random value from range 0..n (inclusive)
=0?0  # push right if not equal to 0, fall through otherwise | convert to zero
++    # increment | no-op
{0//  # output | push left

I've taken 0 to be falsey and 1 to be truthy, though there is no real reason for that seeing as Marbelous doesn't really have an if. More Marbelousy would be output to {0 for true and {> for false. This would look like this:
}0
--
??
=0{>
{0

But I'm not sure that's valid.

I'd be up for a meta discussion on this. Short version of my view: outputting a value to a different output is equivalent to having different output tuples in another language. If (nil,1) and (1,nil) can be your truthy and falsey values in another language, then {0 vs {> should be allowed in Marbelous.
PS: your {> version won't exit because you never fill the other output.

@Sparr it will exit due to inactivity, no?

You're right. I feel dumb.

Java, 43 bytes
boolean b(int a){return a*Math.random()<1;}

a->a*Math.random()<1 is shorter.

Should specify "Java 7 or earlier".

@corsiKlauseHoHoHo This works in Java 8 as well though

Of course it does - but it's not golfed for Java 8, which would use lambdas to save space. By that logic, all Java answers are also Groovy answers, but Groovy is always the same or smaller because it has shortcuts that Java doesn't.

C, 24 bytes
f(n){return!(rand()%n);}

I've rolled back OP's edit removing the first 4 characters. It's nice to have bytes reduced, but to me, having the returnwithout the f(n) doesn't make any sense syntactically.

@insertusernamehere  rand()%n is a standard way of getting a random number in the range 0..n-1. You are correct, it does rely on  n being much smaller than RAND_MAX but there is no upper limit for n mentioned in the question. An alternative approach would be to do a reject and re-roll on all numbers from n to RAND_MAX but it would be hopelessly inefficient at small n.

><>, 27 + 3 for -v = 30 bytes
Here is a not-uniform-at-all solution where I mod N the sum of 15876 random picks of 0 or 1 :
0"~":*>:?vr%0=n;
1-$1+$^-1x

N must be input on the stack with -v flag, output is 0 for falsey and 1 for truthy.
A much smarter and uniform solution that work for 1/2^N instead :
4{:?!v1-}:">"$2p:"x"$3p:"^"$4p1+:">"$3p1+!
   ^1<
0n;
1n;>

For an input 3 you've got 1/8 chances of getting 1 and 7/8 of getting 0.
Explanation :
I append as much x as needed on the 4th line and surround them with directions so there is only two ways out of the x: either the falsey output or the next x. If all x go in the right direction, the last one will route to the truthy output.
For example for N=5, the final codespace is the following :
4{:?!v1-}:">"$2p:"x"$3p:"^"$4p1+:">"$3p1+!
   ^1<
0n; > > > > >
1n;>x>x>x>x>x>
    ^ ^ ^ ^ ^

While it's true you can't get a perfect distribution for arbitrary N, neither can anyone else using a PRNG. You could loop through an x a few times to get a bunch of random bits, assemble them into an int I, then use I%N as your random value.

@Sparr edited my answer but I feel like using a big number of iteration will 'average out' the resulting integer, making the output heavily tend toward (iterNum/2)%N. I don't think using a lower number would be a solution either. Did I maybe not quite understood you, or would you have any further idea to better the solution?

instead of adding 15000 bits together, produce just 32 bits and concatenate them, giving you a uniformly distributed 32-bit random integer. mod that.

@Sparr that seems better indeed, even if I've no idea why ;) That'll cost much more bytes (><> sucks for byte operations & base conversion) but I'll change my answer this evening (CEST).

you can concatenate bits by multiplying by two and adding: r=0; for(0..32) r=r*2+randbit;

Mathematica, 18 16 bytes
#RandomReal[]<1&

Basic solution. The unnamed Function creates a random number in [0, 1), multiplies it by its argument, and checks if it is still less than 1.

Python, 42 bytes
import random
lambda n:1>random.random()*n

Edit: Removed the time.time() answer because of the distribution.

For random, it's worth doing from random import* to save on random.. Not for time though.

Random numbers generated by modulo division are not uniformly distributed.

@TrangOul That's a good point; for larger n the effect could be noticeable. I think 1>time.time()%1*n could work.

@TrangOul I presume you know the difference between rand in C, and time.time in Python... One obvious feature of the latter is that it returns the current time, which is unbounded, so that time.time()%n has a uniform distribution (over long enough periods of time) for any n.

TeaScript, 3 bytes
!N×

Try it here.
Explanation
 N  maps to Math.rand which is a utility function that returns an integer
    between `arg1` and `arg2` or `0` and `arg1` if only one argument is
    provided.
  × is expanded to `(x)`, where `x` is initialised with the value provided
    in the input boxes; × represents byte '\xd7'
!   negate the result, 0 results in true, anything else false

How does seven chars add up to 6 bytes? And is the (R) a (single byte) ANSI char?

@NBZ, haha! I think I lied... I blame hangover... I'll update now as I'm going to change the mechanism to a more straightforward one that I've just noticed! In this current version the ® represents the char '\xae' so is just one byte. :)

Fuzzy Octo Guacamole, 10 bytes
^-!_[0]1.|

Explanation:
^-!_[0]1.|

^          # Get input.
 -         # Decrement, so we can append <ToS> zeros and a 1 to the stack.
  !        # Set loop counter.
   _       # Pop, since we are done with the input.
    [      # Start loop
     0     # Push 0
      ]    # End for loop. We have pushed input-1 0s to the stack.
       1   # Push a single 1 to the stack.
        .  # Switch stacks
         | # Pick a random item from the inactive stack, which has n-1 falsy items and 1 truthy item, so the truthy probability is 1/n.
           # (implicit output)

Ruby, 14
Function
->n{rand(n)<1}

Program is slightly longer
p rand(gets.to_i)<1

Perl 6,  10  8 bytes

!(^*).pick
#  ^- The * is the argument

This code creates a Range from 0 up-to but excluding the input *. It then picks one at random and the ! returns True when it receives a 0.

1>*.rand
# ^- The * is the argument

This takes the input * and multiplies it by a random Num from 0..^1 then returns True if it was smaller than 1.
# store it in a lexical code variable for ease of use
my &code = 1>*.rand;

die "never dies here" unless code 1;

for ^8 { say code 4 }

False
True
False
False
False
True
False
False

C#, 56 45 bytes
Thanks to, pinkfloydx33 it's 45 now.
bool b(int n){return new Random().Next(n)<1;}

Old 56 bytes
Generates random positive integer bigger or equal to 0 and smaller than n and checks if it's smaller than 1 and return comparison result.
bool a(int n){Random r=new Random();return r.Next(n)<1;}

Welcome to PPCG! Unfortunately, this submission doesn't work, because Random.Next(k) returns an integer k such that 0 <= k < n. By changing the condition to <1, it will be correct. In addition, the use of a lambda expression may get your code shorter.

@Mego Sure, thank you for comment. I made it 0 < k <= n and it should be like you said. I'll correct it immediately.

Use var r saves three. Or if c#6, bool a(int n) => new Random().Next(n)<1; for 41. Though not sure if initializing a new Random per method call will work properly as far as distribution?

PHP, 22 bytes
<?=2>rand(1,$argv[1]);

Reads n from command line, like:
$ php probability.php 4

Outputs   (false is cast to an empty string in PHP) or 1 (in case of true).

Prolog (SWI), 24 bytes
Code:
p(N):-X is 1/N,maybe(X).

maybe(+P) is a function which succeeds with probability P and fails with probability 1-P
Example:
p(4).
false

p(4).
false

p(4).
true

PowerShell, 25 Bytes
!(Random -ma($args[0]--))

The Get-Random function when given a -Maximum parameter n returns a value from the range [0,n). We leverage that by subtracting 1 from our input $args[0], so we're properly zero-indexed, and get a random value. Precisely 1/nth of the time, this value will be 0, so when we Boolean-not it with ! it will return True. The other times will return False.

Scratch, 63 bytes
Try it online!
Picture:

Scratchblocks code:
when gf clicked
ask[]and wait
say<(pick random(1)to(answer))=[1

Uh oh my golf is longer than Java D:

J, 3 bytes
0=?

This is a monadic fork that takes an argument on the right. Similarly to APL, ? generates a random integer; however, J arrays are zero-based. So we compare to 0 instead of to the input.

Minkolang 0.14, 7 bytes
1nH1=N.

Try it here.
Explanation
1          Pushes 1
 n         Takes number from input
  H        Pops b,a and pushes a random integer between a and b, inclusive
   1=      1 if equal to 1, 0 otherwise
     N.    Output as number and stop.

Perl, 18 12 bytes
$_=1>rand$_

That is 11 bytes + 1 for the -p commandline argument.
Save in a file (any name, say, 16.pl) and run as: echo 4 | perl -p 16.pl.
It will print an empty line for false, and 1 for true.
As a function: 18 bytes

sub f{1>rand$_[0]}

Would it still be valid if "sub f" was removed? (Updated OP: Naming is not required anymore.)

, 3 chars / 6 bytes
!⁇ï

Try it here (Firefox only).
The punctuation is strong with this one.

Racket, 21 bytes
(λ(x)(=(random x)0))

Reng v.3.3, noncompeting, 6 bytes
iu0en~

i takes input, u pushes a random integer in [0,i), 0e checks if the value is equal to 0, n outputs that value, and ~ terminates the program.
Try it here!

Befunge-93, 99 98 96 95 92 90 84 bytes
<vp90:g80<p80 &
v?v>v>9g1-:0`|
0^1-:0v\g80:$<
>v<10^ +*2p90<
@>\^`$`  >!.
 v  _^>  |

Try it online!
This deserves a separate spot from my other answer, as I did this from scratch.
This generates an integer (x) in the range [0,2^n) using random binary digits, then redoes the program if x>=n (Actually by checking !(n>x), because befunge). Then, it tests if x=0, outputting the result.
Any ways to knock off bytes are wanted!

Perl 5, 10 bytes
A subroutine:
{1>rand@_}

It takes input as a list of 1s of the appropriate length.
Hat-tip.

><>, 44 + 3 = 47 bytes
&v<
0x1v
?^0\l&:&-
1=?\2*+l
?!v\:&:&(
n;~>0=

Try it online, or watch it at the fish playground!
Input is taken on the stack, with the -v flag (hence the +3 bytes). Unlike the other ><> answer, this has a theoretically correct distribution, not just an approximately correct one (assuming the pseudo-random stuff behind the scenes is uniform).
Randomness is tricky in ><>: the only non-deterministic instruction is x, which sets the fish's direction randomly from four choices.
If you want a uniform random number from 1 to N but you only have a (fair) m-sided die, where m > N, you can do it by rolling the die, checking if the result is in the right range, and re-rolling if it isn't until you get a number between 1 and N. There's a probability of exactly 0 that you'll keep rolling the die forever without end, and the result you get (if the process terminates) is uniformly distributed. Also, if 1 < m < N, you can simulate an mk-sided die by rolling it k times, and you can make mk larger than N by picking k large enough. Thus you can simulate any rational probability using any die with more than 1 side (if you don't mind a vanishingly small chance of rolling the die forever).
This program rolls a 2N-sided die, by getting N random 1s or 0s and reading them in binary. The number 2N is always bigger than N for N ≥ 1, although it's usually a LOT bigger, so for large N you'll be waiting a while. TIO handles up to about N = 16.

The idea of using a random number in the range of [1,2^n] definitely works in other languages, (e.g. my Befunge answer)

Befunge-93, 185 171 169 142 125 124 121 118 116 113 124 bytes
 &v>:00pv _v>v>\v
 > ^<  v?v:$1-+ :
@g:    1^2-1^   _$v>g`| @.0_1.
.$1    >v<1-\2*v+1<   >00g-^
 ^-     >\^>^>^>:00^  >
^#_#^

Try it online!
This uses the exact same strategy as this ><> answer (generate an integer in the range [1,2^n] by generating n random binary digits then converting it, then try again if the resulting integer is outside of the range [1,n]), but with two modifications:

Separate case for n=1
The binary digits are at first generated with 1s and 2s, since Befunge pops 0 off of the stack when empty. After the digits are generated, they are decremented to their normal binary and converted to an integer in place.

This is surprisingly fast!
Anything that will reduce the bytecount are welcome, considering I'm not a good befunge-golfer (especially when it comes to g and p)
I apparently am horrible at reading directions, as I originally only outputted a random integer in the range [1,n] >_<.

Jelly, 2 bytes
XỊ

Try it online! (contains a footer that runs the program 100 times and reports the results)
I had to triple-check to make sure that Jelly wasn't here yet; it's a popular language, after all. But it turns out it wasn't.
X picks a random element from a list. Because it's at the start of the program but requires an input, it'll implicitly take the first command line argument as input. Most commands, when they expect a number but are given a list, convert the number into a range from 1 to that number; thus, for example, an input of 4 will pick a random element from [1, 2, 3, 4]. (Actually, Jelly has a special case to optimise this internally by not constructing the list.) Note that for an input of n, this means that there's a 1 in n chance of picking 1 as our element.
Once we have our element, we run Ị on it. That's a test for a small value, i.e. no higher than 1 or smaller than -1. The only element that we can produce that matches this condition is 1, so we get an output of true (expressed as 1 in Jelly) with 1/n probability, and false (expressed as 0 in Jelly) the rest of the time. The output then gets printed implicitly.
(This submission also works as a function rather than a full program, exactly the same way; the implicit input is then taken from the function argument, and the implicit output used as the function's return value.)

SmileBASIC, 15 bytes
INPUT N?!RND(N)

RND(n) generates a random number from 0 to n-1, so there's a 1/n chance that it will be 0. Then it just uses ! (logical not) to convert this to a 1/n chance of generating 1 (true), and prints the result.

Keg, 6 bytes
¿~$%2<

Takes random number & input, modulos them and checks whether the result is less than 2.

MY, 5 bytes
ω0x=←

Try it online!
How it works:
Generates a random integer in the range [0,n), then tests for equality with 0.

I assume you meant [0,n-1] since [1,n] does not include 0.

Yes, thank you! Lol.

GolfScript, 8 bytes
~rand 0=

Try it online!

J, 6 bytes
?&0:<%

explanation
A J fork:
      ?&0:                <               %
NB. uniform float    is less than?    1 / input

Try it online!

x86, 10 bytes
Apparently there's a fairly new instruction called rdrand which makes this program pretty trivial.
Input in ecx, output in ZF. I consider one of x86's flags as a valid return value, which is arguably more useful than setz and returning in eax. It would've been very convenient if div set ZF.
5:  0f c7 f0                rdrand %eax
8:  31 d2                   xor    %edx,%edx
a:  f7 f1                   div    %ecx
c:  85 d2                   test   %edx,%edx
e:  c3                      ret

Treating as signed int saves 1 bytes (only work for small ecx but anyway old one too)

Gol><>, 7 bytes
ISx*1(h

Try it online!
How it works
ISx*1(h

I        Take input as number
 Sx      Generate random number in [0,1)
   *     Multiply the two
    1(   Is it less than 1?
      h  Print the result as number and halt

Thunno 2 !, 2 bytes
Lɼ

Try it online!
Explanation
    # Implicit input
L   # Push [0..input)
 ɼ  # Take a random item
    # Logical NOT
    # (Check for != 0)
    # Implicit output

05AB1E, 2 bytes
LΩ

Only 1 is truthy in 05AB1E, everything else is falsey, which is used to our advantage here.
Try it online or try it online an infinite amount of times with additional 05AB1E-truthify (==1) check.
Explanation:
L   # Push a list in the range [1, (implicit) input]
 Ω  # Pop and push a random integer from this list
    # (which is output implicitly as result)

source: Stack Exchange

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

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

sort: votes


text:
Map string to Hilbert curve
Let's map some strings to 2d space, fractal style. Your task is to compute a Hilbert curve and lay a string along it.

Task
The task is to take the single-line input string, and lay it out along a Hilbert curve big enough to contain it, but no bigger. Try to make the byte count as low as possible; this is code-golf after all!
Conditions

Any gaps to be padded with whitespace, but padding is not required at the end of lines.
The start of the line should be in the top-left corner, and the end in the bottom-left.
You may create a program or function.
There may be some new test-cases appearing, so don't hardcode anything!

Bonuses
Note: Bonuses stack like this: -50% & -20% on 100B = -20% on 50B or -50% on 80B = 40B.

-50% If the input is a multi-line string, reverse the process to create the original input. Test cases for the bonus: just use the existing ones (including the bonus test cases!)
-20% If you strip all unnecessary whitespace from the output (e.g. at the end of a line).
-5% If you don't pollute the global namespace (you know what I mean!)

Test cases
abcdefghijklmn

adef
bchg
 nij
 mlk

The quick brown fox jumps over the lazy dog.

Thn f ju
 ewooxpm
qckr rs
ui btevo
    hlaz
    e  y
      do
      .g

And for the whitespace-stripping bonus:
No  hitespac  her

Noher

hesc
itpa

Leaderboard

/* Configuration */

var QUESTION_ID = 66958; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43394; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:[.]\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

If anyone can make some more testcases, that would be appreciated.

So the charactes should be represented by vertices of the curve?

No..hitespac..her. where the dots are spaces would be a better test case for the bonus. (And currently, the test case is missing the trailing .)

If you are taking the L-system approach, you might also want to try http://codegolf/questions/48697/ascii-l-system-renderer. It could help you to golf your answers.

CJam, 119 117 113 112 109 * 0.5 * 0.8 = 43.6 bytes
Thanks to Dennis for saving 1 byte.
Here is a start...
{+e`W<e~}:F;q_N-,4mLm]0aa{4\#4e!1=f*\:G[zGGW%zW%G].ff+2/{~.+~}%}@:L/\_N&{N/]z:z:~$1f>sS}{4L#' e]f{f=SF}N*N}?F

Test the forward transform. Test the inverse transform.
I'm sure there's a shorter way to generate the curve...
Explanation
First, I define a function to trim some element from the end of an array, because I need that in several places. It expects the array and the element (inside a separate array) on top of the stack.
{
  +  e# Append the element to the array.
  e` e# Run-length encode.
  W< e# Discard last run.
  e~ e# Run-length decode.
}:F; e# Store in F and discard.

Now the majority of the code determines the size of the required Hilbert curve and constructs it as 2D array where the elements are indices along the curve. I construct this based on the following observation:
Consider the 2x2 Hilbert curve:
01
32

The 4x4 Hilbert curve is:
0345
1276
ed89
fcba

If we subtract the minimum value from each quadrant (and separate them a bit for visual clarity), we get:
03 01
12 32

21 01
30 32

This pattern holds for any size. It means that we can construct the next level from the current one, by using as the four quadrants: a) the transpose of the current level, b) the current level itself, c) the transpose along the anti-diagonal, d) again the current level itself. And then we offset them 0, 1, 3, 2 times the size of the current level, respectively.
q           e# Read input.
_N-         e# Make a copy and remove all linefeeds.
,4mLm]      e# Take that string's length's logarithm with base 4, rounded up.
            e# This is the Hilbert curve level we need.
0aa         e# Push [[0]] as the level-0 Hilbert curve.
{           e# Store the Hilbert curve level in L. Then for each i from 0 to L-1...
  4\#       e#   Compute 4^i. This is the offset of the four quadrants.
  4e!1=     e#   Get [0 1 3 2] as the second permutation returned by 4e!.
  f*        e#   Multiply each of them by the offset.
  \:G       e#   Swap with the Hilbert curve so far and call it G.
  [         e#   Create an array with...
    z       e#     The transpose of G.
    G       e#     G itself.
    GW%zW%  e#     The anti-diagonal transpose of G.
    G       e#     G itself.
  ]
  .ff+      e#   Add the appropriate offsets to the indices in each of the four quadrants.
  2/        e# Split into a 2x2 grid.
  {         e# Map this onto each pair of quadrants...
    ~       e#   Dump both quadrants on the stack.
    .+      e#   Concatenate them line by line.
    ~       e#   Dump the lines on the stack.
  }%        e# Since this is a map, the lines will automatically be collected in an array.
}@:L/

Finally, we use this Hilbert curve of indices to apply the appropriate transformation to the input:
\_        e# Swap the curve with the input and make another copy.
N&{       e# If the input contains linefeeds, execute the first block, else the second...
  N/      e#   Split the input into lines. The stack now has a grid of indices and a grid
          e#   of characters.
  ]z:z:~  e#   This is some weird transposition magic which zips up the indices with the
          e#   corresponding characters from both grids, and finally flattens the grid
          e#   into a linear list of index/character pairs. Those cells that don't have
          e#   characters due to trimmed whitespace in the input will be turned into
          e#   arrays containing only an index.
  $       e#   Sort the pairs (which sorts them by indices).
  1f>     e#   Discard the indices.
  s       e#   Flatten the result into a single string.
  S       e#   Leave a space on the stack to be trim trailing spaces later.
}{        e# or...
  4L#     e#   Compute the size of the Hilbert curve.
  ' e]    e#   Pad the input to that size with spaces.
  f{      e#   Map this block over lines of the curve, passing the padding input as an
          e#   additional parameter...
    f=    e#     For each index in the current line, select the appropriate character
          e#     from the padded input.
    SF    e#     Trim spaces from the end of the line.
  }
  N*      e#   Join the lines with linefeed characters.
  N       e#   Leave a linefeed on the stack to be trim trailing linefeeds later.
}?
F         e# We left either a space or a linefeed on stack... trim that character from
          e# the end of the string.

Python 3, 467 434 423 457 451 426 386 374 342 291 304 * 80% * 95% = 231.04 bytes
The way this works is that I make the Hilbert curve using a Lindenmayer system and follow the left, right and forward instructions along an array of strings. There are probably many ways this could be golfed better, though; especially in the conditionals and in making the array of strings. (I did attempt [" "*p for i in range(p)] but strings don't support item assignment (apparently). If I could get that to work, I could get rid of join, too)
Edit: Golfed some of the conditionals with thanks to Dennis. And I golfed down the array of strings. And a no-byte change because the results were coming out transposed compared to the examples above.
Edit: Implemented the whitespace-stripping bonus.
Edit: Fixed a bug in my whitespace-stripping code for six more bytes
Edit: Since this answer doesn't pollute the global namespace, I get the 5% bonus, according to wizzwizz4 here.
Edit: Changed how g is incremented and decremented. Now using eval() and str.translate.
Edit: This answer is now a program instead of a function.
Edit: Fixed some bugs from the previous golf.
s=input();m=(len(bin(len(s)-1))-1)//2;t=eval("[' ']*2**m,"*2**m);t[0][0],*s=s;x=y=g=0;b="A";exec("b=b.translate({65:'-BF+AFA+FB-',66:'+AF-BFB-FA+'});"*m)
while s:
 c,*b=b;g+=(c<"-")-(c=="-")
 if"B"<c:x,y=[[x+1-g%4,y],[x,y+g%4-2]][g%2];t[x][y],*s=s
print("\n".join(''.join(i).rstrip()for i in t).rstrip())

Ungolfed:
# hilbert(it) is now implemented in the code with exec("b=b.translate")

def hilbert(it):
    s="A"
    n=""
    for i in range(it):
        for c in s:
            if c == "A":
                n += "-BF+AFA+FB-"
            elif c == "B":
                n += "+AF-BFB-FA+"
            else:
                n += c
        s=n;n=""
    return s

def string_to_hilbert(string):
    length = len(string)
    it = (len(bin(length-1))-1)//2
    hil = hilbert(it)
    pow_2 = 2**it
    # we use eval("[' ']*pow_2,"*pow_2) in the code, but the following is equivalent
    output = [[" "for j in range(pow_2)] for i in range(pow_2)]
    output[0][0] = string[0]
    x = 0
    y = 0
    heading = 0
    while string: # while there are still characters in string
        char, *hil = hil
        if char == "-": heading = heading - 1
        elif char == "+": heading = heading + 1
        elif char == "F":
            if heading % 4 == 3: y += 1
            elif heading % 4 == 2: x -= 1
            elif heading % 4 == 1: y -= 1
            else: x += 1
            output[x][y], *string = string
    array = [''.join(i).rstrip()for i in output]
    array = "\n".join(array).rstrip()
    print(array)
    return

Curious about the 5% bonus. Are the variables automatically local in Python?

@edc65 I asked the challenge writer a similar thing here: https://chat.stackexchange.com/transcript/240?m=28529277#28529277. Hope that helps a little. If not, we can continue the discussion in chat.

Ruby, 358 356 344 322 319 * 80% * 95% = 242.44 bytes
This is my Python code transpiled to Ruby. I should write more answers in Ruby. It's a decent language to golf in.
Edit: I forgot that functions don't need to be named in this question.
Edit: Since this answer doesn't pollute the global namespace, I get the 5% bonus, according to wizzwizz4 here.
->s{l=s.size;m=((l-1).bit_length+1)/2;x=2**m;t=(1..x).map{[" "]*x};t[0][0]=s[0];x=y=g=z=0;d=1;b=?A;m.times{b=b.split("").map{|c|c==?A?"-BF+AFA+FB-":c==?B?"+AF-BFB-FA+":c}.join("")};(c=b[z];z+=1;g+=c<?-?1:c==?-?-1:0;(g%2>0?y+=g%4-2:x+=1-g%4;t[x][y]=s[d];d+=1)if c>?B)while d<l;puts (t.map{|i|(i*'').rstrip}*"\n").rstrip}

Ungolfed:
def map_string(string)
  len = string.size
  m = ((len-1).bit_length+1)/2
  pow = 2**m
  output = (1..pow).map{[" "]*pow}
  output[0][0] = s[0]
  x = y = heading = char_index = 0
  chars_in_output = 1
  b = ?A
  m.times do |j|
    a = b.split("").map do |char|
      if char == "A"
        "-BF+AFA+FB-"
      else if char == "B"
        "+AF-BFB-FA+"
      else
        char
      end
    end
    b = a.join("")
  end
  while chars_in_output < len
    char = b[char_index]
    char_index += 1
    if char == "-"
      heading += -1
    else if char == "+"
      heading += 1
    else if char == "F"
      if heading % 2 == 0
        y += heading % 4 - 2
      else
        x += 1 - heading % 4
      end
    end
    output[x][y] = string[char_index]
    char_index += 1
  end
  return (output.map{|i|(i*'').rstrip}*"\n").rstrip

Is this code dual-licensed under a code license? I'd like to produce a derivative work that's released under the GPL (although any GPL-compatible license will work with this). It's currently released under CC BY-SA 3.0.

@wizzwizz4 Chat here: http://chat.stackexchange.com/rooms/56405/room-for-sherlock9-and-wizzwizz4

JavaScript (ES6), 227 - 20% : 181.6 bytes
m=>{for(n=1<<((33-Math.clz32(m.length-1))/2),t='',y=0;y<n;y++,t+=`
`)for(x=0;x<n;x++,t+=m[h]||' ')for(u=y,v=x,h=0,s=n;s>>=1;q||(p&&(u=s+~u,v=s+~v),[u,v]=[v,u]))h+=s*s*(3*!!(p=u&s)^!!(q=v&s));return t.replace(/ +$/mg,'').trim()}

Trying to get the 5% bonus
m=>{for(var n=1<<((33-Math.clz32(m.length-1))/2),t='',x,y=0;y<n;y++,t+=`
`)for(x=0;x<n;x++,t+=m[h]||' ')for(var p,q,u=y,v=x,h=0,s=n;s>>=1;q||(p&&(u=s+~u,v=s+~v),[u,v]=[v,u]))h+=s*s*(3*!!(p=u&s)^!!(q=v&s));return t.replace(/ +$/mg,'').trim()}

241 * 0.8 *0.95 : 183.16 bigger
Less golfed
m=>
{
  // calc the size of the bounding square, clz32 is a bit shorter than ceil(log2()
  n = 1<<( (33-Math.clz32(m.length-1)) / 2);
  t = '';
  for(y = 0; y < n; y++)
  {
    for(x = 0 ; x < n; x++)
    {
      // for each position x,y inside the square
      // get the index postion in the hilbert curve
      // see https://en.wikipedia.org/wiki/Hilbert_curve (convert x,y to d)
      for(u=y, v=x, h=0, s=n; s >>= 1; )
      {
        h += s*s*(3 * !!(p = u & s) ^ !!(q = v & s));
        q || (p && (u = s+~u, v = s+~v),[u,v]=[v,u])
      }
      // add char at given index to output
      t += m[h]||' '; // blank if beyond the length of m
    }
    t += '\n'; // add newline add end line
  }
  return t.replace(/ +$/mg,'').trim() // to get the 20% bonus
}

Test

F=m=>{for(n=1<<((33-Math.clz32(m.length-1))/2),t='',y=0;y<n;y++,t+=`
`)for(x=0;x<n;x++,t+=m[h]||' ')for(u=y,v=x,h=0,s=n;s>>=1;q||(p&&(u=s+~u,v=s+~v),[u,v]=[v,u]))h+=s*s*(3*!!(p=u&s)^!!(q=v&s));return t.replace(/ +$/mg,'').trim()}

function Test() { O.textContent = F(I.value) }

Test()
#I { width: 90% }
#O { border: 1px solid #ccc}
<input id=I oninput='Test()' value='The quick brown fox jumps over the lazy dog.'>

Would it be worth adding vars to get the 5% bonus?

var s,x,y,u,v,t,p,q,n,h no it's not worth @wizzwizz4

You can just put var before the first use of each... Oh, that's even worse.

@wizzwizz4 all in all, maybe you have a point... i'm trying ... no. Too bad

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


text:
Santa's Decision
Santa's Decision:
In this challenge, you will help Santa Claus decide whether somebody on their list has been naughty or nice, and subsequently get coal or toys.
But unfortunately, Santa is unorganised, in some of his entries, the naughty, nice  and name fields are in the wrong order.
Input
Input will come in the following, interchangeable format:

the person's name (cannot contain a colon, only a-zA-Z0-9)
the word naughty followed directly by a colon and an non-negative integer representing the amount of times Santa caught you being naughty
the word nice followed directly by a colon and an non-negative integer representing the amount of times Santa caught you being nice

All separated with a single whitespace (ASCII 32) between each of them.
Additionally, the name will have no whitespace between the parts of the name Santa Claus -> SantaClaus.
Bonus:

(25%): He is Santa Claus, so he needs to check the list twice, and make sure there are no duplicates. (In which case, it just gets the first scores that user has)

Example:
Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2

Output:
The output should consist of:
The name of the person followed by:

If there's more points in naughty, then coal:
If there's more points in nice, then toys.
But if naughty and nice are equal, then needs more data
Example output:
With organisation bonus and duplicate removal bonus:

Quill coal
Doorknob toys
balpha needs more data
pops toys

Without bonus:

Quill coal
Doorknob toys
Quill toys
balpha needs more data
pops toys

Lowest byte count wins!

There's also a typo in the test cases. You misspelled our glorious mod DorkNoob's name :^)

@FryAmTheEggman ಠ_ಠ

Can we assume nobody's name is naughty or nice?

Nope, naughty or nice are valid names

Does the output have to be space-separated, or can it be in a list?

Space separated

Just curious: why did you choose to eliminate duplicates instead of adding their totals?  Too complex?

That's a good idea... I guess there's always next time...

"balpha needs more data" That sounds about right.

Pyth, 68 bytes - 25% = 51
V.zI-hA.g}\:kcNdY=+YGjd+G@c"needs more data
coal
toys"b._-Fmsecd\:SH

Try it online: Demonstration

Julia, 176 169 bytes
s->for l=split(s,"\n") M(r)=parse(matchall(r,l)[1]);g=M(r"e:\K\d+");b=M(r"y:\K\d+");println(replace(l,r" *\w+:\d+ *","")," ",g>b?"toys":b>g?"coal":"needs more data")end

This is an anonymous function that accepts a string and prints the result to STDOUT. To call it, give it a name, e.g. f=s->....
Ungolfed:
function santa(s::AbstractString)
    # Split the input on newlines and process each line separately
    for l in split(s, "\n")
        # Define a function to get the number from the result of a
        # regular expression match
        M(r) = parse(matchall(r, l)[1])

        # Goodness
        g = M(r"e:\K\d+")

        # Badness
        b = M(r"y:\K\d+")

        # Get the name by replacing the naughty and nice specifications
        # with empty strings and print the line to STDOUT
        println(replace(l, r" *\w+:\d+ *", ""), " ",
                g > b ? "toys" : b > g ? "coal" : "needs more data")
    end
end

Pyth - 64 bytes
Will try to use packed strings.
jmj\ +hK.g@k\:cd\ @c"needs more data
coal
toys"b._-Fmseck\:SeK.z

Try it online here.

This language is sufficiently advanced technology.

Perl, 138 113 105 103 102 96 - 25% = 72
includes +1 for -p
s/ *\w*(.):(\d+) */$$1=$2,()/eg;$$_++?$_='':s/\n/$".('needs more data',toys,coal)[$e<=>$y].$&/e

Less golfed:
s/ *\w*(.):(\d+) */$$1=$2,()/eg;    # strip naughty/nice, set $a to naughty, $i to nice
                                    # $_ is now the input name followed by \n
$$_++ ? $_='' :                     # only output once per name
s/\n/                               # replace newlines with:
  $".                               # a space,
  ('needs more data',toys,coal)     # one of these strings,
  [$e<=>$y]                         # indexed by -1, 0 or 1
  .$&                               # and the matched newline.
/ex                                 # (/x only for legibility)

update 113

save 25 bytes by using 1 letter from nice or naughty as variable name;
loose 5 bytes by fixing bug when name is last

update 105 save 8 bytes by using <=> to index a list of output strings.
update 103 save 2 bytes by using regex to append output string
update 102 save 1 byte by using last letter of nice or naughty instead of 2nd.
update 96 save 6 bytes by changing $$_ ? ... : ($$_++, ...) into $$_++ ? ... : ... (why didn't I see that before).

Ruby, 144 123 155 * .75 = 116.25 bytes
->s{d={}
s.split("
").map{|l|
a=l.split
b=a.grep /:/
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}

Thanks to histocrat for suggesting grep method.
164 * .75 = 123 bytes
->s{d={}
s.split("
").map{|l|
a=l.split
b=a.select{|t|t[?:]}
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}

144 bytes
->s{puts s.split("
").map{|l|b=(a=l.split).select{|t|t[?:]};i,j=(b.sort*'').scan(/\d+/);(a-b)[0]+' '+['needs more data','coal','toys'][i<=>j]}}

Ungolfed
->s{
  d={}
  s.split("
  ").map{ |l|
    a = l.split
    b = a.grep /:/
    i, j, v = (b.sort * '').scan(/\d+/) + a-b
    d[v] ||
      (d[v]=0
       puts v + ' ' + ['needs more data','coal','toys'][i<=>j]
      )
  }
}

Usage:
# Assign the anonymous function to a variable
f = ->s{d={}
s.split("
").map{|l|
a=l.split
b=a.grep /:/
i,j,v=(b.sort*'').scan(/\d+/)+a-b
d[v]||(d[v]=0
puts v+' '+['needs more data','coal','toys'][i<=>j])}}

f["Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2"]

Quill coal
Doorknob toys
balpha needs more data
pops toys

.select{|t|t[?:]} can be golfed to .grep(/:/)

@histocrat Wow i totally forgot that method. Thank you :)

JavaScript (ES6), 174 bytes - 25% bonus = 130.5 score
s=>s.split`
`.map(l=>l.split` `.map(p=>(m=p.match(/\w:\d+/))?(n=+m[0].slice(2),m>"f")?b=n:c=n:a=p)&&d[a]?"":d[a]=a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),d={}).join``

Explanation
s=>
  s.split`
`.map(l=>                   // for each line l of Santa's list
    l.split` `.map(p=>      // for each word p in l
      (m=p.match(/\w:\d+/)) // m = "y:x" for naughty, "e:x" for nice or null for name
        ?(n=+m[0].slice(2), // n = number at end of match
          m>"f")?b=n:c=n    // if naughty matched b = n, if nice matched c = n
        :a=p                // if no match, a = name
    )
    &&d[a]?"":              // if the name has been used before, add nothing to output
    d[a]=                   // else set d[name] to true

      // Add the appropriate text to the output
      a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),

    // NOTE: This line is executed BEFORE the code above it in the map function...
    d={}                    // d = list of names that have been output
  )
  .join``                   // return the list of outputs as a string

Test

var solution = s=>s.split`
`.map(l=>l.split` `.map(p=>(m=p.match(/\w:\d+/))?(n=+m[0].slice(2),m>"f")?b=n:c=n:a=p)&&d[a]?"":d[a]=a+" "+(b>c?`coal
`:b<c?`toys
`:`needs more data
`),d={}).join``
<textarea rows="5" cols="40" id="input">Quill naughty:4 nice:0
naughty:0 Doorknob nice:3
naughty:2 Quill nice:6
nice:3 balpha naughty:3
pops nice:4 naughty:2</textarea>

<button onclick="result.textContent=solution(input.value)">Go</button>

CJam, 64 bytes
qN/{S/':f/_{,1=},_@^$1f=:~:-g"needs more data
coal
toys"N/=S\N}/

Try it online!

Lua, 329 Bytes - 25% bonus = 246.75
a={...}p={}u=" "k=ipairs for i=1,#a/3 do p[i]={}end for i,v in k(a)do p[math.floor((i+2)/3)][(v:find("y:")and 3)or(v:find("e:")and 2)or 1]=v:gsub("%a+%:","")end for i,v in k(p)do d=tonumber b,g,n=d(v[3]),d(v[2]),v[1]if(not u:find(" "..n.." "))then u=u..n.." "print(n..(gb and" toys"or" needs more data"))end end

Will edit in ungolfed version and explanations later, a bit tired at the moment. All input is taken in through command line, space separated.

Python 2, 206 bytes - 25% = 154.5
s=[]
x=[0,0]
for p in zip(*(iter(input().split()),)*3):
 for w in p:
  j=w.find(':')+1
  if j:x[j<6]=int(w[j:])
  else:N=w
 b,g=x
 if N not in s:print N,['needs more data','coal','toys'][(b>g)-(g>b)];s+=[N]

JavaScript (ES6) 120 (160-25%)
Anonymous function using template strings, there are 4 newlines that are significant and included in the byte count
l=>l.split`
`.map(r=>k[r=r.replace(/\S+:(\d+)/g,(a,c)=>(t-=a[1]<'i'?c:-c,''),t=0).trim()]?'':k[r]=r+(t>0?` toys
`:t<0?` coal
`:` needs more data
`),k={}).join``


text:
Adjust your Chair
Challenge
You just bought a brand new chair! Problem is, you have no idea how to control it so you'll need to write a program to do it for you.

You can only sit in the unadjusted chair for so long. So your code will need to be as short as possible.
Examples
5,3,2,2,1

O
|
|
| _
| |
|_|_
  |
  |
  O

3,5,2,3,5

O
|  _
|  |
|__|__
   |
   |
 __|__
 OOOOO

2,13,1,1,13

O
|      _
|______|______
 ______|______
 OOOOOOOOOOOOO

Am I the only one who thinks this look like an airplane?
Chair parts
The chair has various components:
O
|
|  <- Backrest
|  _  <- Armrest
|  |
|__|__ <- Seat
   |
   |   <- Leg
  _|_
  OOO  <- Wheels

Input
You will be outputting a chair given various variables.
The input will be in the following order, all inputs will be positive integers (always greater than 0) and will always be provided.

Backrest Height
Seat Width always odd
Armrest Height Always less than backrest height
Leg Height
Wheel count Always less than or equal to seat width and Always odd

Detailed part Descriptions
The parts of the chair are:

Backrest: This amount of | is the Backrest Height
O
|
|

Seat: The amount of _ is the Seat Width, insert a | in the middle for the armrest.
__|__

Armrest: The amount of | is the Armrest Height. This should be inserted in the middle of the seat.
_
|
|

Leg: The amount of | is determined by Leg Height
|
|

Wheels: The wheels are centered below the legs. If they are more than one, all but the center wheel should have _ in the line above them.
_ _
OOO

Output
The output may have a trailing newline. Each line may have trailing spaces. Leading whitespace is not allowed

The third test case appears to be wrong. The seat width is far more than 2.

@Doorknob冰 whoops, that was a problem with the input order, I've fixed it.

The "airplane" one reminds me a lot of these tanks from Super Mario Bros 3.

LabVIEW, 146 LabVIEW Primitives
This got a lot bigger than I imagined...
There won't be a GIF this time, on the one Hand because of the size on the other hand because there's no way anyone can follow all the data flowing.
It does work, unless you get LabVIEW and suggest a file hoster there will be no way to check though.

JavaScript (ES6), 197 bytes
(b,s,a,l,w)=>eval('o="";for(i=0;ib?x[r](s/2-w/2+1)+(i>b+l?"O"[r](w):(p=(ib-a?"|":i<b-a?x:"-")+p:"O")+`\n`')

Explanation
Well this got rather convoluted quite quickly. I'll just comment on what each line does at a high level. Hopefully with this formatting it's not too hard to follow all the ternary operators.
(b,s,a,l,w)=>
  eval(
    o="";
    for(i=0;ib?
          x[r](s/2-w/2+1)                       // spaces before wheels
          +(
            i>b+l?
              "O"[r](w)                         // wheels
            :
              (p=(ib-a?"|":i<b-a?x:"-")              // armrest
          +p                                    // spaces or seat after armrest

      // Headrest line
      :"O")
      +\`\n\`
  )

Test

var solution = (b,s,a,l,w)=>eval('o="";for(i=0;ib?x[r](s/2-w/2+1)+(i>b+l?"O"[r](w):(p=(ib-a?"|":i<b-a?x:"-")+p:"O")+`\n`')
Input separated by commas (,) = <input type="text" id="input" value="5,3,2,3,5" />
<button onclick="result.textContent=solution(...input.value.split(',').map(x=>+x))">Go</button>

Python 2, 157 bytes
b,s,a,l,w=input()
y,z,n,A='|_\n '
s/=2;W=w/2;x=A*s;X=n+A*(s-W+1);Y=n+y
print'O'+Y*(b-a-1)+Y+x+z+(Y+x+y)*(a-1)+n+(y+z*s)*2+(n+A+x+y)*(l-1)+X+z*W+y+z*W+X+'O'*w

Example:
3,7,1,2,5
O
|
|   _
|___|___
    |
  __|__
  OOOOO

JavaScript (ES6), 182
An anonymous function. Using template strings, there are 3 newlines that are significant an included in the byte count.
(b,s,a,l,w,R=(x=s/2,c=' ')=>c.repeat(x),f=`
`+R(s/2+1-w/2),h=R(s/2,'_'),g=R(w/2,'_'),v='|')=>'O'+R(b+~a,u=`
`+v)+u+R()+'_'+R(a-1,u+R()+v)+u+h+v+h+R(l-1,`
 `+R()+v)+f+g+v+g+f+R(w,'O')

No loops, using repeat for the same purpose.
Less golfed
(b, s, a, l, w, // parameters
 // local variables as parameters with default values
 R = (x=s/2,c=' ')=>c.repeat(x), // shortcut for repeat
 f = `\n`+R(s/2+1-w/2), // filler before the wheels (used twice)
 h = R(s/2,'_'), // half seat (used twice)
 g = R(w/2,'_'), // last wheel support (used twice)
 v = '|', // vertical bar (used many times)
 u = `\n`+v // newline + bar (define below in the golfed version)
)=>
  'O'+R(b+~a, u)+  // backrest
  u+R()+'_'+       // backrest + armrest top
  R(a-1, u+R()+v)+ // backrest + armrest
  u+h+v+h+         // seat
  R(l-1, `\n`+R()+v)+ // leg
  f+g+v+g+         // wheels support
  f+R(w, 'O')      // wheels

Test Snippet

f=(b,s,a,l,w,R=(x=s/2,c=' ')=>c.repeat(x),f=`
`+R(s/2+1-w/2),h=R(s/2,'_'),g=R(w/2,'_'),v='|')=>'O'+R(b+~a,u=`
`+v)+u+R()+'_'+R(a-1,u+R()+v)+u+h+v+h+R(l-1,`
 `+R()+v)+f+g+v+g+f+R(w,'O')

console.log=x=>O.innerHTML=x+'\n'

function test()
{
  p=I.value.match(/\d+/g).map(x=>+x)
  console.log(p+'\n'+f(...p)+'\n')
}
Input <input type="text" id="I" value="5,5,3,2,3" />
<button onclick="test()">Go</button>

+1 for more of your bytes being in the function parameters than the body of the function.

SpecBAS - 185 168 bytes
1 INPUT b's'a'l'w: sx=(s/2)+1,wx=sx-(w/2)
2  ?"o"'("|"#13)*b
3  ?AT b,1;"_"*s;AT b+l,wx;"_"*w;AT b-a,sx;"-"
4 FOR i=b+1-a TO b+l: ?AT i,sx;"|": NEXT i
5  ?AT b+l+1,wx;"0"*w

Now that SpecBAS allows ? to be used instead of PRINT and doesn't need LET before variable assignment, it starts being a bit better at golfing.
Also helps that you can specify y,x print positions to avoid having to work out lots of spacing. This prints back, seat, arms and legs then wheels.
EDIT:
to print the back, replace a FOR...NEXT loop with pipe + return multiplied by the height (("|"#13)*b)

Perl, 181 bytes
includes +1 for -n. Put in a file and echo 5,3,2,2,1 | perl -n file.pl
($b,$s,$a,$l,$w)=/\d+/g;$,=$/;print'O',('|')x($b-$a-1),($D='|'.$"x($s/=2)).'_',("$D|")x--$a,($q='|'.'_'x$s).$q,($"x$s.' |')x--$l,($x=$"x(1+$s-($W=$w/2))).'_'x$W.'|'.'_'x$W,$x.O x$w

With comments:
#!/usr/bin/perl -n              # -n: iterate stdin, put in $_

($b,$s,$a,$l,$w)=/\d+/g;        # get the parameters

$,=$/;                          # set $OUTPUT_FIELD_SEPARATOR to \n;
                                # this is printed between each of print's args

print                           # shorter than `-p` and @_=(...); $"=$/; $_="@_";
    'O',                        # the headrest

    ('|')x($b-$a-1),            # space between headrest and armrest.
                                # (...) x $n: produces $n lists.

    ($D='|' . $"x($s/=2))       # backrest and padding ($"=' ') up to armrest
    . '_',                      # armrest.

    ("$D|")x--$a,               # backrest, padding, armrest

    ($q='|' . '_'x$s) . $q,     # backrest bottom and 1/2 seat, armrest bottom and 1/2 seat

    ($" x $s . ' |' ) x --$l,   # padding before leg and leg, repeated leg-1 times

    ( $x =
      $" x (1+$s - ($W=$w/2) )  # padding before wheel top
    )
    . '_'x$W . '|'              # left side of wheel top, wheel top,
    . '_'x$W,                   # right side of wheel top

    $x . O x$w                  # padding before wheels, wheels


text:
Tips for golfing in Prolog
What general tips do you have for golfing in Prolog? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Prolog (e.g. one letter variables is not specific to Prolog to reduce the size of programs).
Please indicate in your tips if it is specific to an implementation of Prolog (e.g. SWI-Prolog specific built-ins)
Please post only one tip per answer, or a list of tips that are all closely related to the same main idea.

Use Operators for Predicate Names
It is possible to give predicates operators as names so long as the operator is one of the predefined operators (listed here) and is not already defined as a predicate. This saves a few bytes both when defining and calling the predicate since operator predicates do not need to be written in the normal name(arg1,arg2,etc..) form and can be called as one might expect with operators.
For one and two argument predicates, they can be give the names of unary and binary operators, respectively. For higher arity predicates, we can still avoid parentheses using pattern matching. For example if we have a predicate A+B+C:-..., Prolog will use its operator precedence and associativity rules to transform it into (A+B)+C:-... which is a operator predicate where the first argument is pattern matched to A+B. Or A-B+C*D:-... which becomes (A-B)+(C*D) so its first argument is pattern matched to A-B and its second is pattern matched to C*D.
Examples
_+_+_.
A-B+C*D:-between(A,B,C),C+D.
\X:-X>1,X<10.
X+Y:-length(Y,X),member(X,Y).

5+[10,5,3,2,5],a+b+c,0-20+X*[2,4,6,5,40],\9.

The output will be X = 5.
Try it Online!
Corollary
Since DCGs are syntactic sugar for predicates they too can be given operators for names. This works as expected when calling them as DCGs either from a DCG or using the phrase predicates or others that are designed to work with DCGs. When calling them as predicates parentheses are required (eg A+B-->... must be called like +(A,B,...)) since DCG predicates take an additional two arguments for their difference lists. For operator named DCGs with more than two arguments using operator pattern matching then it is important to make sure when calling it as a predicate that the pattern matched operators are distributed correctly.
Giving operator names to DCGs that take no additional arguments can be useful if you need to call them within your program since then you can do so without using parentheses. Caution is required because it can be the case that what you save in parentheses you can lose to added spacing required to parse adjacent operators.
Examples
/ -->a+b+X,X+d+e.
A+B+C-->[A],[B],[C].

X/[],member(c,X),phrase(f+o+o,Y),+(b+a,r,Z,[]).

Output will be
X = [a, b, c, c, d, e],
Y = [f, o, o],
Z = [b, a, r].

Try it online!
Caveats
With the unary operators + and -, Prolog will interpret +20 or -20 as numbers instead of a call to a +/1 or -/1 predicate. Predicates given unary + or - as names can still be called on number by using parentheses (+(20), -(20)). If avoiding the extra bytes from parentheses is desirable other unary operators such as \, $, etc can be used as names instead.
The combination of pattern matching and operator named predicates is not entirely without flaws. If you have two predicates that have the same operator as their name and with pattern matching one is strictly more general than the other then the more general one may get called first or if the less general one fails (depending on their ordering in the source). For instance in the example above if A-B+C*D fails to match its input then Prolog will try calling X+Y. This will result in an error because length/2 require Y to be an integer which it will not be since it will be in the form C*D. This can be avoided simply by making sure no two predicates have the same operator as their name or if that fails then using cuts and careful ordering of the source.

It's astonishing how useful this trick is for code golf. I just reduced an answer's byte-count by 16% using this tip alone!

You can also use them for arguments. Example: p(a,_,_). p(A,B,C):- .... => p(a,_). p(A,B+C):- .... to save two bytes.

Try to put every possible case into a single rule
The clean way to program in Prolog is to declare multiple rules for the same predicate. For example, a predicate to reverse a list with an accumulator would look like this:
r([],Z,Z).
r([H|T],Z,R):-r(T,[H|Z],R).

In Code-golf, we can remove the first rule, and add a ; at the end of the second rule to code the recursion end:
r([H|T],Z,R):-r(T,[H|Z],R);R=[H|Z].

We know that the first condition r(T,[H|Z],R) will fail if T is empty, i.e. if the recursion need to end and thus we can add our termination as an or clause after it.
The same principle works in a lot of situations. Note however that sometimes it is actually shorter to declare another rule rather than doing this.

Note that the modified code here no longer works if the first argument is empty.

One trick that is frequently useful: Use CLP(FD) constraints for integer arithmetic to obtain predicates that can be automatically used in several directions, thus avoiding conditions and dedicated branches and variants.
Use B-Prolog or GNU Prolog, where such constraints are available out of the box, without needing to load any libraries.

This is always something that I hate with SWI-Prolog when doing challenges here. Using CLPFD would make some things much cleaner and shorter, but you have to add a lot of extra code to make it work (the include by itself is a lot...) which usually doesn't make it worth it. I think I've only ever used it in this answer.

I hate that too, and for sure the time will eventually come when library(clpfd) will be available as a preloaded or at least autoloaded library also in SWI-Prolog. It may take a few years until declarative arithmetic is fully understood and appreciated by all users, who have by now accumulated decades of experience with outdated, low-level features. The more you use and advocate CLP(FD), the sooner we will get it by default. Until then, you can simply put :- use_module(library(clpfd)). in your ~/.swiplrc and just state that you are using that "variant" of SWI-Prolog.

Use arithmetic operators as tuple constructors and cons pairs
If you need to pass a single structure consisting of two or more values, the most obvious thing to use is a list, e.g. [A,B]. That's really verbose, though.
There's an alternative. Prolog values can store a pretty much arbitrary nested structure, which isn't evaluated. Here's an example showing how that works:
| ?- member(member(A,B),C).
C = [member(A,B)|_] ? ;
C = [_,member(A,B)|_] ? ;
(etc.)

member(A,B) is just a named tuple in this situation, and the outside member (which is a function call) is treating it as such.
Although named tuples are fairly useful in non-golfed Prolog programming, they might seem even more verbose than the list approach. However, we can use pretty much arbitrary characters in the name of the tuple constructor (assuming they're properly quoted); instead of something cute like member or a single character like a, we can do something like this:
| ?- A = '-'('/'(1,2), '/'(3,4)).
A = 1/2-3/4

Here, our tuple constructors are '-' and '/'. And it's interesting to note what the pretty-printer did with them; it's using infix notation for the tuples. This is really terse, and parses the same way that the comparable arithmetic operation would. (This also explains why arithmetic uses is not =; A = 1+2 would unify A with the tuple '+'(1,2), so separate syntax is needed to actually evaluate the unevaluated arithmetic expression.) Because a tuple constructor has to be called something, you may as well use a character that has a terse syntax (and as a bonus, - and / are some of the most common choices in non-golfed code too when they want a quick throwaway tuple constructor rather than something meaningful, in much the same way that i is often used as a loop variable, so they're entirely reasonable to use in your input and output if you happen to want a tuple there for some reason).
'-' and '/' are good choices for tuple constructors because they have well-behaved and useful precedence, allowing you to write tuple literals tersely. However, note that you don't need to worry about precedence when intermediate values are produced inside the program. Prolog keeps the tuples stored as a tree rather than as source code, and pretty-printers can output it unambiguously:
| ?- A = '-'('-'(1,2), '-'(3,4)).
A = 1-2-(3-4)

Because the tuple syntax is so terse (f(A,B) is no shorter than f(A-B)), you can replace multiple prediccate arguments with tuples at no cost, meaning that if a predicate needs to pass two or more of its arguments to another predicate, you can often form them into a tuple and just pass the tuple (although this will require changing all calls to the predicate, in addition to the predicate itself, to use an appropriate mix of tuple constructors and commas).
Another advantage of this syntax is if you need to use lists internally (rather than to interoperate with standard predicates); a list is basically just a set of nested cons cells, and a cons cell is just a tuple with constructor '.', as can be seen here:
| ?- Q = '.'('.'(A,B),'.'(C,D)).
Q = [[A|B],C|D]

If your code uses lists "manually", it can make a lot of sense to use a less bulky tuple constructor than '.'. A common choice for me is to represent a cons cell as '/'(Tail,Head) (because it's about the most readable you can get in debug output without wasting characters). Note that you'll probably want your own [] equivalent too; you could use [] but it's two bytes long, and there are plenty of one-byte atoms (all the lowercase letters) that you can use instead.
So for example, the following list:
[1,2,3]

could be converted into a manual representation in the same number of characters like this:
x/3/2/1

whilst gaining the advantage that [H|T]-style pattern matches can now be written more tersely as T/H, and a test against the empty list as just x rather than the longer []. (Of course, this comes with the obvious disadvantage that member, append, etc., won't work on this representation.)

+1! There is no need for single quotes when using - and /. These are perfectly normal atoms already.

And, there is no need for single quotes around ., provided the following characters is neither a % nor a layout.

Shorter syntax for lists of lists and a way to declare maps
You can save bytes on lists of lists. If you have a list [[1,2],[3,4]], you can actually declare it as [1:2,3:4], which saves 4 brackets = 4 bytes. Note that you can use something else than : (for example, ^).
1:2 isn't actually a list in that case (whereas [1,2] was), it is represented internally as :(1,2). Therefore you cannot use predicates that work on lists on those sublists that use colons.
This trick is mainly used to declare maps, i.e. a list of keys with values attached to them. For example, if you want to declare a map M that contains the spelling of a digit in both English and French, you could do something like this:
M=[0:'Zero':'Zéro',1:'One':'Un',2:'Two':'Deux', ... ]

You can then for example retrieve elements of the map with a built-in predicate like member/2. For example, if you want the digit and English word corresponding to 'Quatre' in M, you could do:
member(Digit:Name:'Quatre',M).

You can generalize this. For example, you can wirte [[1,2],[3,4]] as 1*2+3*4, which is +(*(1,2),*(3,4)) and thus also use only one byte where you would otherwise need two, for opening and closing parentheses.

Double quote lists are even shorter: "abc" in stead of [a,b,c]

One neat trick: When you need to fail, use something that is equivalent to false/0, but shorter, such as:
?- repeat, writeln(hi), 0=1.

Obligatory The Art of Prolog quote: "In Prolog programming (in contrast, perhaps, to life in general) our goal is to fail as quickly as possible". Fun fact: you can also use \+! as a 3 bytes weird way to fail which does not actually triggers the cut ! (see this for why). I don't think it is possible to fail in less than 3 bytes.

I was also thinking about that quote when I wrote this ;-)

We really need both versions, \+! glues to the left to other graphic characters, whereas 0=1 glues to the left for names.

@Fatalize maybe not possible to fail in less than 3 bytes alone, but repeat,\+writeln(hi). is slightly shoter.

@TessellatingHeckler Indeed, if a predicate has side-effects like write, you could do it that way!

Shorter stdlib alternatives
These may not apply exactly based on what you are using the predicates for.

numlist/3 is better to generate numeric range lists than between/3 with bagof.
bagof/3 is a substitute for findall/3 if you can guarantee the result to be a non-empty list.
Many string related predicates also use atoms. eg: format(atom(X),Y,R) can be done instead of string(X), saving 2 bytes
some predicates are good aliases for many uses of foldl:

sumlist in place of foldl(plus,...)
similarly for max_list, min_list, etc.

In aggregate_all(X,Y,_)

X=count,Y=member(...) case can be replaced with occurrences_of_term(E,S,O)

name is often a good short substitute for atom_codes or number_codes

get0 is a shorter form of getCode for letters in ASCII range

using get instead of get0 will ignore all whitespace, which can save bytes.

Reuse a predicate with different calling modes
For example, you can parse and print a structure with the same predicate, once with a variable argument and another time with a ground term.
I used this approach in Make the Stretchy Snakes Kiss. This is not possible in all challenges, of course.

Print as a side effect which cannot be undone by backtracking, using backtracking to loop.
Goals like "print the first 1000 integers" can be:
:-findall(X,(between(0,999,X)),Nums),maplist(writeln,Nums).

That can be shortened to:
:-findall(X,(between(0,999,X),writeln(X)),_).

Backtracking can be used to get rid of the findall loop:
:-between(0,999,X),writeln(X),false.

Use a shorter false as per another tip in these answers:
:-between(0,999,X),\+writeln(X).

If you're using a range, you can use nth0 or nth1: e.g. :-nth0(N,_,_),writeln(N),N>999.

findall/3 will evaluate arithmetic expressions. I expected to have to use is/2 and another variable for that, but no:
?- findall(X,(between(1,10,X),Y is X^2,Y>20),Xs).
Xs = [5, 6, 7, 8, 9, 10].

?- findall(X,(between(1,10,X),X^2>20),Xs).
Xs = [5, 6, 7, 8, 9, 10].
```


text:
How much present did you get for Christmas?
Yes, how much, not how many...
As we all know, a large present is far better than a small one. Therefore, the value of the presents should always be measured in total volume, not number of presents, weight, or even combined price.
As it's frowned upon to compare the amount of presents one gets, you don't want a long script that's easily seen and read by others at the Christmas party. Therefore you need to keep the number of bytes in your script at a minimum.
Your task is simple: Create a program that takes a list of dimensions as input, on any suitable format, and outputs the combined volume of your presents. The dimension of each present will either be a set of three numbers, or a single number. If the input is three numbers (L, W, H), the present is a cuboid of dimensions L x W x H. If it's a single number (R), the present is a sphere of radius R.
Rules:

It can be either a full program or a function
The input can be in any convenient format

If desirable, a sphere may be represented by a number followed by two zeros
A cuboid will always have all non-zero dimensions.

The output should be a single decimal number

Additional output is accepted as long as it's obvious what the answer is
Output must have at least two digits after the decimal point
The output can be in standard form / scientific notation if the number is larger than 1000.
In case your language doesn't have a Pi-constant, the answer should be accurate up to 9999.99.

Examples:
((1,4,3),(2,2,2),(3),(4,4,4))
197.0973    // (1*4*3 + 2*2*2 + 4/3*pi*3^3 + 4*4*4)

(5)
523.5988

(5,0,0)
523.5988

Leaderboard
The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

No lady gets hat in one of those funny cylindrical boxes?

@manatwork, no, all ladies will get bowler hats, and you can easily fit those in a sphere =P

I assume (5) is just partial example and our code only has to handle ((5)).

If our language of choice does not have a Pi constant, how much precision is required?

So the list separators can be other than ,? Because I would prefer + between list items and * between sublist items…

@manatwork, + and *  are OK as long as they don't mean addition and multiplication (or other operations) in the language you're using.

Can we take spherical input as (5,4/3,Pi)? :P

I know, I was kidding. ;)

The second I saw the title my finger went straight to the edit button. Then I read your second line...

Jelly, 19 18 bytes
Zµ*3×1420÷339Ḣo@PS

Try it online!
Unfortunately, Jelly does not have a π constant yet, and the vectorizer doesn't handle floats properly.
To overcome these issues, instead of multiplying by 4π/3, we multiply by 1420 and divide by 339. Since 1420 ÷ 339 = 4.18879056… and 4π/3 = 4.18879020…, this is sufficiently precise to comply with the rules.
The newest version of Jelly could accomplish this task in 14 bytes, with better precision.
Zµ*3×240°Ḣo@PS

Try it online!
How it works
Zµ*3×1420÷339Ḣo@PS  Left argument: A, e.g., [[1, 2, 3], [4, 0, 0]]

Z                   Zip A; turn A into [[1, 4], [2, 0], [3, 0]].
 µ                  Begin a new, monadic chain with zip(A) as left argument.
  *3                Cube all involved numbers.
    ×1420           Multiply all involved numbers by 1420.
         ÷339       Divide all involved numbers by 339.
                    This calculates [[4.19, 268.08], [33.51, 0], [113.10, 0]]
             Ḣ      Head; retrieve the first array.
                    This yields [4.19, 268.08].
                P   Take the product across the columns of zip(A).
                    This yields [6, 0].
              o@    Apply logical OR with swapped argument order to the results.
                    This replaces zeroes in the product with the corresponding
                    results from the left, yielding [6, 268.08].
                 S  Compute the sum of the resulting numbers.

The non-competing version uses ×240° instead of ×1420÷339, which multiplies by 240 and converts the products to radians.

Pyth, 19 18 bytes
sm|*Fd*.tC\ð7^hd3Q

1 byte thanks to Dennis
Demonstration
Input format is list of lists:
[[1,4,3],[2,2,2],[3,0,0],[4,4,4]]

It simply multiplies the dimensions together to calculate the cube volume. If that comes out to zero, it calculates the sphere volume.
The sphere constant, 4/3*pi is calculated as 240 degrees in radians. .t ... 7 converts an input in degrees to radians, and C\ð calculates the code point of ð, which is 240.

Haskell, 40 bytes
q[x]=4/3*pi*x^^3
q x=product x
sum.map q

Usage example: sum.map q $ [[1,4,3],[2,2,2],[3],[4,4,4]] -> 197.09733552923254.
How it works: For each element of the input list: if it has a single element x calculate the volume of the sphere, else take the product. Sum it up.

Is this way of counting bytes generally valid? I would have said p=sum.map q (and then told to use p on a list of lists of numbers)

@LeifWillerts:  There's a recent topic on meta which allows unnamed functions that relay on global definitions. sum.map q is an unnamed function that depends on q, so I guess it's fine.

Python 2, 86 70 bytes
lambda i:sum(x[0]*x[1]*x[2]if len(x)>1 else x[0]**3*4.18879for x in i)

I get your byte count as 86, how did you get yours?

Additionally, you can save bytes by just manually putting in a value for pi, you can use up to 3.14159265358979323 to break even

@wnnmaw I forgot to count the import -.-

I believe your hardcoded value for pi is a bit off :)

@wnnmaw That's not Pi; it's 4Pi/3.

Cool, I didn't know you could write 9for without the space.

Mathematica, 34 bytes
Tr[1.##&@@@(#/.{r_}:>{4r^3/3Pi})]&

An unnamed function which takes a nested list of lengths and returns the volume as a real number.
We first replace single values with the volume of the corresponding sphere with /.{r_}:>{4r^3/3Pi}. Then we multiply up the contents of each list with 1.##&@@@. Finally we compute the sum as the trace of the vector with Tr[...].

JavaScript (ES6), 56
l=>l.map(([x,y,z])=>t+=y?x*y*z:x*x*x*4/3*Math.PI,t=0)&&t

The more sensible .reduce version is 1 byte longer
l=>l.reduce((t,[x,y,z])=>t+(y?x*y*z:x*x*x*4/3*Math.PI),0)

You could save a couple of bytes by using 4.11879 in place of 4/3*Math.PI, as that should be accurate enough to qualify.

@ETHproductions yes, but In case your language doesn't have a Pi-constant, and my language has a PI constant, so I don't know if it qualifies

Python, 49 bytes
lambda l:sum(a*b*c or a**3*4.18879for a,b,c in l)

Uses the representation of spheres as (a,0,0). Treated as a cuboid, this has volume 0, in which case the sphere volume is used instead. I'm not clear on how accurate the constant needs to be, so I hope this is enough.

MATL, 20 bytes
it!ptbw~)3^4*3/XT*hs

Input format is a matrix in which each row describes a cube or a sphere. A sphere is defined by only the first number in that row; the other two numbers are zero. So the first example from the challenge would be:
[1 4 3; 2 2 2; 3 0 0; 4 4 4]

This uses the current release of the language, 2.0.2, which is earlier than this challenge.
Examples:
>> matl it!ptbw~)3^4*3/XT*hs
> [1 4 3; 2 2 2; 3 0 0; 4 4 4]
197.0973355292326

>> matl it!ptbw~)3^4*3/XT*hs
> [5 0 0]
523.5987755982989

Explanation:
i             % input matrix
t!            % duplicate and transpose: each object is now a column
p             % product of elements in each column
t             % duplicate
b             % bubble up top-third element in stack
w             % swap top two elements in stack
~             % logical 'not'. This gives logical index of speheres
)             % reference () indexing. This is a logical-linear index to get sphere radii
3^4*3/XT*     % formula for volume of spehere; element-wise operations
h             % horizontal concatenation
s             % sum

Prolog, 115 100 bytes
Code:
[]*0.
[[L,W,H]|T]*V:-W=0,X is 4*pi*L^3/3,T*Y,V is X+Y;X is L*W*H,T*Y,V is X+Y.
p(L):-L*V,write(V).

Explained:
[]*0.
[[L,W,H]|T]*V:-W=0,                           % When 2nd dimension is 0
                  X is 4*pi*L^3/3,            % Calc volume of sphere
                  T*Y,                        % Recurse over list
                  V is X+Y                    % Sum volumes
                  ;                           % When we have a cube
                  X is L*W*H,                 % Calc cube volume
                  T*Y                         % Recurse over list
                  V is X+Y.                   % Sum volumes
p(L):-L*V,                                    % Get combined volume of list of lists
      write(V).                               % Print volume

Examples:
p([[1,4,3],[2,2,2],[3,0,0],[4,4,4]]).
197.09733552923257

p([[5,0,0]]).
523.5987755982989

Try it online here
Edit: saved 15 bytes by defining a dyadic predicate.

Perl, 52 47 bytes
s/,/*/g||s@$@**3*4.18879@,$\+=eval for/\S+/g}{

46 + 1 for -p (that's been common; let me know if it's different here and I'll update)
Usage: put in a file and echo 1,4,3 2,2,2 3 4,4,4 | perl -p x.pl
With comments:
s/,/*/g                # x,y,z becomes x*y*z
||                     # if that fails,
s@$@**3*1420/339@      # x becomes x**3 * 1420/339
,                      #
$\+=eval               # evaluate the expression and accumulate
for/\S+/g              # iterate groups of non-whitespace
}{                     # -p adds while(<>){...}continue{print}; resets $_

update 47 Thanks to @Dennis for saving some bytes using this trick.

s/,/*/g||s@$@**3*4.18879@,$\+=eval for/\S+/g;}{ saves a few bytes.

@Dennis Thanks! I tried with $\ before but resetting $_ cost as much. Still unclear as to why $_ is reset in a new block, though.. Is $_ block-local in while(<>){}?

Yes, $_ is the default variable of the current scope. In the END block, it is undefined.

CJam, 24 21 bytes
q~{3*)4P*3/*+3<:*}%:+

Test it here.
Explanation
q~       e# Read and evaluate input.
{        e# Map this block over the list of presents...
  3*     e#   Repeat the list of lengths 3 times. This will expand cuboids to 9 elements
         e#   and spheres to three copies of the radius.
  )      e#   Pull off the last element.
  4P*3/* e#   Multiply by 4 pi / 3.
  +      e#   Add it back to the list of lengths.
  3<     e#   Truncate to 3 elements. This is a no-op for spheres, which now have three
         e#   elements [r r 4*pi/3*r] but discards everything we've done to cuboids, such
         e#   that they're reduced to their three side lengths again.
  :*     e#   Multiply the three numbers in the list.
}%
:+       e# Sum all the individual volumes.

PowerShell, 67 Bytes
($args|%{($_,((,$_*3)+4.18879))[$_.count-eq1]-join'*'})-join'+'|iex

Some black magic happening here. I'll try to walk through it smoothly.
We first take our input, expected as individual comma-delimited arrays e.g. (1,4,3) (2,2,2) (3) (4,4,4), and pipe that into a loop |%{}.
Inside the loop, we first check whether $_, the particular array we're considering, has only one item and use that to index into an array (essentially a shorter if/else construction). If it's more than one item, suppose (1,4,3) as input, we execute the first half, which is simply to spit out the array via $_, such as (1,4,3). Otherwise, we create a new dynamic array consisting of the element three times with (,$_*3) and tack on an approximation of 4/3rd*Pi. For input (3), this will result in (3,3,3,4.18879) output.
Yes, PowerShell has a Pi constant, accessed via .NET call [math]::PI, but that's longer and I don't want to use it. :p
Regardless, we concatenate that output array with asterisks via -join'*', so "1*4*3". Once we're completely through the loop, we now have a collection of strings. We -join'+' all those together for our addition, and iex the expression to calculate the result.
Phew.

Ruby, 58 characters
->b{b.reduce(0){|t,s|a,b,c=*s;t+(c ?a*b*c :a**3*4.18879)}}

Sample run:
2.1.5 :001 ->b{b.reduce(0){|t,s|a,b,c=*s;t+(c ?a*b*c :a**3*4.18879)}}[[[1,4,3],[2,2,2],[3],[4,4,4]]]
 => 197.09733

Ruby, 50 characters
Improvement idea shamelessly stolen from edc65's JavaScript answer.
->b{t=0;b.map{|a,b,c|t+=c ?a*b*c :a**3*4.18879};t}

Sample run:
2.1.5 :001 > ->b{t=0;b.map{|a,b,c|t+=c ?a*b*c :a**3*4.18879};t}[[[1,4,3],[2,2,2],[3],[4,4,4]]]
 => 197.09733

Japt, 27 22 bytes
N®r*1 ª4/3*M.P*Zg ³} x

Takes input as space-separated arrays. Try it online!
How it works
N®   r*1 ª 4/3*M.P*Zg ³  } x
NmZ{Zr*1 ||4/3*M.P*Zg p3 } x

          // Implicit: N = array of input arrays
NmZ{   }  // Map each item Z in N to:
Zr*1      //  Reduce Z with multiplication.
||4/3*M.P //  If this is falsy, calculate 4/3 times Pi
*Zg p3    //  times the first item in Z to the 3rd power.
x         // Sum the result.
          // Implicit: output last expression

R, 70 bytes
function(l)sum(mapply(function(x)prod(x*!!1:3)*4.18879^is.na(x[2]),l))

Try it online!

Pip, 23 bytes
{$*a|4/3*PI*@a**3}MSg^s

There's a couple ways to give input to this program. It can take each present as a command-line argument of three space-separated numbers (which will need to be wrapped in quotes: pip.py present.pip "1 4 3" "3 0 0"). Alternately, specify the -r flag and give each present as a line of stdin consisting of three space-separated numbers. Try it online!
How?
                         g is list of cmdline args (or lines of stdin, if using -r flag)
                         s is space, PI is what it says on the tin (implicit)
                    g^s  Split each argument on spaces, so we have a list of lists
{                }MS     Map this function to each sublist and sum the results:
 $*a                      Fold the list on * (i.e. take the product)
    |                     Logical OR: if the above value is zero, use this value instead:
     4/3*PI*              4/3 pi, times
            @a            First element of the list
              **3         Cubed
                         Autoprint the result

Perl 5, 142 bytes
Run with -p in the command line, and type numbers delimited with a comma, like so:
5,0,0 or (5,0,0)
would produce
523.598820058997
There is no pi keyword in Perl. This is, in most cases, accurate to the significant figures specified, however even if I typed in all the figures of pi I know, it wouldn't be very accurate for some calculations. So I left it with 3.1415. I'm unsure if this is acceptable or not.
Code:
@a=$_=~/(\d+,*)/g;$_=0;@n = map(split(/\D/),@a);for($i=0;$i<$#n;$i+=3){$x=$n[$i];$n[$i+1]==0?$_+=1420/339*$x**3:$_+=($x*$n[$i+1]*$n[$i+2]);}

Edited for greater precision on the advice of Dennis, who is better at basic mathematics than I, and from a suggestion by MichaelT to save bytes whilst remaining precise.

How would you parse 1511? 2. 3.1415 is neither rounded properly nor sufficiently precise. If my calculations are correct, the error must not be greater than 0.0000017. 3. (4/3)*3.1415 can be replaced with a single float.

The OP says we may assume trailing zero's for spheres (which is in fact the example input I provided), 2. I don't know what calculations you're using, but sure, I'll increase the precision, and 3. good suggestion, I missed that one. Thanks!

I don't have the resources in front of me at the moment, though I wonder if doing 1420/339 would give you a few bytes back with a reasonable approximation. (this is 4/3 * 355/113). The difference between the fraction and the value you have is is -8.49130615e-8

@MichaelT That is the most interesting thing. Do you have a script that finds the smallest fractional representation of numbers? ;)

Codefun64 I just worked off of the other common approximation for pi.  22/7 isn't within enough tolerance, so I glanced at https://en.wikipedia.org/wiki/Approximations_of_%CF%80 an used the next one to see if it had a tolerance better than what @Dennis was asking for.

Re 1. Zeroes are OK, but without a separator between the numbers, how would you differentiate 15,1,1 from 1,51,1? Re 2. 1420/339 is what I use in my answer. See the discussion following this for the precision requirement. (CC @MichaelT)

@Dennis I very much screwed up by getting rid of delimiters for the numbers, I see. Thank you for that. I will be fixing that now. For what it's worth, I had it delimited with commas, but then got rid of it, thinking that was a clever way to save bytes...

Isn't there a math module with pi in it?

@ASCIIThenANSI use Math::Trig ':pi'; takes up quite a few bytes.

Fixed the delimiter, and also changed the regex to be more golfed.

Take a look at http://codegolf.stackexchange.com/questions/5105/tips-for-golfing-in-perl - you can get that down to 66 bytes at least.

Lua, 115 104 bytes
function f(a)b=0 for i=1,#a do c=a[i]b=b+(1<#c and c[1]*c[2]*c[3]or(4/3)*math.pi*c[1]^3)end return b end

Straightforward solution, I have to wrap the pseudo-ternary operation <condition> and <non-false> or <value if false> in parenthesis else b would sum with both areas.
Input must be in the form array={{1,4,3},{2,2,2},{3},{4,4,4}} and the result can be seen by executing print(f(array)).

R, 38 36 bytes
function(x,y=4*pi/3*x,z=x)sum(x*y*z)

Uses default arguments to switch between the cases: with three arguments computes the product, and with one argument computes the sphere formula.

do you need the f<- and the {}?

This code does not output correctly for the test case (5,0,0). Also, it does not accommodate the test case where there are multiple presents and the volumes need to be summed together.

For (5,0,0) I get zero — is that not correct? Have edited to use sum (and removed some stuff that wasn't necessary per Giuseppe's suggestion)

05AB1E, 18 16 bytes
εDgi3m4žq*3/*]PO

Try it online.
Explanation:
ε                # Map each inner list of the (implicit) input to:
 D               #  Duplicate the current inner list
  gi             #  Is the length 1 (is it an `R`):
    3m           #   Take the duplicated current item and take its cube
                 #    i.e. [3] → [27]
      žq         #   PI
        4*       #   Multiplied by 4
          3/     #   Divided by 3
                 #    → 4.1887902047863905
            *    #   And multiply it with the current cubed `R`
                 #    [27] and 4.1887902047863905 → [113.09733552923254]
]                # Close both the if and map
 P               # Take the product of each inner list
                 #  i.e. [[1,4,3],[2,2,2],[113.09733552923254],[4,4,4]]
                 #   → [12,8,113.09733552923254,64]
  O              # Take the total sum (and output implicitly)
                 #  i.e. [12,8,113.09733552923254,64] → 197.09733552923254

Japt -mx, 16 bytes
ÊÉ?U×:Um³*4/3*MP

Try it