2017-06-08 32 views
1

我有10个对象。每个对象都可以处于3个状态1,2或3中。让我们看看结果1111111111.对于那个结果(或任何其他结果),我试图循环遍历所有的方式,可以得到8个正确的10个猜测中的8个它。例如,2111211111就是其中之一。我已经设法使用下面的循环与9/10一起工作,但我需要帮助才能使它与8/10和7/10一起工作。通过所有可能的方式遍历n个正确的猜测

为简单起见,假设我们正在不断检查的唯一组合是1111111111.

Dim incorrectcombos As New Text.StringBuilder 
    For i = 2 To 3 
     For j = 0 To 9 
      Dim combo As New Text.StringBuilder 
      For k = 0 To 9 
       If k = j Then 
        combo.Append(i) 
       Else 
        combo.Append(1) 
       End If 
      Next 
      incorrectcombos.AppendLine(combo.ToString) 
     Next 
    Next 
    MessageBox.Show(incorrectcombos.ToString) 

回答

1

递归的方法是非常简单的。 Delphi代码(注意,德尔福字符串基于1)

procedure GenerateCombs(s: string; MaxLen, Position, ErrCount: Integer); 
    begin 
    if Position = MaxLen + 1 then 
     Memo1.Lines.Add(s) //output string 
    else begin 
     if ErrCount <= MaxLen - Position then 
     GenerateCombs(s + '1', MaxLen, Position + 1, ErrCount); 
     if ErrCount > 0 then begin 
     GenerateCombs(s + '2', MaxLen, Position + 1, ErrCount - 1); 
     GenerateCombs(s + '3', MaxLen, Position + 1, ErrCount - 1); 
     end; 
    end; 
    end; 

begin 
    GenerateCombs('', 4, 1, 2); 

产生

1122 
1123 
1132 
1133 
1212 
1213 
1221 
1231 
1312 
1313 
1321 
1331 
2112 
2113 
2121 
2131 
2211 
2311 
3112 
3113 
3121 
3131 
3211 
3311 

C#(ideone):

using System; 

public class Test 
{ 
     static public void GenerateCombs(string s, int MaxLen, int Position, int ErrCount) 
     { 
      if (Position == MaxLen + 1) 
      { 
       Console.WriteLine(s); 
       return; 
      } 

     if (ErrCount <= MaxLen - Position) 
     { 
       GenerateCombs(s + "1", MaxLen, Position + 1, ErrCount); 
     } 

      if (ErrCount > 0) 
      { 
       GenerateCombs(s + "2", MaxLen, Position + 1, ErrCount - 1); 
       GenerateCombs(s + "3", MaxLen, Position + 1, ErrCount - 1); 
      } 
     } 

    public static void Main() 
    { 
     GenerateCombs("", 4, 1, 2); 
    } 
} 
+0

看伪代码没有开始,结束 – MBo

+0

我不确定如何在.net代码中实现。如果我不包含“开始”行跳转部分(除了在每个组合的末尾添加另一个1),它几乎可以工作。如果包含,它只会在第一部分无限循环。 编辑:显然,“开始”是所有Delphi程序的一部分。 “Else开始”究竟是什么意思? – user8128940

+0

'begin .. end == {..}' – MBo