Created
December 18, 2017 19:30
-
-
Save magmel48/a15159f93624630aa7ae96ed37419437 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const dict = fs.readFileSync('./RusS.txt', { encoding: 'utf8' }).split('\r\n'); | |
const LAST_FIELD_INDEX = 4; | |
const MINIMAL_WORD_LENGTH = 3; | |
const MAXIMAL_TRIES = 25000; | |
const letters = [ | |
'кийые', | |
'исряк', | |
'бйиао', | |
'лсцчп', | |
'еатой' | |
]; | |
let word = ''; | |
let traversedIds = []; | |
const traversedWords = []; | |
const isPossiblePosition = (i, j) => { | |
if (i > LAST_FIELD_INDEX) | |
return false; | |
if (j > LAST_FIELD_INDEX) | |
return false; | |
if (i < 0) | |
return false; | |
if (j < 0) | |
return false; | |
for (const ids of traversedIds) | |
if (ids[0] === i && ids[1] === j) | |
return false; | |
return true; | |
}; | |
const isFound = () => { | |
return word.length >= MINIMAL_WORD_LENGTH && dict.indexOf(word) !== -1; | |
}; | |
const getDirection = () => { | |
// get direction (1, 2, 3, 4, 6, 7, 8, 9); 5 - the same position | |
return Math.ceil(Math.random() * 9); | |
}; | |
const getNextPosition = (i, j, maxAttempts) => { | |
if (maxAttempts > LAST_FIELD_INDEX * 3) | |
return null; | |
let direction = getDirection(); | |
while (direction === 5) | |
direction = getDirection(); | |
const newI = i + (direction < 4 ? -1 : (direction > 6 ? 1 : 0)); | |
const newJ = j + (direction % 3 === 0 ? 1 : ((direction + 2) % 3 === 0 ? -1 : 0)); | |
if (isPossiblePosition(newI, newJ)) | |
return [newI, newJ]; | |
return getNextPosition(i, j, maxAttempts + 1); | |
}; | |
const printUnique = () => { | |
if (traversedWords.indexOf(word) === -1) { | |
traversedWords.push(word); | |
console.log(word, traversedIds[0][0] + 1, traversedIds[0][1] + 1); | |
} | |
}; | |
const traverse = (i, j) => { | |
word += letters[i][j]; | |
traversedIds.push([i, j]); | |
if (isFound()) { | |
printUnique(word); | |
return; | |
} | |
const newPosition = getNextPosition(i, j, 0); | |
if (newPosition) { | |
return traverse(newPosition[0], newPosition[1]); | |
} | |
}; | |
for (let c = 0; c < MAXIMAL_TRIES; ++c) { | |
// start position | |
const i = Math.ceil(Math.random() * LAST_FIELD_INDEX); | |
const j = Math.ceil(Math.random() * LAST_FIELD_INDEX); | |
// to initial | |
word = ''; | |
traversedIds = []; | |
traverse(i, j); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment