text:
Magic: the Gathering Combat Golf
Magic: the Gathering is a trading card game where, among other things, players play cards representing creatures, which can then attack the other player, or defend against the other player's attacks by blocking.
In this code-golf challenge, your program will be in the place of a Magic player deciding how to block in combat.

Each creature has two relevant attributes: Power, and toughness. A creature's power is the amount of damage it can deal in a combat, and its toughness is the amount of damage necessary to destroy it. Power is always at least 0, and toughness is always at least 1.
During combat in Magic, the player whose turn it is declares some of their creatures to be attacking the opponent. Then, the other player, known as the defending player, may assign their creatures as blockers. A creature may block only one creature per combat, but multiple creatures may all block the same creature.
After blockers are declared, the attacking player decides, for each attacking creature that was blocked, how to distribute the damage (equal to its power) that that creature deals to the creatures blocking it.
Then, damage is dealt. Each creature deals damage equal to its power. Attacking creatures that were blocked deal damage as descibed above. Unblocked attacking creatures deal damage to the defending player. Blocking creatures deal damage to the creature they blocked. Creatures belonging to the defending player that did not block deal no damage. (Creatures are not required to block.)
Finally, any creature dealt damage equal to or greater than its toughness is destroyed, and removed from the battlefield. Any amount of damage less than a creature's toughness has no effect.

Here's an example of this process:
A creature with power P and toughness T is represented as P/T
Attacking:
2/2, 3/3
Defending player's creatures:
1/4, 1/1, 0/1
Defending player declares blockers:
1/4 and 1/1 block 2/2, 0/1 does not block.
Attacking player distributes damage:
2/2 deals 1 damage to 1/4 and 1 damage to 1/1
Damage is dealt:
2/2 takes 2 damage, destroyed.
3/3 takes 0 damage.
1/1 takes 1 damage, destroyed.
1/4 takes 1 damage.
0/1 takes 0 damage.
Defending player is dealt 3 damage.

The defending player has 3 goals in combat: Destroy the opponent's creatures, preserve one's own creatures, and be dealt as little damage as possible. In addition, creatures with more power and toughness are more valuable.
To combine these into a single measure, we will say that the defending player's score from a combat is equal to the sum of the powers and toughnesses of their surviving creatures, minus the sum of the powers and toughnesses of their opponent's surviving creatures, minus one half of the amount of damage dealt to the defending player. The defending player wants to maximize this score, while the attacking player wants to minimize it.
In the combat shown above, the score was:
Defending player's surviving creatures:
1/4, 0/1
1 + 4 + 0 + 1 = 6
Attacking player's surviving creature:
3/3
3 + 3 = 6
Damage dealt to defending player:
3
6 - 6 - 3/2 = -1.5

If the defending player had not blocked at all in the combat described above, the score would have been
8 - 10 - (5/2) = -4.5

The optimal choice for the defending player would have been to block the 2/2 with the 1/1 and the 1/4, and to block the 3/3 with the 0/1. If they had done so, only 1/4 and the 3/3 would have survived, and no damage would have been dealt to the defending player, making the score
5 - 6 - (0/2) = -1

Your challenge is to write a program which will output the optimal blocking choice for the defending player. "Optimal" means the choice which maximizes the score, given that the opponent distributes damage in the way which minimizes the score, given how you blocked.
This is a maximin: The maximum score over the damage distributions which minimize score for each blocking combination.

Input: The input will consist of two lists of 2-tuples, where each 2-tuple is of the form (Power, Toughness). The first list will contain the powers and toughnesses of each attacking creature (you opponent's creatures). The second list will contain the powers and toughnesses of each of your creatures.
Tuples and lists may be represented in any convenient format, such as:
[[2, 2], [3, 3]]
[[1, 4], [1, 1], [0, 1]]

Output: The output will consist of a series of 2-tuples, in the form (blocking creature, blocked creature) - that is, one of your creatures followed by one of their creatures. Creatures will be refered to by their index in the input lists. Indexes may be 0 or 1 indexed. Again, any convenient format. Any order is fine. For example, the optimal blocking scenario from above, given the above input, might be represented as:
[0, 0]    # 1/4 blocks 2/2
[1, 0]    # 1/1 blocks 2/2
[2, 1]    # 0/1 blocks 3/3

Examples:
Input:
[[2, 2], [3, 3]]
[[1, 4], [1, 1], [0, 1]]
Output:
[0, 0]
[1, 0]
[2, 1]

Input:
[[3, 3], [3, 3]]
[[2, 3], [2, 2], [2, 2]]
Output:
[1, 0]
[2, 0]
or
[1, 1]
[2, 1]

Input:
[[3, 1], [7, 2]]
[[0, 4], [1, 1]]
Output:
[1, 0]
or
[0, 0]
[1, 0]

Input:
[[2, 2]]
[[1, 1]]
Output:

(No output tuples).

Input and output may be via STDIN, STDOUT, CLA, function input/return, etc. Standard loopholes apply. This is code-golf: shortest code in bytes wins.

To clarify the spec and provide initial ideas, this pastebin provides a reference solution in Python. The best_block function is a sample solution to this challenge, and running the program will provide more verbose input and output.

You should make this king of the hill.

@Arnauld nope, that's also a valid answer.

JavaScript (ES7),  354  348 bytes
Takes input as ([attackers], [defenders]).
(a,d,O,M)=>eval(`for(N=(A=a.push([,0]))**d.length;N--;)O=a[X='map'](([P,T],i)=>S-=((g=(n,l)=>n?l[X](([t,S],i)=>g(n-1,b=[...l],b[i]=[t-1,S])):m=l[X](([t,S])=>s+=t>0&&S,s=0)&&s>m?m:s)(P,l[n=0,i][X](m=([p,t])=>[t,p+t,n+=p])),n<T&&P+T)+(l[i]<1?T/2:-m),S=0,d[X]((x,i)=>l[(j=N/A**i%A|0)<A-1&&o.push([i,j]),j].push(x),o=[],l=a[X](_=>[])))&&S<M?O:(M=S,o)`)

Try it online!
Less golfed and formatted
This code is identical to the golfed version, just without the map aliases and the eval() wrapping for readability.
(a, d, O, M) => {
  for(N = (A = a.push([, 0])) ** d.length; N--;)
    O =
      a.map(([P, T], i) =>
        S -=
          (
            (g = (n, l) =>
              n ?
                l.map(([t, S], i) => g(n - 1, b = [...l], b[i] = [t - 1, S]))
              :
                m = l.map(([t, S]) => s += t > 0 && S, s = 0) && s > m ? m : s
            )(
              P,
              l[n = 0, i].map(m = ([p, t]) => [t, p + t, n += p])
            ),
            n < T && P + T
          ) + (
            l[i] < 1 ? T / 2 : -m
          ),
        S = 0,
        d.map((x, i) =>
          l[
            (j = N / A ** i % A | 0) < A - 1 && o.push([i, j]),
            j
          ].push(x),
          o = [],
          l = a.map(_ => [])
        )
      ) && S < M ? O : (M = S, o)
  return O
}

How?
Initialization and main loop
The first thing we do is add a dummy attacking creature with an undefined power and a toughness of \$0\$. The push method returns the new number \$A\$ of attacking creatures, including this one.
A = a.push([, 0])

We are going to block this dummy creature instead of blocking no creature at all. This allows some simplifications in the code.
The number of combinations for the defending player can be expressed as \$A^D\$, where \$D\$ is the number of defenders. We use a for loop with the counter \$N\$ to iterate over all these possibilities.
for(N = (A = a.push([, 0])) ** d.length; N--;)

The score of the current iteration and the maximum score are stored in \$S\$ and \$M\$ respectively. Similarly, the current solution and the best solution are stored in \$o\$ and \$O\$.
At the end of each iteration, we test whether \$M\$ and \$O\$ need to be updated.
O = (...) && S < M ? O : (M = S, o)

Building our defense
Below is the block of code which is executed at the beginning of each iteration. A new important variable in there is \$l\$, which holds a list of blockers for each attacker.
d.map((x, i) =>              // for each defender x at position i:
  l[                         //   update l[]:
    (j = N / A ** i % A | 0) //     j = index of the attacker that we're going to block
    < A - 1 &&               //     if this is not the 'dummy' creature:
    o.push([i, j]),          //       add the pair [i, j] to the current solution
    j                        //     use j as the actual index to update l[]
  ].push(x),                 //   push x in the list of blockers for this attacker
  o = [],                    //   initialize o to an empty list
  l = a.map(_ => [])         //   initialize l to an array containing as many empty lists
                             //   that there are attackers
)                            // end of map()

Optimizing the attack
The decisions of the attackers are uncorrelated to each other. The global optimum for the attacking side is the sum of the local optima for each attacker.
We iterate on each attacker of power \$P\$ and toughness \$T\$ at index \$i\$.
a.map(([P, T], i) => ...)

To find the best decision for an attacker, we first build a new list derived from \$l[i]\$:
l[n = 0, i].map(m = ([p, t]) => [t, p + t, n += p])

Each entry in this list contains the toughness of the blocker, followed by its score (power + toughness). While building this list, we also compute \$n\$ which is the sum of the powers of all blockers. We'll use it later to test if the attacker is destroyed. (The fact that intermediate sums are stored as a 3rd entry for each blocker is just a golfing trick to save a few bytes. This 3rd entry is not used.)
We now call the recursive function \$g\$ with 2 parameters: the power \$P\$ of the current attacker and the list defined above. This function tries all possible ways of dispatching the damage points among the blockers.
(g = (n, l) =>            // n = remaining damage points; l = list of blockers
  n ?                     // if we still have damage points:
    l.map(([t, S], i) =>  //   for each blocker of toughness t and score S at index i:
      g(                  //     do a recursive call:
        n - 1,            //       decrement the number of damage points
        b = [...l],       //       create a new instance b of l
        b[i] = [t - 1, S] //       decrement the toughness of blocker i
      )                   //     end of recursive call
    )                     //   end of map()
  :                       // else:
    m =                   //   update the best score m (the lower, the better):
      l.map(([t, S]) =>   //     for each blocker of toughness t and score S:
        s += t > 0 && S,  //       add S to s if this blocker has survived
        s = 0             //       start with s = 0
      ) &&                //     end of map()
      s > m ? m : s       //     set m = min(m, s)
)                         //

Updating the defender score
After each iteration on an attacker, we update the defender score with:
S -= (n < T && P + T) + (l[i] < 1 ? T / 2 : -m)

The left part subtracts the score of the attacker if it has survived. The right part subtracts half the toughness of the attacker if the attack was not blocked at all, or adds the best attacker score otherwise (which is the worst one from the defending side perspective).

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


text:
Check all the keys of a keyboard
Write the shortest program that waits for every key of a Standard 101 key US Keyboard* to be pressed and then exits writing OK!
Every time a key is pressed the program displays on a new line the remaining number of unpressed unique keys that need to be pressed until all key are pressed at least once. The program should be able to test a 101 keyboard and see if every key works. So pressing twice a key or enter is to be allowed as long as this is specified to the user.
Pressing same key twice or more should not disrupt the code nor change the displayed number of remaining unpressed keys.
All keys (Left Shift, Right Shift, Right Control, Esc, Enter, etc.) should be included.
The actual keyboard keys are important in this challenge so from the perspective of the program (A and a, are the same and so are 6 and ^).
Combined keys will not be registered as a combined command and only the individual keys will be registered if Ctrl + Alt + Del is pressed that will count for all the individual keys in the combination being pressed. So no need to press also the capital letters if you pressed already the lowercase and vice-versa.
Numeric keys on the numeric keypad are different from the perspective of the program, so they are still needed to be pressed for the program to finish, if you have a laptop or any other keyboard that doesn't have the US Standard 101 keyboard layout you cannot fulfill the challenge unless you plugin a compatible keyboard.
*Keyboards having Fn key and laptop key will not be supported to keep this challenge doable
This is the list of keys for a US Standard 101 keyboard layout:
backspace
tab
enter
right shift
right ctrl
right alt
left shift
left ctrl
left alt
print screen
pause/break
caps lock
escape
page up
page down
end
home
left arrow
up arrow
right arrow
down arrow
insert
delete
0
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
numpad 0
numpad 1
numpad 2
numpad 3
numpad 4
numpad 5
numpad 6
numpad 7
numpad 8
numpad 9
multiply
add
subtract
decimal point
numpad enter
divide
f1
f2
f3
f4
f5
f6
f7
f8
f9
f10
f11
f12
num lock
scroll lock
semi-colon
equal sign
comma
dash
period
forward slash
grave accent
open bracket
back slash
close braket
single quote
space

Is it okay to require the Enter/Return key to be pressed after every keypress? If not, this is impossible in many languages.

List of keys please!

Also, does the program have to support non-printable-ASCII? (ex. Escape, Tab, Ctrl, Shift, Alt, Insert, the arrow keys, Caps Lock, Home, End, Page Up/Down, Backspace,  Del, the F keys, etc.)? Do a character and its shifted version both have to be pressed? What about Ctrl + a character? Do numpad keys count differently than regular ones?

Does this include operating system specific keys? Does it include both left and right versions of shift and control keys? What about caps lock, num lock, scroll lock?

After your edit: What should happen if two keys are pressed at the same time? What if shift is held and then, say, A is pressed? Does this count as a press for both shift and a, and does this need to be handled accordingly? Also, does your keyboard include a numpad, and are these keypresses significant / different from the regular numbers?

@Doorknob I edited the question

On my laptop keyboard, the "Fn" key does not act like a normal key. For example, it is the only key that xev does not recognize when pressed alone, because it is handled by the hardware and it is not possible for any program to detect when it is pressed by itself. What are the rules for this?

@Doorknob You cannot fulfill the challenge using a laptop's keyboard unless it has all 101 keys needed by the US Standard 101 keys layout

@EduardFlorinescu So what is the US Standard 101 keys layout?

Same as 104 keys layout use in every keyboard but without the two windows keys and right click key -  http://www.pcguide.com/ref/kb/layout/stdEnh101-c.html

Let us continue this discussion in chat.

@feersum I added the complete list of keys

@beta-decay Most of the people that closed this question never asked what they don't understand from it so is hard for me to guess.

Do the keys have to be pressed in any specific order?

@ASCIIThenANSI no any order would do, but they have to be pressed at least once

One algorithm answerers might try (anyone's free to use this in their answer) is to make an empty set (speaking in Python terms; a set is like just the keys of a dictionary; all entries are unique an unordered). Start the loop that gets the key presses. Add the number or sign that represents each user-entered key press to the set. When the set's length is 101, then you're done (you have 101 unique keys that have been pressed). Of course, you'll need to make sure each key actually has a unique number or symbol associated with it on your OS, language, and library. You can ignore combination keys

Javascript, 524 bytes
Hi, this is my first ever post here, so excuse me if I'm still ignorant on some stuff, I think I stayed within the rules though.
k=[8,9,"130","133","161","162","171","172","181","182",19,20,27,44,45,46,48,49,50,51,52,53,54,55,56,57,144,145,186,187,188,189,190,191,192,219,220,221,222];for(i=32;i<124;i+=1){i<41?k.push(i):i>64?i<91?k.push(i):i>95?i!=108?k.push(i):0:0:0}d=[13,16,17,18];m=document.addEventListener;c=console.log;m("keydown",e=>{e.preventDefault()});m("keyup",e=>{c(e.code);if(d.includes(e.which)){l=e.which+""+e.location;if(k.includes(l)){k.splice(k.indexOf(l),1)}}else if(k.includes(e.which)){k.splice(k.indexOf(e.which),1)}c(k.length)})

It seems buggy if I don't use Chrome, but you can try it out here.
(be sure to open the console before you focus on the example window, as the default functionality of F12 is prevented)
Overview
The program makes an array of all the 101 "keycodes". Some are written explicitly, some sequences are added with a for loop and some are stored as strings. I have a seperate array for the "double" keycodes, since left and right control for instance give the same keycode. They also give a location, however, so I combine the keycodes with the locations as strings in the array. From there it's just an eventlistener that prevents default keydown functionality (don't wanna refresh with F5 in this case) and a seperate eventlistener for keyup, because every single key can be detected on keydown, EXCEPT FOR PRINTSCREEN.
After every keyup event the remaining keys (aka the length of the array) gets logged, as well as the name of the keycode (so there is the distinction between left and right shift, etc). I wasn't sure if that was a requirement, if not you can subtract another 10 bytes from the score.
Limitations

It only seems to work well in Chrome

I hope this answer is appreciated and please let me know if I've done anything wrong.

Welcome to PPCG!

Can you change some or all of the semicolons to newlines? It won’t help your byte count but it would be much easier to read.

here's a version that's much easier to read https://pastebin.com/PE4anSFw

Java 8, 607 + 64 = 671 bytes
This is a lambda taking an unused parameter and throwing InterruptedException. It launches a window which, when in focus, intercepts presses of the 101 standard keys. Byte count includes lambda and required imports.
import java.awt.event.*;import javax.swing.*;import java.util.*;

v->{Set<Integer>s=new HashSet();long[]l={0x2bfff1ff081f0300l,0x8fffefff3ffffffel,3075<<16,4<<28|1};JFrame f=new JFrame();f.addKeyListener(new KeyAdapter(){public void keyReleased(KeyEvent e){int c=e.getKeyCode(),o=e.getKeyLocation(),n;c=(c==10|c>15&c<19)&o<3?-c:c==225?98:c==226?100:c==65386?101:c==227?102:c==224?104:o>3?c==33?105:c==34?99:c==35?97:c==36?103:c==127?110:c==155?96:c:(l[c/64]>>>c&1)<1?0:c;if(c!=0)s.add(c);System.out.println(n=101-s.size());if(n<1)synchronized(f){f.notify();}}});f.setFocusTraversalKeysEnabled(0<1);f.show();synchronized(f){f.wait();}System.out.print("OK!");System.exit(0);}

You can find a test class with an ungolfed version here.
Overview
As keys are pressed, values uniquely identifying them (in most cases the key code) are stored in a set. The first few levels of the ternary assignment to c handle cases where the key code is ambiguous (e.g. the "Home" key, which could come from the main portion of the keyboard or the number pad) and cases where the same key can map to multiple key codes (e.g. number pad behavior with Num Lock on or off). The final branch handles the "normal" keys whose key code can simply be used in the set. The key code indexes into the bitmap l which indicates whether the key is one of the standard 101.
Limitations

The program should be able to test a 101 keyboard and see if every key works.

If any key other than the standard 101 is pressed, a stack trace may be printed to standard error, or unexpected behavior may occur.

The program uses the numeric values of key code constants directly, and Oracle's KeyEvent documentation indicates that these values may change over time.

Acknowledgments

-10 bytes thanks to Kevin Cruijssen

f.setVisible(1>0); can be golfed to f.show(); and ()-> can be golfed to v-> by using an unused Void null parameter.

JavaScript, 98 90 75 bytes
So ... I suspect I may be underthinking things here but this should work. Let me know if I have overlooked anything. Only tested in Chrome.
s=new Set()
f=onkeydown=e=>!(onkeyup=e=>f(e,alert(101-s.add(e.code).size)))

Try it
alert overridden for your sanity and order reversed to save scrolling.

alert=x=>o.prepend(document.createTextNode(x+`\n`))
s=new Set()
f=onkeydown=e=>!(onkeyup=e=>f(e,alert(101-s.add(e.code).size)))
p{font-family:sans-serif;font-size:14px;}pre{margin:0 10px;}

Focus here and start typing ...

One thing you overlooked is that it also counts down when you press keys that are not on the 101-key keyboard, like the windows keys.

@M4Y, my interpretation of the challenge was that we assume that the specified keyboard is what's being used, especially given this line: "if you have a laptop or any other keyboard that doesn't have the US Standard 101 keyboard layout you cannot fulfill the challenge unless you plugin a compatible keyboard."

that's fair enough I suppose, clever solution!

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:
Computing the geometric median
Given a list of integer points in an n-dimensional space, output the geometric median. Note that the output is not necessarily integer. Your answer must be precise to at least two digits after the decimal point.
You may assume that n < 16 and that every component of each point fits in a 32-bit signed integer.
You may write a program or a function. You may take input and give output in any reasonable format. You may optionally pass n as a separate argument, instead of having to deduce it.
You must implement an algorithm to compute the geometric median, and not brute force over the output domain.
Examples:
(5), (14), (10), (7)                         -> any 7 <= x <= 10 is valid
(2, 3), (8, 4), (12, -3), (0, 0), (0, 0)     -> (2.17, 1.29)
(0, 0, 3), (20, 7, 3), (13, 14, 15)          -> (13.18, 7.94, 7.23)
(2, 20, 3, 30), (20, 2, 20, 2), (1, 2, 3, 4) -> (5.46, 5.12, 6.84, 8.06)

The answer is only unique if the set of points do not lie on a line. If the answer is not unique, you may return any valid answer.

Any requirement on complexity? Double-loop from min to max with step 0.01 will probably do the job. Is this allowed? (not sure whether it's less or more fun)

@anatolyg You must not brute force over the output domain. (Previously I stated that your solution mustn't rely on the input domain, but this unfairly rules out some probabilistic / hill climbing algorithms).

An accuracy of two decimal points isn't meaningful without some bound on the input coordinates. Perhaps when you say "integers" you mean 32-bit signed integers? Also, how do you expect us to confirm that our iterative algorithm is sufficiently accurate? Is it OK to just check this on the test points? I haven't found a proof of a formal quantitative bound of the Weiszfeld's algorithm in the worst case.

@xnor 32-bit signed integers as input bound is fine. Similarly, let's say that n < 16. Sadly I do not know the answer to your second question. I do not consider just these 4 test cases enough, though.  If someone finds another counterexample to your answer you must fix it.

@xnor A proven algorithm does exist however: http://www.pnas.org/content/97/4/1423.full.pdf. You can see my implementation (without weights, just like the challenge) here: http://stackoverflow.com/a/30305181/565635.

@orlp I'm not seeing a rate of convergence in that paper though, just a claim of the correct limit.

Matlab, 77 75
I just use the definition of the geometric median with a numerical minimization. In this case I make use of the Nelder-Mead simplex algorithm. It sould always converge as we try to find the minimum of a convex function (according to Wikipedia).
n=@(m)trace((m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))

Old version:
    n=@(m)sum(diag(m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))
The input format is a matix with the input vectors as columns, e.g:
m = [[2; 20; 3; 30],[20; 2; 20; 2],[1; 2; 3; 4]];

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


text:
Computationally Calculate Core Count
Almost all operating systems allow you to run multiple programs at the same time. If your system does not have enough processors to run all the programs you want to run, it starts to give each program just a tiny slice of time on the processor it runs on. This is normally not noticeable but can lead to strange artefacts that you might not expect.
Your task is to write a program that tries to find out how many cores your computer has without asking the operating system. This is a popularity contest, the most upvoted solution wins. Here are the constraints:

While you cannot expect that your submission is the only thing that runs, you may expect that all other programs on the system are idling and wake up only sporadically.
You may not ask the operating system how many cores your computer has. Neither may you look up this number from any configuration file or similar. You may also not invoke a utility that provides you with that information.
For the sake of this challenge, the number of cores your computer has is the number of processes your computer can run at the same time. For instance, if you have an Intel processor with 2 cores and hyper threading, that would count as 4 cores.
Your solution needs not to be precise. It should not be terribly wrong all the time though.

int num_cores() { return 1; } - only works on certain devices.

def num_cores(): return random.choice([1,2,4,8]) - works with about 25% accuracy for most consumer devices. "Your solution needs not to be precise. It should not be terribly wrong all the time though."

What if a device uses hyperthreading (we have then a device that pretends to have more cores than it physically has)? Should we try to report the number of real physical cores, or the one reported by the system?

@pawel.boczarski That's defined in the 3rd bullet item of the question.

What does "find out" mean? Do I need to print the number somewhere or is it sufficient if the program has the information internally only? My expected solution might not be able to print anything any more after finding out the number of CPUs...

Does the program need to terminate?

@FryAmTheEggman: There are AMD hexacore systems in which case it'll always be wrong

Most virtualization software will allow you to control how many virtual cores are assigned to a given VM.  This allows you to easily test against different configs, probably with reasonable results in many cases.  For example I have an Ubuntu VM running in VMWare Fusion on OSX.

@ThomasWeller This is a popularity contest. What attracts to most votes wins. You should try to print that number out though.

C++11
Simply compares single core performance with threaded performance until there is not a linear speedup anymore. It's important that you do not have any other CPU intensive process running at the same time.
Compile with -O2 -m64 -march=native -std=c++11. You might have to pass -lpthread.
#include <chrono>
#include <cstdint>
#include <future>
#include <iostream>
#include <vector>

double f() {
    double cnt = 0;
    std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
    start = std::chrono::system_clock::now();

    while (true) {
        end = std::chrono::system_clock::now();
        std::chrono::duration<double> elapsed = end - start;
        if (elapsed.count() > 1.) break;
        cnt++;
    }

    return cnt;
}

int main(int argc, char** argv) {
    double one_core = f();

    int n = 1;
    while (true) {
        std::vector<std::future<double>> futures;
        for (int i = 0; i < n; ++i) {
            futures.push_back(std::async(std::launch::async, f));
        }

        double tot = 0;
        for (int i = 0; i < n; ++i) tot += futures[i].get();
        if (int(tot / one_core + 0.5) != n) {
            std::cout << n - 1 << " core(s)\n";
            return 0;
        }

        ++n;
    }
}

Succesfully tested on Intel Haswell, Raspberry Pi (both quadcore) and some laptop Intel (dual core).

Yes, I was going to do something like this in [tag:c], but you save me the effort ;-).  Have a +1.

C
Here's a new, imprecise approach:
/* ncpu.c */

#include <stdio.h>
#include <pthread.h>
#include <signal.h>

pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
int count = 1;  /* start at 1 for the main() thread */

static void *inc_thread (void *arg) {
    /* Woohoo - now we're no longer languishing on the ready queue -
     * We're actually running on a real core.  Atomically bump the counter. */
    pthread_mutex_lock(&count_mutex); {
        count++;
    } pthread_mutex_unlock(&count_mutex);

    /* keep this core spinning so another thread doesn't get it */
    while (1);
    return NULL;
}

#define MAX_CORE 64
int main (int argc, char **argv) {
    pthread_t tid_array[MAX_CORE];
    int i;

    /* create a bunch of threads */
    for (i = 0; i < MAX_CORE; i++) {
        pthread_create(&tid_array[i], NULL, inc_thread, NULL);
    }
    /* cancel all those threads, regardless of whether they ran or not */
    for (i = 0; i < MAX_CORE; i++) {
        pthread_cancel(tid_array[i]);
    }

    printf("Your core count is approximately %d\n", count);
}

Build with LDFLAGS=-pthread make ncpu.
This works some of the time on Ubuntu 14.04.  I have tested with 1, 2 and 4 virtual cores in a VM.
This kicks off 64 threads, and then (almost) immediately cancels all those threads.  pthread_create() will put the new thread in a ready queue, but won't necessarily jump into the thread start routine immediately.  When the threads get to run depends on core availability at that time.
For example if there are 4 cores, then 3 of the threads can potentially start running immediately.  Each thread atomically increments a counter then spins for a bit until it is cancelled.  Beyond the third thread, the rest of the threads will still be sitting in the ready queue when the main thread cancels them, and so they won't get to increment the counter.
This is certainly not very precise, but its only terribly wrong some of the time.  Here are some runs with 1, 2 and 4 virtual cores:
1 core:
$ for i in {1..10}; do ./ncpu; done
Your core count is approximately 65
Your core count is approximately 1
Your core count is approximately 1
Your core count is approximately 15
Your core count is approximately 1
Your core count is approximately 19
Your core count is approximately 1
Your core count is approximately 1
Your core count is approximately 42
Your core count is approximately 1
$

2 cores:
$ for i in {1..10}; do ./ncpu; done
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 2
Your core count is approximately 3
Your core count is approximately 3
Your core count is approximately 2
Your core count is approximately 2
$

4 cores:
$ for i in {1..10}; do ./ncpu; done
Your core count is approximately 4
Your core count is approximately 5
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
Your core count is approximately 4
$

My previous answer:
Here's a start, though it only distinguishes between exactly one core and more than one core:
/* 1cpu.c */

#include <stdio.h>
#include <pthread.h>

int c = 0;

static void *inc_thread (void *arg) {
    int i;
    for (i = 0; i < 10000000; i++) c++;
    return NULL;
}

static void *dec_thread (void *arg) {
    int i;
    for (i = 0; i < 10000000; i++) c--;
    return NULL;
}

int main (int argc, char **argv) {
    pthread_t inc_tid, dec_tid;

    pthread_create(&inc_tid, NULL, inc_thread, NULL);
    pthread_create(&dec_tid, NULL, dec_thread, NULL);

    pthread_join(inc_tid, NULL);
    pthread_join(dec_tid, NULL);

    if (c) {
        printf("c=%d, More than one CPU\n", c);
    } else {
        printf("c=%d, Only one CPU\n", c);
    }
}

Build with LDFLAGS=-pthread make 1cpu.
This is a nice demonstration of how normal ++ and -- are not atomic operations.  In the single-core situation, inc_thread() and dec_thread() can never run concurrently, so the global counter c will always be incremented and decremented exactly 10 million times and thus end up as 0.  However with more than one core, these two threads will likely end up on different cores, and thus colliding with their operations on the global counter.  As we know, these operations have to load, [in|de]crement, then save each time, so threads can end up operating on stale data as they go through these operations.  Therefore over 10 million runs we will likely end up with a different number of effective increment vs decrement operations and the counter will end up non-zero.
This method seems to be fairly accurate, and works on OSX as well as Linux.

Python 2
import decimal
from timeit import Timer

elapsed = decimal.Decimal(Timer("""1 and 1""").timeit())
speed = 1/elapsed
cores = speed/decimal.Decimal(3.6)

cores = round(cores)

print cores

I kind of lost what I was doing halfway through  but this works fairly well for me.
Edit
I guess modern computer cores have a greater speed. The program should now be more accurate (hopefully).

This outputs numbers in the range 20-22 for me... I have 4 cores.

Outputs 9-13 for me, 4 cores as well.

@Doorknob Strange... It outputs 2-4 for me with 4 cores..

It's not said, that the output of the core count has to be precise on every system! Also, the elapsed time of a statement depends on the core speed, so it'll only equal with equal cores.


text:
Distributing Numbers
In this challenge you'll be using be distributing a product over sums and differences of numbers, as explained here.

Examples
  Input      |     Output
-------------|-------------
23(12+42)    | (23*12)+(23*42)
9(62-5)      | (9*62)-(9*5)
4(17+8-14)   | (4*17)+(4*8)-(4*14)
15(-5)       | -(15*5)
2(3)         | (2*3)
8(+18)       | +(8*18)
8(-40+18)    | -(8*40)+(8*18)

Specification
The input will be a string of the form n(_), with a single positive unsigned integer n followed by a parenthesized expression _. This expression _ will consist of sums and difference of one of more positive-integer terms separated by + and - signs. The first term may be preceded by a + sign, a - sign, or by no sign.
In the output, the initial number n should be distributed to multiply each of the terms. Each term of a should be left-multiplied by n to produce the parenthesized expression (n*a), and these new terms should be combined with + and - signs in exactly the same way as the original terms were.
Invalid Inputs
These are examples of inputs you don't have to handle.
3(5 plus 3)
6(5 13)
(5+8)(6+6)
(5+3)8

Winning
This is code-golf, so shortest code in bytes wins.

It occurs to me that regex is really well-suited for this problem. If you're not OK with reg-ex solutions, you could ban it, though people might be working on it already.

Are libraries allowed?

@orlp To a certain extent which was discussed on meta.

Interesting case: 8(-40+18)

Pip, 28 bytes
DQaUnxWa^'(xR`\d+`'(.n.`*&)`

Explanation:
                              a is first cmdline arg (implicit)
DQa                           Remove (DeQueue) the closing paren from a
   UnxWa^'(                   Unify n and x with a split on open paren--Python equivalent
                                n,x=a.split("(")
                              n is thus the number to be distributed, and x is the
                                addition/subtraction expression
           xR                 In x, replace...
             `\d+`            ... regex matching numbers...
                  '(.n.`*&)`  ... with the replacement pattern (n*&), where n is the
                                appropriate number and & substitutes the complete match
                              Print result (implicit)

Pip's Pattern objects mostly follow Python regex syntax, but the & replacement pattern is borrowed from sed.
Read more about Pip at the Github repository

JavaScript 65 bytes
s=>(q=s.split(/[()]/))[1].replace(/(\D?)(\d+)/g,`$1(${q[0]}*$2)`)

This will take the input. Get the + or -, then the digits, then replace it in the correct order.
Explanation
s=>   // Function with argument "s"
  (q= // Set q to...
    s.split(/[()]/) // Splits on parenthesis, returns array
  )
  [1] // Gets second match or text inside brackets
  .replace(/ // Replaces string
     (\D?)  // Try to match a non-digit, the +-/* (group 1)
     (\d+)  // Then match one or more digits (group 2)
  /,
      // $1 is group 1 and $2 is group 2 q[0] is the text before the parenthesis
  `$1(${q[0]}*$2)`
  )

Usage
This only works in Firefox and Safari Nightly maybe Edge? because it uses ES6 features. You can run it by:

var t=s=>(q=s.split(/[()]/))[1].replace(/(\D?)(\d+)/g,`$1(${q[0]}*$2)`)

t("5(-6+7+3-8+9)"); // -(5*6)+(5*7)+(5*3)-(5*8)+(5*9)

(.?)(\d+) is broken. This fails on 23(12+42), producing 1(23*2)+(23*42).

@orlp I have fixed that

This code will only work in Firefox b/c of the arrow function, but that's fine

@SpeedyNinja It also works in Edge. For Chrome/Opera you need to enable "experimental JavaScript features".

\D? could be used instead of [+-]?

@rink.attendant.6 Only Firefox and Edge by default

Python 2.7, 110 108 Bytes
import re
p=re.findall('([+-]?)(\d+)',raw_input())
print"".join("%s(%s*%s)"%(e[0],p[0][1],e[1])for e in p[1:])

The program takes input from stdin, searches for matches against - ([+-]?)(\d+) regex and creates the output string.
Testing it -
<< 23(12+42)
>> (23*12)+(23*42)

<< 9(62-5)
>> (9*62)-(9*5)

<< 4(17+8-14)
>> (4*17)+(4*8)-(4*14)

<< 15(-5)
>> -(15*5)

<< 2(3)
>> (2*3)

<< 8(+18)
>> +(8*18)

<< 8(-40+18)
>> -(8*40)+(8*18)

Retina, 40 bytes
+`(\d+)\((\D)?(\d+)
$2($1*$3)$1(
\d+..$
<empty line>

Each line should go to its own file but you can run the code as one file with the -s flag. E.g.:
>echo -n "8(-40+18)"|retina -s distributing_numbers
-(8*40)+(8*18)

The first two lines push the multiplier next to every number in the expected form:
8(-40+18)
-(8*40)8(+18)
-(8*40)+(8*18)8()

The last two lines remove the unnecessary trailing part:
-(8*40)+(8*18)8()
-(8*40)+(8*18)

sed, 105 bytes
Just wanted to see if this can be done with sed.
Maybe a bit old school, but it works.
$ cat distnum.sed
s@\([0-9]*\)(\([0-9]*\)\([+-]*\)\([0-9]*\)\([+-]*\)\([0-9]*\))@(\1*\2)\3(\1*\4)\5(\1*\6)@
s@([0-9]*\*)@@g

$ cat distnum.txt
23(12+42)
9(62-5)
4(17+8-14)
15(-5)
2(3)
8(+18)
8(-40+18)

$ sed -f distnum.sed distnum.txt
(23*12)+(23*42)
(9*62)-(9*5)
(4*17)+(4*8)-(4*14)
-(15*5)
(2*3)
+(8*18)
-(8*40)+(8*18)

rs, 77 bytes
$$d=(?<!\))([+-]?)(\d+)
+$d\($d([+-])/\3(\1\2*\4)\5\1\2(
$d\($d\)/\3(\1\2*\4)

Live demo and all test cases.
This is the first time rs's macros have actually been used!

REGXY, 45 bytes
Uses REGXY, a regex substitution based language.
/(\d+)\((\D)?(\d+)/\2(\1*\3)\1(/
//
/\d+\(.//

How does the // work? I suppose it loops to the top until the string changes but I can't find in the esolang page why.

It's a bit of a cheeky abuse of the vagueness in the language spec, but I've explained it here: http://codegolf.stackexchange.com/questions/52946/backhandedhhhhhhspaces/53002#53002

I still don't get why doesn't the // create an infinite loop as nothing will always match so we always jump back to the first line.

Y'know what? I actually have no idea why. You're absolutely right, thinking about it now it makes no logical sense, but it definitely compiles and runs in the provided interpreter. Even looking at the compiled Perl it generates confuses me, because it looks even clearer that it should be an infinite loop: http://pastebin.com/9q7M0tpZ

Perl, 36 bytes
35 bytes code + 1 byte command line
($a,$_)=split/[()]/;s/\d+/($a*$&)/g

Usage:
echo "4(17+8-14)" | perl -p entry.pl

Pyth, 39 38 bytes
A terrible regex solution:
P:eJcz\("([+-]?)(\d+)"X"\\1(_*\\2)"3hJ

I can't seem to get this to run in the online interpreter.

@BrainSteel It works in the offline interpreter, it seems to be a problem with heroku.

@orlp It's not a problem with heroku. Dynamic imports are disabled in safe mode, to reduce the likelihood of a hack, and the re module does a dynamic import. So re can't be used in safe mode, including online.

Ruby, 94 bytes
gets.scan(/(\d+)\(([[-+]?\d+]+)/){|a,b|b.scan(/([-+]?)(\d+)/).map{|c,d|$><<"#{c}(#{a}*#{d})"}}

Retina, 50 51 43 bytes
I think this may be my first Retina program. If not, it's my first Retina program that's this complex (not that complex, really.) Each line goes in its own file.
+`(\d+)\((\D?)(\d+)
$1($'$2($1*$3)
.+?\)
$'

I didn't actually test this with Retina, I tested it using a regex-replace tester multiple times, but it should work.
Description for first example:
Since there are an even number of files, Retina uses replace mode. The first replace (first two files) removes a number to be distributed and adds that distribution pair (23*12) to the end, giving 23(+42)(23*12). +` at the start tells Retina to repeatedly replace until the pattern doesn't match, and since this is matched again, the pattern replaces this with 23()(23*12)+(23*42). This doesn't match anymore, so the next 2 files are used for the next replace. This time, it merely removes the 23(). This works nicely: since products are appended to the end, I don't have to do anything weird if a number doesn't have a sign, since the only one that can be without a sign is the first number.
EDIT: $' in replacement represents the rest of the string after the match, so I can removing the trailing (.*)s.

CJam, 50 bytes
l__'(#_@<'*+@@)>);'+/'-f/\ff{1$'(@@++')+L?}'-f*'+*

Try it online
CJam does not have regex support, or anything beyond string searching and splitting that is very convenient for parsing expressions. So there's some labor involved here.
Explanation:
l__   Get input and push 2 copies for splitting.
'(#   Find index of '(.
_     Copy index, will be used twice.
@<    Get one copy of input to top, and slice to get first multiplier.
'*+   Append '* to first multiplier.
@@    Get another copy of input and '( index to top.
)>    Increment and slice to get everything after '(.
);    Remove trailing ').
'+/   Split at '+.
'-f/  Split each part at '-.
\     Swap first multiplier to top.
ff{   Apply block to nested list of second multipliers.
  1$    Copy term. Will use this copy as condition to skip empty second multipliers
        that result from unary + or -.
  '(    Opening parentheses.
  @@    Get first and second multiplier to top.
  ++    Concatenate it all.
  ')+   Concatenate closing parentheses.
  L     Push empty string for case where term is skipped.
  ?     Ternary if to pick term or empty string.
}     End of loop over list of second multipliers.
'-f*  Join sub-lists with '-.
'+*   Join list with '+.

gawk - 60 58
$0=gensub(/(.*\()?(+|-)?([0-9]+))?/,"\\2("$0+0"*\\3)","G")

Phew... haven't worked with regexp in quite a while.

Perl 5, 70 60 55 44 Bytes + 1 penalty
A perl solution that only uses split and 1 regular expression.
Also calculates the longer inputs.
($a,$_)=split/[()]/;s/(\D?)(\d+)/$1($a*$2)/g

Test
$ echo "8(9-10+11-12+13-14)"|perl -p distnums.pl
(8*9)-(8*10)+(8*11)-(8*12)+(8*13)-(8*14)

A version that takes a parameter
($a,$_)=split/[()]/,pop;s/(\D?)(\d+)/$1($a*$2)/g;print

A version that only uses regular expressions.
s/(\d+)\((.*)\)/$2:$1/;s/(\D?)(\d+)(?=.*:(\d+)).*?/$1($3*$2)/g;s/:.*//

This one works via a capture group within a positive lookahead and lazy matching.  Probably would have used a positive lookbehind if Perl 5 supported it, but alas. Took me a while to figure out that this kinda thing is possible with regex.

Hey Luk, You might be able to save some chars using -p command line option (I think this is +1 char vs 9 for ,<> and ;print) as split will work on $_ by default (which will be whatever is in <>) and print is included in the loop too! Hope that helps!

Thanks! It helped.  The -p option simply didn't cross my mind. Probably since it's something that's rarely used outside a golfing context. Why do you think it's +1 char?  This challenge doesn't mention anything about a penalties for using switches.

I can't find the post now, but this meta post mentions scoring for Perl's flags.

My bad, looks like I came up and posted a very similar solution to you, which is effectively just a slightly more golfed version of yours! Basically you don't even need to capture the [+-] because you leave them intact in the substitution anyway: http://codegolf.stackexchange.com/a/57117/26977

That's cool. Because of you, Perl beats even the Pyth/Cjam solutions in this challenge.
I shouldn't have cared about the invalid inputs anyway after that split removed the brackets.

k, 98 bytes
Not very golfed.
{,/(*x){(s#y),("*"/:(x;(s:(*y)in"+-")_y))/:$"()"}/:1_x@:&~~#:'x:((0,&~x in .Q.n)_x){x_'x?'y}/"()"}

Split on non-digit, remove parens, remove empty strings, then holding x constant as the first string, combine with * with each remaining string y, parenthesize, and move sign to the beginning if present; flatten output into a single string.

Pip, 23 bytes
HDQa^'(R:+XD'(.+a.`*&)`

Attempt This Online!
Explanation
HDQa^'(R:+XD'(.+a.`*&)`
   a                    ; Command-line argument
    ^'(                 ; Split on open parenthesis
 DQ                     ; Get the last element of that list
H                       ; Take all but the last character
                        ; This gives us the expression inside the parentheses
       R:               ; Replace
         +XD            ; each regex match of a run of digits
                        ; with:
            '(          ;  Open parenthesis
              .         ;  concatenated to
               +a       ;  Convert a to number (gets the part before the open paren)
                 .      ;  concatenated to
                  `*&)` ;  Replacement pattern: * followed by match followed by )