以前同事为了炫耀ruby的简洁,特意出一道题来考小陈:
在写一个爆破密码的字典生成工具,其中有这样一个需求:
输入一个单词:列出这个单词的所有大小写组合,比如ruby Ruby rUby ruBy rubY RuBy RuBY ....等等,这样2^n个
用C#该怎么写?
然后他把ruby的写法给了小陈:
s='abcd'[nil].product(*[s.chars, s.swapcase.chars].transpose).map(&:join)
小陈只有从linq另辟蹊径了。最后在大牛的帮助下解决了问题:
void Main() {string word = "abcd";List<List<string>> letters = new List<List<string>>();letters = word.ToCharArray().Select(w => new List<string>(){w.ToString().ToLower(),w.ToString().ToUpper()} ).ToList();CartesianProduct(letters).Select (x => x.Aggregate ((a,b) => a + b)).ToList().ForEach(Console.WriteLine); }static IEnumerable<IEnumerable<T>> CartesianProduct<T>( IEnumerable<IEnumerable<T>> sequences){IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };return sequences.Aggregate(emptyProduct,(accumulator, sequence) =>from accseq in accumulatorfrom item in sequenceselect accseq.Concat(new[] {item}));}
在小陈看来已经是很简洁了。不过还是败了。