How many people have X and Y? I have a problem for which I know the answer, but have no idea why it works.

Of 40 people, 30 have a condition. 15 have condition X and 25 have condition Y. How many people have both X and Y?

I know the answer is 10 (thanks to the answers sheet) but why? When I simulate the question by giving random people X's and Y's, and count the people with both, I get answers ranging from 8 to 13. Is my simulation off? Is my thinking wrong?

Why would it be 10, all the time?

Only theory is 15+25=40, 40-30=10, but this doesn't seem logical. (25-15=10, but that's just coincidence right?)
Use the law $n(X \cup Y)=n(X)+n(Y)-n(X \cap Y),$ where $n(A)$ means the number of elements in set $A$. In your case, you know $n(X \cup Y)$ and also know $n(X),n(Y).$

EDIT: Note that the 40 in "Of 40 people..." has no effect. The same answer of 10 would result if this phrase were replaced by "Of 1000 people." Only the people having a condition can count toward those having both conditions X and Y.
I misunderstood the question earlier. By condition you mean symptom - which means that there could be people with a disease who don't have either symptom X or Y. I am posting a new answer:

Total no. of people = 40 = number of people with only symptom X + Number of people with only symptom Y + number of people with both symptom X and Y + number of people with neither symptom X or Y.

number of people with neither symptom X or Y = total population - people with either symptom = 40 - 30 = 10

Number of people without symptom X = total population - people with symptom X = 40 - 15 = 25

number of people with only symptom Y = people without symptom X - people with neither symptom = 25 - 10 = 15

number of people without symptom Y = total population - people with symptom Y = 40 -25 = 15

number of people with only symptom X = people without symptom Y - people with neither symptom = 15 - 10 = 5

therefore total number of people with only X or only Y symptom  = 15 + 5 = 20

therefore total number of people with both X and Y = Total number of people with either symptom X or Y - total number of people with only X or only Y symptom = 30 - 20 = 10