Finding all non-conflicting combinations of values from multiple lists of values

前端 未结 9 1029
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 05:34

I have the following array which contains arrays of values:

$array = array(
    array(\'1\', \'2\'),
    array(\'a\', \'b\', \'c\'),
    array(\'x\', \'y\'),         


        
9条回答
  •  借酒劲吻你
    2021-01-01 06:18

    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.

    ps. I don't know php, the example is written in Delphi.

    Edit: recursive solution with arbitrary # arrays

    type
      TSingleArray = array of string;
      TMasterArray = array of TSingleArray;
    var
      solutions: array of integer; // Q&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 <> 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.
    

提交回复
热议问题