Binary search

This commit is contained in:
2022-11-09 20:30:56 +01:00
parent d438eb37b9
commit a3616bd701
13 changed files with 16318 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
!.meta
# Protected or generated
.git
.vscode
# When using npm
node_modules/*
# Configuration files
.eslintrc.cjs
babel.config.cjs
jest.config.cjs

View File

@@ -0,0 +1,41 @@
module.exports = {
root: true,
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
overrides: [
// Student provided files
{
files: ['*.ts'],
excludedFiles: ['.meta/proof.ci.ts', '.meta/exemplar.ts', '*.test.ts'],
extends: '@exercism/eslint-config-typescript',
},
// Exercism given tests
{
files: ['*.test.ts'],
excludedFiles: ['custom.test.ts'],
env: {
jest: true,
},
extends: '@exercism/eslint-config-typescript/maintainers',
},
// Student provided tests
{
files: ['custom.test.ts'],
env: {
jest: true,
},
extends: '@exercism/eslint-config-typescript',
},
// Exercism provided files
{
files: ['.meta/proof.ci.ts', '.meta/exemplar.ts', '*.test.ts'],
excludedFiles: ['custom.test.ts'],
extends: '@exercism/eslint-config-typescript/maintainers',
rules: {
"@typescript-eslint/semi": 0,
},
},
],
}

View File

@@ -0,0 +1,12 @@
{
"blurb": "Implement a binary search algorithm.",
"authors": ["anuragsoni"],
"contributors": ["masters3d", "SleeplessByte"],
"files": {
"solution": ["binary-search.ts"],
"test": ["binary-search.test.ts"],
"example": [".meta/proof.ci.ts"]
},
"source": "Wikipedia",
"source_url": "http://en.wikipedia.org/wiki/Binary_search_algorithm"
}

View File

@@ -0,0 +1 @@
{"track":"typescript","exercise":"binary-search","id":"5cf2bca8a7db47c6ab347c24290b25dd","url":"https://exercism.org/tracks/typescript/exercises/binary-search","handle":"briemens","is_requester":true,"auto_approve":false}

View File

@@ -0,0 +1,44 @@
# Help
## Running the tests
Execute the tests with:
```bash
$ yarn test
```
## Skipped tests
In the test suites all tests but the first have been skipped.
Once you get a test passing, you can enable the next one by changing `xit` to
`it`.
## Submitting your solution
You can submit your solution using the `exercism submit binary-search.ts` command.
This command will upload your solution to the Exercism website and print the solution page's URL.
It's possible to submit an incomplete solution which allows you to:
- See how others have completed the exercise
- Request help from a mentor
## Need to get help?
If you'd like help solving the exercise, check the following pages:
- The [TypeScript track's documentation](https://exercism.org/docs/tracks/typescript)
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
To get help if you're having trouble, you can use one of the following resources:
- [TypeScript QuickStart](https://www.typescriptlang.org/docs/handbook/release-notes/overview.html)
- [ECMAScript 2015 Language Specification](https://www.ecma-international.org/wp-content/uploads/ECMA-262_6th_edition_june_2015.pdf) (pdf)
- [Mozilla JavaScript Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference)
- [/r/typescript](https://www.reddit.com/r/typescript) is the TypeScript subreddit.
- [StackOverflow](https://stackoverflow.com/questions/tagged/typescript) can be used to search for your problem and see if it has been answered already. You can also ask and answer questions.

View File

@@ -0,0 +1,55 @@
# Binary Search
Welcome to Binary Search on Exercism's TypeScript Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
## Instructions
Implement a binary search algorithm.
Searching a sorted collection is a common task. A dictionary is a sorted
list of word definitions. Given a word, one can find its definition. A
telephone book is a sorted list of people's names, addresses, and
telephone numbers. Knowing someone's name allows one to quickly find
their telephone number and address.
If the list to be searched contains more than a few items (a dozen, say)
a binary search will require far fewer comparisons than a linear search,
but it imposes the requirement that the list be sorted.
In computer science, a binary search or half-interval search algorithm
finds the position of a specified input value (the search "key") within
an array sorted by key value.
In each step, the algorithm compares the search key value with the key
value of the middle element of the array.
If the keys match, then a matching element has been found and its index,
or position, is returned.
Otherwise, if the search key is less than the middle element's key, then
the algorithm repeats its action on the sub-array to the left of the
middle element or, if the search key is greater, on the sub-array to the
right.
If the remaining array to be searched is empty, then the key cannot be
found in the array and a special "not found" indication is returned.
A binary search halves the number of items to check with each iteration,
so locating an item (or determining its absence) takes logarithmic time.
A binary search is a dichotomic divide and conquer search algorithm.
## Source
### Created by
- @anuragsoni
### Contributed to by
- @masters3d
- @SleeplessByte
### Based on
Wikipedia - http://en.wikipedia.org/wiki/Binary_search_algorithm

View File

@@ -0,0 +1,4 @@
module.exports = {
presets: ['@exercism/babel-preset-typescript'],
plugins: [],
}

View File

@@ -0,0 +1,55 @@
import { find } from "./binary-search";
describe("Binary Search", () => {
it("finds a value in an array with one element", () => {
expect(find([6], 6)).toEqual(0);
});
it("finds a value in the middle of an array", () => {
const array = [1, 3, 4, 6, 8, 9, 11];
expect(find(array, 6)).toEqual(3);
});
it("finds a value at the beginning of an array", () => {
const array = [1, 3, 4, 6, 8, 9, 11];
expect(find(array, 1)).toEqual(0);
});
it("finds a value at the end of an array", () => {
const array = [1, 3, 4, 6, 8, 9, 11];
expect(find(array, 11)).toEqual(6);
});
it("finds a value in an array of odd length", () => {
const array = [1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634];
expect(find(array, 144)).toEqual(9);
});
it("finds a value in an array of even length", () => {
const array = [1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377];
expect(find(array, 21)).toEqual(5);
});
it("identifies that a value is not included in the array", () => {
const array = [1, 3, 4, 6, 8, 9, 11];
expect(() => find(array, 7)).toThrow(new Error("Value not in array"));
});
it("a value smaller than the array's smallest value is not found", () => {
const array = [1, 3, 4, 6, 8, 9, 11];
expect(() => find(array, 0)).toThrow(new Error("Value not in array"));
});
it("a value larger than the array's largest value is not found", () => {
const array = [1, 3, 4, 6, 8, 9, 11];
expect(() => find(array, 13)).toThrow(new Error("Value not in array"));
});
it("nothing is found in an empty array", () => {
expect(() => find([], 1)).toThrow(new Error("Value not in array"));
});
it("nothing is found when the left and right bounds cross", () => {
expect(() => find([1, 2], 0)).toThrow(new Error("Value not in array"));
});
});

View File

@@ -0,0 +1,19 @@
export function find(
haystack: number[],
needle: number,
start: number = 0,
end: number = haystack.length - 1
): number | never {
if (start > end || end < start) {
throw new Error("Value not in array");
}
const index = start + Math.floor((end - start) / 2);
const value = haystack[index];
if (needle > value) {
return find(haystack, needle, index + 1, end);
}
if (needle < value) {
return find(haystack, needle, start, index - 1);
}
return index;
}

View File

@@ -0,0 +1,19 @@
module.exports = {
verbose: true,
projects: ['<rootDir>'],
testMatch: [
'**/__tests__/**/*.[jt]s?(x)',
'**/test/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)',
],
testPathIgnorePatterns: [
'/(?:production_)?node_modules/',
'.d.ts$',
'<rootDir>/test/fixtures',
'<rootDir>/test/helpers',
'__mocks__',
],
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
},
}

15996
typescript/binary-search/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,31 @@
{
"name": "@exercism/typescript-binary-search",
"version": "1.0.0",
"description": "Exercism exercises in Typescript.",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/exercism/typescript"
},
"type": "module",
"engines": {
"node": "^14.13.1 || >=16.0.0"
},
"devDependencies": {
"@exercism/babel-preset-typescript": "^0.1.0",
"@exercism/eslint-config-typescript": "^0.4.1",
"@types/jest": "^27.4.0",
"@types/node": "^16.11.24",
"babel-jest": "^27.5.1",
"core-js": "^3.21.0",
"eslint": "^8.9.0",
"jest": "^27.5.1",
"typescript": "^4.5.4"
},
"scripts": {
"test": "yarn lint:types && jest --no-cache",
"lint": "yarn lint:types && yarn lint:ci",
"lint:types": "yarn tsc --noEmit -p .",
"lint:ci": "eslint . --ext .tsx,.ts"
}
}

View File

@@ -0,0 +1,28 @@
{
"display": "Configuration for Exercism TypeScript Exercises",
"compilerOptions": {
// Allows you to use the newest syntax, and have access to console.log
// https://www.typescriptlang.org/tsconfig#lib
"lib": ["ESNEXT", "dom"],
// Make sure typescript is configured to output ESM
// https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c#how-can-i-make-my-typescript-project-output-esm
"module": "ES2020",
// Since this project is using babel, TypeScript may target something very
// high, and babel will make sure it runs on your local Node version.
// https://babeljs.io/docs/en/
"target": "ESNext", // ESLint doesn't support this yet: "es2022",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
// Because we'll be using babel: ensure that Babel can safely transpile
// files in the TypeScript project.
//
// https://babeljs.io/docs/en/babel-plugin-transform-typescript/#caveats
"isolatedModules": true
},
"include": ["*.ts", "*.tsx", ".meta/*.ts", ".meta/*.tsx"],
"exclude": ["node_modules"]
}