forked from shams-ali/recursion-prompts
-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathrecursion.js
More file actions
606 lines (514 loc) · 14.9 KB
/
recursion.js
File metadata and controls
606 lines (514 loc) · 14.9 KB
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
// Solve all of the following prompts using recursion.
// 1. Calculate the factorial of a number. The factorial of a non-negative integer n,
// denoted by n!, is the product of all positive integers less than or equal to n.
// Example: 5! = 5 x 4 x 3 x 2 x 1 = 120
// factorial(5); // 120
var factorial = function(n) {
if (Math.sign(n) === -1){
return null
}
if (n === 0){
return 1
}
return n * factorial(n - 1)
};
// 2. Compute the sum of an array of integers.
// Example: sum([1, 2, 3, 4, 5, 6]); // 21
var sum = function(array) {
if (!array.length){
return 0
}
return array[0]+sum(array.slice(1))
};
// 3. Sum all numbers in an array containing nested arrays.
// Example: arraySum([1,[2,3],[[4]],5]); // 15
var arraySum = function(array) {
if (!array.length){
return 0
}
if (Array.isArray(array[0])){
var sum = arraySum(array[0]) // continue logic here
}
else {
var sum = array[0]
}
return sum + arraySum(array.slice(1))
};
// 4. Check if a number is even.
var isEven = function(n) {
if (n === 0) {
return true
}
else if (n === 1) {
return false
}
if (Math.sign(n) === -1) {
return isEven(n + 2)
}
else {
return isEven(n - 2)
}
};
// 5. Sum all integers below a given integer.
// sumBelow(10); // 45
// sumBelow(7); // 21
var sumBelow = function(n) {
if (n === 0) {
return 0
}
if (Math.sign(n) === -1){
var currentN = n + 1}
else{
var currentN = n - 1}
if (currentN === 0){
return 0
}
if (Math.sign(currentN) === -1) {
return currentN + sumBelow(currentN)
}
else {
return currentN + sumBelow(currentN)
}
};
// 6. Get the integers in range (x, y).
// Example: range(2, 9); // [3, 4, 5, 6, 7, 8]
var range = function(x, y) {
//debugger;
if (x === y || x-1 === y || x+1 === y || y === undefined){
return[]
}
if(x < y){
var nextX = x+1
}
if(x > y){
var nextX = x-1
}
return [nextX].concat(range(nextX, y))
};
// 7. Compute the exponent of a number.
// The exponent of a number says how many times the base number is used as a factor.
// 8^2 = 8 x 8 = 64. Here, 8 is the base and 2 is the exponent.
// Example: exponent(4,3); // 64
// https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/computing-powers-of-a-number
var exponent = function(base, exp) {
if (exp === 0){
return 1
}
if (exp === 1){
return base
}
if (exp > 0){
return base * exponent(base, exp-1)
}
if (exp < 0){
return 1 / exponent(base, (-1*exp))
}
};
// 8. Determine if a number is a power of two.
// powerOfTwo(1); // true
// powerOfTwo(16); // true
// powerOfTwo(10); // false
var powerOfTwo = function(n) {
if(n === 1){
return true
}else if(n % 2 !== 0 || n === 0){
return false
}
return powerOfTwo(n/2)
};
// 9. Write a function that accepts a string and reverses it.
var reverse = function(string) {
if (Array.isArray(string)){
var reversedText = string.reverse()
return reversedText.join("")
}else{
var text = string
var textArr = text.split("")
return reverse(textArr)
}
};
// 10. Write a function that determines if a string is a palindrome.
var palindrome = function(string) {
if (Array.isArray(string)){
var reversedText = string.reverse()
return reversedText.join("")
}else{
var correctString = string.toLowerCase()
var correctString1 = correctString.replace(/\s+/g, '');
return (correctString1 === palindrome(correctString1.split("")))
}
};
// 11. Write a function that returns the remainder of x divided by y without using the
// modulo (%) operator.
// modulo(5,2) // 1
// modulo(17,5) // 2
// modulo(22,6) // 4
var modulo = function(x, y) {
if( x === 0 && y === 0){
return NaN
}
if (x >= 0 && y >= 0){
if (y > x){
return x
}else if(y <= x){
return modulo(x-y, y)
}
}
if (x < 0 && y < 0){
if (y < x){
return x
}else if(y >= x){
return modulo(x-y, y)
}
}
if (x < 0 && y > 0){
if (y < x){
return x
}else if(y >= x){
var negativeXModulo = modulo(y+x, y)
if(x < y && negativeXModulo > 0){
return x
}else{
return negativeXModulo
}
}
}
};
// 12. Write a function that multiplies two numbers without using the * operator or
// JavaScript's Math object.
var multiply = function(x, y) {
if (y === 1){
return x
}
if (y === 0 || x === 0){
return 0
}
if (y > 0){
return x+multiply(x, y-1)
}else if (y < 0 && x < 0){
return multiply(x, y+1)-x
}else if (y < 0){
return x+multiply(x, y+1)
}
};
// 13. Write a function that divides two numbers without using the / operator or
// JavaScript's Math object.
var divide = function(x, y) {
if (y === 0){
return NaN
}
if (x === 0){
return 0
}
if (y === 1){
return x
}
if (x < 0 && y < 0){
if (y < x){
return 0
}
}
if (y > x){
return 0
}
if (y === x){
return 1
}
if (x > 0 && y > 0){
return 1+divide(x-y, y)
}
if (x < 0 && y < 0){
return 1+divide(x-y, y)
}
if (x < 0 && y > 0){
return 1+divide(x+y, y)
}
};
// 14. Find the greatest common divisor (gcd) of two positive numbers. The GCD of two
// integers is the greatest integer that divides both x and y with no remainder.
// Example: gcd(4,36); // 4
// http://www.cse.wustl.edu/~kjg/cse131/Notes/Recursion/recursion.html
// https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm
var gcd = function(x, y) {
if (Math.sign(x) === -1 || Math.sign(y) === -1) {
return null
}
if (x === 0){
return y
}
if(y === 0){
return x
}
if (x > y){
if(x === (y * ~~(x/y)+(x % y))){
return gcd(y, (x % y))
}
}
if (y > x){
if(y === (x * ~~(y/x)+(y % x))){
return gcd(x, (y % x))
}
}
};
// 15. Write a function that compares each character of two strings and returns true if
// both are identical.
// compareStr('house', 'houses') // false
// compareStr('', '') // true
// compareStr('tomato', 'tomato') // true
var compareStr = function(str1, str2) {
if (Array.isArray(str1) && Array.isArray(str2)){
if (str1.length === str2.length){
for (i = 0; i < str1.length; i++){
if (str2[i] !== str1[i]){
return false
}
}
return true
}else{
return false
}
}else{
return compareStr(str1.split(""), str2.split(""))}
};
// 16. Write a function that accepts a string and creates an array where each letter
// occupies an index of the array.
var createArray = function(str){
};
// 17. Reverse the order of an array
var reverseArr = function (array) {
};
// 18. Create a new array with a given value and length.
// buildList(0,5) // [0,0,0,0,0]
// buildList(7,3) // [7,7,7]
var buildList = function(value, length) {
};
// 19. Count the occurence of a value inside a list.
// countOccurrence([2,7,4,4,1,4], 4) // 3
// countOccurrence([2,'banana',4,4,1,'banana'], 'banana') // 2
var countOccurrence = function(array, value) {
};
// 20. Write a recursive version of map.
// rMap([1,2,3], timesTwo); // [2,4,6]
var rMap = function(array, callback) {
};
// 21. Write a function that counts the number of times a key occurs in an object.
// var testobj = {'e': {'x':'y'}, 't':{'r': {'e':'r'}, 'p': {'y':'r'}},'y':'e'};
// countKeysInObj(testobj, 'r') // 1
// countKeysInObj(testobj, 'e') // 2
var countKeysInObj = function(obj, key) {
};
// 22. Write a function that counts the number of times a value occurs in an object.
// var testobj = {'e': {'x':'y'}, 't':{'r': {'e':'r'}, 'p': {'y':'r'}},'y':'e'};
// countValuesInObj(testobj, 'r') // 2
// countValuesInObj(testobj, 'e') // 1
var countValuesInObj = function(obj, value) {
};
// 23. Find all keys in an object (and nested objects) by a provided name and rename
// them to a provided new name while preserving the value stored at that key.
var replaceKeysInObj = function(obj, key, newKey) {
};
// 24. Get the first n Fibonacci numbers. In the Fibonacci Sequence, each subsequent
// number is the sum of the previous two.
// Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.....
// fibonacci(5); // [0, 1, 1, 2, 3, 5]
// Note: The 0 is not counted.
var fibonacci = function(n) {
};
// 25. Return the Fibonacci number located at index n of the Fibonacci sequence.
// [0,1,1,2,3,5,8,13,21]
// nthFibo(5); // 5
// nthFibo(7); // 13
// nthFibo(3); // 2
var nthFibo = function(n) {
};
// 26. Given an array of words, return a new array containing each word capitalized.
// var words = ['i', 'am', 'learning', 'recursion'];
// capitalizedWords(words); // ['I', 'AM', 'LEARNING', 'RECURSION']
var capitalizeWords = function(input) {
};
// 27. Given an array of strings, capitalize the first letter of each index.
// capitalizeFirst(['car', 'poop', 'banana']); // ['Car', 'Poop', 'Banana']
var capitalizeFirst = function(array) {
};
// 28. Return the sum of all even numbers in an object containing nested objects.
// var obj1 = {
// a: 2,
// b: {b: 2, bb: {b: 3, bb: {b: 2}}},
// c: {c: {c: 2}, cc: 'ball', ccc: 5},
// d: 1,
// e: {e: {e: 2}, ee: 'car'}
// };
// nestedEvenSum(obj1); // 10
var nestedEvenSum = function(obj) {
};
// 29. Flatten an array containing nested arrays.
// Example: flatten([1,[2],[3,[[4]]],5]); // [1,2,3,4,5]
var flatten = function(arrays) {
};
// 30. Given a string, return an object containing tallies of each letter.
// letterTally('potato'); // {'p':1, 'o':2, 't':2, 'a':1}
var letterTally = function(str, obj) {
};
// 31. Eliminate consecutive duplicates in a list. If the list contains repeated
// elements they should be replaced with a single copy of the element. The order of the
// elements should not be changed.
// Example: compress([1, 2, 2, 3, 4, 4, 5, 5, 5]) // [1, 2, 3, 4, 5]
// Example: compress([1, 2, 2, 3, 4, 4, 2, 5, 5, 5, 4, 4]) // [1, 2, 3, 4, 2, 5, 4]
var compress = function(list) {
};
// 32. Augment every element in a list with a new value where each element is an array
// itself.
// Example: augmentElements([[],[3],[7]], 5); // [[5],[3,5],[7,5]]
var augmentElements = function(array, aug) {
};
// 33. Reduce a series of zeroes to a single 0.
// minimizeZeroes([2,0,0,0,1,4]) // [2,0,1,4]
// minimizeZeroes([2,0,0,0,1,0,0,4]) // [2,0,1,0,4]
var minimizeZeroes = function(array) {
};
// 34. Alternate the numbers in an array between positive and negative regardless of
// their original sign. The first number in the index always needs to be positive.
// alternateSign([2,7,8,3,1,4]) // [2,-7,8,-3,1,-4]
// alternateSign([-2,-7,8,3,-1,4]) // [2,-7,8,-3,1,-4]
var alternateSign = function(array) {
};
// 35. Given a string, return a string with digits converted to their word equivalent.
// Assume all numbers are single digits (less than 10).
// numToText("I have 5 dogs and 6 ponies"); // "I have five dogs and six ponies"
var numToText = function(str) {
};
// *** EXTRA CREDIT ***
// 36. Return the number of times a tag occurs in the DOM.
var tagCount = function(tag, node) {
};
// 37. Write a function for binary search.
// Sample array: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
// console.log(binarySearch(5)) will return '5'
var binarySearch = function(array, target, min, max) {
};
// 38. Write a merge sort function.
// Sample array: [34,7,23,32,5,62]
// Sample output: [5,7,23,32,34,62]
var mergeSort = function(array) {
};
//-----------------------------------
// DON'T REMOVE THIS CODE -----------
//-----------------------------------
if ((typeof process !== 'undefined') &&
(typeof process.versions.node !== 'undefined')) {
/**
* Due to some node-related issues with spying on recursive functions,
* it isn't possible to test them with sinon spies like so:
*
* var originalSum = sum;
* sum = sinon.spy(sum);
*
* sum([1, 2, 3, 4, 5, 6]);
*
* // callCount will always 1 causing, this test to always fail in node :(
* expect(sum.callCount).to.be.above(1);
*
* sum = originalSum;
*
* However, we can work around this by using proxies!
* If you reassign the function to a proxy and use the `apply` trap,
* you can make a `proxyCallCount` property on the function,
* increment it each time it's called, and then test that instead.
*
* sum.proxyCallCount = 0;
* sum([1, 2, 3, 4, 5, 6]);
* expect(sum.proxyCallCount).to.be.above(1);
*
* MDN Proxies: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
* MDN Proxy Apply Trap: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply
*/
const createSpyProxy = (func) => {
func.toString = func.toString.bind(func);
const recursiveFunctionCallCounterHandler = {
apply(target, thisArg, args) {
target.proxyCallCount = target.proxyCallCount ? target.proxyCallCount + 1 : 1;
return target.apply(thisArg, args);
},
};
return new Proxy(func, recursiveFunctionCallCounterHandler);
};
factorial = createSpyProxy(factorial);
sum = createSpyProxy(sum);
arraySum = createSpyProxy(arraySum);
isEven = createSpyProxy(isEven);
sumBelow = createSpyProxy(sumBelow);
range = createSpyProxy(range);
exponent = createSpyProxy(exponent);
powerOfTwo = createSpyProxy(powerOfTwo);
reverse = createSpyProxy(reverse);
palindrome = createSpyProxy(palindrome);
modulo = createSpyProxy(modulo);
multiply = createSpyProxy(multiply);
divide = createSpyProxy(divide);
gcd = createSpyProxy(gcd);
compareStr = createSpyProxy(compareStr);
createArray = createSpyProxy(createArray);
reverseArr = createSpyProxy(reverseArr);
buildList = createSpyProxy(buildList);
countOccurrence = createSpyProxy(countOccurrence);
rMap = createSpyProxy(rMap);
countKeysInObj = createSpyProxy(countKeysInObj);
countValuesInObj = createSpyProxy(countValuesInObj);
replaceKeysInObj = createSpyProxy(replaceKeysInObj);
fibonacci = createSpyProxy(fibonacci);
nthFibo = createSpyProxy(nthFibo);
capitalizeWords = createSpyProxy(capitalizeWords);
capitalizeFirst = createSpyProxy(capitalizeFirst);
nestedEvenSum = createSpyProxy(nestedEvenSum);
flatten = createSpyProxy(flatten);
letterTally = createSpyProxy(letterTally);
compress = createSpyProxy(compress);
augmentElements = createSpyProxy(augmentElements);
minimizeZeroes = createSpyProxy(minimizeZeroes);
alternateSign = createSpyProxy(alternateSign);
numToText = createSpyProxy(numToText);
tagCount = createSpyProxy(tagCount);
binarySearch = createSpyProxy(binarySearch);
mergeSort = createSpyProxy(mergeSort);
module.exports = {
factorial,
sum,
arraySum,
isEven,
sumBelow,
range,
exponent,
powerOfTwo,
reverse,
palindrome,
modulo,
multiply,
divide,
gcd,
compareStr,
createArray,
reverseArr,
buildList,
countOccurrence,
rMap,
countKeysInObj,
countValuesInObj,
replaceKeysInObj,
fibonacci,
nthFibo,
capitalizeWords,
capitalizeFirst,
nestedEvenSum,
flatten,
letterTally,
compress,
augmentElements,
minimizeZeroes,
alternateSign,
numToText,
tagCount,
binarySearch,
mergeSort,
};
}
//-----------------------------------