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+ console . log ( path . join ( '' ) ) ;
17+ result . push ( path . join ( '' ) ) ;
18+ return ;
19+ }
20+
21+ for ( let i = 0 ; i < chars . length ; i ++ ) {
22+ if ( used [ i ] ) continue ;
23+ if ( i > 0 && chars [ i ] === chars [ i - 1 ] && ! used [ i - 1 ] ) continue ;
24+
25+ used [ i ] = true ;
26+ path . push ( chars [ i ] ) ;
27+
28+ backtrack ( ) ;
29+
30+ path . pop ( ) ;
31+ used [ i ] = false ;
32+ }
33+ }
34+
35+ backtrack ( ) ;
36+ return result ;
37+ }
38+
39+ function solution ( input ) {
40+ const N = input [ 0 ] [ 0 ] ;
41+ const words = input . slice ( 1 ) . map ( ( el ) => el [ 0 ] ) ;
42+
43+ for ( let i = 0 ; i < N ; i ++ ) {
44+ generateAnagrams ( words [ i ] ) ;
45+ }
46+ }
47+
48+ solution ( input ) ;
You can’t perform that action at this time.
0 commit comments