Skip to content

Instantly share code, notes, and snippets.

@RQN
Last active August 28, 2016 09:58
Show Gist options
  • Save RQN/969fb82b6c7bd9fddfd3c9ab37d36170 to your computer and use it in GitHub Desktop.
Save RQN/969fb82b6c7bd9fddfd3c9ab37d36170 to your computer and use it in GitHub Desktop.
重複順列
using System;
using System.Collections.Generic;
namespace RQN
{
public static class RepeatedPermutation
{
/// <summary>
/// 指定した文字を使用して、指定した長さの重複順列を生成します。
/// </summary>
public static IEnumerable<string> Generate(char[] chars, int length)
{
int loopCount = (int)Math.Pow(chars.Length, length);
int[] numAry = new int[length];
for (int i = 0; i < loopCount; i++)
{
string str = "";
for (int j = length; j > 0; j--)
{
str += chars[numAry[j - 1]];
}
yield return str;
int digit = 0; // 桁
while (true)
{
if (numAry[digit] != chars.Length - 1) // !最大値
{
numAry[digit]++;
break;
}
else
{
if (digit != length - 1) // !最大桁
{
numAry[digit] = 0;
digit++;
}
else
{
break;
}
}
}
}
}
}
}
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char[] keys = { 'a', 'b', 'c' };
foreach (var word in RQN.RepeatedPermutation.Generate(keys, 3))
{
Console.WriteLine(word);
}
// 出力
// aaa
// aab
// aac
// aba
// abb
// ...
// cca
// ccb
// ccc
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment