Last active
October 23, 2020 13:15
-
-
Save re-gor/2cf7f5201aed4513f475955be4c40ac5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 {performance } = require('perf_hooks'); | |
const N = 1000; | |
const M = 100000; | |
const alphabet = 'abcdefghijklmnopqrstuvwxyz'; | |
const getRandomNum = to => Math.floor(Math.random() * to); | |
const getRandIdx = () => getRandomNum(alphabet.length); | |
function makeStrings(len = 100) { | |
let arr = Array(len); | |
let arr2 = Array(len); | |
let rotPoint = getRandomNum(len); | |
for (let i = 0; i < len; ++i) { | |
let char = alphabet[getRandIdx()]; | |
arr[i] = char; | |
arr2[(i + rotPoint) % len] = char; | |
} | |
return [arr.join(''), arr2.join('')]; | |
} | |
function isRotate(s1, s2) { | |
if (s1.length !== s2.length) { | |
return false; | |
} | |
return (s1 + s1).indexOf(s2) > -1; | |
} | |
function isRotate2(s1, s2) { | |
if (s1.length !== s2.length) { | |
return false; | |
} | |
for (let i = 0; i < s2.length; ++i) { | |
if (s1 === (s2.slice(i) + s2.slice(0, i))) { | |
return true; | |
} | |
} | |
return false; | |
} | |
let couples = Array(N); | |
for (let i = 0; i < N; ++i) { | |
couples[i] = makeStrings(M)//getRandomNum(100) + 1); | |
} | |
const t0 = performance.now(); | |
let result1 = Array(couples.length); | |
for (let i = 0; i < couples.length; ++i) { | |
result1[i] = isRotate(couples[i][0], couples[i][1]); | |
} | |
const t1 = performance.now(); | |
console.log(`isRotate: ${t1 - t0} milliseconds.`); | |
const t2 = performance.now(); | |
let result2 = Array(couples.length); | |
for (let i = 0; i < couples.length; ++i) { | |
result2[i] = isRotate2(couples[i][0], couples[i][1]); | |
} | |
const t3 = performance.now(); | |
console.log(`isRotate2: ${t3 - t2} milliseconds.`); | |
console.log( | |
couples.length, | |
result1.length, | |
result2.length, | |
// couples.slice(0, 3), | |
// result1.slice(0, 3), | |
// result2.slice(0, 3) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment