File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( ( el ) => el . split ( ' ' ) ) ;
7+
8+ function generateAnagrams ( word ) {
9+ const chars = word . split ( '' ) . sort ( ) ;
10+ const used = Array ( chars . length ) . fill ( false ) ;
11+ const result = [ ] ;
12+ const path = [ ] ;
13+
14+ function backtrack ( ) {
15+ if ( path . length === chars . length ) {
16+ result . push ( path . join ( '' ) ) ;
17+ return ;
18+ }
19+
20+ for ( let i = 0 ; i < chars . length ; i ++ ) {
21+ if ( used [ i ] ) continue ;
22+ if ( i > 0 && chars [ i ] === chars [ i - 1 ] && ! used [ i - 1 ] ) continue ;
23+
24+ used [ i ] = true ;
25+ path . push ( chars [ i ] ) ;
26+
27+ backtrack ( ) ;
28+
29+ path . pop ( ) ;
30+ used [ i ] = false ;
31+ }
32+ }
33+
34+ backtrack ( ) ;
35+ return result ;
36+ }
37+
38+ function solution ( input ) {
39+ const N = input [ 0 ] [ 0 ] ;
40+ const words = input . slice ( 1 ) . map ( ( el ) => el [ 0 ] ) ;
41+ const output = [ ] ;
42+
43+ for ( let i = 0 ; i < N ; i ++ ) {
44+ const anagrams = generateAnagrams ( words [ i ] ) ;
45+ output . push ( ...anagrams ) ;
46+ }
47+ console . log ( output . join ( '\n' ) ) ;
48+ }
49+
50+ solution ( input ) ;
Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( ( el ) => el . split ( ' ' ) ) ;
7+
8+ function canTransform ( S , T ) {
9+ function dfs ( current ) {
10+ if ( current . length < S . length ) return false ;
11+ if ( current === S ) return true ;
12+
13+ let result = false ;
14+
15+ if ( current [ current . length - 1 ] === 'A' ) {
16+ result = result || dfs ( current . slice ( 0 , - 1 ) ) ;
17+ }
18+
19+ if ( current [ 0 ] === 'B' ) {
20+ const reversed = current . slice ( 1 ) . split ( '' ) . reverse ( ) . join ( '' ) ;
21+ result = result || dfs ( reversed ) ;
22+ }
23+
24+ return result ;
25+ }
26+
27+ return dfs ( T ) ? 1 : 0 ;
28+ }
29+
30+ function solution ( input ) {
31+ const S = input [ 0 ] [ 0 ] ;
32+ const T = input [ 1 ] [ 0 ] ;
33+
34+ console . log ( canTransform ( S , T ) ) ;
35+ }
36+
37+ solution ( input ) ;
You can’t perform that action at this time.
0 commit comments