Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Optimize Dice's Coefficient

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:

  1. For string1, turn it into a set of trigrams trigrams1
  2. For string2, turn it into a set of trigrams trigrams2
  3. Calculate the size of the intersection of those two sets (number of trigrams)
  4. Multiply the intersection size by two and divide it by the sum of the sizes of trigrams1 and trigrams2 (in triagrams)

Example:

For string1 = "hello" and string2 = "help":

  1. trigrams1 = {"hel", "ell", "llo"} (size 3)
  2. trigrams2 = {"hel", "elp"} (size 2)
  3. Intersection: {"hel"} (size 1)
  4. 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

About

Dice's Coefficient

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages