有这样一个需求,有10个不同的球:01,02,03,10,12,15,17,20,25,33。现在想从这10个球里面选择5个球,
一:用5个变量a,b,c,d,e分别接收一下这5个球,并用if语句判断一下a+b+c+d+e==47的时候共有多少注,打印出来全部符合条件的组合到桌面上一个叫1.txt的文本文档里。
二:统计一下符合条件的共有多少注。
比如选择的是01,02,03,20,25 02,03,10,15,17。 01,10,20,25,33。 ......
用C语言或者C++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int n = 5;
string[] are = { "01", "02", "03", "10", "12", "15", "17", "20", "25", "33" };
var result = are.Select(x => new string[] { x });
for (int i = 0; i < n - 1; i++)
{
result = result.SelectMany(x => are.Where(y => y.CompareTo(x.First()) < 0).Select(y => new string[] { y }.Concat(x).ToArray()));
}
foreach (var item in result.Where(x => x.Select(y => int.Parse(y)).Sum() == 47))
{
Console.WriteLine(string.Join(", ", item));
}
Console.WriteLine("total:" + result.Count());
}
}
}
47只有3组
02, 03, 10, 15, 17
01, 02, 12, 15, 17
02, 03, 10, 12, 20
total:252
Press any key to continue . . .
以上是C#的程序,你可以在 ideone.com 这个网站上在线运行。
C++版本的程序等我回去给你写。
0102121517
0203101220
0203101517
total:3
Press any key to continue . . .
// Q688344.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
string balls[] = { "01", "02", "03", "10", "12", "15", "17", "20", "25", "33" };
typedef void (*ONFINDFUNC)(string);
#define N 5
#define CNT 10
void solve(string feed, int start, int n, ONFINDFUNC f)
{
if (n == 0)
{
f(feed);
}
else
{
for (int i = start; i < CNT; i++)
{
string feed1 = "";
feed1 += feed;
feed1 += balls[i];
solve(feed1, i + 1, n - 1, f);
}
}
}
int resN;
void _find(string s)
{
const char * temp = s.c_str();
int sum = 0;
for (int i = 0; i < N * 2; i += 2)
{
char temp1[3]; temp1[2] = '\0';
temp1[0] = temp[i];
temp1[1] = temp[i + 1];
sum += atoi(temp1);
}
if (sum == 47)
{
cout << s.c_str() << endl;
resN++;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
resN = 0;
solve("", 0, N, _find);
cout << "total:" << resN << endl;
return 0;
}