自然数の分割
Posted feedbacks - C#
追加して並び替えました。こんな感じでしょうか。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | using System;
using System.Collections.Generic;
static class Program {
static void Main(String[] args) {
int n = int.Parse(args[0]), m = int.Parse(args[1]);
List<int[]> result = new List<int[]>();
Append(result, n, m, 0, new int[0]);
result.Sort(delegate(int[] x, int[] y) {
for(int i = 0; i < x.Length; i++) {
if (x[i] != y[i]) {
return x[i].CompareTo(y[i]) * -1;
}
}
return 0;
});
foreach(int[] res in result) {
Console.WriteLine(string.Join(", ", Array.ConvertAll<int, string>(res,
delegate(int x) { return x.ToString(); })));
}
}
static void Append(List<int[]> result, int n, int m, int sum, int[] items) {
if (m <= items.Length) {
if (n == sum) {
result.Add(items);
}
}
else {
List<int> temp = new List<int>(items);
temp.Add(0);
for(int i = 0; i + sum <= n; i++) {
temp[temp.Count - 1] = i;
Append(result, n, m, sum + i, temp.ToArray());
}
}
}
}
|
なんということだ。Sort どころか List<int[]> すら要らなかった/(^o^)\
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | using System;
using System.Collections.Generic;
static class Program {
static void Main(String[] args) {
hoge(int.Parse(args[0]), 0, 0, new int[int.Parse(args[1])]);
}
static void hoge(int n, int m, int sum, int[] items) {
if (items.Length <= m) {
if (n == sum) {
Console.WriteLine(string.Join(", ", Array.ConvertAll<int, string>(items,
delegate(int x) { return x.ToString(); })));
}
}
else {
for(int i = n - sum; 0 <= i ; i--) {
items[m] = i;
hoge(n, m + 1, sum + i, items);
}
}
}
}
|
再帰 & yieldで
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System;
using System.Collections.Generic;
class Program {
static IEnumerable<string> PartNum(int n, int m) {
if (m == 1) {
yield return n.ToString();
} else if (m > 1) {
for (int i = 0; i <= n; i++)
foreach (string s in PartNum(i, m - 1))
yield return (n - i).ToString() + ", " + s;
}
}
static void Main(string[] args) {
foreach (string s in PartNum(5, 3))
Console.WriteLine(s);
}
}
|




herumi
#4099()
Rating1/1=1.00
[ reply ]