-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodewars.cpp
More file actions
1778 lines (1605 loc) · 62.1 KB
/
codewars.cpp
File metadata and controls
1778 lines (1605 loc) · 62.1 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
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
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <vector>
#include <stack>
#include <map>
#include <regex>
#include <numeric>
#include <iterator>
#include <functional>
#include <exception>
#include <string>
#include <unordered_map>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// RGB To Hex Conversion
// https://www.codewars.com/kata/rgb-to-hex-conversion/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class RGBToHex
{
protected:
static int rangeCheck(int v)
{
return (v < 0) ? 0 : ((v > 255) ? 255 : v);
}
static int rangeCheck2(int v)
{
return std::max(0, std::min(255, v));
}
public:
static std::string rgb(int r, int g, int b)
{
std::stringstream ss;
ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << rangeCheck(r);
ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << rangeCheck(g);
ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << rangeCheck(b);
return ss.str();
}
static std::string rgb2(int r, int g, int b)
{
std::ostringstream ss;
ss.flags(std::ios::hex | std::ios::uppercase);
ss.fill('0');
ss << std::setw(2) << rangeCheck2(r);
ss << std::setw(2) << rangeCheck2(g);
ss << std::setw(2) << rangeCheck2(b);
return ss.str();
}
static void byte2hex(unsigned char b, std::string& s)
{
static const char* hex = "0123456789ABCDEF";
s.push_back(hex[b >> 4]);
s.push_back(hex[b & 0xf]);
}
static std::string rgb3(int r, int g, int b)
{
std::string result;
byte2hex(rangeCheck2(r), result);
byte2hex(rangeCheck2(g), result);
byte2hex(rangeCheck2(b), result);
return result;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Find the odd int
// https://www.codewars.com/kata/find-the-odd-int/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
int findOdd(const std::vector<int>& numbers)
{
std::unordered_map<int, int> m;
for (auto v : numbers)
m[v]++;
for (auto v : m)
if (v.second % 2)
return v.first;
return 0;
}
int findOdd2(const std::vector<int>& numbers)
{
for (auto v : numbers)
if (std::count(numbers.begin(), numbers.end(), v) % 2)
return v;
return 0;
}
int findOdd3(const std::vector<int>& numbers)
{
return std::accumulate(numbers.begin(), numbers.end(), 0, std::bit_xor<int>());
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Valid Braces
// https://www.codewars.com/kata/valid-braces/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool valid_braces(std::string braces)
{
std::stack<char> st;
for (auto ch : braces)
switch (ch)
{
case '(': st.push(')'); break;
case '[': st.push(']'); break;
case '{': st.push('}'); break;
default:
if (st.empty() || st.top() != ch) return false;
st.pop();
}
return st.empty();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// longest_palindrome
// https://www.codewars.com/kata/longest-palindrome/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool is_palindrome(const std::string &s)
{
return s == std::string(s.rbegin(), s.rend());
}
int longest_palindrome(const std::string &s)
{
size_t max = 0;
for (size_t offs = 0; offs < s.size() - 1; offs++)
{
size_t count = s.size() - offs;
while (count > max)
{
if (is_palindrome(s.substr(offs, count)))
{
max = count;
break;
}
count--;
}
}
return max;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Mexican Wave
// https://www.codewars.com/kata/mexican-wave/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<std::string> wave(std::string y)
{
std::vector<std::string> res;
for (size_t i = 0; i < y.size(); i++)
{
if (isalpha(y[i]))
{
res.push_back(y);
res.back()[i] = toupper(y[i]);
}
}
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Roman Numerals Encoder
// https://www.codewars.com/kata/roman-numerals-encoder/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
static const std::vector<std::pair<int, std::string>> roman = {
{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}
};
std::string RomanNumeralsEncoder(int number)
{
std::string res;
for (const auto p : roman)
while (number >= p.first)
{
res += p.second;
number -= p.first;
}
return res;
}
// Expected: equal to MMMCDLXXII // 31
// Actual : MMMCCCCLXXII // 3472
int from_roman(std::string s)
{
int res = 0;
for (const auto p : roman)
while (s.find(p.second) == 0)
{
s = s.substr(p.second.length());
res += p.first;
}
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)
// https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string my_first_interpreter(const std::string& code)
{
char reg = 0;
std::string res;
for (auto op : code)
if (op == '+')
reg++;
else
if (op == '.')
res += reg;
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fibonacci, Tribonacci and friends
// https://www.codewars.com/kata/fibonacci-tribonacci-and-friends/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<int> xbonacci(std::vector<int> signature, size_t n)
{
std::vector<int> res(signature);
size_t count = res.size();
if (count > n)
res.resize(n);
else
while (res.size() < n)
res.push_back(std::accumulate(res.crbegin(), res.crbegin() + count, 0));
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Find the missing term in an Arithmetic Progression
// https://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
static long findMissing(std::vector<long> list)
{
long step = (list.back() - list.front()) / (long)list.size();
long pr = list.front();
for (auto v : list)
{
if (pr != v)
return pr;
pr += step;
}
return 0;
/*
long long expectedSum = (list.front() + list.back()) * (list.size() + 1);
long long actualSum = std::accumulate(list.begin(), list.end(), 0ll);
return (expectedSum - 2 * actualSum) / 2;
*/
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Counting Duplicates
// https://www.codewars.com/kata/counting-duplicates/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
size_t duplicateCount(const char *in)
{
std::unordered_map<char, int> m;
while (char ch = *in++)
++m[tolower(ch)];
return std::count_if(m.cbegin(), m.cend(), [](const auto& v) { return v.second > 1; });
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Which are in?
// https://www.codewars.com/kata/which-are-in/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class WhichAreIn
{
public:
static std::vector<std::string> inArray(std::vector<std::string> &array1, std::vector<std::string> &array2)
{
std::vector<std::string> res;
std::copy_if(array1.begin(), array1.end(), std::back_inserter(res), [&](const std::string& item1) {
return std::any_of(array2.begin(), array2.end(), [&](const std::string& item2) {
return item2.find(item1) != std::string::npos;
});
});
return res;
};
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Simple Pig Latin
// https://www.codewars.com/kata/simple-pig-latin/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string pig_it(std::string str)
{
/*
std::string res;
bool bFirst = true;
char chFirst;
for (auto ch : str)
if (bFirst)
if (isalpha(ch))
{
bFirst = false;
chFirst = ch;
}
else
res.push_back(ch);
else
if (isalpha(ch))
res.push_back(ch);
else
{
res.push_back(chFirst);
res.push_back('a');
res.push_back('y');
res.push_back(ch);
bFirst = true;
}
if (!bFirst)
{
res.push_back(chFirst);
res.push_back('a');
res.push_back('y');
}
return res;
*/
std::regex re("(\\w)(\\w*)(\\s|$)");
return std::regex_replace(str, re, "$2$1ay$3");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// int32 to IPv4
// https://www.codewars.com/kata/int32-to-ipv4/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string uint32_to_ip(uint32_t ip)
{
std::stringstream ss;
ss << ((ip >> 24) & 0xFF) << '.' << ((ip >> 16) & 0xFF) << '.' << ((ip >> 8) & 0xFF) << '.' << (ip & 0xFF);
return ss.str();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Esoteric Language: 'Poohbear' Interpreter
// https://www.codewars.com/kata/esoteric-language-poohbear-interpreter/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string poohbear(const char* sourcecode)
{
std::string result;
std::unordered_map<size_t, unsigned char> cells;
size_t curr_cell = 0;
unsigned char clipboard;
const char* p_loop = nullptr;
while (char code = *sourcecode++)
switch (code)
{
case '+': cells[curr_cell]++; break;
case '-': cells[curr_cell]--; break;
case '>': curr_cell++; break;
case '<': curr_cell--; break;
case 'c': clipboard = cells[curr_cell]; break;
case 'p': cells[curr_cell] = clipboard; break;
case 'W':
if (cells[curr_cell])
p_loop = sourcecode;
else
while ('E' != *sourcecode++) ;
break;
case 'E': if (cells[curr_cell] && p_loop) sourcecode = p_loop; break;
case 'P': result += cells[curr_cell]; break;
case 'N': result += std::to_string((int)cells[curr_cell]); break;
case 'T': cells[curr_cell] *= 2; break;
case 'Q': cells[curr_cell] = cells[curr_cell] * cells[curr_cell]; break;
case 'U': cells[curr_cell] = static_cast<int>(sqrt(cells[curr_cell])); break;
case 'L': cells[curr_cell] += 2; break;
case 'I': cells[curr_cell] -= 2; break;
case 'V': cells[curr_cell] /= 2; break;
case 'A': cells[curr_cell] += clipboard; break;
case 'B': cells[curr_cell] -= clipboard; break;
case 'Y': cells[curr_cell] *= clipboard; break;
case 'D': cells[curr_cell] /= clipboard; break;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Simple assembler interpreter
// https://www.codewars.com/kata/simple-assembler-interpreter/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
mov x y - copies y (either a constant value or the content of a register) into register x
inc x - increases the content of register x by one
dec x - decreases the content of register x by one
jnz x y - jumps to an instruction y steps away (positive means forward, negative means backward), but only if x (a constant or a register) is not zero
*/
enum class OP { MOVE, INC, DEC, JNZ };
bool decode(const std::string &instr, OP &op, std::string &p1, std::string &p2)
{
static std::regex rMov("(mov)\\s+([[:alpha:]])\\s+([[:alpha:]]|([\\+|-]?[[:digit:]]+))");
static std::regex rInc("(inc)\\s+([[:alpha:]])");
static std::regex rDec("(dec)\\s+([[:alpha:]])");
static std::regex rJnz("(jnz)\\s+([[:alpha:]]|([\\+|-]?[[:digit:]]+))\\s+([\\+|-]?[[:digit:]]+)");
std::smatch rRes;
if (std::regex_match(instr, rRes, rMov))
{
op = OP::MOVE;
p1 = rRes[2];
p2 = rRes[3];
return true;
}
if (std::regex_match(instr, rRes, rInc))
{
op = OP::INC;
p1 = rRes[2];
return true;
}
if (std::regex_match(instr, rRes, rDec))
{
op = OP::DEC;
p1 = rRes[2];
return true;
}
if (std::regex_match(instr, rRes, rJnz))
{
op = OP::JNZ;
p1 = rRes[2];
p2 = rRes[4];
return true;
}
return false;
}
int getReg(std::unordered_map<std::string, int>& regs, std::string name)
{
try
{
int res = std::stoi(name);
return res;
}
catch (...)
{
return regs[name];
}
}
std::unordered_map<std::string, int> assembler(const std::vector<std::string>& program)
{
std::unordered_map<std::string, int> regs;
std::vector<std::pair<OP, std::pair<std::string, std::string> > > prog;
for (auto line : program)
{
OP op;
std::string p1, p2;
if (decode(line, op, p1, p2))
prog.push_back({ op, {p1, p2} });
}
for (size_t ip = 0; ip < prog.size(); ip++)
{
//if (decode(program[ip], op, p1, p2))
switch (prog[ip].first)
{
case OP::MOVE: regs[prog[ip].second.first] = getReg(regs, prog[ip].second.second); break;
case OP::INC: ++regs[prog[ip].second.first]; break;
case OP::DEC: --regs[prog[ip].second.first]; break;
case OP::JNZ:
if (getReg(regs, prog[ip].second.first))
ip += getReg(regs, prog[ip].second.second) - 1;
break;
}
}
return regs;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Simple Encryption #2 - Index-Difference
// https://www.codewars.com/kata/simple-encryption-number-2-index-difference/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
const std::string region = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\"";
class SimpleEncryption
{
static void check(const std::string &text)
{
for (size_t i = 0; i < text.length(); i++)
if (region.find(text[i]) == region.npos)
throw std::exception("bad symbol");
}
static void changeCase(std::string &text)
{
for (size_t i = 1; i < text.length(); i += 2)
text[i] = isupper(text[i]) ? tolower(text[i]) : toupper(text[i]);
}
public:
static std::string encrypt(std::string text)
{
if (text.empty()) return text;
check(text);
changeCase(text);
std::string res = text;
for (size_t i = 1; i < text.length(); i++)
{
int idx = region.find(text[i - 1]) - region.find(text[i]);
if (idx < 0) idx += region.length();
res[i] = region[idx];
}
res[0] = region[region.length() - region.find(res[0]) - 1];
return res;
}
static std::string decrypt(std::string text)
{
if (text.empty()) return text;
check(text);
text[0] = region[region.length() - region.find(text[0]) - 1];
for (size_t i = 1; i < text.length(); i++)
{
int idx = region.find(text[i - 1]) - region.find(text[i]);
if (idx < 0) idx += region.length();
text[i] = region[idx];
}
changeCase(text);
return text;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Square Matrix Multiplication
// https://www.codewars.com/kata/square-matrix-multiplication/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<std::vector<int>> matrix_multiplication(std::vector<std::vector<int>> &a, std::vector<std::vector<int>> &b, size_t n)
{
std::vector<std::vector<int>> result(n, std::vector<int>(n));
for (size_t row = 0; row < n; row++)
for (size_t col = 0; col < n; col++)
for (size_t i = 0; i < n; i++)
result[row][col] += a[row][i] * b[i][col];
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// My smallest code interpreter (aka Brainf**k)
// https://www.codewars.com/kata/my-smallest-code-interpreter-aka-brainf-star-star-k/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string brainLuck(std::string code, std::string input)
{
const size_t max_regs = 50;
std::string result;
std::vector<unsigned char> regs(max_regs);
size_t ireg = max_regs / 2;
auto stream = input.begin();
for (size_t ip = 0; ip < code.length(); ip++)
switch (code[ip])
{
case '>': ireg++; break;
case '<': ireg--; break;
case '+': ++regs[ireg]; break;
case '-': --regs[ireg]; break;
case '.': result += regs[ireg]; break;
case ',': regs[ireg] = *stream++; break;
case '[':
if (regs[ireg] == 0)
{
int braces = 1;
while (braces > 0)
{
ip++;
if (code[ip] == '[') braces++;
if (code[ip] == ']') braces--;
}
}
break;
case ']':
if (regs[ireg] != 0)
{
int braces = 1;
while (braces > 0) {
ip--;
if (code[ip] == '[') braces--;
if (code[ip] == ']') braces++;
}
}
break;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Directions Reduction
// https://www.codewars.com/kata/directions-reduction/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class DirReduction
{
static bool is_opposite_dir(const std::string& dir1, const std::string& dir2)
{
return ((dir1 == "NORTH" && dir2 == "SOUTH") || (dir1 == "SOUTH" && dir2 == "NORTH") ||
(dir1 == "EAST" && dir2 == "WEST") || (dir1 == "WEST" && dir2 == "EAST"));
}
public:
static std::vector<std::string> dirReduc(std::vector<std::string> &arr)
{
std::vector<std::string> result;
for (auto dir : arr)
if (result.empty() || !is_opposite_dir(result.back(), dir))
result.push_back(dir);
else
result.pop_back();
return result;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sort - one, three, two
// https://www.codewars.com/kata/sort-one-three-two/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Dinglemouse
{
static std::string number_to_words(int num)
{
static const std::vector<std::string> names = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
static const std::vector<std::string> tens = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (num == 0) return names[0];
std::string result;
if ((num / 100) > 0)
{
result += number_to_words(num / 100) + " hundred ";
num %= 100;
}
if (num > 0)
{
if (num < 20)
result += names[num];
else
{
result += tens[num / 10];
if ((num % 10) > 0)
result += "-" + names[num % 10];
}
}
return result;
}
public:
static std::vector<int> sort(const std::vector<int> &array)
{
std::vector<int> result(array);
std::sort(result.begin(), result.end(), [](const auto &p1, const auto &p2) -> bool
{
return number_to_words(p1) < number_to_words(p2);
});
return result;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Weight for weight
// https://www.codewars.com/kata/weight-for-weight/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class WeightSort
{
public:
static std::string orderWeight(const std::string &strng)
{
std::vector<std::string> arr1;
std::istringstream iss(strng);
std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(arr1));
std::sort(arr1.begin(), arr1.end(), [](const std::string &s1, const std::string &s2)
{
auto fn_weight = [](const int weight, const char ch) -> int { return weight + (ch - '0'); };
int w1 = std::accumulate(s1.begin(), s1.end(), 0, fn_weight);
int w2 = std::accumulate(s2.begin(), s2.end(), 0, fn_weight);
return (w1 == w2) ? s1 < s2 : w1 < w2;
});
std::ostringstream oss;
std::copy(arr1.begin(), arr1.end(), std::ostream_iterator<std::string>(oss, " "));
std::string result = oss.str();
return result.substr(0, result.length() - 1);
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// A Chain adding function
// https://www.codewars.com/kata/a-chain-adding-function/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Chain
{
int _v;
public:
Chain(int v = 0) : _v(v) { }
Chain operator()(const int v) const { return Chain(_v + v); }
operator int() const { return _v; }
};
std::ostream& operator<<(std::ostream &os, Chain const &x)
{
os << (int)x;
return os;
}
auto add(int n)
{
return Chain(n);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Greed is Good
// https://www.codewars.com/kata/greed-is-good/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
int score(const std::vector<int>& dice)
{
int score = 0;
int count[7] = { 0 };
for (auto v : dice)
if (++count[v] == 3)
{
score += (v == 1) ? 1000 : v * 100;
count[v] = 0;
}
score += count[1] * 100;
score += count[5] * 50;
return score;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Scramblies
// https://www.codewars.com/kata/scramblies/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool scramble(const std::string& s1, const std::string& s2)
{
int nums['z' - 'a' + 1] = { 0 };
for (auto c : s1) nums[c - 'a']++;
for (auto c : s2) if (!nums[c - 'a']--) return false;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Snail
// https://www.codewars.com/kata/snail/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<int> snail(std::vector<std::vector<int>> &matrix)
{
std::vector<int> result;
if (matrix.empty()) return result;
size_t x = 0, y = 0, x0 = 0, x1 = matrix[0].size() - 1, y0 = 0, y1 = matrix.size() - 1;
while (y0 <= y1)
{
while (x < x1) result.push_back(matrix[y][x++]); y0++;
while (y < y1) result.push_back(matrix[y++][x]); x1--;
while (x > x0) result.push_back(matrix[y][x--]); y1--;
while (y > y0) result.push_back(matrix[y--][x]); x0++;
}
result.push_back(matrix[y][x]);
return result;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sudoku Solution Validator
// https://www.codewars.com/kata/sudoku-solution-validator/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool checkRow(int row, unsigned int board[9][9])
{
char checks[10] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
for (int c = 0; c < 9; c++)
if (!checks[board[row][c]]--) return false;
return true;
}
bool checkCol(int col, unsigned int board[9][9])
{
char checks[10] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
for (int r = 0; r < 9; r++)
if (!checks[board[r][col]]--) return false;
return true;
}
bool checkQuadr(int col, int row, unsigned int board[9][9])
{
char checks[10] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
for (int r = row; r < row + 3; r++)
for (int c = col; c < col + 3; c++)
if (!checks[board[r][c]]--) return false;
return true;
}
bool validSudoku(unsigned int board[9][9])
{
for (int i = 0; i < 9; i++)
{
if (!checkRow(i, board)) return false;
if (!checkCol(i, board)) return false;
}
for (int r = 0; r < 9; r += 3)
for (int c = 0; c < 9; c += 3)
if (!checkQuadr(r, c, board)) return false;
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Multiplying numbers as strings
// https://www.codewars.com/kata/multiplying-numbers-as-strings/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::string multiply(std::string a, std::string b)
{
if (a.empty() || b.empty()) return "";
std::vector<std::string> arr;
std::reverse(a.begin(), a.end());
std::reverse(b.begin(), b.end());
int ten = 0;
for(auto b1 : b) //multiplication
{
int mem = 0;
std::string mul;
for (auto a1 : a)
{
int p = (a1 - '0') * (b1 - '0') + mem;
mem = (p > 9) ? p / 10 : 0;
p -= mem * 10;
mul.push_back('0' + p);
}
if (mem) mul.push_back('0' + mem);
arr.push_back(std::string(ten++, '0') + mul);
}
std::string res;
int mem = 0;
for (size_t i = 0; i < arr[arr.size() - 1].length(); i++) //addition
{
int sum = mem;
for (const auto s : arr)
if (i < s.length())
sum += s[i] - '0';
mem = (sum > 9) ? sum / 10 : 0;
sum -= mem * 10;
res.push_back('0' + sum);
}
if (mem) res.push_back('0' + mem);
while (res.back() == '0' && res.length() > 1) res.pop_back();
std::reverse(res.begin(), res.end());
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Roman Numerals Helper
// https://www.codewars.com/kata/roman-numerals-helper/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class RomanN
{
public:
std::string to_roman(int number)
{
std::string res;
for (auto p : roman)
while (number >= p.first)
{
res += p.second;
number -= p.first;
}
return res;
}
int from_roman(std::string s)
{
int res = 0;
for (const auto p : roman)
while (s.find(p.second) == 0)
{
s = s.substr(p.second.length());
res += p.first;
}
return res;
}
} RomanNumerals;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Rotations and reflections I
// https://www.codewars.com/kata/rotations-and-reflections-i/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Dih4
{
private:
int _tr;
public:
static Dih4 IDENTITY;
static Dih4 ROTATE_90_ANTICLOCKWISE;
static Dih4 ROTATE_180;
static Dih4 ROTATE_90_CLOCKWISE;
static Dih4 REFLECT_VERTICAL;
static Dih4 REFLECT_FORWARD_DIAGONAL;
static Dih4 REFLECT_HORIZONTAL;
static Dih4 REFLECT_REVERSE_DIAGONAL;
Dih4(int tr = 0) : _tr(tr) { }
bool is_rotation() const { return _tr < 4; }
bool is_reflection() const { return !is_rotation(); }
Dih4 inv() const
{
if (_tr == 1) return Dih4(3);
if (_tr == 3) return Dih4(1);
return Dih4(_tr);
}
Dih4 then(Dih4 to) const
{
static const int m_tr[8][8] = {
{0, 1, 2, 3, 4, 5, 6, 7 },
{1, 2, 3, 0, 5, 6, 7, 4 },
{2, 3, 0, 1, 6, 7, 4, 5 },
{3, 0, 1, 2, 7, 4, 5, 6 },
{4, 7, 6, 5, 0, 3, 2, 1 },
{5, 4, 7, 6, 1, 0, 3, 2 },
{6, 5, 4, 7, 2, 1, 0, 3 },
{7, 6, 5, 4, 3, 2, 1, 0 }
};
return Dih4(m_tr[_tr][to._tr]);
}
bool operator==(const Dih4 &o) const { return _tr == o._tr; }
bool operator!=(const Dih4 &o) const { return !(*this == o); }
};
Dih4 Dih4::IDENTITY(0);
Dih4 Dih4::ROTATE_90_ANTICLOCKWISE(1);
Dih4 Dih4::ROTATE_180(2);
Dih4 Dih4::ROTATE_90_CLOCKWISE(3);
Dih4 Dih4::REFLECT_VERTICAL(4);
Dih4 Dih4::REFLECT_FORWARD_DIAGONAL(5);
Dih4 Dih4::REFLECT_HORIZONTAL(6);
Dih4 Dih4::REFLECT_REVERSE_DIAGONAL(7);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fun with trees : array to tree
// https://www.codewars.com/kata/fun-with-trees-array-to-tree/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
class TreeNode
{
public:
int m_value;
TreeNode* m_left;
TreeNode* m_right;
TreeNode(int value, TreeNode* left, TreeNode* right) : m_value(value), m_left(left), m_right(right) { }
TreeNode(int value) : m_value(value), m_left(nullptr), m_right(nullptr) { }
};
class Solution
{
public:
static TreeNode* arrayToTree(const std::vector<int>& arr, size_t i = 0)
{
if (i >= arr.size()) return nullptr;
return new TreeNode(arr[i], arrayToTree(arr, 2 * i + 1), arrayToTree(arr, 2 * i + 2));
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Simple Encryption #3 - Turn The Bits Around
// https://www.codewars.com/kata/simple-encryption-number-3-turn-the-bits-around/cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
const std::string region3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .";
void to_codes(std::string& text)
{
for (size_t i = 0; i < text.length(); i++)
{
auto code = region3.find(text[i]);
if (code == region3.npos)
throw std::exception("unknown symbol");
else
text[i] = static_cast<char>(code);
}
}
void to_chars(std::string& codes)
{
for (size_t i = 0; i < codes.length(); i++)
codes[i] = region3[codes[i]];
}
union cOdE {
struct {
char code;