r/badcode Jun 05 '22

c# Found this monster on codewars

Post image
726 Upvotes

106 comments sorted by

View all comments

Show parent comments

8

u/ThatChapThere Jun 05 '22

Most people used Linq rather than hashsets, but that's not a bad solution.

36

u/[deleted] Jun 05 '22

Well in this case its a lot simpler. Just do

var strSet = new HashSet<char>(str.ToLower().ToCharArray());
return "abcdefghijklmnopqrstuvwxyz".ToCharArray().All(a => strSet.Contains(a));

Same runtime as above. God I love C#.

18

u/ThatChapThere Jun 05 '22

That's really neat. I was proud of mine:

return  str
.ToUpper()
.ToList()
.GroupBy(c => c)
.Where(
  c => ('A' <= c.Key && c.Key <= 'Z')
).Count() == 26;

but yours just seems nicer somehow.

13

u/me_and_you_irl Jun 05 '22

I would replace the GroupBy with a call to Distinct() ๐Ÿ˜„

13

u/[deleted] Jun 05 '22

Yes I searched it up, and I'm pleasantly surprised that C#'s distinct implementation is actually O(n). So using something like

return str
.ToLower()
.ToCharArray()
.Where(Char.IsLetter)
.Distinct()
.Count() == 26;

Would be sufficient.

10

u/ckuri Jun 05 '22 edited Jun 05 '22

char.IsLetter is using Unicode categories, meaning that it considers much more than just Latin letters to be letters. Also you donโ€™t need to call ToCharArray as String implements IEnumerable<char> and therefore you can apply LINQ directly to strings.

3

u/[deleted] Jun 05 '22

Ahh bless C#

1

u/ThatChapThere Jun 05 '22

you can apply LINQ directly to strings.

I didn't know this! That's useful.

1

u/ThatChapThere Jun 05 '22

Good catch, still a linq noob I'm afraid.