Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CodeWars #28

Closed
wants to merge 55 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
d129605
Convert string to camel case.py
mutil2 Sep 17, 2024
3d68980
Duplicate Encoder.py
mutil2 Sep 17, 2024
a4819bd
Find the missing letter.py
mutil2 Sep 17, 2024
2412db7
Merge two arrays.js
mutil2 Sep 17, 2024
e93e494
Moving Zeros To The End.py
mutil2 Sep 17, 2024
a8fe327
Tic-Tac-Toe Checker.py
mutil2 Sep 17, 2024
7eca1f7
Linked List - Sorted Insert.py
mutil2 Sep 17, 2024
413af94
Sum of Digits - Digital Root.py
mutil2 Sep 17, 2024
ac89d26
Build Tower.py
mutil2 Sep 17, 2024
f0c5e57
Array Deep Count.py
mutil2 Sep 17, 2024
dd1753c
Flatten a Nested Map.js
mutil2 Sep 21, 2024
d0de999
Sum of Intervals.py
mutil2 Sep 21, 2024
c23b0d6
Anagram difference.py
mutil2 Sep 23, 2024
bcbd9a2
Sum of Pairs.py
mutil2 Sep 23, 2024
85eb1dd
Valid Parentheses.py
mutil2 Sep 23, 2024
5e2a013
Product of consecutive Fib numbers.py
mutil2 Sep 23, 2024
8c05d0c
Snail.py
mutil2 Sep 23, 2024
797dae4
Adding Big Numbers.js
mutil2 Sep 23, 2024
5f9a820
Simple Pig Latin.py
mutil2 Sep 23, 2024
15d7af6
Fun with trees: max sum.py
mutil2 Sep 23, 2024
13aee0a
Where my anagrams at.py
mutil2 Sep 23, 2024
1edb255
Permutations.py
mutil2 Sep 23, 2024
87eb6e0
Lab1
mutil2 Oct 1, 2024
582f091
Create tasks.ts
mutil2 Dec 10, 2024
6190813
Update index.ts
mutil2 Dec 10, 2024
c3e8f79
Create taskAB.spec.ts
mutil2 Dec 10, 2024
22f9d66
Update taskAB.spec.ts
mutil2 Dec 10, 2024
dc31877
formula.spec.ts
mutil2 Dec 10, 2024
14edd64
lab1.ts
mutil2 Dec 17, 2024
16cf92a
lab2.ts
mutil2 Dec 17, 2024
a7d9e00
lab3.ts
mutil2 Dec 17, 2024
e32aa3a
Delete rpgsaga/saga/tests/example.spec.ts
mutil2 Dec 17, 2024
08aa300
Delete rpgsaga/saga/tests/taskAB.spec.ts
mutil2 Dec 17, 2024
79d4249
lab1.spec.ts
mutil2 Dec 17, 2024
3d33816
Hero.ts
mutil2 Dec 17, 2024
70e63d4
HeroFactory.ts
mutil2 Dec 17, 2024
cc5f087
HeroFactory.ts
mutil2 Dec 17, 2024
0a96f44
Hero.ts
mutil2 Dec 17, 2024
0351cb3
Knight.ts
mutil2 Dec 17, 2024
1003f77
Mage.ts
mutil2 Dec 17, 2024
de70184
Archer.ts
mutil2 Dec 17, 2024
fd08dac
Game.ts
mutil2 Dec 17, 2024
9d330e6
Logger.ts
mutil2 Dec 17, 2024
4069d7e
index.ts
mutil2 Dec 17, 2024
cb79844
HeroFactory.spec.ts
mutil2 Dec 17, 2024
15dbd46
Knight.spec.ts
mutil2 Dec 17, 2024
c65c121
Mage.spec.ts
mutil2 Dec 17, 2024
954726a
Archer.spec.ts
mutil2 Dec 17, 2024
0e02ca4
lab2.spec.ts
mutil2 Dec 17, 2024
122d5d1
lab2.spec.ts
mutil2 Dec 17, 2024
b4c0b62
lab3.spec.ts
mutil2 Dec 17, 2024
68596ca
example.spec.ts
mutil2 Dec 17, 2024
016218b
example.spec.ts
mutil2 Dec 17, 2024
774c9f7
example.spec.ts
mutil2 Dec 17, 2024
9ddb7c7
example.spec.ts
mutil2 Dec 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions codewars/Adding Big Numbers/Adding Big Numbers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function add(num1, num2) {
let result = '';
let carry = 0;
while (num1.length < num2.length) num1 = '0' + num1;
while (num2.length < num1.length) num2 = '0' + num2;
for (let i = num1.length - 1; i >= 0; i--) {
let sum = parseInt(num1[i]) + parseInt(num2[i]) + carry;
let digit = sum % 10;
carry = Math.floor(sum / 10);
result = digit + result;
}
if (carry > 0) {
result = carry + result;
}
return result;
}
3 changes: 3 additions & 0 deletions codewars/Anagram difference/Anagram difference.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
def anagram_difference(word1, word2):
from collections import Counter
return sum((Counter(word1) - Counter(word2)).values()) + sum((Counter(word2) - Counter(word1)).values())
7 changes: 7 additions & 0 deletions codewars/Array Deep Count/Array Deep Count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def deep_count(a):
count = 0
for element in a:
if isinstance(element, list):
count += deep_count(element)
count += 1
return count
8 changes: 8 additions & 0 deletions codewars/Build Tower/Build Tower.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def tower_builder(n_floors):
tower = []
for i in range(1, n_floors + 1):
num_spaces = n_floors - i
num_stars = 2 * i - 1
tower.append(" " * num_spaces + "*" * num_stars + " " * num_spaces)
return tower
print(tower_builder(2))
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def to_camel_case(s):
if not s:
return ""
words = s.replace('-', ' ').replace('_', ' ').split()
camel_case = words[0] + ''.join(word.capitalize() for word in words[1:])
return camel_case
print(to_camel_case("the-stealth-warrior"))
print(to_camel_case("The_Stealth_Warrior"))
print(to_camel_case("The_Stealth-Warrior"))
print(to_camel_case(""))
9 changes: 9 additions & 0 deletions codewars/Duplicate Encoder/Duplicate Encoder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def duplicate_encode(s):
char_count ={}
for char in s.lower():
char_count[char] = char_count.get(char, 0) + 1
result = ""
for char in s:
result += "(" if char_count[char.lower()] == 1 else ")"
return result
print(duplicate_encode("(( @"))
5 changes: 5 additions & 0 deletions codewars/Find the missing letter/Find the missing letter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def find_missing_letter(chars):
for i in range(len(chars) - 1):
if ord(chars[i + 1]) - ord(chars[i]) > 1:
return chr(ord(chars[i]) + 1)
print(find_missing_letter(['a', 'b', 'c', 'd', 'f']))
45 changes: 45 additions & 0 deletions codewars/Flatten a Nested Map/Flatten a Nested Map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
function flattenMap(map) {
let flattenedMap = {};

function flattenRecursive(map, prefix = "") {
for (let [key, value] of Object.entries(map)) {
let newPrefix = prefix ? prefix + key + "/" : key + "/";

if (typeof value === "object" && value !== null && !Array.isArray(value)) {
flattenRecursive(value, newPrefix);
} else {
flattenedMap[newPrefix.slice(0, -1)] = value;
}
}
}

flattenRecursive(map);
return flattenedMap;
}

// Test case
const testMap = {
a: {
b: {
c: 12,
d: "Hello World"
},
e: [1, 2, 3]
}
};

// Expected flattened structure
const expectedOutput = {
'a/b/c': 12,
'a/b/d': 'Hello World',
'a/e': [1, 2, 3]
};

const actualOutput = flattenMap(testMap);

const assert = require('assert');

// Ensure deep equality
assert.deepEqual(actualOutput, expectedOutput);

console.log("Test passed!");
21 changes: 21 additions & 0 deletions codewars/Fun with tree - max sum/Fun with trees: max sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class TreeNode:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right

def max_sum(root):
# If the root is None, the tree is empty, return 0
if root is None:
return 0

# If it's a leaf node, return its value
if root.left is None and root.right is None:
return root.value

# Recursively find the maximum sum for the left and right subtrees
left_sum = max_sum(root.left) if root.left is not None else float('-inf')
right_sum = max_sum(root.right) if root.right is not None else float('-inf')

# Return the current node's value plus the maximum of the left or right subtree sums
return root.value + max(left_sum, right_sum)
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Node:
def __init__(self, data):
self.data = data
self.next = None
def buildOneTwoThree():
head = Node(1)
second =Node(2)
third = Node(3)
head.next = second
second.next = third
return head
def sorted_insert(head, data):
newNode = Node(data)
if head is None or head.data >= data:
newNode.next = head
head = newNode
else:
current = head
while current.next is not None and current.next.data < data:
current = current.next
newNode.next = current.next
current.next = newNode
return head
head = buildOneTwoThree()
sorted_insert(head, 5)
21 changes: 21 additions & 0 deletions codewars/Merge two arrays/Merge two arrays.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function mergeArrays(array1, array2) {
let combinedResult = [];
let index1 = 0;
let index2 = 0;

while (index1 < array1.length || index2 < array2.length) {
if (index1 < array1.length) {
combinedResult.push(array1[index1]);
index1 += 1;
}
if (index2 < array2.length) {
combinedResult.push(array2[index2]);
index2 += 1;
}
}
return combinedResult;
}

const array2 = ['a', 'b', 'c', 'd', 'e', 'f'];
const array1 = [1, 2, 3];
console.log(mergeArrays(array1, array2));
8 changes: 8 additions & 0 deletions codewars/Moving Zeros To The End/Moving Zeros To The End.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def move_zeros(lst):
slow = 0
for fast in range(len(lst)):
if lst[fast] != 0:
lst[slow], lst[fast] = lst[fast], lst[slow]
slow += 1
return lst
print(move_zeros([1, 0, 1, 2, 0, 1, 3]))
12 changes: 12 additions & 0 deletions codewars/Permutations/Permutations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def permutations(s):
if len(s) == 0:
return ['']
perm_list = []
for i in range(len(s)):
m = s[i]
remaining_list = s[:i] + s[i+1:]
subperm_list = permutations(remaining_list)
for p in subperm_list:
perm_list.append(m + p)
return set(perm_list)
print(permutations('abc'))
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def productFib(prod):
n = 0
nPlus = 1
while n * nPlus < prod:
nPlus = n + nPlus
n = nPlus - n
return [n, nPlus, n * nPlus == prod]
20 changes: 20 additions & 0 deletions codewars/Simple Pig Latin/Simple Pig Latin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import string

def pig_it(text):
words = text.split()
transformed_words = []

for word in words:
if word[-1] in string.punctuation:
punctuation = word[-1]
word = word[:-1]
else:
punctuation = ''

if word:
transformed_word = word[1:] + word[0] + 'ay' + punctuation
transformed_words.append(transformed_word)
else:
transformed_words.append(punctuation)

return ' '.join(transformed_words)
13 changes: 13 additions & 0 deletions codewars/Snail/Snail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def snail(array):
if len(array) == 0:
return []
if len(array) == 1:
return array[0]

top = array[0][:-1]
right = [a[-1] for a in array]
bottom = array[-1][:-1][::-1]
left = [b[0] for b in array[1:-1]][::-1]
inner = [c[1:-1] for c in array[1:-1]]

return top + right + bottom + left + snail(inner)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def digital_root(n):
while n > 9:
n = sum((int(digit)) for digit in str(n))
return n
11 changes: 11 additions & 0 deletions codewars/Sum of Intervals/Sum of Intervals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def sum_of_intervals(intervals):
intervals = sorted(intervals)
merged = [intervals[0]]

for interval in intervals[1:]:
if interval[0] <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], interval[1]))
else:
merged.append(interval)

return sum(end - start for start, end in merged)
9 changes: 9 additions & 0 deletions codewars/Sum of pairs/Sum of Pairs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def sum_pairs(ints, s):
seen = {}
for i, num in enumerate(ints):
complement = s - num
if complement in seen:
return [complement, num]
else:
seen[num] = i
return None
27 changes: 27 additions & 0 deletions codewars/Tic-Tac-Toe Checker/Tic-Tac-Toe Checker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def is_solved (board):
for row in board:
if row[0] == row[1] == row[2] and row[0] != 0:
return row[0]
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] and board[0][col] != 0:
return board[0][col]
if board[0][0] == board[1][1] == board[2][2] and board[0][0] != 0:
return board[0][0]
if board[0][2] == board[1][1] == board [2][0] and board[0][2] != 0:
return board[0][2]
for row in board:
if 0 in row:
return -1
return 0
board = [[0, 0, 1],
[0, 1, 2],
[2, 1, 0]]
winner = is_solved(board)
if winner == -1:
print("The game is not finished")
elif winner == 1:
print("X won!")
elif winner == 2:
print("0 won!")
else:
print("It's a cat's game.")
10 changes: 10 additions & 0 deletions codewars/Valid Parentheses/Valid Parentheses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def valid_parentheses(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return not stack
3 changes: 3 additions & 0 deletions codewars/Where my anagrams at/Where my anagrams at.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
def anagrams(word, words):
sorted_word = sorted(word)
return [w for w in words if sorted(w) == sorted_word]
69 changes: 69 additions & 0 deletions rpgsaga/saga/src/abstract/Hero.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
export abstract class Hero {
protected health: number;
protected strength: number;
protected readonly name: string;

constructor(name: string, health: number, strength: number) {
this.name = name;
this.health = health;
this.strength = strength;
}

abstract attack(target: Hero, useAbility?: boolean): void;

public getName(): string {
return this.name;
}

public getHealth(): number {
return this.health;
}

protected takeDamage(damage: number): void {
this.health = Math.max(this.health - damage, 0);
}
}

export class Knight extends Hero {
attack(target: Hero, useAbility: boolean = false): void {
let damage = this.strength;
if (useAbility) {
damage = Math.floor(this.strength * 1.3);
Logger.log(`${this.name} uses Vengeance Strike!`);
}
target.takeDamage(damage);
Logger.log(`${this.name} deals ${damage} damage to ${target.getName()}`);
}
}

export class Mage extends Hero {
private isStunned: boolean = false;

attack(target: Hero, useAbility: boolean = false): void {
if (useAbility) {
this.isStunned = true;
Logger.log(`${this.name} uses Charm! ${target.getName()} misses next turn.`);
} else {
target.takeDamage(this.strength);
Logger.log(`${this.name} deals ${this.strength} damage to ${target.getName()}`);
}
}

public isImmuneToFreeze(): boolean {
return true;
}
}

export class Archer extends Hero {
private burnTurns: number = 0;

attack(target: Hero, useAbility: boolean = false): void {
if (useAbility && this.burnTurns === 0) {
this.burnTurns = 3;
Logger.log(`${this.name} uses Flaming Arrows! ${target.getName()} is burning.`);
} else {
target.takeDamage(this.strength);
Logger.log(`${this.name} deals ${this.strength} damage to ${target.getName()}`);
}
}
}
Loading