Dice's Coefficient is a simple statistic that measures the similarities of two strings. A Dice's Coefficient of 1 means the strings are exactly the same, and 0 means they have no similarities at all.
Computing Dice's Coefficient is really easy. It goes like this:
- For
string1, turn it into a set of trigramstrigrams1 - For
string2, turn it into a set of trigramstrigrams2 - Calculate the size of the intersection of those two sets (number of trigrams)
- Multiply the intersection size by two and divide it by the sum of the sizes of
trigrams1andtrigrams2(in triagrams)
Example:
For string1 = "hello" and string2 = "help":
trigrams1 = {"hel", "ell", "llo"}(size 3)trigrams2 = {"hel", "elp"}(size 2)- Intersection:
{"hel"}(size 1) - Dice's Coefficient:
(2 * 1) / (3 + 2) = 0.4
This problem is available in two languages β pick whichever you prefer:
| Language | Directory | Baseline file | File to fix | Run benchmark |
|---|---|---|---|---|
| JavaScript | js/ |
dice_baseline.js |
dice_fast.js |
node js/bench.js |
| C++ | c++/ |
dice_baseline.cpp |
dice_fast.cpp |
cd c++ && make run |
Windows (C++): Use make -f Makefile.win run instead of make run.
The baseline file contains a gold-standard implementation of Dice's Coefficient. The only problem is that it's slow.
The dice_fast file contains a hacky attempt to speed it up by approximating the answer. It succeeds in speeding up the result, but fails by returning an incorrect answer - the result is 14.1% off from the baseline on one of the test cases.
Your job is to fix dice_fast - make the function as fast as possible, while returning a result within 5% of the baseline.
Get the % of baseline number as low as possible while not failing the tests.
Test data lives in test_data.json at the project root and is shared between both implementations. The C++ build downloads nlohmann/json on first run, so you'll need network access the first time you build.
Feel free to google things and/or use a profiler, but don't use any AI.
It shouldn't be too hard to get to ~50% of baseline with 0% degradation.
This is what Ivo's Head of Engineering got:
| (index) | length | Baseline | Baseline ms | fastDice | fastDice ms |
|---|---|---|---|---|---|
| 0 | 5 | '0.40' | '0.01' | 'β ' | '0.00 (67.2%) πππ' |
| 1 | 61183 | '0.98' | '12.40' | 'β ' | '0.79 (6.4%) πππππππππ' |
| 2 | 360606 | '0.99' | '22.09' | 'β ' | '2.20 (10.0%) πππππππππ' |
| 3 | 145169 | '0.23' | '56.47' | 'β (0.24: 3.0% off)' | '2.59 (4.6%) πππππππππ' |
Total elapsed (baseline): 90.97ms
Total elapsed (fastDice): 5.59ms
Runtime (fastDice): 6.1% of baseline πππππππππ
β
All test cases passed