File tree Expand file tree Collapse file tree 2 files changed +19
-27
lines changed
src/08-dynamic-programming Expand file tree Collapse file tree 2 files changed +19
-27
lines changed Original file line number Diff line number Diff line change @@ -24,38 +24,30 @@ class HanoiTowers {
2424 }
2525
2626 getMovements ( ) {
27- const t1 = this . t1 ;
28- const t2 = this . t2 ;
29- const t3 = this . t3 ;
30-
3127 while ( ! this . t1 . isEmpty ( ) ) {
32- this . move ( t1 , t2 ) ;
33- while ( t2 . peek ( ) > t3 . peek ( ) ) {
34- this . move ( t3 , t2 ) ;
35- while ( t2 . peek ( ) > t1 . peek ( ) ) {
36- this . move ( t1 , t2 ) ;
37- while ( t2 . peek ( ) > t3 . peek ( ) ) {
38- this . move ( t3 , t2 ) ;
39- while ( t2 . peek ( ) > t1 . peek ( ) ) {
40- this . move ( t1 , t2 ) ;
41- while ( t2 . peek ( ) > t3 . peek ( ) ) {
42- this . move ( t3 , t2 ) ;
43- this . move ( t2 , t1 ) ;
44- }
45- this . move ( t2 , t3 ) ;
46- }
47- this . move ( t2 , t1 ) ;
48- }
49- this . move ( t2 , t3 ) ;
50- }
51- this . move ( t2 , t1 ) ;
52- }
53- this . move ( t2 , t3 ) ;
28+ this . move ( this . t1 , this . t2 ) ;
29+ this . moveFromT2toT3 ( ) ;
5430 }
5531
5632 return this . movements ;
5733 }
5834
35+ moveFromT2toT3 ( ) {
36+ while ( this . t2 . peek ( ) > this . t3 . peek ( ) ) {
37+ this . move ( this . t3 , this . t2 ) ;
38+ this . moveFromT2toT1 ( ) ;
39+ }
40+ this . move ( this . t2 , this . t3 ) ;
41+ }
42+
43+ moveFromT2toT1 ( ) {
44+ while ( this . t2 . peek ( ) > this . t1 . peek ( ) ) {
45+ this . move ( this . t1 , this . t2 ) ;
46+ this . moveFromT2toT3 ( ) ;
47+ }
48+ this . move ( this . t2 , this . t1 ) ;
49+ }
50+
5951 move ( t1 , t2 ) {
6052 if ( t2 . peek ( ) < t1 . peek ( ) ) {
6153 throw new Error ( 'A disk cannot be placed on top of a smaller disk' ) ;
Original file line number Diff line number Diff line change @@ -31,6 +31,6 @@ describe('hanoiTower', function() {
3131 } ) ;
3232
3333 it ( '7' , function ( ) {
34- expect ( hanoiTower ( 7 ) ) . to . equal ( 728 ) ;
34+ expect ( hanoiTower ( 7 ) ) . to . equal ( 2186 ) ;
3535 } ) ;
3636} ) ;
You can’t perform that action at this time.
0 commit comments