Skip to content

Commit b9760de

Browse files
committed
new exercise: word-search
Added a new Exercise per issue exercism#238
1 parent ff3f7d1 commit b9760de

11 files changed

+5092
-0
lines changed

config.json

+16
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,22 @@
275275
"unicode"
276276
]
277277
},
278+
{
279+
"slug": "word-search",
280+
"uuid": "8ba2c83e-f544-11e9-802a-5aa538984bd8",
281+
"core": false,
282+
"unlocked_by": "linked-list",
283+
"difficulty": 8,
284+
"topics": [
285+
"arrays",
286+
"conditionals",
287+
"loops",
288+
"equality",
289+
"optional_values",
290+
"parsing",
291+
"text_formatting"
292+
]
293+
},
278294
{
279295
"slug": "difference-of-squares",
280296
"uuid": "3f649490-dc7d-4a77-a2a0-2ae71ae834a9",

exercises/word-search/.eslintignore

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
bin/*
2+
dist/*
3+
docs/*
4+
node_modules/*
5+
production_node_modules/*
6+
test/fixtures/*
7+
tmp/*
8+
jest.config.js

exercises/word-search/.eslintrc

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
{
2+
"root": true,
3+
"parser": "@typescript-eslint/parser",
4+
"parserOptions": {
5+
"project": "./tsconfig.json",
6+
"ecmaFeatures": {
7+
"jsx": true
8+
},
9+
"ecmaVersion": 2018,
10+
"sourceType": "module"
11+
},
12+
"env": {
13+
"browser": true,
14+
"es6": true
15+
},
16+
"extends": [
17+
"eslint:recommended",
18+
"plugin:@typescript-eslint/eslint-recommended",
19+
"plugin:@typescript-eslint/recommended",
20+
],
21+
"globals": {
22+
"Atomics": "readonly",
23+
"SharedArrayBuffer": "readonly"
24+
},
25+
"plugins": [
26+
"@typescript-eslint"
27+
],
28+
"rules": {
29+
"@typescript-eslint/array-type": "off", // Styling not forced upon the student
30+
"@typescript-eslint/explicit-function-return-type": [
31+
"warn", {
32+
"allowExpressions": false,
33+
"allowTypedFunctionExpressions": true,
34+
"allowHigherOrderFunctions": true
35+
}
36+
], // Prevent bugs
37+
"@typescript-eslint/explicit-member-accessibility": "off", // Styling not forced upon the student
38+
"@typescript-eslint/indent": "off", // Styling not forced upon the student
39+
"@typescript-eslint/no-inferrable-types": [
40+
"error", {
41+
"ignoreParameters": true
42+
}
43+
],
44+
"@typescript-eslint/member-delimiter-style": "off", // Styling not forced upon the student
45+
"@typescript-eslint/no-non-null-assertion": "off",
46+
"@typescript-eslint/no-parameter-properties": [
47+
"warn", {
48+
"allows": [
49+
"private", "protected", "public",
50+
"private readonly", "protected readonly", "public readonly"
51+
]
52+
}
53+
], // only disallow readonly without an access modifier
54+
"@typescript-eslint/no-unused-vars": "off", // Covered by the tsc compiler (noUnusedLocals)
55+
"@typescript-eslint/no-use-before-define": [
56+
"error", {
57+
"functions": false,
58+
"typedefs": false
59+
}
60+
], // Prevent bugs, not styling
61+
"semi": "off", // Always disable base-rule
62+
"@typescript-eslint/semi": "off" // Styling not forced upon student
63+
}
64+
}

exercises/word-search/README.md

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Word Search
2+
3+
In word search puzzles you get a square of letters and have to find specific
4+
words in them.
5+
6+
For example:
7+
8+
```text
9+
jefblpepre
10+
camdcimgtc
11+
oivokprjsm
12+
pbwasqroua
13+
rixilelhrs
14+
wolcqlirpc
15+
screeaumgr
16+
alxhpburyi
17+
jalaycalmp
18+
clojurermt
19+
```
20+
21+
There are several programming languages hidden in the above square.
22+
23+
Words can be hidden in all kinds of directions: left-to-right, right-to-left,
24+
vertical and diagonal.
25+
26+
Given a puzzle and a list of words return the location of the first and last
27+
letter of each word.
28+
## Setup
29+
30+
Go through the setup instructions for TypeScript to install the necessary
31+
dependencies:
32+
33+
[https://exercism.io/tracks/typescript/installation](https://exercism.io/tracks/typescript/installation)
34+
35+
## Requirements
36+
37+
Install assignment dependencies:
38+
39+
```bash
40+
$ yarn install
41+
```
42+
43+
## Making the test suite pass
44+
45+
Execute the tests with:
46+
47+
```bash
48+
$ yarn test
49+
```
50+
51+
In the test suites all tests but the first have been skipped.
52+
53+
Once you get a test passing, you can enable the next one by changing `xit` to
54+
`it`.
55+
56+
## Source
57+
58+
This is a classic toy problem, but we were reminded of it by seeing it in the Go Tour.
59+
60+
## Submitting Incomplete Solutions
61+
62+
It's possible to submit an incomplete solution so you can see how others have
63+
completed the exercise.

exercises/word-search/jest.config.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
module.exports = {
2+
verbose: true,
3+
projects: [
4+
'<rootDir>'
5+
],
6+
testMatch: [
7+
"**/__tests__/**/*.[jt]s?(x)",
8+
"**/test/**/*.[jt]s?(x)",
9+
"**/?(*.)+(spec|test).[jt]s?(x)"
10+
],
11+
testPathIgnorePatterns: [
12+
'/(?:production_)?node_modules/',
13+
'.d.ts$',
14+
'<rootDir>/test/fixtures',
15+
'<rootDir>/test/helpers',
16+
'__mocks__'
17+
],
18+
transform: {
19+
'^.+\\.[jt]sx?$': 'ts-jest',
20+
},
21+
};

exercises/word-search/package.json

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"name": "@exercism/typescript",
3+
"version": "1.0.0",
4+
"description": "Exercism exercises in Typescript.",
5+
"author": "",
6+
"private": true,
7+
"repository": {
8+
"type": "git",
9+
"url": "https://github.com/exercism/typescript"
10+
},
11+
"devDependencies": {
12+
"@types/jest": "^24.0.18",
13+
"@types/node": "^12.7.12",
14+
"@typescript-eslint/eslint-plugin": "^2.5.0",
15+
"@typescript-eslint/parser": "^2.3.3",
16+
"eslint": "^6.5.1",
17+
"eslint-plugin-import": "^2.18.2",
18+
"jest": "^24.9.0",
19+
"ts-jest": "^24.1.0",
20+
"typescript": "^3.6.4"
21+
},
22+
"scripts": {
23+
"test": "yarn lint:types && jest --no-cache",
24+
"lint": "yarn lint:types && yarn lint:ci",
25+
"lint:types": "yarn tsc --noEmit -p .",
26+
"lint:ci": "eslint . --ext .tsx,.ts"
27+
},
28+
"dependencies": {}
29+
}

exercises/word-search/tsconfig.json

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
5+
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
6+
"lib": ["esnext", "es2016", "es2017"], /* Specify library files to be included in the compilation. */
7+
// "allowJs": true, /* Allow javascript files to be compiled. */
8+
// "checkJs": true, /* Report errors in .js files. */
9+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
10+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
11+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
12+
"sourceMap": true, /* Generates corresponding '.map' file. */
13+
// "outFile": "./", /* Concatenate and emit output to single file. */
14+
"outDir": "./build", /* Redirect output structure to the directory. */
15+
// "rootDirs": ["./"], /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
16+
// "composite": true, /* Enable project compilation */
17+
// "removeComments": true, /* Do not emit comments to output. */
18+
// "noEmit": true, /* Do not emit outputs. */
19+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
20+
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
21+
"isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
22+
"noEmitOnError": true, /* Do not emit outputs when compilation fails. */
23+
24+
/* Strict Type-Checking Options */
25+
"strict": true, /* Enable all strict type-checking options. */
26+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
27+
// "strictNullChecks": true, /* Enable strict null checks. */
28+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
29+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
30+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
31+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
32+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
33+
34+
/* Additional Checks */
35+
// "noUnusedLocals": true, /* Report errors on unused locals. */
36+
"noUnusedParameters": true, /* Report errors on unused parameters. */
37+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
38+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
39+
40+
/* Module Resolution Options */
41+
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
42+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
43+
// "paths": { "~src/*": ["./src/*"] }, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
44+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
45+
// "typeRoots": [], /* List of folders to include type definitions from. */
46+
// "types": [], /* Type declaration files to be included in compilation. */
47+
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
48+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
49+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
50+
51+
/* Source Map Options */
52+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
53+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
54+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
55+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
56+
57+
/* Experimental Options */
58+
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
59+
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
60+
},
61+
"compileOnSave": true,
62+
"exclude": [
63+
"node_modules"
64+
]
65+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
interface Result {
2+
start: number[];
3+
end: number[];
4+
}
5+
6+
export default class WordSearch {
7+
private grid: string[]
8+
constructor(grid: string[]) {
9+
this.grid = grid
10+
}
11+
private findCoordsWhereLetterMatch(currentLetter: string, board: string[]): number[][] {
12+
return board.reduce((accumulatedCoordinates: number[][], row: string, rowNumber: number) => [...accumulatedCoordinates,
13+
...row.split('')
14+
.reduce((matchingLetterIndecies: number[], letter: string, index: number) => letter === currentLetter ? [...matchingLetterIndecies, index] : matchingLetterIndecies, [])
15+
.reduce((coordinates: number[][], col) => [...coordinates, [rowNumber, col]], [])
16+
],
17+
[])
18+
}
19+
20+
private getCoordsOfSurroundingLetters(initialCoord: number[], totalRows: number, totalColumns: number): number[][] {
21+
22+
const top: number[] = [initialCoord[0] - 1, initialCoord[1]]
23+
const bottom: number[] = [initialCoord[0] + 1, initialCoord[1]]
24+
25+
const right: number[] = [initialCoord[0], initialCoord[1] + 1]
26+
const left: number[] = [initialCoord[0], initialCoord[1] - 1]
27+
28+
const topRight: number[] = [initialCoord[0] + 1, initialCoord[1] + 1]
29+
const topLeft: number[] = [initialCoord[0] + 1, initialCoord[1] - 1]
30+
31+
const bottomRight: number[] = [initialCoord[0] - 1, initialCoord[1] + 1]
32+
const bottomLeft: number[] = [initialCoord[0] - 1, initialCoord[1] - 1]
33+
34+
return [top, bottom, right, left, topRight, topLeft, bottomRight, bottomLeft]
35+
.filter((coordinates: number[]) =>
36+
coordinates[0] <= (totalRows - 1) &&
37+
coordinates[1] <= (totalColumns - 1) &&
38+
coordinates[0] >= 0 &&
39+
coordinates[1] >= 0)
40+
}
41+
42+
private getValueFromCoordinate(board: string[], coordinates: number[]): string {
43+
return board[coordinates[0]] && board[coordinates[0]].split('')[coordinates[1]]
44+
}
45+
46+
private matchingValues(board: string[], coordinates: number[], letter: string): boolean {
47+
return this.getValueFromCoordinate(board, coordinates) === letter
48+
}
49+
50+
private getDirectionFunction(originCoords: number[], destinationCoords: number[]): (currentCoords: number[]) => number[] {
51+
return (nextCoord: number[]): number[] => [nextCoord[0] + (destinationCoords[0] - originCoords[0]), nextCoord[1] + (destinationCoords[1] - originCoords[1])]
52+
}
53+
54+
55+
private getValidNeighbouringCoordinates(initial: number[], board: string[], letter: string): number[][] {
56+
return this.getCoordsOfSurroundingLetters(initial, board.length, board[0].length)
57+
.filter(neighbouringCoordinate => this.matchingValues(board, neighbouringCoordinate, letter))
58+
}
59+
60+
private findOne(word: string, board: string[]): Result {
61+
const allPossibleStartCoords: number[][] = this.findCoordsWhereLetterMatch(word[0], board)
62+
const allPossibleCoordsForFirstTwoLetters: number[][][] = allPossibleStartCoords.reduce((accum: number[][][], initial) => {
63+
return [...accum, ...this.getValidNeighbouringCoordinates(initial, board, word[1]).map(secondCoordinate => [initial, secondCoordinate])]
64+
}, [])
65+
66+
const allPossiblePaths: number[][][] = allPossibleCoordsForFirstTwoLetters.map((coordsSoFar: number[][]) => {
67+
const incrementFunction = this.getDirectionFunction(coordsSoFar[0], coordsSoFar[1])
68+
return word.substr(2, word.length).split('').reduce((accum: number[][], _) => [...accum, incrementFunction(accum[accum.length - 1])], coordsSoFar)
69+
})
70+
71+
const validPaths: number[][][] = allPossiblePaths.reduce((validPaths: number[][][], path: number[][]) =>
72+
word.split('')
73+
.map((letter, index) => this.matchingValues(board, path[index], letter))
74+
.includes(false) ? validPaths : [...validPaths, path], [] as number[][][])
75+
76+
77+
return validPaths.reduce((_: Result, path: number[][]) => ({
78+
start: path[0].map(c => c + 1),
79+
end: path[path.length - 1].map(c => c + 1)
80+
}), {} as Result)
81+
}
82+
83+
public find(words: string[]): { [word: string]: Result } | { [word: string]: undefined } {
84+
return words.reduce((accum: { [word: string]: Result } | { [word: string]: undefined }, word) => {
85+
const result = this.findOne(word, this.grid)
86+
accum[word] = Object.keys(result).length == 0 ? undefined : result
87+
88+
return accum
89+
}, {} as { [word: string]: Result } | { [word: string]: undefined })
90+
}
91+
}

exercises/word-search/word-search.md

Whitespace-only changes.

0 commit comments

Comments
 (0)