-
Notifications
You must be signed in to change notification settings - Fork 34
/
rosetta-code.json
6762 lines (6762 loc) · 395 KB
/
rosetta-code.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"name": "Rosetta Code",
"order": 5,
"time": "",
"helpRoom": "",
"nChallenges": 437,
"challenges": [
{
"title": "100 doors",
"description": [
"<p>There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and 'toggle' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (i.e., door #2, #4, #6, ...) and toggle it. The third time, visit every 3rd door (i.e., door #3, #6, #9, ...), etc., until you only visit the 100th door.</p>",
"<p>Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.</p>"
],
"solutions": [
"function getFinalOpenedDoors (numDoors) {\n // this is the final pattern (always squares).\n // thus, the most efficient solution simply returns an array of squares up to numDoors).\n const finalState = [];\n let i = 1;\n while (Math.pow(i, 2) <= numDoors) {\n finalState.push(Math.pow(i, 2));\n i++;\n }\n return finalState;\n}\n"
],
"tests": [
{
"text": "<code>getFinalOpenedDoors</code> is a function.",
"testString": "assert(typeof getFinalOpenedDoors === 'function', '<code>getFinalOpenedDoors</code> is a function.');"
},
{
"text": "<code>getFinalOpenedDoors</code> should return an array.",
"testString": "assert(Array.isArray(getFinalOpenedDoors(100)), '<code>getFinalOpenedDoors</code> should return an array.');"
},
{
"text": "<code>getFinalOpenedDoors</code> did not produce the correct results.",
"testString": "assert.deepEqual(getFinalOpenedDoors(100), solution, '<code>getFinalOpenedDoors</code> did not produce the correct results.');"
}
],
"id": "594810f028c0303b75339acb",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function getFinalOpenedDoors (numDoors) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const solution = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];"
]
}
}
},
{
"title": "24 game",
"description": [
"<p>Implement a function that takes a string of four digits as its argument, with each digit from 1 ──► 9 (inclusive) with repetitions allowed, and returns an arithmetic expression that evaluates to the number 24. If no such solution exists, return \"no solution exists.\"</p>",
"<p>Rules:</p>",
" Only the following operators/functions are allowed: multiplication, division, addition, subtraction",
" Division should use floating point or rational arithmetic, etc, to preserve remainders.",
" Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).",
" The order of the digits when given does not have to be preserved.",
"<p>Example inputs:</p>",
"<code>solve24(\"4878\");</code>",
"<code>solve24(\"1234\");</code>",
"<code>solve24(\"6789\");</code>",
"<code>solve24(\"1127\");</code>",
"<p>Example outputs (strings):</p>",
"<code>(7-8/8)*4</code>",
"<code>3*1*4*2</code>",
"<code>(6*8)/(9-7)</code>",
"<code>(1+7)*(2+1)</code>"
],
"solutions": [
"// noprotect\n\nfunction solve24 (numStr) {\n const digitsArr = numStr.split('');\n const answers = [];\n\n const digitPermutations = [];\n const operatorPermutations = [];\n\n function generateDigitPermutations (digits, permutations = []) {\n if (digits.length === 0) {\n digitPermutations.push(permutations);\n }\n else {\n for (let i = 0; i < digits.length; i++) {\n const curr = digits.slice();\n const next = curr.splice(i, 1);\n generateDigitPermutations(curr.slice(), permutations.concat(next));\n }\n }\n }\n\n function generateOperatorPermutations (permutations = []) {\n const operators = ['+', '-', '*', '/'];\n if (permutations.length === 3) {\n operatorPermutations.push(permutations);\n }\n else {\n for (let i = 0; i < operators.length; i++) {\n const curr = permutations.slice();\n curr.push(operators[i]);\n generateOperatorPermutations(curr);\n }\n }\n }\n\n generateDigitPermutations(digitsArr);\n generateOperatorPermutations();\n\n interleave();\n\n return answers[0];\n\n function interleave () {\n for (let i = 0; i < digitPermutations.length; i++) {\n for (let j = 0; j < operatorPermutations.length; j++) {\n const d = digitPermutations[i];\n const o = operatorPermutations[j];\n const perm = [\n `${d[0]}${o[0]}${d[1]}${o[1]}${d[2]}${o[2]}${d[3]}`,\n `(${d[0]}${o[0]}${d[1]})${o[1]}${d[2]}${o[2]}${d[3]}`,\n `${d[0]}${o[0]}(${d[1]}${o[1]}${d[2]})${o[2]}${d[3]}`,\n `${d[0]}${o[0]}${d[1]}${o[1]}(${d[2]}${o[2]}${d[3]})`,\n `${d[0]}${o[0]}(${d[1]}${o[1]}${d[2]}${o[2]}${d[3]})`,\n `(${d[0]}${o[0]}${d[1]}${o[1]}${d[2]})${o[2]}${d[3]}`,\n `(${d[0]}${o[0]}${d[1]})${o[1]}(${d[2]}${o[2]}${d[3]})`\n ];\n\n perm.forEach(combination => {\n const res = eval(combination);\n\n if (res === 24) {\n return answers.push(combination);\n }\n });\n }\n }\n }\n}\n"
],
"tests": [
{
"text": "<code>solve24</code> is a function.",
"testString": "assert(typeof solve24 === 'function', '<code>solve24</code> is a function.');"
},
{
"text": "<code>solve24(\"4878\")</code> should return <code>(7-8/8)*4</code> or <code>4*(7-8/8)</code>",
"testString": "assert(include(answers[0], solve24(testCases[0])), '<code>solve24(\"4878\")</code> should return <code>(7-8/8)*4</code> or <code>4*(7-8/8)</code>');"
},
{
"text": "<code>solve24(\"1234\")</code> should return any arrangement of <code>1*2*3*4</code>",
"testString": "assert(include(answers[1], solve24(testCases[1])), '<code>solve24(\"1234\")</code> should return any arrangement of <code>1*2*3*4</code>');"
},
{
"text": "<code>solve24(\"6789\")</code> should return <code>(6*8)/(9-7)</code> or <code>(8*6)/(9-7)</code>",
"testString": "assert(include(answers[2], solve24(testCases[2])), '<code>solve24(\"6789\")</code> should return <code>(6*8)/(9-7)</code> or <code>(8*6)/(9-7)</code>');"
},
{
"text": "<code>solve24(\"1127\")</code> should return a permutation of <code>(1+7)*(1*2)</code>",
"testString": "assert(include(answers[3], solve24(testCases[3])), '<code>solve24(\"1127\")</code> should return a permutation of <code>(1+7)*(1*2)</code>');"
}
],
"id": "5951e88f64ebf159166a1176",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function solve24 (numStr) {",
" // Good luck!",
" return true;",
"}"
],
"head": [],
"tail": [
"const testCases = [",
" '4878',",
" '1234',",
" '6789',",
" '1127'",
"];",
"",
"const answers = [",
" ['(7-8/8)*4', '4*(7-8/8)', '(4-8+7)*8', '(4+7-8)*8', '(7+4-8)*8', '(7-8+4)*8', '8*(4-8+7)', '8*(4+7-8)', '8*(7+4-8)', '8*(7-8+4)'],",
" ['1*2*3*4', '1*2*4*3', '1*3*2*4', '1*3*4*2', '1*4*2*3', '1*4*3*2', '2*1*3*4', '2*1*4*3', '2*3*1*4', '2*3*4*1', '2*4*3*1', '2*4*1*3', '3*1*2*4', '3*1*4*2', '3*2*1*4', '3*2*4*1', '3*4*1*2', '3*4*2*1', '4*1*2*3', '4*1*3*2', '4*2*1*3', '4*2*3*1', '4*3*1*2', '4*3*2*1', '(1+2+3)*4', '(1+3+2)*4', '(2+1+3)*4', '(2+3+1)*4', '(3+1+2)*4', '(3+2+1)*4', '4*(1+2+3)', '4*(2+1+3)', '4*(2+3+1)', '4*(3+1+2)', '4*(3+2+1)'],",
" ['(6*8)/(9-7)', '(8*6)/(9-7)', '6*8/(9-7)', '8*6/(9-7)'],",
" ['(1+7)*(2+1)', '(1+7)*(1+2)', '(1+2)*(1+7)', '(1+2)*(7+1)', '(2+1)*(1+7)', '(7+1)*(2+1)']",
"];",
"",
"function include(ansArr, res) {",
" const index = ansArr.indexOf(res);",
" return index >= 0;",
"}"
]
}
}
},
{
"title": "9 billion names of God the integer",
"description": [
"<p>This task is a variation of the <a href=\"https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary\" title=\"wp: The Nine Billion Names of God#Plot_summary\">short story by Arthur C. Clarke</a>.</p>",
"<p>(Solvers should be aware of the consequences of completing this task.)</p>",
"<p>In detail, to specify what is meant by a “name”:</p>",
"<p>The integer 1 has 1 name “1”.</p>",
"<p>The integer 2 has 2 names “1+1”, and “2”.</p>",
"<p>The integer 3 has 3 names “1+1+1”, “2+1”, and “3”.</p>",
"<p>The integer 4 has 5 names “1+1+1+1”, “2+1+1”, “2+2”, “3+1”, “4”.</p>",
"<p>The integer 5 has 7 names “1+1+1+1+1”, “2+1+1+1”, “2+2+1”, “3+1+1”, “3+2”, “4+1”, “5”.</p>",
"<p>This can be visualized in the following form:</p>",
"<pre>",
" 1",
" 1 1",
" 1 1 1",
" 1 2 1 1",
" 1 2 2 1 1",
"1 3 3 2 1 1",
"</pre>",
"<p>Where row $n$ corresponds to integer $n$, and each column $C$ in row $m$ from left to right corresponds to the number of names beginning with $C$.</p>",
"<p>Optionally note that the sum of the $n$-th row $P(n)$ is the <a href=\"http://mathworld.wolfram.com/PartitionFunctionP.html\" title=\"link: http://mathworld.wolfram.com/PartitionFunctionP.html\">integer partition function</a>.</p>",
"Task",
"<p>Implement a function that returns the sum of the $n$-th row.</p>"
],
"solutions": [
"function numberOfNames (num) {\n const cache = [\n [1]\n ];\n for (let l = cache.length; l < num + 1; l++) {\n let Aa;\n let Mi;\n const r = [0];\n for (let x = 1; x < l + 1; x++) {\n r.push(r[r.length - 1] + (Aa = cache[l - x < 0 ? cache.length - (l - x) : l - x])[(Mi = Math.min(x, l - x)) < 0 ? Aa.length - Mi : Mi]);\n }\n cache.push(r);\n }\n return cache[num][cache[num].length - 1];\n}\n"
],
"tests": [
{
"text": "<code>numberOfNames</code> is a function.",
"testString": "assert(typeof numberOfNames === 'function', '<code>numberOfNames</code> is a function.');"
},
{
"text": "<code>numberOfNames(5)</code> should equal 7.",
"testString": "assert.equal(numberOfNames(5), 7, '<code>numberOfNames(5)</code> should equal 7.');"
},
{
"text": "<code>numberOfNames(12)</code> should equal 77.",
"testString": "assert.equal(numberOfNames(12), 77, '<code>numberOfNames(12)</code> should equal 77.');"
},
{
"text": "<code>numberOfNames(18)</code> should equal 385.",
"testString": "assert.equal(numberOfNames(18), 385, '<code>numberOfNames(18)</code> should equal 385.');"
},
{
"text": "<code>numberOfNames(23)</code> should equal 1255.",
"testString": "assert.equal(numberOfNames(23), 1255, '<code>numberOfNames(23)</code> should equal 1255.');"
},
{
"text": "<code>numberOfNames(42)</code> should equal 53174.",
"testString": "assert.equal(numberOfNames(42), 53174, '<code>numberOfNames(42)</code> should equal 53174.');"
},
{
"text": "<code>numberOfNames(123)</code> should equal 2552338241.",
"testString": "assert.equal(numberOfNames(123), 2552338241, '<code>numberOfNames(123)</code> should equal 2552338241.');"
}
],
"id": "5949b579404977fbaefcd736",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function numberOfNames (num) {",
" // Good luck!",
" return true;",
"}"
],
"head": [],
"tail": []
}
}
},
{
"title": "ABC Problem",
"description": [
"<p>You are given a collection of ABC blocks (e.g., childhood alphabet blocks). There are 20 blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:</p>",
"<p>(B O)</p>",
"<p>(X K)</p>",
"<p>(D Q)</p>",
"<p>(C P)</p>",
"<p>(N A)</p>",
"<p>(G T)</p>",
"<p>(R E)</p>",
"<p>(T G)</p>",
"<p>(Q D)</p>",
"<p>(F S)</p>",
"<p>(J W)</p>",
"<p>(H U)</p>",
"<p>(V I)</p>",
"<p>(A N)</p>",
"<p>(O B)</p>",
"<p>(E R)</p>",
"<p>(F S)</p>",
"<p>(L Y)</p>",
"<p>(P C)</p>",
"<p>(Z M)</p>",
"<p>Some rules to keep in mind:</p>",
"Once a letter on a block is used, that block cannot be used again.",
"The function should be case-insensitive.",
"<p>Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.</p>"
],
"solutions": [
"function canMakeWord (word) {\n const characters = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM';\n const blocks = characters.split(' ').map(pair => pair.split(''));\n\n const letters = [...word.toUpperCase()];\n let length = letters.length;\n const copy = new Set(blocks);\n\n letters.forEach(letter => {\n for (let block of copy) {\n const index = block.indexOf(letter);\n\n if (index !== -1) {\n length--;\n copy.delete(block);\n break;\n }\n }\n });\n return !length;\n}\n"
],
"tests": [
{
"text": "<code>canMakeWord</code> is a function.",
"testString": "assert(typeof canMakeWord === 'function', '<code>canMakeWord</code> is a function.');"
},
{
"text": "<code>canMakeWord</code> should return a boolean.",
"testString": "assert(typeof canMakeWord('hi') === 'boolean', '<code>canMakeWord</code> should return a boolean.');"
},
{
"text": "<code>canMakeWord(\"bark\")</code> should return true.",
"testString": "assert(canMakeWord(words[0]), '<code>canMakeWord(\"bark\")</code> should return true.');"
},
{
"text": "<code>canMakeWord(\"BooK\")</code> should return false.",
"testString": "assert(!canMakeWord(words[1]), '<code>canMakeWord(\"BooK\")</code> should return false.');"
},
{
"text": "<code>canMakeWord(\"TReAT\")</code> should return true.",
"testString": "assert(canMakeWord(words[2]), '<code>canMakeWord(\"TReAT\")</code> should return true.');"
},
{
"text": "<code>canMakeWord(\"COMMON\")</code> should return false.",
"testString": "assert(!canMakeWord(words[3]), '<code>canMakeWord(\"COMMON\")</code> should return false.');"
},
{
"text": "<code>canMakeWord(\"squAD\")</code> should return true.",
"testString": "assert(canMakeWord(words[4]), '<code>canMakeWord(\"squAD\")</code> should return true.');"
},
{
"text": "<code>canMakeWord(\"conFUSE\")</code> should return true.",
"testString": "assert(canMakeWord(words[5]), '<code>canMakeWord(\"conFUSE\")</code> should return true.');"
}
],
"id": "594810f028c0303b75339acc",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function canMakeWord (word) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const words = ['bark', 'BooK', 'TReAT', 'COMMON', 'squAD', 'conFUSE'];"
]
}
}
},
{
"title": "Abundant, deficient and perfect number classifications",
"description": [
"<p>These define three classifications of positive integers based on their <a href=\"http://rosettacode.org/wiki/Proper divisors\" title=\"Proper divisors\">proper divisors</a>.</p>",
"<p>Let $P(n)$ be the sum of the proper divisors of n where proper divisors are all positive integers n other than n itself.</p>",
"<p>If <code>P(n) < n</code> then n is classed as \"deficient\"</p>",
"<p>If <code>P(n) === n</code> then n is classed as \"perfect\"</p>",
"<p>If <code>P(n) > n</code> then n is classed as \"abundant\"</p>",
"<p>Example:</p>",
"<p>6 has proper divisors of 1, 2, and 3.</p>",
"<p>1 + 2 + 3 = 6, so 6 is classed as a perfect number.</p>",
"<p>Implement a function that calculates how many of the integers from 1 to 20,000 (inclusive) are in each of the three classes. Output the result as an array in the following format <code>[deficient, perfect, abundant]</code>.</p>"
],
"solutions": [
"function getDPA (num) {\n const dpa = [1, 0, 0];\n for (let n = 2; n <= num; n += 1) {\n let ds = 1;\n const e = Math.sqrt(n);\n for (let d = 2; d < e; d += 1) {\n if (n % d === 0) {\n ds += d + (n / d);\n }\n }\n if (n % e === 0) {\n ds += e;\n }\n dpa[ds < n ? 0 : ds === n ? 1 : 2] += 1;\n }\n return dpa;\n}\n"
],
"tests": [
{
"text": "<code>getDPA</code> is a function.",
"testString": "assert(typeof getDPA === 'function', '<code>getDPA</code> is a function.');"
},
{
"text": "<code>getDPA</code> should return an array.",
"testString": "assert(Array.isArray(getDPA(100)), '<code>getDPA</code> should return an array.');"
},
{
"text": "<code>getDPA</code> return value should have a length of 3.",
"testString": "assert(getDPA(100).length === 3, '<code>getDPA</code> return value should have a length of 3.');"
},
{
"text": "<code>getDPA(20000)</code> should equal [15043, 4, 4953]",
"testString": "assert.deepEqual(getDPA(20000), solution, '<code>getDPA(20000)</code> should equal [15043, 4, 4953]');"
}
],
"id": "594810f028c0303b75339acd",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function getDPA (num) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const solution = [15043, 4, 4953];"
]
}
}
},
{
"title": "Accumulator factory",
"description": [
"<p>Create a function that takes a single (numeric) argument and returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).</p>",
"<p>Rules:</p>",
"<p>Do not use global variables.</p>",
"<p>Hint:</p>",
"<p>Closures save outer state.</p>"
],
"solutions": [
"function accumulator (sum) {\n return function (n) {\n return sum += n;\n };\n}\n"
],
"tests": [
{
"text": "<code>accumulator</code> is a function.",
"testString": "assert(typeof accumulator === 'function', '<code>accumulator</code> is a function.');"
},
{
"text": "<code>accumulator(0)</code> should return a function.",
"testString": "assert(typeof accumulator(0) === 'function', '<code>accumulator(0)</code> should return a function.');"
},
{
"text": "<code>accumulator(0)(2)</code> should return a number.",
"testString": "assert(typeof accumulator(0)(2) === 'number', '<code>accumulator(0)(2)</code> should return a number.');"
},
{
"text": "Passing in the values 3, -4, 1.5, and 5 should return 5.5.",
"testString": "assert(testFn(5) === 5.5, 'Passing in the values 3, -4, 1.5, and 5 should return 5.5.');"
}
],
"id": "594810f028c0303b75339ace",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function accumulator (sum) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const testFn = typeof accumulator(3) === 'function' && accumulator(3);",
"if (testFn) {",
" testFn(-4);",
" testFn(1.5);",
"}"
]
}
}
},
{
"title": "Ackermann function",
"description": [
"<p>The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.</p>",
"<p>The Ackermann function is usually defined as follows:</p>",
"$$A(m, n) =",
" \\begin{cases}",
" n+1 & \\mbox{if } m = 0 \\\\",
" A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\",
" A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0.",
" \\end{cases}$$",
"<p>Its arguments are never negative and it always terminates. Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.</p>"
],
"solutions": [
"function ack (m, n) {\n return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1));\n}\n"
],
"tests": [
{
"text": "<code>ack</code> is a function.",
"testString": "assert(typeof ack === 'function', '<code>ack</code> is a function.');"
},
{
"text": "<code>ack(0, 0)</code> should return 1.",
"testString": "assert(ack(0, 0) === 1, '<code>ack(0, 0)</code> should return 1.');"
},
{
"text": "<code>ack(1, 1)</code> should return 3.",
"testString": "assert(ack(1, 1) === 3, '<code>ack(1, 1)</code> should return 3.');"
},
{
"text": "<code>ack(2, 5)</code> should return 13.",
"testString": "assert(ack(2, 5) === 13, '<code>ack(2, 5)</code> should return 13.');"
},
{
"text": "<code>ack(3, 3)</code> should return 61.",
"testString": "assert(ack(3, 3) === 61, '<code>ack(3, 3)</code> should return 61.');"
}
],
"id": "594810f028c0303b75339acf",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function ack (m, n) {",
" // Good luck!",
"}"
],
"head": [],
"tail": []
}
}
},
{
"title": "Align columns",
"description": [
"<p>Given a text file of many lines, where fields within a line are delineated by a single <code>$</code> character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column.</p>",
"<p>Use the following text to test your programs:</p>",
"<pre>",
"Given$a$text$file$of$many$lines",
"where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character",
"write$a$program",
"that$aligns$each$column$of$fields",
"by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified",
"or$center$justified$within$its$column.",
"</pre>",
"<p>Note that:</p>",
"The example input texts lines may, or may not, have trailing dollar characters.",
"All columns should share the same alignment.",
"Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.",
"Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.",
"The minimum space between columns should be computed from the text and not hard-coded.",
"It is not a requirement to add separating characters between or around columns."
],
"solutions": [
"const testArr = [\n 'Given$a$text$file$of$many$lines',\n 'where$fields$within$a$line$',\n 'are$delineated$by$a$single$\"dollar\"$character',\n 'write$a$program',\n 'that$aligns$each$column$of$fields$',\n 'by$ensuring$that$words$in$each$',\n 'column$are$separated$by$at$least$one$space.',\n 'Further,$allow$for$each$word$in$a$column$to$be$either$left$',\n 'justified,$right$justified',\n 'or$center$justified$within$its$column.'\n];\n\nString.prototype.repeat = function (n) { return new Array(1 + parseInt(n)).join(this); };\n\nfunction formatText (input, justification) {\n let x, y, max, cols = 0, diff, left, right;\n for (x = 0; x < input.length; x++) {\n input[x] = input[x].split('$');\n if (input[x].length > cols) {\n cols = input[x].length;\n }\n }\n for (x = 0; x < cols; x++) {\n max = 0;\n for (y = 0; y < input.length; y++) {\n if (input[y][x] && max < input[y][x].length) {\n max = input[y][x].length;\n }\n }\n for (y = 0; y < input.length; y++) {\n if (input[y][x]) {\n diff = (max - input[y][x].length) / 2;\n left = ' '.repeat(Math.floor(diff));\n right = ' '.repeat(Math.ceil(diff));\n if (justification === 'left') {\n right += left; left = '';\n }\n if (justification === 'right') {\n left += right; right = '';\n }\n input[y][x] = left + input[y][x] + right;\n }\n }\n }\n for (x = 0; x < input.length; x++) {\n input[x] = input[x].join(' ');\n }\n input = input.join('\\n');\n return input;\n}\n"
],
"tests": [
{
"text": "<code>formatText</code> is a function.",
"testString": "assert(typeof formatText === 'function', '<code>formatText</code> is a function.');"
},
{
"text": "<code>formatText</code> with the above input and \"right\" justification should produce the following: ",
"testString": "assert.strictEqual(formatText(testInput, 'right'), rightAligned, '<code>formatText</code> with the above input and \"right\" justification should produce the following: ');"
},
{
"text": "<code>formatText</code> with the above input and \"left\" justification should produce the following: ",
"testString": "assert.strictEqual(formatText(testInput, 'left'), leftAligned, '<code>formatText</code> with the above input and \"left\" justification should produce the following: ');"
},
{
"text": "<code>formatText</code> with the above input and \"center\" justification should produce the following: ",
"testString": "assert.strictEqual(formatText(testInput, 'center'), centerAligned, '<code>formatText</code> with the above input and \"center\" justification should produce the following: ');"
}
],
"id": "594810f028c0303b75339ad0",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"const testArr = [",
" 'Given$a$text$file$of$many$lines',",
" 'where$fields$within$a$line$',",
" 'are$delineated$by$a$single$\"dollar\"$character',",
" 'write$a$program',",
" 'that$aligns$each$column$of$fields$',",
" 'by$ensuring$that$words$in$each$',",
" 'column$are$separated$by$at$least$one$space.',",
" 'Further,$allow$for$each$word$in$a$column$to$be$either$left$',",
" 'justified,$right$justified',",
" 'or$center$justified$within$its$column.'",
"];",
"",
"function formatText (input, justification) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const testInput = [",
" 'Given$a$text$file$of$many$lines',",
" 'where$fields$within$a$line$',",
" 'are$delineated$by$a$single$\"dollar\"$character',",
" 'write$a$program',",
" 'that$aligns$each$column$of$fields$',",
" 'by$ensuring$that$words$in$each$',",
" 'column$are$separated$by$at$least$one$space.',",
" 'Further,$allow$for$each$word$in$a$column$to$be$either$left$',",
" 'justified,$right$justified',",
" 'or$center$justified$within$its$column.'",
"];",
"",
"const rightAligned = ` Given a text file of many lines",
" where fields within a line ",
" are delineated by a single \"dollar\" character",
" write a program",
" that aligns each column of fields ",
" by ensuring that words in each ",
" column are separated by at least one space.",
" Further, allow for each word in a column to be either left ",
"justified, right justified",
" or center justified within its column.`;",
"",
"const leftAligned = `Given a text file of many lines ",
"where fields within a line ",
"are delineated by a single \"dollar\" character",
"write a program ",
"that aligns each column of fields ",
"by ensuring that words in each ",
"column are separated by at least one space.",
"Further, allow for each word in a column to be either left ",
"justified, right justified",
"or center justified within its column. `;",
"",
"const centerAligned = ` Given a text file of many lines ",
" where fields within a line ",
" are delineated by a single \"dollar\" character",
" write a program ",
" that aligns each column of fields ",
" by ensuring that words in each ",
" column are separated by at least one space.",
" Further, allow for each word in a column to be either left ",
"justified, right justified",
" or center justified within its column. `;"
]
}
}
},
{
"title": "Amicable pairs",
"description": [
"Two integers $N$ and $M$ are said to be <a href=\"https://en.wikipedia.org/wiki/Amicable numbers\" title=\"wp: Amicable numbers\">amicable pairs</a> if $N \\neq M$ and the sum of the <a href=\"http://rosettacode.org/wiki/Proper divisors\" title=\"Proper divisors\">proper divisors</a> of $N$ ($\\mathrm{sum}(\\mathrm{propDivs}(N))$) $= M$ as well as $\\mathrm{sum}(\\mathrm{propDivs}(M)) = N$.",
"Example:",
"1184 and 1210 are an amicable pair, with proper divisors:",
" 1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and ",
" 1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.",
"Task:",
"Calculate and show here the Amicable pairs below 20,000 (there are eight).",
"Related tasks",
"<a href=\"http://rosettacode.org/wiki/Proper divisors\" title=\"Proper divisors\">Proper divisors</a>",
"<a href=\"http://rosettacode.org/wiki/Abundant, deficient and perfect number classifications\" title=\"Abundant, deficient and perfect number classifications\">Abundant, deficient and perfect number classifications</a>",
"<a href=\"http://rosettacode.org/wiki/Aliquot sequence classifications\" title=\"Aliquot sequence classifications\">Aliquot sequence classifications</a> and its amicable classification."
],
"solutions": [
"// amicablePairsUpTo :: Int -> [(Int, Int)]\nfunction amicablePairsUpTo (maxNum) {\n return range(1, maxNum)\n .map(x => properDivisors(x)\n .reduce((a, b) => a + b, 0))\n .reduce((a, m, i, lst) => {\n const n = i + 1;\n\n return (m > n) && lst[m - 1] === n ?\n a.concat([\n [n, m]\n ]) : a;\n }, []);\n}\n\n// properDivisors :: Int -> [Int]\nfunction properDivisors (n) {\n if (n < 2) return [];\n\n const rRoot = Math.sqrt(n);\n const intRoot = Math.floor(rRoot);\n const blnPerfectSquare = rRoot === intRoot;\n const lows = range(1, intRoot)\n .filter(x => (n % x) === 0);\n\n return lows.concat(lows.slice(1)\n .map(x => n / x)\n .reverse()\n .slice(blnPerfectSquare | 0));\n}\n\n// Int -> Int -> Maybe Int -> [Int]\nfunction range (m, n, step) {\n const d = (step || 1) * (n >= m ? 1 : -1);\n\n return Array.from({\n length: Math.floor((n - m) / d) + 1\n }, (_, i) => m + (i * d));\n}\n"
],
"tests": [
{
"text": "<code>amicablePairsUpTo</code> is a function.",
"testString": "assert(typeof amicablePairsUpTo === 'function', '<code>amicablePairsUpTo</code> is a function.');"
},
{
"text": "<code>amicablePairsUpTo(300)</code> should return <code>[[220,284]]</code>.",
"testString": "assert.deepEqual(amicablePairsUpTo(300), answer300, '<code>amicablePairsUpTo(300)</code> should return <code>[[220,284]]</code>.');"
},
{
"text": "<code>amicablePairsUpTo(3000)</code> should return <code>[[220,284],[1184,1210],[2620,2924]]</code>.",
"testString": "assert.deepEqual(amicablePairsUpTo(3000), answer3000, '<code>amicablePairsUpTo(3000)</code> should return <code>[[220,284],[1184,1210],[2620,2924]]</code>.');"
},
{
"text": "<code>amicablePairsUpTo(20000)</code> should return <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code>.",
"testString": "assert.deepEqual(amicablePairsUpTo(20000), answer20000, '<code>amicablePairsUpTo(20000)</code> should return <code>[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</code>.');"
}
],
"id": "5949b579404977fbaefcd737",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function amicablePairsUpTo (maxNum) {",
" // Good luck!",
" return true;",
"}"
],
"head": [],
"tail": [
"const answer300 = [[220, 284]];",
"const answer3000 = [",
" [220, 284],",
" [1184, 1210],",
" [2620, 2924]",
"];",
"const answer20000 = [",
" [220, 284],",
" [1184, 1210],",
" [2620, 2924],",
" [5020, 5564],",
" [6232, 6368],",
" [10744, 10856],",
" [12285, 14595],",
" [17296, 18416]",
"];"
]
}
}
},
{
"title": "Averages/Mode",
"description": [
"<p>Write a program to find the <a href=\"https://en.wikipedia.org/wiki/Mode (statistics)\" title=\"wp: Mode (statistics)\">mode</a> value of a collection.</p><p>The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.</p><p>If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.</p>"
],
"solutions": [
"function mode(arr) {\n const counter = {};\n let result = [];\n let max = 0;\n // for (const i in arr) {\n arr.forEach(el => {\n if (!(el in counter)) {\n counter[el] = 0;\n }\n counter[el]++;\n\n if (counter[el] === max) {\n result.push(el);\n }\n else if (counter[el] > max) {\n max = counter[el];\n result = [el];\n }\n });\n return result;\n}\n"
],
"tests": [
{
"text": "<code>mode</code> is a function.",
"testString": "assert(typeof mode === 'function', '<code>mode</code> is a function.');"
},
{
"text": "<code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>",
"testString": "assert.deepEqual(mode(arr1), [6], '<code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>');"
},
{
"text": "<code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.",
"testString": "assert.deepEqual(mode(arr2).sort(), [1, 4], '<code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.');"
}
],
"id": "594d8d0ab97724821379b1e6",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function mode (arr) {",
" // Good luck!",
" return true;",
"}"
],
"head": [],
"tail": [
"const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];",
"const arr2 = [1, 2, 4, 4, 1];"
]
}
}
},
{
"title": "Averages/Pythagorean means",
"description": [
"<p class='rosetta__paragraph'>Compute all three of the <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Pythagorean means' title='wp: Pythagorean means'>Pythagorean means</a> of the set of integers <big>1</big> through <big>10</big> (inclusive).</p><p class='rosetta__paragraph'>Show that <big>$A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$</big> for this set of positive integers.</p> The most common of the three means, the <a class='rosetta__link--rosetta' href='http://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean'>arithmetic mean</a>, is the sum of the list divided by its length: <big>$ A(x_1, \\ldots, x_n) = \\frac{x_1 + \\cdots + x_n}{n}$</big>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean'>geometric mean</a> is the $n$th root of the product of the list: <big>$ G(x_1, \\ldots, x_n) = \\sqrt[n]{x_1 \\cdots x_n} $</big>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean'>harmonic mean</a> is $n$ divided by the sum of the reciprocal of each item in the list: <big>$ H(x_1, \\ldots, x_n) = \\frac{n}{\\frac{1}{x_1} + \\cdots + \\frac{1}{x_n}} $</big>",
"<p class='rosetta__paragraph'>Assume the input is an ordered array of all inclusive numbers.</p>",
"<p class='rosetta__paragraph'>For the answer, please output an object in the following format:</p>",
"<pre class='rosetta__pre'>",
"{",
" values: {",
" Arithmetic: 5.5,",
" Geometric: 4.528728688116765,",
" Harmonic: 3.414171521474055",
" },",
" test: 'is A >= G >= H ? yes'",
"}",
"</pre>"
],
"solutions": [
"function pythagoreanMeans (rangeArr) {\n // arithmeticMean :: [Number] -> Number\n const arithmeticMean = xs =>\n foldl((sum, n) => sum + n, 0, xs) / length(xs);\n\n // geometricMean :: [Number] -> Number\n const geometricMean = xs =>\n raise(foldl((product, x) => product * x, 1, xs), 1 / length(xs));\n\n // harmonicMean :: [Number] -> Number\n const harmonicMean = xs =>\n length(xs) / foldl((invSum, n) => invSum + (1 / n), 0, xs);\n\n // GENERIC FUNCTIONS ------------------------------------------------------\n\n // A list of functions applied to a list of arguments\n // <*> :: [(a -> b)] -> [a] -> [b]\n const ap = (fs, xs) => //\n Array.prototype.concat(...fs.map(f => //\n Array.prototype.concat(...xs.map(x => [f(x)]))));\n\n // foldl :: (b -> a -> b) -> b -> [a] -> b\n const foldl = (f, a, xs) => xs.reduce(f, a);\n\n // length :: [a] -> Int\n const length = xs => xs.length;\n\n // mapFromList :: [(k, v)] -> Dictionary\n const mapFromList = kvs =>\n foldl((a, [k, v]) =>\n (a[(typeof k === 'string' && k)] = v, a), {}, kvs);\n\n // raise :: Num -> Int -> Num\n const raise = (n, e) => Math.pow(n, e);\n/*\n // show :: a -> String\n // show :: a -> Int -> String\n const show = (...x) =>\n JSON.stringify.apply(\n null, x.length > 1 ? [x[0], null, x[1]] : x\n );\n*/\n // zip :: [a] -> [b] -> [(a,b)]\n const zip = (xs, ys) =>\n xs.slice(0, Math.min(xs.length, ys.length))\n .map((x, i) => [x, ys[i]]);\n\n // TEST -------------------------------------------------------------------\n // mean :: Dictionary\n const mean = mapFromList(zip(\n ['Arithmetic', 'Geometric', 'Harmonic'],\n ap([arithmeticMean, geometricMean, harmonicMean], [\n rangeArr\n ])\n ));\n\n return {\n values: mean,\n test: `is A >= G >= H ? ${mean.Arithmetic >= mean.Geometric &&\n mean.Geometric >= mean.Harmonic ? 'yes' : 'no'}`\n };\n}\n"
],
"tests": [
{
"text": "<code>pythagoreanMeans</code> is a function.",
"testString": "assert(typeof pythagoreanMeans === 'function', '<code>pythagoreanMeans</code> is a function.');"
},
{
"text": "<code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.",
"testString": "assert.deepEqual(pythagoreanMeans(range1), answer1, '<code>pythagoreanMeans([1, 2, ..., 10])</code> should equal the same output above.');"
}
],
"id": "594d966a1467eb84194f0086",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function pythagoreanMeans (rangeArr) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const range1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];",
"const answer1 = {",
" values: {",
" Arithmetic: 5.5,",
" Geometric: 4.528728688116765,",
" Harmonic: 3.414171521474055",
" },",
" test: 'is A >= G >= H ? yes'",
"};",
""
]
}
}
},
{
"title": "Averages/Root mean square",
"description": [
"<p>Compute the <a href=\"https://en.wikipedia.org/wiki/Root mean square\" title=\"wp: Root mean square\">Root mean square</a> of the numbers 1 through 10 inclusive.</p>",
"<p>The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.</p><p>The RMS is calculated as the mean of the squares of the numbers, square-rooted:</p>",
"<p><big>$$x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. $$</big></p>"
],
"solutions": [
"function rms (arr) {\n const sumOfSquares = arr.reduce((s, x) => s + x * x, 0);\n return Math.sqrt(sumOfSquares / arr.length);\n}\n"
],
"tests": [
{
"text": "<code>rms</code> is a function.",
"testString": "assert(typeof rms === 'function', '<code>rms</code> is a function.');"
},
{
"text": "<code>rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])</code> should equal <code>6.2048368229954285</code>.",
"testString": "assert.equal(rms(arr1), answer1, '<code>rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])</code> should equal <code>6.2048368229954285</code>.');"
}
],
"id": "594da033de4190850b893874",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function rms (arr) {",
" // Good luck!",
"}"
],
"head": [],
"tail": [
"const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];",
"const answer1 = 6.2048368229954285;"
]
}
}
},
{
"title": "Babbage problem",
"description": [
"<p><a href=\"https://en.wikipedia.org/wiki/Charles_Babbage\" title=\"wp: Charles_Babbage\">Charles Babbage</a>, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:</p>",
"<blockquote>What is the smallest positive integer whose square ends in the digits 269,696?</blockquote>",
" <p> - Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, <i>Electronic Computers</i>, second edition, 1970, p. 125.</p>",
"<p>He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.</p>",
"<p>The task is to find out if Babbage had the right answer.</p>",
"<p>Implement a function to return the lowest integer that satisfies the Babbage problem. If Babbage was right, return Babbage's number.</p>"
],
"solutions": [
"function babbage (babbageAns, endDigits) {\n const babbageNum = Math.pow(babbageAns, 2);\n const babbageStartDigits = parseInt(babbageNum.toString().replace('269696', ''));\n let answer = 99736;\n\n // count down from this answer and save any sqrt int result. return lowest one\n for (let i = babbageStartDigits; i >= 0; i--) {\n const num = parseInt(i.toString().concat('269696'));\n const result = Math.sqrt(num);\n if (result === Math.floor(Math.sqrt(num))) {\n answer = result;\n }\n }\n\n return answer;\n}\n"
],
"tests": [
{
"text": "<code>babbage</code> is a function.",
"testString": "assert(typeof babbage === 'function', '<code>babbage</code> is a function.');"
},
{
"text": "<code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).",
"testString": "assert.equal(babbage(babbageAns, endDigits), answer, '<code>babbage(99736, 269696)</code> should not return 99736 (there is a smaller answer).');"
}
],
"id": "594db4d0dedb4c06a2a4cefd",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function babbage (babbageNum, endDigits) {",
" // Good luck!",
" return true;",
"}"
],
"head": [],
"tail": [
"const babbageAns = 99736;",
"const endDigits = 269696;",
"const answer = 25264;"
]
}
}
},
{
"title": "Balanced brackets",
"description": [
"<p>Determine whether a generated string of brackets is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.</p>",
"Examples:",
"<p class='rosetta__paragraph'>(empty) true</p>",
"<p class='rosetta__paragraph'><code>[]</code> true</p>",
"<p class='rosetta__paragraph'><code>][</code> false</p>",
"<p class='rosetta__paragraph'><code>[][]</code> true</p>",
"<p class='rosetta__paragraph'><code>][][</code> false</p>",
"<p class='rosetta__paragraph'><code>[]][[]</code> false</p>",
"<p class='rosetta__paragraph'><code>[[[[]]]]</code> true</p>"
],
"solutions": [
"function isBalanced (str) {\n if (str === '') return true;\n let a = str;\n let b;\n do {\n b = a;\n a = a.replace(/\\[\\]/g, '');\n } while (a !== b);\n return !a;\n}\n"
],
"tests": [
{
"text": "<code>isBalanced</code> is a function.",
"testString": "assert(typeof isBalanced === 'function', '<code>isBalanced</code> is a function.');"
},
{
"text": "<code>isBalanced(\"[]\")</code> should return true.",
"testString": "assert(isBalanced(testCases[0]), '<code>isBalanced(\"[]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"]][[[][][][]][\")</code> should return false.",
"testString": "assert(!isBalanced(testCases[1]), '<code>isBalanced(\"]][[[][][][]][\")</code> should return false.');"
},
{
"text": "<code>isBalanced(\"[][[[[][][[[]]]]]]\")</code> should return true.",
"testString": "assert(isBalanced(testCases[2]), '<code>isBalanced(\"[][[[[][][[[]]]]]]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"][\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[3]), '<code>isBalanced(\"][\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[[[]]]][[]\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[4]), '<code>isBalanced(\"[[[]]]][[]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"][[]\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[5]), '<code>isBalanced(\"][[]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"][[][]][[[]]\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[6]), '<code>isBalanced(\"][[][]][[[]]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[[][]]][\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[7]), '<code>isBalanced(\"[[][]]][\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[[[]]][[]]]][][[\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[8]), '<code>isBalanced(\"[[[]]][[]]]][][[\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[]][[]]][[[[][]]\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[9]), '<code>isBalanced(\"[]][[]]][[[[][]]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"][]][[][\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[10]), '<code>isBalanced(\"][]][[][\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[[]][[][]]\")</code> should return true.",
"testString": "assert(isBalanced(testCases[11]), '<code>isBalanced(\"[[]][[][]]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[[]]\")</code> should return true.",
"testString": "assert(isBalanced(testCases[12]), '<code>isBalanced(\"[[]]\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"]][]][[]][[[\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[13]), '<code>isBalanced(\"]][]][[]][[[\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"][]][][[\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[14]), '<code>isBalanced(\"][]][][[\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"][][\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[15]), '<code>isBalanced(\"][][\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"[[]]][][][[]][\")</code> should return true.",
"testString": "assert(!isBalanced(testCases[16]), '<code>isBalanced(\"[[]]][][][[]][\")</code> should return true.');"
},
{
"text": "<code>isBalanced(\"\")</code> should return true.",
"testString": "assert(isBalanced(testCases[17]), '<code>isBalanced(\"\")</code> should return true.');"
}
],
"id": "594dc6c729e5700999302b45",
"challengeType": 5,
"releasedOn": "December 27, 2017",
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function isBalanced (str) {",
" // Good luck!",
" return true;",
"}"
],
"head": [],
"tail": [
"const testCases = [",
" '[]',",
" ']][[[][][][]][',",
" '[][[[[][][[[]]]]]]',",
" '][',",
" '[[[]]]][[]',",
" '][[]',",
" '][[][]][[[]]',",
" '[[][]]][',",
" '[[[]]][[]]]][][[',",
" '[]][[]]][[[[][]]',",
" '][]][[][',",
" '[[]][[][]]',",
" '[[]]',",
" ']][]][[]][[[',",
" '][]][][[',",
" '][][',",
" '[[]]][][][[]][',",
" ''",
"];"
]
}
}
},
{
"title": "Circles of given radius through two points",
"description": [
"<p>Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.</p>",
"Exceptions:",
"A radius of zero should be treated as never describing circles (except in the case where the points are coincident).",
"If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless the radius is equal to zero as well which then collapses the circles to a point.",
"If the points form a diameter then return a single circle.",
"If the points are too far apart then no circles can be drawn.Task:",
"Implement a function that takes two points and a radius and returns the two circles through those points. For each resulting circle, provide the coordinates for the center of each circle rounded to four decimal digits. Return each coordinate as an array, and coordinates as an array of arrays.",
"For edge cases, return the following:",
"If points are on the diameter, return one point. If the radius is also zero however, return <code>\"Radius Zero\"</code>.",
"If points are coincident, return <code>\"Coincident point. Infinite solutions\"</code>.",
"If points are farther apart than the diameter, return <code>\"No intersection. Points further apart than circle diameter\"</code>.",
"Sample inputs:",
"<pre>",
" p1 p2 r",
"0.1234, 0.9876 0.8765, 0.2345 2.0",
"0.0000, 2.0000 0.0000, 0.0000 1.0",
"0.1234, 0.9876 0.1234, 0.9876 2.0",
"0.1234, 0.9876 0.8765, 0.2345 0.5",