Skip to content

Commit

Permalink
feat: sieve (#92)
Browse files Browse the repository at this point in the history
* feat: sieve

* use signed comparison in primes func.
add some commentary
  • Loading branch information
glennj authored Nov 26, 2023
1 parent 3a409e5 commit 3ff43c1
Show file tree
Hide file tree
Showing 12 changed files with 389 additions and 0 deletions.
7 changes: 7 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,13 @@
"practices" : [],
"prerequisites": [],
"difficulty": 4
}, {
"slug": "sieve",
"name": "Sieve of Eratosthenes",
"uuid" : "99498715-4615-4aa8-83a7-6cb0a32bd721",
"practices" : [],
"prerequisites": [],
"difficulty": 6
}
]
},
Expand Down
28 changes: 28 additions & 0 deletions exercises/practice/sieve/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Instructions

Your task is to create a program that implements the Sieve of Eratosthenes algorithm to find prime numbers.

A prime number is a number that is only divisible by 1 and itself.
For example, 2, 3, 5, 7, 11, and 13 are prime numbers.

The Sieve of Eratosthenes is an ancient algorithm that works by taking a list of numbers and crossing out all the numbers that aren't prime.

A number that is **not** prime is called a "composite number".

To use the Sieve of Eratosthenes, you first create a list of all the numbers between 2 and your given number.
Then you repeat the following steps:

1. Find the next unmarked number in your list. This is a prime number.
2. Mark all the multiples of that prime number as composite (not prime).

You keep repeating these steps until you've gone through every number in your list.
At the end, all the unmarked numbers are prime.

~~~~exercism/note
[Wikipedia's Sieve of Eratosthenes article][eratosthenes] has a useful graphic that explains the algorithm.
The tests don't check that you've implemented the algorithm, only that you've come up with the correct list of primes.
A good first test is to check that you do not use division or remainder operations.
[eratosthenes]: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
~~~~
7 changes: 7 additions & 0 deletions exercises/practice/sieve/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Introduction

You bought a big box of random computer parts at a garage sale.
You've started putting the parts together to build custom computers.

You want to test the performance of different combinations of parts, and decide to create your own benchmarking program to see how your computers compare.
You choose the famous "Sieve of Eratosthenes" algorithm, an ancient algorithm, but one that should push your computers to the limits.
28 changes: 28 additions & 0 deletions exercises/practice/sieve/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"authors": [
"glennj"
],
"files": {
"solution": [
"sieve.wat"
],
"test": [
"sieve.spec.js"
],
"example": [
".meta/proof.ci.wat"
],
"invalidator": [
"package.json"
]
},
"blurb": "Use the Sieve of Eratosthenes to find all the primes from 2 up to a given number.",
"source": "Sieve of Eratosthenes at Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes",
"custom": {
"version.tests.compatibility": "jest-27",
"flag.tests.task-per-describe": false,
"flag.tests.may-run-long": false,
"flag.tests.includes-optional": false
}
}
79 changes: 79 additions & 0 deletions exercises/practice/sieve/.meta/proof.ci.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
;; based on algorithm at
;; https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

(module
(memory (export "mem") 1)

(global $i32Size i32 (i32.const 4))

(func $location (param i32) (result i32)
(i32.mul (local.get 0) (global.get $i32Size)))


;; create a sequence of integers, stored at the
;; corresponding memory offset
(func $initialize-work-array (param $limit i32)
(local $i i32)
(local.set $i (i32.const 2))
(loop $A
(if (i32.le_u (local.get $i) (local.get $limit))
(then
(i32.store (call $location (local.get $i)) (local.get $i))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $A)))))


;; mark multiples of primes as non-prime
(func $mark-multiples (param $limit i32)
(local $i i32) (local $j i32) (local $p i32) (local $sqrt i32)
(local.set $sqrt (i32.trunc_f32_u (f32.sqrt (f32.convert_i32_u (local.get $limit)))))
(local.set $i (i32.const 2))
(loop $B
(if (i32.le_u (local.get $i) (local.get $sqrt))
(then
(if (i32.load (call $location (local.get $i)))
(then
(local.set $j (i32.mul (local.get $i) (local.get $i)))
(loop $C
(if (i32.le_u (local.get $j) (local.get $limit))
(then
(i32.store (call $location (local.get $j)) (i32.const 0))
(local.set $j (i32.add (local.get $j) (local.get $i)))
(br $C))))))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $B)))))


;; find the resulting prime numbers, and
;; store sequentially starting at memory offset 0
(func $collect-primes (param $limit i32) (result i32)
(local $len i32) (local $i i32) (local $n i32)
(local.set $i (i32.const 2))
(loop $D
(if (i32.le_u (local.get $i) (local.get $limit))
(then
(if (local.tee $n (i32.load (call $location (local.get $i))))
(then
(i32.store (call $location (local.get $len)) (local.get $n))
(local.set $len (i32.add (local.get $len) (i32.const 1)))))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $D))))
(return (local.get $len)))


;;
;; Determine all the prime numbers below a given limit.
;; Return the offset and length of the resulting array of primes.
;;
;; @param {i32} limit - the upper bound for the prime numbers
;;
;; @return {i32} - offset off the u32[] array
;; @return {i32} - length off the u32[] array in elements
;;
(func (export "primes") (param $limit i32) (result i32 i32)
(local $length i32)
(if (i32.lt_s (local.get $limit) (i32.const 2))
(then (return (i32.const 0) (i32.const 0))))
(call $initialize-work-array (local.get $limit))
(call $mark-multiples (local.get $limit))
(return (i32.const 0) (call $collect-primes (local.get $limit)))))
25 changes: 25 additions & 0 deletions exercises/practice/sieve/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[88529125-c4ce-43cc-bb36-1eb4ddd7b44f]
description = "no primes under two"

[4afe9474-c705-4477-9923-840e1024cc2b]
description = "find first prime"

[974945d8-8cd9-4f00-9463-7d813c7f17b7]
description = "find primes up to 10"

[2e2417b7-3f3a-452a-8594-b9af08af6d82]
description = "limit is prime"

[92102a05-4c7c-47de-9ed0-b7d5fcd00f21]
description = "find primes up to 1000"
21 changes: 21 additions & 0 deletions exercises/practice/sieve/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 Exercism

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions exercises/practice/sieve/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
presets: ["@exercism/babel-preset-javascript"],
plugins: [],
};
63 changes: 63 additions & 0 deletions exercises/practice/sieve/canonical-data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"exercise": "sieve",
"cases": [
{
"uuid": "88529125-c4ce-43cc-bb36-1eb4ddd7b44f",
"description": "no primes under two",
"property": "primes",
"input": {
"limit": 1
},
"expected": []
},
{
"uuid": "4afe9474-c705-4477-9923-840e1024cc2b",
"description": "find first prime",
"property": "primes",
"input": {
"limit": 2
},
"expected": [2]
},
{
"uuid": "974945d8-8cd9-4f00-9463-7d813c7f17b7",
"description": "find primes up to 10",
"property": "primes",
"input": {
"limit": 10
},
"expected": [2, 3, 5, 7]
},
{
"uuid": "2e2417b7-3f3a-452a-8594-b9af08af6d82",
"description": "limit is prime",
"property": "primes",
"input": {
"limit": 13
},
"expected": [2, 3, 5, 7, 11, 13]
},
{
"uuid": "92102a05-4c7c-47de-9ed0-b7d5fcd00f21",
"description": "find primes up to 1000",
"property": "primes",
"input": {
"limit": 1000
},
"expected": [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433,
439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521,
523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
]
}
]
}
35 changes: 35 additions & 0 deletions exercises/practice/sieve/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "@exercism/wasm-acronym",
"description": "Exercism exercises in WebAssembly.",
"author": "Sean McBride",
"type": "module",
"private": true,
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/exercism/wasm",
"directory": "exercises/practice/acronym"
},
"jest": {
"maxWorkers": 1
},
"devDependencies": {
"@babel/core": "^7.23.3",
"@exercism/babel-preset-javascript": "^0.4.0",
"@exercism/eslint-config-javascript": "^0.6.0",
"@types/jest": "^29.5.8",
"@types/node": "^20.9.1",
"babel-jest": "^29.7.0",
"core-js": "^3.33.2",
"eslint": "^8.54.0",
"jest": "^29.7.0"
},
"dependencies": {
"@exercism/wasm-lib": "^0.2.0"
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js ./*",
"watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch ./*",
"lint": "eslint ."
}
}
76 changes: 76 additions & 0 deletions exercises/practice/sieve/sieve.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { compileWat, WasmRunner } from "@exercism/wasm-lib";

let wasmModule;
let currentInstance;

beforeAll(async () => {
try {
const watPath = new URL("./sieve.wat", import.meta.url);
const { buffer } = await compileWat(watPath);
wasmModule = await WebAssembly.compile(buffer);
} catch (err) {
console.log(`Error compiling *.wat: \n${err}`);
process.exit(1);
}
});

function primes(limit) {
const [outputOffset, outputLength] = currentInstance.exports.primes(limit);

const outputBuffer = currentInstance.get_mem_as_i32(
outputOffset,
outputLength
);

return [...outputBuffer];
}

describe("Sieve of Eratosthenes", () => {
beforeEach(async () => {
currentInstance = null;
if (!wasmModule) {
return Promise.reject();
}
try {
currentInstance = await new WasmRunner(wasmModule);
return Promise.resolve();
} catch (err) {
console.log(`Error instantiating WebAssembly module: ${err}`);
return Promise.reject();
}
});

test("no primes under two", () => {
expect(primes(1)).toEqual([]);
});

xtest("find first prime", () => {
expect(primes(2)).toEqual([2]);
});

xtest("find primes up to 10", () => {
expect(primes(10)).toEqual([2, 3, 5, 7]);
});

xtest("limit is prime", () => {
expect(primes(13)).toEqual([2, 3, 5, 7, 11, 13]);
});

xtest("find primes up to 1000", () => {
expect(primes(1000)).toEqual([
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433,
439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521,
523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613,
617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,
907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
]);
});

});
Loading

0 comments on commit 3ff43c1

Please sign in to comment.