098_bit_manipulation2.zig 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // Another useful practice for bit manipulation is setting bits as flags.
  3. // This is especially useful when processing lists of something and storing
  4. // the states of the entries, e.g. a list of numbers and for each prime
  5. // number a flag is set.
  6. //
  7. // As an example, let's take the Pangram exercise from Exercism:
  8. // https://exercism.org/tracks/zig/exercises/pangram
  9. //
  10. // A pangram is a sentence using every letter of the alphabet at least once.
  11. // It is case insensitive, so it doesn't matter if a letter is lower-case
  12. // or upper-case. The best known English pangram is:
  13. //
  14. // "The quick brown fox jumps over the lazy dog."
  15. //
  16. // There are several ways to select the letters that appear in the pangram
  17. // (and it doesn't matter if they appear once or several times).
  18. //
  19. // For example, you could take an array of bool and set the value to 'true'
  20. // for each letter in the order of the alphabet (a=0; b=1; etc.) found in
  21. // the sentence. However, this is neither memory efficient nor particularly
  22. // fast. Instead we take a simpler way, very similar in principle, we define
  23. // a variable with at least 26 bits (e.g. u32) and also set the bit for each
  24. // letter found at the corresponding position.
  25. //
  26. // Zig provides functions for this in the standard library, but we prefer to
  27. // solve it without these extras, after all we want to learn something.
  28. //
  29. const std = @import("std");
  30. const ascii = std.ascii;
  31. const print = std.debug.print;
  32. pub fn main() !void {
  33. // let's check the pangram
  34. print("Is this a pangram? {?}!\n", .{isPangram("The quick brown fox jumps over the lazy dog.")});
  35. }
  36. fn isPangram(str: []const u8) bool {
  37. // first we check if the string has at least 26 characters
  38. if (str.len < 26) return false;
  39. // we uses a 32 bit variable of which we need 26 bit
  40. var bits: u32 = 0;
  41. // loop about all characters in the string
  42. for (str) |c| {
  43. // if the character is an alphabetical character
  44. if (ascii.isASCII(c) and ascii.isAlphabetic(c)) {
  45. // then we set the bit at the position
  46. //
  47. // to do this, we use a little trick:
  48. // since the letters in the ASCI table start at 65
  49. // and are numbered by, we simply subtract the first
  50. // letter (in this case the 'a') from the character
  51. // found, and thus get the position of the desired bit
  52. bits |= @as(u32, 1) << @truncate(u5, ascii.toLower(c) - 'a');
  53. }
  54. }
  55. // last we return the comparison if all 26 bits are set,
  56. // and if so, we know the given string is a pangram
  57. //
  58. // but what do we have to compare?
  59. return bits == 0x..???;
  60. }