Snippets created by Arjen Kopinga

  • Parsing string expressions, the lazy way

    Sometimes you'd be surprised at what functionality you can find inside the .Net framework. Apparently the DataTable object can compute string expressions. Nice for testing your own parser implementation, and/or for lazy coders like me. Note that the DataTable is created only once and reused with each function call.

    34 people like this

    Posted: 6 years ago by Arjen Kopinga

  • A fast sieve of Eratosthenes

    A prime Eratosthenes' sieve, using a bit array and sieving only odd composites to conserve memory and keep things fast.

    3 people like this

    Posted: 5 years ago by Arjen Kopinga

  • Anagrams

    Let's use the fundamental theorem of arithmetic to determine if two words are anagrams of each other. How? The theorem states (roughly) that each number can be written as a product of prime numbers in only one unique way. For instance 42 = 7 * 2 * 3 = 3 * 7 * 2. Now what will happen if you associate a letter with a unique prime number? You can see that "team" [71*11*2*41] = "meat" [41*11*2*71]. Oh, the possibilities. Note that in the code below big integers are used since the product of many primes will overflow a 32- or even a 64-bit integer.

    25 people like this

    Posted: 6 years ago by Arjen Kopinga

  • Folding over prime factors

    Let's have some fun with higher order functions and instead of folding over a list, fold over the prime factors of a number. It can be optimized further by dividing out real primes instead of numbers of the form 6k+/-1, but it's not embarrassingly slow.

    2 people like this

    Posted: 5 years ago by Arjen Kopinga