2017-04-25 78 views
0

我有使用组合方法的编码。C#如何仅显示组合的第一个,第二个和第三个答案?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 


class Program 
{ 
static void Main(string[] args) 
{ 

    string input; 
    int NoDisplay; 
    decimal goal; 
    decimal element; 

    do 
    { 
     Console.WriteLine("Please enter the target:"); 
     input = Console.ReadLine(); 
    } 
    while (!decimal.TryParse(input, out goal)); 

    Console.WriteLine("Please enter the numbers (separated by spaces)"); 
    input = Console.ReadLine(); 
    string[] elementsText = input.Split(' '); 
    List<decimal> elementsList = new List<decimal>(); 
    foreach (string elementText in elementsText) 
    { 
     if (decimal.TryParse(elementText, out element)) 
     { 
      elementsList.Add(element); 

     } 

    } 

    int i; 
    int j; 
    decimal tmp; 
    int[] arr1 = new int[10]; 

    for (i = 0; i < elementsList.Count; i++) 

    { 
     for (j = i + 1; j < elementsList.Count; j++) 
     { 
      if (elementsList[i] < elementsList[j]) 
      { 
       tmp = elementsList[i]; 
       elementsList[i] = elementsList[j]; 
       elementsList[j] = tmp; 
      } 
     } 
    } 


    Console.WriteLine("Please enter the maximum combination :"); 
    NoDisplay = Convert.ToInt32(Console.ReadLine()); 


    Solver solver = new Solver(); 
    List<List<decimal>> results = solver.Solve(goal, elementsList.ToArray()); 

    //results.Reverse(); 

    Boolean recordexist = false; 
    foreach (List<decimal> result in results) 
    { 
     if (result.Count == NoDisplay) 
     { 
      recordexist = true; 
      foreach (decimal value in result) 
      { 
       Console.Write("{0}\t", value); 
      } 
      if (recordexist == true) 
      { 

       Console.WriteLine(); 
      } 

     } 
    } 


    if (recordexist == false) 
    { 
     Console.WriteLine("No record exist"); 
    } 

    Console.ReadLine(); 
} 
} 

Here is the output

我的问题是如何显示的第一,第二和第三个答案只有 Like this

对不起我的英文不好,我希望有人能帮助我与此有关。我还是新的c#顺便说一句。谢谢

+0

你可以在这里添加图片本身,或通过应对粘贴的输出本身。 Imgur链接可能会标记为垃圾邮件。 – garg10may

+0

好的。感谢您的建议:) – Nobody

回答

0

我的问题是我如何才能显示第一个,第二个和第三个答案 只?

只需创建一个counter变量,它由1每个已显示results列表的子列表的时间增加,当达到3那么我们就可以break圈外。

int counter = 0; 

foreach (List<decimal> result in results) 
{ 
     if(counter == 3) break; 

     if (result.Count == NoDisplay) 
     { 
      recordexist = true; 

      foreach (decimal value in result) 
      { 
       Console.Write("{0}\t", value); 
      } 

      if (recordexist == true) 
      { 
       Console.WriteLine(); 
      } 
      counter++; 
     } 
} 
0

我要说最简单的选择是使用LINQ的方法Where(过滤结果),并Take(取前n个结果):

var filteredResults = results 
    .Where(r => r.Count == NoDisplay) 
    .Take(3); 

foreach (var result in filteredResults) 
{ 
    foreach (decimal value in result) 
    { 
     Console.Write("{0}\t", value); 
    } 
    Console.WriteLine(); 
} 
相关问题