After the troubles of the last few days, the elves deserve a break. So they decided to organize a Secret Santa. In Italy there is no such translation: the elves had to explain it to me. In return they asked me how I would solve the problem of matching pairs. Here is my solution.

### The puzzle: Secret Santa 🤫

I don’t have hallucinations: I’m talking about problem number 8 of the Dev Advent Calendar 🎅. Today’s challenge is to match each element of an array with another element. I cannot match an element to itself and each pair of elements must be different.

Before my code, a brief parenthesis for those unfamiliar with the tradition of the Secret Santa:

The concept of “secret santa” is the following: Each participant is assigned a so-called “secret santa”, a person that will have to get a thoughtful gift for that person.

Usually this is in-person: All names are thrown in a hat, and each participant draws one. The paper you draw it the person you have to give a gift to.

### My solution

The puzzle can be solved quickly using array methods. But let’s go in order. There are 3 requests to satisfy, I start with the first.

First, if there are two elves with the same name I have to get an error. In this case, the text of the quiz already contains a hint:

So I just have to write a simple condition:

The second and third conditions can be solved together. I have to give each name a Secret Santa. And an elf cannot be his own Secret Santa.

To solve this first I mix the hat, sorry, the array with the names of the participants:

Then I decide to pair the various names in pairs based on their position in the array. In practice I create pairs like this:

Using this technique I am sure that each elf will have a different companion.

The complete code of my solution is simply this:

Well, today’s problem is solved.

But there is one thing I want to say. It helps me keep track of problems and solutions. It is also helpful for me to translate these pieces into English. On the one hand, it allows me to practice in a language that is not mine, and which I learned by myself. On the other hand, translating concepts helps me simplify my prose, and verify what I think I understand.

Ok, so what? So I’m really happy with a report from Marc Schärer about a misleading title (this title). It’s difficult for me to find a title in English. But I’m glad someone reads what I write. And I’m very happy that you take the time to report my mistakes. Thanks!

Tags:

Categorie:

Aggiornato: