110,566
社区成员
发帖
与我相关
我的任务
分享
var source = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var query = from x in 排列(source)
from p in Enumerable.Range(0, 7)
let a = x[p]
let b = x[p + 1]
let c = x[p + 2]
where a + 1 == b && b + 1 == c
let s = from n in Enumerable.Range(0, source.Length)
select x[n] + n
where s.Sum() <= 100
select x;
var result = query.Take(10).ToArray();
这种能力才是我们要的。如果只会一小段计算代码,而不放到宽广的应用背景中,你就会错失 c# 的很多内容。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
namespace NUMBER10
{
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
StreamWriter sw = new StreamWriter(@"E:\Services\PK10\PK10\PK10\obj\Debug\all.txt");
DateTime startDate = DateTime.Now;
sw.WriteLine(string.Join(",", a));
int counts = 1;
while (NextPermutation(a))
{
sw.WriteLine(string.Join(",", a));
counts++;
}
sw.Close();
sw.Dispose();
TimeSpan ts = DateTime.Now.Subtract(startDate);
Console.WriteLine(counts.ToString() + " items");
Console.WriteLine(ts.TotalMilliseconds.ToString() + " mill seconds");
Console.ReadKey();
}
public static bool NextPermutation(int[] a)
{
int first = 0;
int last = a.Length;
int c, j, m, n;
int i = last;
i--;
while (true)
{
var t = i;
i--;
if (a[i] < a[t])
{
j = last;
while (!(a[i] < a[--j])) ;
c = a[i];
a[i] = a[j];
a[j] = c;
m = t;
n = last - 1;
while (m < n)
{
c = a[n];
a[n] = a[m];
a[m] = c;
m++;
n--;
}
return true;
}
if (i == first)
{
m = first;
n = last - 1;
while (m < n)
{
c = a[n];
a[n] = a[m];
a[m] = c;
m++;
n--;
}
return false;
}
}
}
}
}
output 3628800 items
3450 mill secondsusing System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var source = new int[] { 1, 2, 8, 9 };
var cnt = 0;
foreach (var x in 排列(source))
{
Console.Write("{0}:\t", ++cnt);
foreach (var y in x)
Console.Write("{0} ", y);
Console.WriteLine();
}
Console.WriteLine("...............按任意键退出");
Console.ReadKey();
}
private static IEnumerable<List<int>> 排列(int[] arr)
{
return 排列(arr, arr.Length);
}
private static IEnumerable<List<int>> 排列(int[] arr, int len)
{
if (len <= 1)
yield return new List<int> { arr[0] };
else if (len <= arr.Length)
{
var 最右边元素 = arr[len - 1];
foreach (var x in 排列(arr, len - 1))
for (var i = 0; i <= x.Count; i++)
{
var clone = x.ToList();
clone.Insert(i, 最右边元素);
yield return clone;
}
}
}
}
}
public static bool NextPermutation(int[] a)
{
int first = 0;
int last = a.Length;
int c, j, m, n;
int i = last;
i--;
while (true)
{
var t = i;
i--;
if (a[i] < a[t])
{
j = last;
while (!(a[i] < a[--j])) ;
c = a[i];
a[i] = a[j];
a[j] = c;
m = t;
n = last - 1;
while (m < n)
{
c = a[n];
a[n] = a[m];
a[m] = c;
m++;
n--;
}
return true;
}
if (i == first)
{
m = first;
n = last - 1;
while (m < n)
{
c = a[n];
a[n] = a[m];
a[m] = c;
m++;
n--;
}
return false;
}
}
}
调用
int[] a = {1,2,3,4,5,6,7,8,9,10};
while(NextPermutation(a))
{
........
}