Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This can be refactored using recursion making it work with any arbitrary amount of arrays. If I find the time, I'll give it a try myself.</p> <p><em>ps. I don't know php, the example is written in Delphi.</em></p> <p><strong>Edit:</strong> recursive solution with arbitrary # arrays</p> <pre><code>type TSingleArray = array of string; TMasterArray = array of TSingleArray; var solutions: array of integer; // Q&amp;D container to hold currently used indexes of SingleArrays procedure WriteSolution(const masterArray: TMasterArray); var I: Integer; indexes: string; solution: string; begin for I := 0 to High(solutions) do begin indexes := indexes + IntToStr(solutions[I]) + ' '; solution := solution + masterArray[I][solutions[I]]; end; Writeln('Solution: ' + solution + ' Using indexes: ' + indexes); end; procedure FindSolution(const masterArray: TMasterArray; const singleArrayIndex: Integer; var bits: Integer); var I: Integer; begin for I := 0 to High(masterArray[singleArrayIndex]) do begin //***** Use bit manipulation to check if current index is already in use if bits and (1 shl I) = (1 shl I ) then continue; solutions[singleArrayIndex] := I; Inc(bits, 1 shl I); //***** If it is not the last array in our masterArray, continue by calling RecursArrays recursivly. if singleArrayIndex &lt;&gt; High(masterArray) then FindSolution(masterArray, Succ(singleArrayIndex), bits) else WriteSolution(masterArray); Dec(bits, 1 shl I); end; end; //*************** // Initialization //*************** var I, J: Integer; bits: Integer; singleArrayString: string; masterArray: TMasterArray; begin I := 10; SetLength(masterArray, I); for I := 0 to High(masterArray) do begin SetLength(masterArray[I], High(masterArray) + Succ(I)); singleArrayString := EmptyStr; for J := 0 to High(masterArray[I]) do begin masterArray[I][J] := IntToStr(J); singleArrayString := singleArrayString + masterArray[I][J]; end; WriteLn(singleArrayString) end; ReadLn; //****** Start solving the problem using recursion bits := 0; SetLength(solutions, Succ(High(masterArray))); FindSolution(masterArray, 0, bits); end. </code></pre>
 

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