Created
May 14, 2019 19:49
-
-
Save mgudesblatart/31d73bbbdfb33f8badff5cf272d5b697 to your computer and use it in GitHub Desktop.
Daily Coding Problem #5
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
function getAnagram( word, string ) { | |
let t1 = performance.now() | |
let res = []; | |
let word_array = word.split( '' ); | |
for ( let i of [ ...Array( string.length - word.length + 1 ).keys() ] ) { | |
let a_window = string.substring( i, i + word.length ); | |
let a_window_array = a_window.split( '' ); | |
if ( JSON.stringify( word_array ) == JSON.stringify( a_window_array ) || | |
JSON.stringify( word_array ) == JSON.stringify( a_window_array.reverse() ) | |
) { | |
res.push( i ); | |
} | |
} | |
let t2 = performance.now(); | |
let t = t2 - t1; | |
return { res, t }; | |
} | |
console.log( getAnagram( 'ab', 'abxaba' ) ) | |
function getAnagram2( word, string ) { | |
let t1 = performance.now() | |
function delIfZero( dict, char ) { | |
if ( dict[ char ] == 0 ) { | |
delete dict[ char ] | |
} | |
} | |
let res = []; | |
let freq = {}; | |
for ( let i of word ) { | |
freq[ i ] = freq[ i ] ? freq[ i ] + 1 : 1; | |
} | |
console.log( freq ) | |
for ( let i of string.substring( 0, word.length ) ) { | |
freq[ i ] = freq[ i ] ? freq[ i ] - 1 : -1; | |
delIfZero( freq, i ); | |
} | |
if ( Object.entries( freq ).length === 0 ) { | |
res.push( 0 ) | |
} | |
for ( let i of [ ...Array( string.length ).keys() ].map( i => i + word.length ) ) { | |
let start_char = string[ i - word.length ], | |
end_char = string[ i ]; | |
freq[ start_char ] = freq[ start_char ] ? freq[ start_char ] + 1 : 1; | |
delIfZero( freq, start_char ); | |
freq[ end_char ] = freq[ end_char ] ? freq[ end_char ] - 1 : -1; | |
delIfZero( freq, end_char ); | |
if ( Object.entries( freq ).length === 0 ) { | |
let beginning_index = i - word.length + 1; | |
res.push( beginning_index ); | |
} | |
} | |
let t2 = performance.now(); | |
let t = t2 - t1; | |
return { res, t }; | |
} | |
console.log( getAnagram2( 'ab', 'abxaba' ) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment