Skip to content

alphametics: optimise implementation for last test - #935

Merged
SleeplessByte merged 1 commit into
exercism:masterfrom
slaymance:issue-897/alphametics
Jan 15, 2021
Merged

SleeplessByte merged 1 commit into
exercism:masterfrom
slaymance:issue-897/alphametics

Conversation

@slaymance

Copy link
Copy Markdown
Contributor

This PR addresses Issue 897.

I refactored the example solution using my solution to alphametics as a guideline. The example implementation struggled a bit with the last test because we would replace each letter with a number every time we wanted to test a permutation. I refactored it so that we sum up the places of each letter and then multiply that sum by a number for each permutation, which is much faster than replacing each letter individually. For example:

// If we have the string 'MOM':
{
  'M': 10 ** 2 + 10 ** 0, // === 101
  'O': 10 ** 1 // === 10
}
// and if we want to test M = 9 and O = 2:
{
  'M': 909, // === 101 * 9
  'O': 20 // 10 * 2
}

For letters the appear in the total (right side of the equals sign), then their count is subtracted. At the end, we add up all the counts of the letters and check to see if the sum is equal to 0. If so, then that permutation of numbers is our solution.

@SleeplessByte SleeplessByte left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much better solution. Thank you @slaymance

@SleeplessByte SleeplessByte changed the title (Issue 897) alphametics: optimise implementation for last test alphametics: optimise implementation for last test Jan 15, 2021
@SleeplessByte
SleeplessByte merged commit 093d842 into exercism:master Jan 15, 2021
@slaymance
slaymance deleted the issue-897/alphametics branch January 16, 2021 05:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants