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- class genSum {
2- constructor ( n ) {
3- this . array = [ ] ;
4- this . toss ( n ) ;
1+ class genSum {
2+ constructor ( n ) {
3+ this . array = [ ]
4+ if ( n > 0 ) this . toss ( n )
55 }
6- toss ( n ) {
7- let arrSum = 1 ;
8- while ( arrSum != 0 ) {
9- this . array . length = 0 ;
6+ toss ( n ) {
7+ if ( n ) {
8+ let arrSum = 1
9+ while ( arrSum != 0 ) {
10+ this . array . length = 0
1011
11- for ( let i = 0 ; i < n ; i ++ ) {
12- let num ;
13- do {
14- num = this . pickRandNum ( {
15- min : 0 ,
16- max : 100 ,
17- negative : true } ) ;
18- } while ( this . array . includes ( num ) )
19- this . array . push ( num ) ;
12+ for ( let i = 0 ; i < n ; i ++ ) {
13+ let num
14+ do {
15+ num = this . pickRandNum ( {
16+ min : 0 ,
17+ max : 100 ,
18+ negative : true ,
19+ } )
20+ } while ( this . array . includes ( num ) )
21+ this . array . push ( num )
22+ }
23+ arrSum = this . sumArray ( )
2024 }
21- arrSum = this . sumArray ( ) ;
2225 }
2326 }
24- pickRandNum ( { min, max, negative = false } ) {
25- let num = Math . floor ( Math . random ( ) * max ) + min ;
26- if ( negative ) num *= Math . random ( ) > 0.5 ? 1 : - 1 ;
27- return num ;
27+ pickRandNum ( { min, max, negative = false } ) {
28+ let num = Math . floor ( Math . random ( ) * max ) + min
29+ if ( negative ) num *= Math . random ( ) > 0.5 ? 1 : - 1
30+ return num
2831 }
29- sumArray ( ) {
30- return this . array . reduce ( ( a , b ) => a + b ) ;
32+ sumArray ( ) {
33+ if ( this . array . length ) {
34+ if ( this . array . length == 1 ) {
35+ return this . array [ 0 ]
36+ } else {
37+ return this . array . reduce ( ( a , b ) => a + b )
38+ }
39+ } else {
40+ return this . array
41+ }
3142 }
3243}
33-
34- let random = new genSum ( 5 ) ;
35-
36- console . log ( random . array ) ;
37- console . log ( random . sumArray ( ) ) ;
You can’t perform that action at this time.
0 commit comments