C#,如何找到组合 [英] C#, how to find combinations

查看:96
本文介绍了C#,如何找到组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大指数存在问题。



例如,如果我有公式2 pow n和n = 2则2 pow 2 = 4



,组合为:



00

01

10

11



但是如果n = 100怎么办?如何在c#中为这个解决方案编写代码...



thnx friends。

解决方案

你应该递归(请注意 2 ^ 100 是巨大的,所以你需要耐心等待程序完成:-)),例如

 静态  void 位( int  [] ab, int  depth, int  maxdept)
{
if (深度< maxdept)
{
ab [深度] = 0 ;
位(ab,深度+ 1 ,maxdept);
ab [深度] = 1 ;
位(ab,深度+ 1 ,maxdept);
}
其他
{
foreach (< span class =code-keyword> int i in ab)
{
Console.Write(i);
}
Console.WriteLine();
}
}

public static void Main()
{
int [] ab;
ab = new int [ 100 ];
位(ab, 0 100 );
}


我假设您的意思是对于2 n n == 2 ,8为 n == 3 ,等等。



要显示固定值 n 的总组合并不复杂 - 你只需要一组嵌套循环,每个循环一个 n - 所以 n == 2 需要两个循环(一个用于第一个位,一个用于第二个),以及 n == 3 需要3.

但是对于n的任何值,你不能提前指定循环次数,所以你需要看一下递归。这并不复杂,但是因为这对家庭作业很不好,我不会给你代码。



关于它:创建一个方法一个数字和一个字符串作为参数。它用字符串+0调用自己,数字少于1,然后用字符串+1调用自身,数字少于1。 (你需要在这里检查终止,然后打印你传递的字符串)



尝试一下,看看你得到了什么...

hi, there is a problem with huge exponent.

example if I have the formula 2 pow n and n=2 then 2 pow 2=4

and the combinations are:

00
01
10
11

but what if n=100 ??? how to write code in c# for this solution...

thnx friends.

解决方案

You should go recursive (please note 2^100 is huge, so you need to be patient while waiting for the program to complete :-) ), e.g.

static void bits(int[]  ab, int depth, int maxdept)
   {
     if (depth < maxdept)
     {
       ab[depth] = 0;
       bits(ab, depth + 1, maxdept);
       ab[depth] = 1;
       bits(ab, depth + 1, maxdept);
     }
     else
     {
       foreach (int i in ab)
       {
         Console.Write(i);
       }
       Console.WriteLine();
     }
   }

   public static void Main()
   {
     int[] ab;
     ab = new int[100];
     bits(ab, 0, 100);
   }


I assume you mean that for 2n there are 4 possible bit combinations for n == 2, 8 for n == 3, and so forth.

To display the total combinations for a fixed value of n isn''t complex - you just need a set of nested loops, one for each n - so n == 2needs two loops (one for the first bit, one for the second), and n == 3 needs 3.
But for any value of n, you can''t specify the number of loops in advance, so you need to look at recursion. It''s not complex, but since this smells badly of homework, I won''t give you the code.

This about it: create a method which takes a number and a string as a parameter. It calls itself with the string + ''0'' and the number less one, then calls itself with the string + ''1'' and the number less one. (You will need to check for a termination here, and just print the string you are passed instead)

Try it, and see what you get...


这篇关于C#,如何找到组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆