-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-wars.js
More file actions
482 lines (380 loc) · 10.3 KB
/
code-wars.js
File metadata and controls
482 lines (380 loc) · 10.3 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
// Regex validate PIN code
// https://www.codewars.com/kata/55f8a9c06c018a0d6e000132/
// My solution
const validatePIN = pin => {
const validLength = pin.length === 4 || pin.length === 6;
const integerQuantity = pin.match(/[0-9]/g) ? pin.match(/[0-9]/g).length : 0;
return validLength && integerQuantity === pin.length;
};
// Community solutionss
function validatePIN(pin) {
return /^(\d{4}|\d{6})$/.test(pin);
}
// \d = digits!
// ^ = start of a line
// $ = end of a line
// /REGEX/.test(thingToTest)
function validatePIN(pin) {
return (pin.length == 4 || pin.length == 6) && parseInt(pin) == pin;
}
// Complementary DNA
// https://www.codewars.com/kata/554e4a2f232cdd87d9000038/
// My solution
const DNAStrand = dna => {
const complimentMap = {
A: "T",
T: "A",
G: "C",
C: "G"
};
return dna.replace(/A|T|G|C/gi, match => complimentMap[match]);
};
// Good to know the match can be passed into a replacement function
// Community solution
let pairs = { A: "T", T: "A", C: "G", G: "C" };
const DNAStrand = dna => dna.replace(/./g, c => pairs[c]);
// Can just use the '.' to return each character and map that
// Find The Parity Outlier
// https://www.codewars.com/kata/5526fc09a1bbd946250002dc/
// My solution
const findOutlier = integers => {
const isEven = int => Math.abs(int) % 2 === 0 || int === 0;
let mostlyEven = integers.filter(int => isEven(int)).length > 1;
const outlierIndex = integers.findIndex(val =>
mostlyEven ? val % 2 !== 0 : val % 2 === 0
);
return integers[outlierIndex];
};
// Community solution
function findOutlier(integers) {
const even = integers.filter(int => int % 2 === 0);
const odd = integers.filter(int => int % 2 !== 0);
return even.length === 1 ? even[0] : odd[0];
}
// Equal Sides Of An Array
// https://www.codewars.com/kata/5679aa472b8f57fb8c000047/
// My answer
const findEvenIndex = arr => {
for (let i = 0; i < arr.length - 1; i++) {
const leftSegment = arr.slice(0, i + 1).reduce((acc, cur) => acc + cur, 0);
const rightSegment = arr.slice(i).reduce((acc, cur) => acc + cur, 0);
if (leftSegment === rightSegment) {
return i;
}
}
return -1;
};
// Community answer
const sum = (a, from, to) => a.slice(from, to).reduce((a, b) => a + b, 0);
const findEvenIndex = a =>
a.findIndex((el, i) => sum(a, 0, i) === sum(a, i + 1));
// findIndex tracks down exactly what you're iterating for in other approaches, and returns -1 if none found
// Sum of Digits / Digital Root
// https://www.codewars.com/kata/541c8630095125aba6000c00
// My solution
const digital_root = n => {
const sum = String(n)
.split("")
.map(parseFloat)
.reduce((acc, cur) => acc + cur);
if (sum < 10) return digital_root(sum);
return sum;
};
// Community
function digital_root(n) {
return ((n - 1) % 9) + 1;
}
// Stop gninnipS My sdroW!
// https://www.codewars.com/kata/5264d2b162488dc400000001/
// My solution
const spinWords = incoming => {
const reverse = word =>
word
.split("")
.reverse()
.join("");
return incoming
.split(" ")
.map(word => (word.length > 5 ? reverse(word) : word));
};
// Community solutions
function spinWords(string) {
return string.replace(/\w{5,}/g, function(w) {
return w
.split("")
.reverse()
.join("");
});
}
// Playing with digits
// https://www.codewars.com/kata/5552101f47fc5178b1000050/
// My solution
const digPow = (n, p) => {
const summedDigits = String(n)
.split("")
.map(Number)
.reduce((cur, acc, index) => cur + acc ** (index + p), 0);
let candidate = 0;
while (candidate <= n * 2) {
if (summedDigits % candidate === 0 && candidate * n === summedDigits) {
return candidate;
}
candidate++;
}
return -1;
};
//Community solution
function digPow(n, p) {
var x = String(n)
.split("")
.reduce((s, d, i) => s + Math.pow(d, p + i), 0);
return x % n ? -1 : x / n;
}
// x % n = any positive number would evaluate to true
// x % n = 0 is falsey and means divisible, so you can just divide
// Tribonacci Sequence
// https://www.codewars.com/kata/556deca17c58da83c00002db/
// My solution
const tribonacci = (signature, n) => {
if (n == 0) {
return [];
}
if (n < 3) {
return signature.slice(0, n);
}
const returnArray = signature;
for (let x = 2; x < n - 1; x++) {
const nextValue = returnArray[x] + returnArray[x - 1] + returnArray[x - 2];
returnArray.push(nextValue);
}
return returnArray;
};
// Community solutions
function tribonacci(signature, n) {
const sequence = signature;
for (var i = 0; i < n - 3; i++) {
sequence.push(sequence[i] + sequence[i + 1] + sequence[i + 2]);
}
return sequence.slice(0, n);
}
// Single slice at the end
// slice(0,0) = []
function tribonacci(signature, n) {
while (signature.length < n) {
signature.push(signature.slice(-3).reduce(sum));
}
return signature.slice(0, n);
}
function sum(a, b) {
return a + b;
}
// slice(-3) allowing previous three elements, then immediate reduce
// Highest and Lowest
// https://www.codewars.com/kata/554b4ac871d6813a03000035/
// My solution
const highAndLow = str => {
const asArray = str.split(" ").map(el => parseFloat(el));
return `${Math.max(...asArray)} ${Math.min(...asArray)}`;
};
// Community solutions
function highAndLow(numbers) {
numbers = numbers.split(" ").map(Number);
return Math.max.apply(0, numbers) + " " + Math.min.apply(0, numbers);
}
// .map(Number)
// Sum of a sequence
// https://www.codewars.com/kata/586f6741c66d18c22800010a
// My solution:
const sequenceSum = (begin, end, step) => {
let sequence = [];
while (step * sequence.length + begin <= end) {
sequence.push(begin + step * sequence.length);
}
return sequence.reduce((acc, cur) => acc + cur, 0);
};
// Community solutions:
// Super elegant recursion
// Ending condition "return 0" ends the recursion of the last return call, allowing a number to be returned
const sequenceSum = (begin, end, step) => {
if (begin > end) {
return 0;
}
return begin + sequenceSum(begin + step, end, step);
};
// Similar to mine structurally, but probably equally gross to read
const sequenceSum = (begin, end, step) => {
var sum = 0;
for (var i = begin; i <= end; i += step) {
sum += i;
}
return sum;
};
// Delete occurrences of an element if it occurs more than n times
// https://www.codewars.com/kata/554ca54ffa7d91b236000023/
// My solution:
const deleteNth = (arr, n) => {
const countObj = {};
const returnArr = [];
arr.map(val => {
countObj[val] = countObj[val] >= 0 ? countObj[val] + 1 : 0;
if (countObj[val] >= n) {
return null;
} else {
returnArr.push(val);
}
});
return returnArr;
};
// Community solution
// return straight from filter()
// (cache[n]||0) to establish initial value
// filter() with a basic condition
function deleteNth(arr, x) {
var cache = {};
return arr.filter(function(n) {
cache[n] = (cache[n] || 0) + 1;
return cache[n] <= x;
});
}
// Remove the minimum
// https://www.codewars.com/kata/563cf89eb4747c5fb100001b/
// My solution
const removeSmallest = numbers => {
if (numbers.length === 0) return [];
const lowest = numbers.reduce((acc, cur) => (cur < acc ? cur : acc));
const indexAway = numbers.indexOf(lowest);
return [...numbers.slice(0, indexAway), ...numbers.slice(indexAway + 1)];
};
// Community solution
// Math.min(...numbers) is slick!
function removeSmallest(numbers) {
let indexOfMin = numbers.indexOf(Math.min(...numbers));
return [...numbers.slice(0, indexOfMin), ...numbers.slice(indexOfMin + 1)];
}
// Take a Ten Minute Walk
// https://www.codewars.com/kata/54da539698b8a2ad76000228/
// My solution
const isValidWalk = walk => {
if (walk.length !== 10) {
return false;
}
let xPosition = 0;
let yPosition = 0;
walk.map(direction => {
switch (direction) {
case "n":
yPosition++;
break;
case "s":
yPosition--;
break;
case "e":
xPosition++;
break;
case "w":
xPosition--;
break;
default:
console.log("Invalid direction");
}
});
return xPosition === 0 && yPosition === 0;
};
// Community solution
// Nice compact switch spacing
function isValidWalk(walk) {
var dx = 0;
var dy = 0;
var dt = walk.length;
for (var i = 0; i < walk.length; i++) {
switch (walk[i]) {
case "n":
dy--;
break;
case "s":
dy++;
break;
case "w":
dx--;
break;
case "e":
dx++;
break;
}
}
return dt === 10 && dx === 0 && dy === 0;
}
// Persistent Bugger.
// https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec/
// My solution
// Recursion note: I forgot to *return* persistence in the else clause
const persistence = (num, count = 0) => {
if (num < 10 && count === 0) return 0;
const digits = [];
const numberArray = [...num.toString()];
let multiplied = 1;
count += 1;
numberArray.map(digit => {
multiplied = parseInt(digit) * multiplied;
});
if (multiplied < 10) {
return count;
} else return persistence(multiplied, count);
};
// Community solution A
function persistence(num) {
var times = 0;
num = num.toString();
while (num.length > 1) {
times++;
num = num
.split("")
.map(Number)
.reduce((a, b) => a * b)
.toString();
}
return times;
}
// Community solution B
const persistence = num => {
return `${num}`.length > 1
? 1 + persistence(`${num}`.split("").reduce((a, b) => a * +b))
: 0;
};
// Categorize New Member
// https://www.codewars.com/kata/5502c9e7b3216ec63c0001aa/
// My solution
const openOrSenior = data => {
const output = [];
for (const person of data) {
if (person[0] >= 55 && person[1] > 7) {
output.push("Senior");
} else {
output.push("Open");
}
}
return output;
};
// Community solution
// * Destructuring!
function openOrSenior(data) {
return data.map(([age, handicap]) =>
age > 54 && handicap > 7 ? "Senior" : "Open"
);
}
// Disemvowel challenge
// My solution
function disemvowel(str) {
const vowels = ["a", "e", "i", "o", "u"];
let devoweled = str;
for (const letter in str) {
if (vowels.includes(str[letter].toLowerCase())) {
devoweled = devoweled.replace(str[letter], "");
}
}
return devoweled;
}
// Community solution
function disemvowel(str) {
return str.replace(/[aeiou]/gi, "");
}