System.OutOfMemoryException when generating permutations

后端 未结 4 1982
野的像风
野的像风 2020-12-06 09:55

I\'m getting System.OutOfMemoryException when trying to generate 6 letter permutations. 5 letter permutations still work.

Here is the code I\'m using to

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 10:30

    The best thing to do here is to use the lazy initialization to avoid having all the permutations in memory at the same time.

    private static IEnumerable getPermutations(int n,string source)
    {
        IEnumerable q = source.Select(x => x.ToString());
        for (int i = 0; i < n - 1; i++)
        {
            q = q.SelectMany(x => source, (x, y) => x + y);
        }
    
        return q; 
    }
    
    private static List filterListByRegex(IEnumerable list, string regex)
    {
        List newList = new List();
        foreach(var item in list)
        {
            Match match = Regex.Match(item, regex, RegexOptions.IgnoreCase);
            if (match.Success)
            {
                newList.Add(item);
            }
        }
    
        return newList;
    }
    

    This may not be the most efficient way to do it, but at least it should get you past the memory issues.

提交回复
热议问题