Skip to content

Instantly share code, notes, and snippets.

@tsaniel
Forked from 140bytes/LICENSE.txt
Created July 22, 2011 14:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsaniel/1099617 to your computer and use it in GitHub Desktop.
Save tsaniel/1099617 to your computer and use it in GitHub Desktop.
solveAlgebraicEquation (using RegExp)
function(
a, // the set of variables
b, // the sum
c, // placeholder
d, // placeholder
e // placeholder
){
c = '^';
for (d = 0; e = a[d++];)
c += '(,*)\\' + d + '{' + ~-e + '}' // part of the RegExp pattern.
return (
(
Array(-~b) + '' // let b plus one and coerce the array into a string that consists of commas.
).match(c + '$')
||
'' // if no matches, go to an empty string.
).slice(1) // shift the matched whole substring or do nothing when no matches.
}
function(a,b,c,d,e){c="^";for(d=0;e=a[d++];)c+="(,*)\\"+d+"{"+~-e+"}";return((Array(-~b)+"").match(c+"$")||"").slice(1)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "solveAlgebraicEquation",
"description": "Solve algebraic equation with RegExp",
"keywords": [
"solveAlgebraicEquation",
"algebraic equation",
"RegExp"
]
}
<!DOCTYPE html>
<title>solveAlgebraicEquation</title>
<div>Output: <b id="ret"></b></div>
<script>
var myFunction = function(a,b,c,d,e){c="^";for(d=0;e=a[d++];)c+="(,*)\\"+d+"{"+~-e+"}";return((Array(-~b)+"").match(c+"$")||"").slice(1)};
// The input should be ([a, b, c, ...], sum)
// e.g. Solve 11x + 2y + 5z = 115
var solution = myFunction([11, 2, 5], 115);
document.getElementById( "ret" ).innerHTML = 'One of the solutions of 11x + 2y + 5z = 115 is x = ' +
solution[0].length + ', y = ' +
solution[1].length + ', z = ' +
solution[2].length;
</script>
@atk
Copy link

atk commented Jul 22, 2011

You can leave out the "RegExp", since the arguments of match get coerced to RegExp anyway. So it is:

function(a,b,c,d,e){c="^";for(d=0;e=a[d++];)c+="(,*)\\"+d+"{"+~-e+"}";return((Array(-~b)+"").match(c+"$")||"").slice(1)};

@tsaniel
Copy link
Author

tsaniel commented Jul 23, 2011

Thanks @atk!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment