Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Don't use regex. A regex matches only 1 element as you say, instead you need to find all the possible "meanings" of your string. Given the fact that each element's lenght is 1-2 chars, I'd go with this algorythm (forgive the pseudocode):</p> <pre><code>string[][] results; void formulas(string[] elements, string formula){ string[] elements2=elements; if(checkSymbol(formula.substring(0,1))){ elements.append(formula.substring(0,1)); if(formula.length-1 ==0){ results.append(elements); } else { formulas(elements,formula.substring(1,formula.length); } } if(checkSymbol(formula.substring(0,2))){ elements2.append(formula.substring(0,2)); if(formula.length-2 ==0){ results.append(elements2); } else { formulas(elements2,formula.substring(2,formula.length); } } } bool checkSymbol(string symbol){ // verifies if symbol is the name of an element } </code></pre> <p>input <code>"hgas"</code> (let's go depth first)</p> <p>first step: <code>checkSymbol(formula.substring(0,1))</code> is true for <code>"h"</code></p> <pre><code>elements2 = [h] </code></pre> <p>recursive call, <code>if(checkSymbol(formula.substring(0,1))) false</code></p> <p>then it tests <code>ga</code> => true</p> <pre><code>elements2 = [h, ga] </code></pre> <p>third recursive call</p> <p>test <code>s</code>, <code>checksymbol</code> returns true, elements is then <code>[h, ga, s]</code>. Length of the substring is 0 so it appends to results the first array: <code>[h, ga, s]</code></p> <p>-- let's go back to the second "branch" of first step</p> <p>The test <code>checkSymbol(formula.substring(0,2)</code> finds that <code>"hg"</code> is an element as well</p> <pre><code>elements2 = [hg] </code></pre> <p>Then we call <code>formulas([hg],"as")</code></p> <p>The test for <code>"a"</code> fails (it is not an element) and the test for <code>"as"</code> works, the length is totally consumed, the result <code>[hg,as]</code> is appended to <code>results[]</code></p> <p>This algorythm should run in O(n^2) time in the worst case, n being the length of the string.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload