DEV Community

Discussion on: Interview Question: A two-player card game

Collapse
 
alainvanhout profile image
Alain Van Hout

I’d expect an interviewee to (hopefully) recognize that OOP isn’t that well-suited for this task, compared to a functional approach:

  • take the list of cards
  • randomize their order
  • reduce them two-by-two by substracting
  • map then into 1 and -1
  • sum them

The sign of that number will tell you which player wins. The rest is window dressing.

As for a multi-player variant:

  • reduce them per N and pass on the index of the highest value
  • map them to a dictionary of index and count
  • sort them by count
  • take the first or last, depending on your sorting direction

Note that if the goal was an actual, playable game, then things would be different. But the requirement here seems to be that we want to know which player wins the game (distilling core requirements is very valuable skill).

Collapse
 
plastix profile image
Aidan Pieper

I love the functional approach! Thanks for sharing.

Collapse
 
moopet profile image
Ben Sinclair

This was my initial thought too. As it's a simulation you can map the steps to functions that pop N from the list and determine the index of the player which wins.
That extends to as many players as you want without using classes (which in this test, YAGN...) and only becomes trickier in the later parts of the question where new rules are introduced.

At that point I can see myself preferring to defend my assumptions for a while before actually changing any code.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

OOP works fine here, but you only need like 2-3 classes to group the data. No virtual functions, interfaces, nor anything else. I'm refering just to some basic encapsulation.

I'd not be opposed to a functional approach, albeit there is a caveat to it. Your algortihm deviates significantly from the source wording; having code that is mappable to source requirements is important. You might have a higher burden of naming in this approach to compensate.

I had one interviewee approach close to this way once. I don't penalize for it, but I add a requirement like emitting events as cards are dealt, or as they are turned up. That person didn't have much trouble changing their approach. That alone is a positive sign: they've shown functional design, but flexibility as well.

As you say, they've distilled a core requirement. Not many people actually ask for clarification as to what is allowed. For those that do I tend to imply it's a simplified program that would actually have UI.

I think it's why coding interviews need to be quite personal, with the interviewer having good knowledge of coding. It wouldn't be fair of me to accept only a rigid OOP structure. Sure, it's what I'd expect in a practical situation, but it's not the only option based on the stated requirements.