Created
December 20, 2019 15:28
-
-
Save Honga1/70a53118f60c1ae9bd10f1f240cd8042 to your computer and use it in GitHub Desktop.
Solution to 20/12/19 Devmat problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const countTokens = (tokenMatcher: RegExp, input: string) => | |
input | |
.match(tokenMatcher) | |
?.map((token: string) => | |
token.replace(/((\+|\-|^){1}$(?![0-9]))/g, match => (match === '-' ? '-1' : '1')), | |
) | |
.map(token => parseInt(token)) | |
.reduce((accumulator, currentValue) => accumulator + currentValue, 0) ?? 0; | |
const countVariables = (input: string) => countTokens(/((\+|\-|^)|(-*)[0-9]){1}(?=x)/g, input); | |
const countConstants = (input: string) => countTokens(/(-|\+|^){1}[0-9](?!x)/g, input); | |
function solve(input: string): string { | |
const [left, right] = input.split('='); | |
const totalX = countVariables(left) - countVariables(right); | |
const totalConstants = countConstants(left) - countConstants(right); | |
if (totalX !== 0) return `x=${-totalConstants / totalX}`; | |
if (totalConstants === 0) return 'Infinite solutions'; | |
return 'No solution'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment