Skip to content

Instantly share code, notes, and snippets.

@mes51
Created April 29, 2013 17:39
Show Gist options
  • Save mes51/5483294 to your computer and use it in GitHub Desktop.
Save mes51/5483294 to your computer and use it in GitHub Desktop.
最長共通部分列問題
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ProgrammingContestChallenge.LongestCommonSubsequence
{
class CharInfo
{
public char Char { get; set; }
public int[] Indexes { get; set; }
}
static class Program
{
private const string A = "XMJYAUZ";
private const string B = "MZJAWXU";
static void Main(string[] args)
{
string s = A;
if (A.Length > B.Length)
{
s = B;
}
string l = s == A ? B : A;
int d = 0;
var t = s
.Select(c => new CharInfo
{
Char = c,
Indexes = l.Select((x, i) => new { Char = x, Index = i }).Where(x => x.Char == c)
.Select(x => x.Index).ToArray()
})
.ToArray()
.Recursive(
(sequence, f) =>
{
int index = 0;
d++;
return sequence.Any() ? new[]
{
((Func<IEnumerable<CharInfo>, Delegate, IEnumerable<char>>)f)(sequence.Skip(1).ToArray(), f),
sequence.Where(c => c.Indexes.Any(x => x >= index) && (index = c.Indexes.First(x => x >= index) + 1) != -1).Select(x => x.Char).ToArray()
}.OrderByDescending(x => x.Count()).First().ToArray() : Enumerable.Empty<char>();
}
);
string result = new string(t.ToArray());
Console.WriteLine("Count: " + result.Length.ToString());
Console.WriteLine(result);
}
public static IEnumerable<TResult> Recursive<T, TResult>(this IEnumerable<T> source, Func<IEnumerable<T>, Delegate, IEnumerable<TResult>> func)
{
return func(source, func);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment