mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-23 08:53:48 +01:00
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
commit
fc899b0b02
217 changed files with 5356 additions and 0 deletions
127
3kyu/battleship_field_validator/solution.cs
Normal file
127
3kyu/battleship_field_validator/solution.cs
Normal file
|
@ -0,0 +1,127 @@
|
|||
namespace Solution {
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class BattleshipField {
|
||||
private enum Direction {
|
||||
HORIZONTAL,
|
||||
VERTICAL
|
||||
}
|
||||
|
||||
private class Ship {
|
||||
private int y, x;
|
||||
private Direction d;
|
||||
private int size;
|
||||
|
||||
public int Size {get => size;}
|
||||
|
||||
public Ship(int y, int x, Direction d, int size) {
|
||||
this.y = y;
|
||||
this.x = x;
|
||||
this.d = d;
|
||||
this.size = size;
|
||||
}
|
||||
public bool IsTouching(Ship b) {
|
||||
if (d == Direction.HORIZONTAL) {
|
||||
if ((b.y >= this.y - 1 && b.y <= this.y + 1) &&
|
||||
(b.x >= this.x - 1 && b.x <= this.x + this.size))
|
||||
return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
if (d == Direction.VERTICAL) {
|
||||
if ((b.x >= this.x - 1 && b.x <= this.x + 1) &&
|
||||
(b.y >= this.y - 1 && b.y <= this.y + this.size))
|
||||
return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
public override string ToString() {
|
||||
string direction = this.d == Direction.HORIZONTAL ? "horizontal" : "vertical";
|
||||
return $"x: {this.x}\ty: {this.y}\tdir: {direction}\tsize: {this.size}";
|
||||
}
|
||||
}
|
||||
|
||||
private List<Ship> ships;
|
||||
private int battleships = 1,
|
||||
cruisers = 2,
|
||||
destroyers = 3,
|
||||
submarines = 4;
|
||||
|
||||
public BattleshipField() {
|
||||
this.ships = new List<Ship>();
|
||||
}
|
||||
|
||||
private void registerShip(int y, int x, Direction d, int count) {
|
||||
this.ships.Add(new Ship(y, x, d, count));
|
||||
switch (count) {
|
||||
case 1:
|
||||
this.submarines--;
|
||||
break;
|
||||
case 2:
|
||||
this.destroyers--;
|
||||
break;
|
||||
case 3:
|
||||
this.cruisers--;
|
||||
break;
|
||||
case 4:
|
||||
this.battleships--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private bool areTouching() {
|
||||
for (var i = 0; i < this.ships.Count - 1; i++)
|
||||
for (var j = i + 1; j < this.ships.Count; j++)
|
||||
if (this.ships[i].IsTouching(this.ships[j])) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool IsValidField() {
|
||||
if (this.submarines != 0 || this.destroyers != 0 ||
|
||||
this.cruisers != 0 || this.battleships != 0)
|
||||
return false;
|
||||
else if (this.areTouching())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool ValidateBattlefield(int[,] field) {
|
||||
// Write your magic here
|
||||
var validator = new BattleshipField();
|
||||
int count = 0;
|
||||
|
||||
for (int y = 0, rows = field.GetLength(0); y < rows; y++) {
|
||||
for (int x = 0, cols = field.GetLength(0); x < cols; x++) {
|
||||
if (field[y, x] == 1) {
|
||||
// check for vertical ship
|
||||
if (count == 0) {
|
||||
if (y < rows - 1 && field[y + 1, x] == 1) {
|
||||
for (int dy = 0; y + dy < rows; dy++) {
|
||||
if (field[y + dy, x] == 1) {
|
||||
field[y + dy, x] = 0;
|
||||
count++;
|
||||
} else break;
|
||||
}
|
||||
|
||||
if (count > 1) {
|
||||
validator.registerShip(y, x, Direction.VERTICAL, count);
|
||||
count = 0;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
field[y, x] = 0;
|
||||
count++;
|
||||
} else if (field[y, x] == 0 && count > 0) {
|
||||
validator.registerShip(y, x - count, Direction.HORIZONTAL, count);
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return validator.IsValidField();
|
||||
}
|
||||
}
|
||||
}
|
103
3kyu/binomial_expansion/solution.cs
Normal file
103
3kyu/binomial_expansion/solution.cs
Normal file
|
@ -0,0 +1,103 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class KataSolution {
|
||||
public static IEnumerable<long> Combinations(long n) {
|
||||
if (n < 0) {
|
||||
Console.WriteLine("Error happened");
|
||||
throw new ArgumentException("n cannot be negative");
|
||||
}
|
||||
|
||||
for (
|
||||
long k = 0, nCk = 1;
|
||||
k <= n;
|
||||
nCk = nCk * (n - k) / (k + 1), k++
|
||||
) {
|
||||
yield return nCk;
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<long> Range(long count) {
|
||||
for (var i = 0; i < count; i++) {
|
||||
yield return i;
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<long> Expand(int a, int b, int n) {
|
||||
long aExpd = (long) Math.Pow(a, n);
|
||||
long bExpd = 1;
|
||||
foreach (var nCk in Combinations(n)) {
|
||||
yield return nCk * aExpd * bExpd;
|
||||
|
||||
aExpd /= a;
|
||||
bExpd *= b;
|
||||
}
|
||||
}
|
||||
|
||||
public static (int, int, string) ParseInner(string expr) {
|
||||
var innerPart = expr.Split('^')[0];
|
||||
innerPart = innerPart.Substring(1, innerPart.Length - 2);
|
||||
|
||||
var coeffA = new String(
|
||||
innerPart.TakeWhile(c => !char.IsLetter(c)).ToArray()
|
||||
);
|
||||
var variable = new String(
|
||||
innerPart.SkipWhile(c => !char.IsLetter(c)).TakeWhile(char.IsLetter).ToArray()
|
||||
);
|
||||
var coeffB = new String(
|
||||
innerPart.SkipWhile(c => !char.IsLetter(c)).SkipWhile(char.IsLetter).ToArray()
|
||||
);
|
||||
|
||||
var parsedCoeffA = coeffA switch {
|
||||
"" => 1,
|
||||
"-" => -1,
|
||||
_ => int.Parse(coeffA)
|
||||
};
|
||||
|
||||
return (parsedCoeffA, int.Parse(coeffB), variable);
|
||||
}
|
||||
|
||||
public static int ParseExponent(string expr) {
|
||||
var splitExpr = expr.Split('^');
|
||||
return int.Parse(splitExpr[1]);
|
||||
}
|
||||
|
||||
public static string FormatTerm(long coefficient, string variable, long exponent) {
|
||||
var prefix = (coefficient > 0) ? "+" : "";
|
||||
|
||||
if (coefficient == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if ((coefficient == 1 || coefficient == -1) && exponent == 0) {
|
||||
return $"{prefix}{coefficient}";
|
||||
}
|
||||
|
||||
var coeff = coefficient switch {
|
||||
0 => "",
|
||||
1 => prefix,
|
||||
-1 => "-",
|
||||
_ => $"{prefix}{coefficient}"
|
||||
};
|
||||
var varExp = exponent switch {
|
||||
0 => "",
|
||||
1 => variable,
|
||||
_ => $"{variable}^{exponent}"
|
||||
};
|
||||
return $"{coeff}{varExp}";
|
||||
}
|
||||
|
||||
public static string Expand(string expr) {
|
||||
var n = ParseExponent(expr);
|
||||
var (a, b, variable) = ParseInner(expr);
|
||||
|
||||
var result = "";
|
||||
|
||||
foreach (var (exponent, coefficient) in Range(n + 1).Reverse().Zip(Expand(a, b, n))) {
|
||||
result += FormatTerm(coefficient, variable, exponent);
|
||||
}
|
||||
|
||||
return result.TrimStart(new char[] {'+'});
|
||||
}
|
||||
}
|
88
3kyu/screen_locking_patterns/solution.cs
Normal file
88
3kyu/screen_locking_patterns/solution.cs
Normal file
|
@ -0,0 +1,88 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public static class Kata {
|
||||
private class Graph {
|
||||
private struct Edge {
|
||||
public char Through { get; set; }
|
||||
public char To { get; set; }
|
||||
};
|
||||
|
||||
public static readonly char NO_CONDITION = '\0';
|
||||
|
||||
private Dictionary<char, List<Edge>> edges = new Dictionary<char, List<Edge>>();
|
||||
private HashSet<char> visited = new HashSet<char>();
|
||||
|
||||
private Graph addEdge(char src, char through, char dst) {
|
||||
var newEdge = new Edge {
|
||||
Through = through,
|
||||
To = dst
|
||||
};
|
||||
|
||||
if (edges.TryGetValue(src, out var lst)) {
|
||||
lst.Add(newEdge);
|
||||
} else {
|
||||
edges.Add(src, new List<Edge>() { newEdge });
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public Graph AddDirectEdge(char src, char dst)
|
||||
=> addEdge(src, NO_CONDITION, dst);
|
||||
public Graph AddIndirectEdge(char src, char through, char dst)
|
||||
=> addEdge(src, through, dst);
|
||||
public Graph AddBiDirectEdge(char src, char dst)
|
||||
=> AddBiIndirectEdge(src, NO_CONDITION, dst);
|
||||
public Graph AddBiIndirectEdge(char src, char through, char dst) =>
|
||||
addEdge(src, through, dst)
|
||||
.addEdge(dst, through, src);
|
||||
|
||||
public void ResetVisited() => visited.Clear();
|
||||
public bool BeenVisited(char vertex) => visited.Contains(vertex);
|
||||
public void Mark(char vertex) => visited.Add(vertex);
|
||||
public void Unmark(char vertex) => visited.Remove(vertex);
|
||||
|
||||
public bool HasEdge(char fromVertex, char toVertex)
|
||||
=> edges[fromVertex].Any(e => e.To == toVertex && (e.Through == NO_CONDITION || BeenVisited(e.Through)));
|
||||
|
||||
public Graph AddMultipleBiDirectEdges(char fromVertex, string toVertices) {
|
||||
foreach (var toVertex in toVertices) {
|
||||
AddBiDirectEdge(fromVertex, toVertex);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
private static Graph g = new Graph()
|
||||
.AddMultipleBiDirectEdges('A', "BDEFH").AddMultipleBiDirectEdges('B', "CDEFGI")
|
||||
.AddMultipleBiDirectEdges('C', "DEFH").AddMultipleBiDirectEdges('D', "EGHI")
|
||||
.AddMultipleBiDirectEdges('E', "FGHI").AddMultipleBiDirectEdges('F', "GHI")
|
||||
.AddMultipleBiDirectEdges('G', "H").AddMultipleBiDirectEdges('H', "I")
|
||||
.AddBiIndirectEdge('A', 'B', 'C').AddBiIndirectEdge('A', 'D', 'G').AddBiIndirectEdge('A', 'E', 'I')
|
||||
.AddBiIndirectEdge('B', 'E', 'H').AddBiIndirectEdge('C', 'E', 'G').AddBiIndirectEdge('C', 'F', 'I')
|
||||
.AddBiIndirectEdge('D', 'E', 'F').AddBiIndirectEdge('G', 'H', 'I');
|
||||
|
||||
public static int CountPatternsFrom(char firstDot, int length) {
|
||||
if (length <= 0 || length >= 10) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (length == 1) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int total = 0;
|
||||
|
||||
g.Mark(firstDot);
|
||||
foreach (var vertex in "ABCDEFGHI") {
|
||||
if (!g.BeenVisited(vertex) && g.HasEdge(firstDot, vertex)) {
|
||||
total += CountPatternsFrom(vertex, length - 1);
|
||||
}
|
||||
}
|
||||
g.Unmark(firstDot);
|
||||
|
||||
return total;
|
||||
}
|
||||
}
|
181
4kyu/4_by_4_skyscrapers/solution.cs
Normal file
181
4kyu/4_by_4_skyscrapers/solution.cs
Normal file
|
@ -0,0 +1,181 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class Skyscrapers {
|
||||
private static IEnumerable<List<T>> Permutations<T>(List<T> initial)
|
||||
where T: IComparable<T> {
|
||||
yield return initial;
|
||||
|
||||
var hasNext = initial.Count > 1;
|
||||
while (hasNext) {
|
||||
var k = 0;
|
||||
var l = 0;
|
||||
hasNext = false;
|
||||
|
||||
for (var i = initial.Count - 1; i > 0; i--) {
|
||||
if (initial[i].CompareTo(initial[i - 1]) > 0) {
|
||||
k = i - 1;
|
||||
hasNext = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = initial.Count - 1; i > k; i--) {
|
||||
if (initial[i].CompareTo(initial[k]) > 0) {
|
||||
l = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
(initial[k], initial[l]) = (initial[l], initial[k]);
|
||||
initial.Reverse(k + 1, initial.Count - k - 1);
|
||||
|
||||
if (hasNext) {
|
||||
yield return initial;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsValid(List<int> heights, int clue) {
|
||||
var canSee = 1;
|
||||
var lastHeight = heights[0];
|
||||
|
||||
for (var i = 1; i < heights.Count; i++) {
|
||||
var currentHeight = heights[i];
|
||||
if (currentHeight > lastHeight) {
|
||||
lastHeight = currentHeight;
|
||||
canSee++;
|
||||
}
|
||||
}
|
||||
|
||||
return canSee == clue;
|
||||
}
|
||||
|
||||
private static IEnumerable<List<int>> PossibleHeights(int size, int clue) {
|
||||
var initial = new List<int>();
|
||||
for (var i = 0; i < size; i++) {
|
||||
initial.Add(i + 1);
|
||||
}
|
||||
|
||||
if (clue == 0) {
|
||||
return Permutations(initial);
|
||||
}
|
||||
|
||||
return Permutations(initial).Where(heights => IsValid(heights, clue));
|
||||
}
|
||||
|
||||
private static int Size {
|
||||
get => 4;
|
||||
}
|
||||
|
||||
private static (int, int) GetDiffs(int clueIndex) {
|
||||
if (clueIndex < Size) {
|
||||
return (0, 1);
|
||||
} else if (clueIndex < 2 * Size) {
|
||||
return (-1, 0);
|
||||
} else if (clueIndex < 3 * Size) {
|
||||
return (0, -1);
|
||||
}
|
||||
return (1, 0);
|
||||
}
|
||||
|
||||
private static (int, int) GetStarts(int clueIndex) {
|
||||
if (clueIndex < Size) {
|
||||
return (clueIndex, 0);
|
||||
} else if (clueIndex < 2 * Size) {
|
||||
return (Size - 1, clueIndex % Size);
|
||||
} else if (clueIndex < 3 * Size) {
|
||||
return (Size - 1 - clueIndex % Size, Size - 1);
|
||||
}
|
||||
return (0, Size - 1 - clueIndex % Size);
|
||||
}
|
||||
|
||||
private static List<int> BackupHeights(int[][] heights, int clueIndex) {
|
||||
var backup = new List<int>();
|
||||
|
||||
var (dx, dy) = GetDiffs(clueIndex);
|
||||
for (
|
||||
var (x, y) = GetStarts(clueIndex);
|
||||
x >= 0 && x < Size && y >= 0 && y < Size;
|
||||
x += dx, y += dy
|
||||
) {
|
||||
backup.Add(heights[y][x]);
|
||||
}
|
||||
|
||||
return backup;
|
||||
}
|
||||
|
||||
private static bool EmplaceHeights(
|
||||
int[][] heights, int clueIndex, List<int> newHeights, bool force
|
||||
) {
|
||||
int i = 0;
|
||||
|
||||
var (dx, dy) = GetDiffs(clueIndex);
|
||||
for (
|
||||
var (x, y) = GetStarts(clueIndex);
|
||||
x >= 0 && x < Size && y >= 0 && y < Size;
|
||||
x += dx, y += dy
|
||||
) {
|
||||
if (
|
||||
!force && heights[y][x] != 0 && heights[y][x] != newHeights[i]
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
heights[y][x] = newHeights[i++];
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool SolvePuzzle(
|
||||
int[][] heights, int[] clues, int clueIndex, bool ignoreZeroes
|
||||
) {
|
||||
while (clueIndex < 4 * Size && (
|
||||
(ignoreZeroes && clues[clueIndex] == 0) || (!ignoreZeroes && clues[clueIndex] != 0)
|
||||
)) {
|
||||
clueIndex++;
|
||||
}
|
||||
|
||||
if (clueIndex >= 4 * Size) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// create copy of heights to ensure correct resetting
|
||||
var currentHeights = BackupHeights(heights, clueIndex);
|
||||
|
||||
// iterate through the options
|
||||
foreach (var possibleHeights in PossibleHeights(Size, clues[clueIndex])) {
|
||||
// emplace heights and if conflict occurs, reset and try next one
|
||||
if (!EmplaceHeights(heights, clueIndex, possibleHeights, false)) {
|
||||
EmplaceHeights(heights, clueIndex, currentHeights, true);
|
||||
continue;
|
||||
}
|
||||
|
||||
// if no conflict present, try filling out other clues
|
||||
if (SolvePuzzle(heights, clues, clueIndex + 1, ignoreZeroes)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// otherwise reset heights and try again
|
||||
EmplaceHeights(heights, clueIndex, currentHeights, true);
|
||||
}
|
||||
|
||||
// if we got here, there is no feasible configuration of buildings
|
||||
return false;
|
||||
}
|
||||
|
||||
public static int[][] SolvePuzzle(int[] clues) {
|
||||
var result = new int[Size][];
|
||||
for (var i = 0; i < Size; i++) {
|
||||
result[i] = new int[Size];
|
||||
}
|
||||
SolvePuzzle(result, clues, 0, true);
|
||||
|
||||
// in case there are left zeroes
|
||||
SolvePuzzle(result, clues, 0, false);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
264
4kyu/4_by_4_skyscrapers/solution.java
Normal file
264
4kyu/4_by_4_skyscrapers/solution.java
Normal file
|
@ -0,0 +1,264 @@
|
|||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public class SkyScrapers {
|
||||
private static class Permutations<T extends Comparable<T>> implements Iterable<List<T>> {
|
||||
public class PermutationsIterator implements Iterator<List<T>> {
|
||||
private List<T> elements;
|
||||
private boolean _hasNext;
|
||||
private boolean firstIteration = true;
|
||||
|
||||
public PermutationsIterator(List<T> elements) {
|
||||
this.elements = elements;
|
||||
_hasNext = elements.size() > 0;
|
||||
}
|
||||
|
||||
private void swap(int k, int l) {
|
||||
T tmp = elements.get(k);
|
||||
elements.set(k, elements.get(l));
|
||||
elements.set(l, tmp);
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return _hasNext;
|
||||
}
|
||||
|
||||
public List<T> next() {
|
||||
if (!_hasNext) {
|
||||
throw new NoSuchElementException("No more permutations are left");
|
||||
}
|
||||
|
||||
var lastIteration = new ArrayList<T>(elements);
|
||||
|
||||
int k = 0, l = 0;
|
||||
_hasNext = false;
|
||||
for (int i = elements.size() - 1; i > 0; i--) {
|
||||
if (elements.get(i).compareTo(elements.get(i - 1)) > 0) {
|
||||
k = i - 1;
|
||||
_hasNext = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = elements.size() - 1; i > k; i--) {
|
||||
if (elements.get(i).compareTo(elements.get(k)) > 0) {
|
||||
l = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
swap(k, l);
|
||||
Collections.reverse(elements.subList(k + 1, elements.size()));
|
||||
|
||||
return lastIteration;
|
||||
}
|
||||
}
|
||||
|
||||
private List<T> elements;
|
||||
|
||||
public Permutations(List<T> elements) {
|
||||
this.elements = elements;
|
||||
Collections.sort(this.elements);
|
||||
}
|
||||
|
||||
public Iterator<List<T>> iterator() {
|
||||
return new PermutationsIterator(elements);
|
||||
}
|
||||
|
||||
public Stream<List<T>> stream() {
|
||||
return StreamSupport.stream(this.spliterator(), false);
|
||||
}
|
||||
}
|
||||
|
||||
private static class PossibleConfigurations implements Iterable<List<Integer>> {
|
||||
private List<Integer> initial;
|
||||
private int clue;
|
||||
|
||||
private void generateInitial(int size) {
|
||||
initial = new ArrayList<Integer>();
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
initial.add(i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public PossibleConfigurations(int size, int clue) {
|
||||
generateInitial(size);
|
||||
this.clue = clue;
|
||||
}
|
||||
|
||||
public Iterator<List<Integer>> iterator() {
|
||||
if (clue == 0) {
|
||||
return (new Permutations(initial)).iterator();
|
||||
}
|
||||
|
||||
return (new Permutations(initial))
|
||||
.stream()
|
||||
.filter(heights -> isValid((List<Integer>) heights, clue))
|
||||
.iterator();
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isValid(List<Integer> heights, int clue) {
|
||||
int canSee = 1;
|
||||
int lastHeight = heights.get(0);
|
||||
|
||||
for (int i = 1; i < heights.size(); i++) {
|
||||
int currentHeight = heights.get(i);
|
||||
if (currentHeight > lastHeight) {
|
||||
lastHeight = currentHeight;
|
||||
canSee++;
|
||||
}
|
||||
}
|
||||
|
||||
return canSee == clue;
|
||||
}
|
||||
|
||||
private static int getDx(int clueIndex) {
|
||||
if (clueIndex >= 4 && clueIndex <= 7) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (clueIndex >= 12) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int getDy(int clueIndex) {
|
||||
if (clueIndex <= 3) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (clueIndex >= 8 && clueIndex <= 11) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int getStartX(int clueIndex) {
|
||||
if (clueIndex < 4) {
|
||||
return clueIndex;
|
||||
}
|
||||
|
||||
if (clueIndex <= 7) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
if (clueIndex <= 11) {
|
||||
return 3 - clueIndex % 4;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int getStartY(int clueIndex) {
|
||||
if (clueIndex < 4) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (clueIndex <= 7) {
|
||||
return clueIndex % 4;
|
||||
}
|
||||
|
||||
if (clueIndex <= 11) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
return 3 - clueIndex % 4;
|
||||
}
|
||||
|
||||
private static List<Integer> backupHeights(int[][] heights, int clueIndex) {
|
||||
List<Integer> backup = new ArrayList<Integer>();
|
||||
|
||||
int dx = getDx(clueIndex);
|
||||
int dy = getDy(clueIndex);
|
||||
|
||||
for (
|
||||
int x = getStartX(clueIndex), y = getStartY(clueIndex);
|
||||
x >= 0 && x < 4 && y >= 0 && y < 4;
|
||||
x += dx, y += dy
|
||||
) {
|
||||
backup.add(heights[y][x]);
|
||||
}
|
||||
|
||||
return backup;
|
||||
}
|
||||
|
||||
private static boolean emplaceHeights(
|
||||
int[][] heights, int clueIndex, List<Integer> newHeights, boolean force
|
||||
) {
|
||||
int i = 0;
|
||||
int dx = getDx(clueIndex);
|
||||
int dy = getDy(clueIndex);
|
||||
|
||||
for (
|
||||
int x = getStartX(clueIndex), y = getStartY(clueIndex);
|
||||
x >= 0 && x < 4 && y >= 0 && y < 4;
|
||||
x += dx, y += dy
|
||||
) {
|
||||
if (
|
||||
!force && heights[y][x] != 0 && heights[y][x] != newHeights.get(i)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
heights[y][x] = newHeights.get(i++);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean solvePuzzle(
|
||||
int[][] heights, int[] clues, int clueIndex, boolean ignoreZeroes
|
||||
) {
|
||||
while (clueIndex < 16 && ((ignoreZeroes && clues[clueIndex] == 0) || (!ignoreZeroes && clues[clueIndex] != 0))) {
|
||||
clueIndex++;
|
||||
}
|
||||
|
||||
if (clueIndex >= 16) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// create copy of heights to ensure correct resetting
|
||||
List<Integer> currentHeights = backupHeights(heights, clueIndex);
|
||||
|
||||
// iterate through the options
|
||||
for (List<Integer> possibleHeights : new PossibleConfigurations(4, clues[clueIndex])) {
|
||||
|
||||
// emplace heights and if conflict occurs, reset and try next one
|
||||
if (!emplaceHeights(heights, clueIndex, possibleHeights, false)) {
|
||||
emplaceHeights(heights, clueIndex, currentHeights, true);
|
||||
continue;
|
||||
}
|
||||
|
||||
// if no conflict present, try filling out other clues
|
||||
if (solvePuzzle(heights, clues, clueIndex + 1, ignoreZeroes)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// otherwise reset heights and try again
|
||||
emplaceHeights(heights, clueIndex, currentHeights, true);
|
||||
}
|
||||
|
||||
// if we got here, there is no feasible configuration of buildings
|
||||
return false;
|
||||
}
|
||||
|
||||
static int[][] solvePuzzle(int[] clues) {
|
||||
var result = new int[4][4];
|
||||
solvePuzzle(result, clues, 0, true);
|
||||
|
||||
// in case there are left zeroes
|
||||
solvePuzzle(result, clues, 0, false);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
44
4kyu/adding_big_numbers/solution.cs
Normal file
44
4kyu/adding_big_numbers/solution.cs
Normal file
|
@ -0,0 +1,44 @@
|
|||
using System;
|
||||
|
||||
public class Kata {
|
||||
public static (uint remainder, uint digit) SumTwo(char a, char b, uint c = 0) {
|
||||
uint val_a = (uint) a - 48;
|
||||
uint val_b = (uint) b - 48;
|
||||
|
||||
var sum = val_a + val_b + c;
|
||||
return (sum / 10, sum % 10);
|
||||
}
|
||||
public static string Add(string a, string b) {
|
||||
var result = "";
|
||||
|
||||
if (a.Length > b.Length) {
|
||||
var temp = a;
|
||||
a = b;
|
||||
b = temp;
|
||||
}
|
||||
|
||||
int idx_a = a.Length - 1;
|
||||
int idx_b = b.Length - 1;
|
||||
uint remainder = 0;
|
||||
uint last_digit = 0;
|
||||
|
||||
while (idx_a >= 0) {
|
||||
(remainder, last_digit) = SumTwo(a[idx_a], b[idx_b], remainder);
|
||||
result = last_digit.ToString() + result;
|
||||
idx_a--;
|
||||
idx_b--;
|
||||
}
|
||||
|
||||
while (idx_b >= 0) {
|
||||
(remainder, last_digit) = SumTwo('0', b[idx_b], remainder);
|
||||
result = last_digit.ToString() + result;
|
||||
idx_b--;
|
||||
}
|
||||
|
||||
if (remainder > 0) {
|
||||
result = remainder.ToString() + result;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
61
4kyu/breadcrumb_generator/solution.js
Normal file
61
4kyu/breadcrumb_generator/solution.js
Normal file
|
@ -0,0 +1,61 @@
|
|||
function checkExtension(name) {
|
||||
const extensions = ['.html', '.htm', '.php', '.asp'];
|
||||
return name.replace(/\.html/g, '').replace(/\.htm/g, '').replace(/\.php/g, '').replace(/\.asp/g, '');
|
||||
}
|
||||
|
||||
function shorten(name) {
|
||||
if (name.length <= 30) {
|
||||
name = name.replace(/-/g, ' ');
|
||||
} else {
|
||||
const ignore = ["the","of","in","from","by","with","and", "or", "for", "to", "at", "a"];
|
||||
|
||||
name = name.split('-').filter(e => !ignore.includes(e)).map(e => e[0]);
|
||||
name = name.join('');
|
||||
}
|
||||
|
||||
return name.toUpperCase();
|
||||
}
|
||||
|
||||
function buildSegment(url, name, last=false) {
|
||||
if (last) {
|
||||
return `<span class="active">${shorten(checkExtension(name))}</span>`;
|
||||
} else {
|
||||
return `<a href="${url}">${shorten(checkExtension(name))}</a>`;
|
||||
}
|
||||
}
|
||||
|
||||
function generateBC(url, separator) {
|
||||
console.log(url);
|
||||
if (url.includes('//')) {
|
||||
url = url.split('//')[1];
|
||||
}
|
||||
|
||||
url = url.split("/").filter(e => {
|
||||
return !e.startsWith('index');
|
||||
}).map(e => {
|
||||
if (e.includes("#"))
|
||||
return e.substring(0, e.indexOf("#"));
|
||||
else if (e.includes("?"))
|
||||
return e.substring(0, e.indexOf("?"));
|
||||
else
|
||||
return e;
|
||||
});
|
||||
|
||||
let result = [];
|
||||
let path = '/';
|
||||
if ((url.length == 2 && url[1] == '') || url.length == 1) {
|
||||
result.push(buildSegment('/', 'home', true));
|
||||
return result.join('');
|
||||
} else
|
||||
result.push(buildSegment('/', 'home'));
|
||||
|
||||
|
||||
for (let i = 1; i < url.length - 1; i++) {
|
||||
path += `${url[i]}/`;
|
||||
result.push(buildSegment(path, url[i]));
|
||||
}
|
||||
path += `/${url[url.length - 1]}`
|
||||
result.push(buildSegment(path, url[url.length - 1], true));
|
||||
|
||||
return result.join(separator);
|
||||
}
|
28
4kyu/counting_change_combinations/solution.cs
Normal file
28
4kyu/counting_change_combinations/solution.cs
Normal file
|
@ -0,0 +1,28 @@
|
|||
using System;
|
||||
|
||||
public static class Kata {
|
||||
public static int CountCombinations(int money, int[] coins, bool recursivelyCalled = false) {
|
||||
if (money == 0 && recursivelyCalled) return 1;
|
||||
else if (coins.GetLength(0) == 1) {
|
||||
if (money % coins[0] == 0) return 1;
|
||||
else return 0;
|
||||
} else if (!recursivelyCalled) {
|
||||
Array.Sort(coins);
|
||||
Array.Reverse(coins);
|
||||
}
|
||||
|
||||
var result = 0;
|
||||
|
||||
var times = money / coins[0];
|
||||
var newCoins = new int[coins.GetLength(0) - 1];
|
||||
|
||||
for (var i = 0; i < coins.GetLength(0) - 1; i++)
|
||||
newCoins[i] = coins[i + 1];
|
||||
|
||||
for (var i = 0; i <= times; i++) {
|
||||
result += CountCombinations(money - i * coins[0], newCoins, true);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
115
4kyu/es5_generators_i/solution.js
Normal file
115
4kyu/es5_generators_i/solution.js
Normal file
|
@ -0,0 +1,115 @@
|
|||
function generator(sequencer) {
|
||||
return sequencer.apply(
|
||||
null,
|
||||
[]
|
||||
.slice
|
||||
.call(arguments)
|
||||
.slice(1)
|
||||
);
|
||||
}
|
||||
|
||||
function dummySeq() {
|
||||
this.next = function() {
|
||||
return "dummy";
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
function factorialSeq() {
|
||||
this.n = 1;
|
||||
this.i = 0;
|
||||
|
||||
this.next = function() {
|
||||
const value = this.n;
|
||||
|
||||
this.i++;
|
||||
this.n *= this.i;
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
function fibonacciSeq() {
|
||||
this.prev = 0;
|
||||
this.current = 1;
|
||||
|
||||
this.next = function() {
|
||||
const value = this.current;
|
||||
|
||||
const newValue = this.prev + this.current;
|
||||
this.prev = this.current;
|
||||
this.current= newValue;
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
function rangeSeq(start, step) {
|
||||
this.value = start;
|
||||
this.step = step;
|
||||
|
||||
this.next = function() {
|
||||
const oldValue = this.value;
|
||||
this.value += this.step;
|
||||
|
||||
return oldValue;
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
function primeSeq() {
|
||||
const isPrime = function(n) {
|
||||
const top = Math.floor(Math.sqrt(n));
|
||||
for (let i = 2; i <= top; i++) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const nextPrime = function(n) {
|
||||
n++;
|
||||
while (!isPrime(n)) {
|
||||
n++;
|
||||
}
|
||||
|
||||
return n;
|
||||
};
|
||||
|
||||
this.p = 1;
|
||||
|
||||
this.next = function() {
|
||||
this.p = nextPrime(this.p);
|
||||
|
||||
return this.p;
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
function partialSumSeq() {
|
||||
this.values = arguments;
|
||||
this.length = arguments.length;
|
||||
this.runningSum = 0;
|
||||
this.i = 0;
|
||||
|
||||
this.next = function() {
|
||||
if (this.i >= this.length) {
|
||||
throw new RangeError("All input was processed!");
|
||||
}
|
||||
|
||||
this.runningSum += this.values[this.i++];
|
||||
|
||||
return this.runningSum;
|
||||
};
|
||||
|
||||
return this;
|
||||
}
|
39
4kyu/human_readable_duration_format/solution.cs
Normal file
39
4kyu/human_readable_duration_format/solution.cs
Normal file
|
@ -0,0 +1,39 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class HumanTimeFormat{
|
||||
private static Dictionary<string, int> conversions = new Dictionary<string, int>() {
|
||||
{"year", 31536000},
|
||||
{"day", 86400},
|
||||
{"hour", 3600},
|
||||
{"minute", 60},
|
||||
{"second", 1}
|
||||
};
|
||||
|
||||
public static string formatDuration(int seconds){
|
||||
if (seconds == 0) return "now";
|
||||
|
||||
var results = new List<string>();
|
||||
foreach (var pair in conversions) {
|
||||
var units = seconds / pair.Value;
|
||||
seconds %= pair.Value;
|
||||
if (units > 0) {
|
||||
var part = $"{units} {pair.Key}";
|
||||
if (units > 1) {
|
||||
part += "s";
|
||||
}
|
||||
results.Add(part);
|
||||
}
|
||||
}
|
||||
|
||||
if (results.Count == 1) return results[0];
|
||||
else {
|
||||
var last = results.Last();
|
||||
results.Remove(last);
|
||||
|
||||
var result = String.Join(", ", results);
|
||||
return result + " and " + last;
|
||||
}
|
||||
}
|
||||
}
|
15
4kyu/magnet_particules_in_boxes/solution.cs
Normal file
15
4kyu/magnet_particules_in_boxes/solution.cs
Normal file
|
@ -0,0 +1,15 @@
|
|||
using System;
|
||||
|
||||
public class Magnets
|
||||
{
|
||||
public static double Doubles(int maxk, int maxn)
|
||||
{
|
||||
double val = 0;
|
||||
|
||||
for (int k = 1; k <= maxk; k++)
|
||||
for (int n = 1; n <= maxn; n++)
|
||||
val += 1 / (k * Math.Pow(n + 1, 2 * k));
|
||||
|
||||
return val;
|
||||
}
|
||||
}
|
44
4kyu/matrix_determinant/solution.cpp
Normal file
44
4kyu/matrix_determinant/solution.cpp
Normal file
|
@ -0,0 +1,44 @@
|
|||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
vector<vector<long long>> transform(vector<vector<long long>> m, int row,
|
||||
int col) {
|
||||
vector<vector<long long>> result;
|
||||
|
||||
for (int i = 0; i < m.size(); i++) {
|
||||
if (i == row)
|
||||
continue;
|
||||
vector<long long> actual_row;
|
||||
for (int j = 0; j < m[i].size(); j++) {
|
||||
if (j == col)
|
||||
continue;
|
||||
actual_row.push_back(m[i][j]);
|
||||
}
|
||||
result.push_back(actual_row);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
long long determinant(vector<vector<long long>> m) {
|
||||
switch (m.size()) {
|
||||
case 1:
|
||||
return m[0][0];
|
||||
break;
|
||||
case 2:
|
||||
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
|
||||
break;
|
||||
}
|
||||
|
||||
long long result = 0;
|
||||
|
||||
for (int i = 0; i < m.size(); i++) {
|
||||
auto l_m = transform(m, i, 0);
|
||||
result += pow(-1, i + 2) * m[i][0] * determinant(l_m);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
65
4kyu/next_bigger_with_same_digits/solution.cs
Normal file
65
4kyu/next_bigger_with_same_digits/solution.cs
Normal file
|
@ -0,0 +1,65 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class Kata {
|
||||
public static List<long> ExtractDigits(long n) {
|
||||
var result = new List<long>();
|
||||
|
||||
while (n > 0) {
|
||||
result.Add(n % 10);
|
||||
n /= 10;
|
||||
}
|
||||
|
||||
result.Reverse();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static bool NextPermutation(List<long> digits) {
|
||||
// foreach (var digit in digits) Console.Write($"{digit} ");
|
||||
// Console.WriteLine();
|
||||
|
||||
var k = -1;
|
||||
|
||||
for (var i = 0; i < digits.Count - 1; i++) {
|
||||
if (digits[i] < digits[i + 1])
|
||||
k = i;
|
||||
}
|
||||
if (k == -1) return false;
|
||||
|
||||
var l = k;
|
||||
for (var i = 0; i < digits.Count; i++)
|
||||
if (digits[k] < digits[i]) l = i;
|
||||
if (l == k) return false;
|
||||
|
||||
var tmp = digits[k];
|
||||
digits[k] = digits[l];
|
||||
digits[l] = tmp;
|
||||
|
||||
// foreach (var digit in digits) Console.Write($"{digit} ");
|
||||
// Console.WriteLine();
|
||||
|
||||
digits.Reverse(k + 1, digits.Count - k - 1);
|
||||
|
||||
// foreach (var digit in digits) Console.Write($"{digit} ");
|
||||
// Console.WriteLine();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static long NextBiggerNumber(long n) {
|
||||
if (n < 10) return -1;
|
||||
|
||||
var digits = ExtractDigits(n);
|
||||
if (!NextPermutation(digits)) {
|
||||
return -1;
|
||||
} else {
|
||||
var result = 0l;
|
||||
foreach (var digit in digits) {
|
||||
result *= 10;
|
||||
result += digit;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
47
4kyu/permutations/solution.cpp
Normal file
47
4kyu/permutations/solution.cpp
Normal file
|
@ -0,0 +1,47 @@
|
|||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
template <typename T> bool nextPermutation(std::vector<T> &vec) {
|
||||
// Find non-increasing suffix
|
||||
if (vec.empty())
|
||||
return false;
|
||||
typename std::vector<T>::iterator i = vec.end() - 1;
|
||||
while (i > vec.begin() && *(i - 1) >= *i)
|
||||
--i;
|
||||
if (i == vec.begin())
|
||||
return false;
|
||||
|
||||
// Find successor to pivot
|
||||
typename std::vector<T>::iterator j = vec.end() - 1;
|
||||
while (*j <= *(i - 1))
|
||||
--j;
|
||||
std::iter_swap(i - 1, j);
|
||||
|
||||
// Reverse suffix
|
||||
std::reverse(i, vec.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::string> permutations(std::string s) {
|
||||
std::set<std::string> strings;
|
||||
std::vector<std::string> result;
|
||||
std::vector<char> s_vec;
|
||||
|
||||
// copy string into vector
|
||||
|
||||
for (auto ch = s.begin(); ch != s.end(); ch++) {
|
||||
s_vec.push_back(*ch);
|
||||
}
|
||||
|
||||
// do the magic
|
||||
std::sort(s_vec.begin(), s_vec.end());
|
||||
do {
|
||||
strings.insert(std::string(s_vec.begin(), s_vec.end()));
|
||||
} while (nextPermutation(s_vec));
|
||||
|
||||
std::copy(strings.begin(), strings.end(), std::back_inserter(result));
|
||||
return result;
|
||||
}
|
24
4kyu/priori_incantatem/solution.js
Normal file
24
4kyu/priori_incantatem/solution.js
Normal file
|
@ -0,0 +1,24 @@
|
|||
class Wand {
|
||||
constructor(spells) {
|
||||
this.history = [];
|
||||
Object.assign(this, spells);
|
||||
|
||||
return new Proxy(this, {
|
||||
get: (target, property) => {
|
||||
const val = target[property];
|
||||
if (typeof val === 'function') {
|
||||
target.history.unshift(property);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
prioriIncantatem() {
|
||||
return this.history.slice(1, MAX_PRIOR_SPELLS + 1);
|
||||
}
|
||||
|
||||
deletrius() {
|
||||
this.history = ['deletrius'];
|
||||
}
|
||||
}
|
19
4kyu/pyramid_slide_down/solution.cs
Normal file
19
4kyu/pyramid_slide_down/solution.cs
Normal file
|
@ -0,0 +1,19 @@
|
|||
using System;
|
||||
|
||||
public class PyramidSlideDown
|
||||
{
|
||||
public static int LongestSlideDown(int[][] pyramid)
|
||||
{
|
||||
for (var i = pyramid.GetLength(0) - 2; i >= 0; i--) {
|
||||
for (var j = 0; j <= i; j++) {
|
||||
if (pyramid[i + 1][j] > pyramid[i + 1][j + 1]) {
|
||||
pyramid[i][j] += pyramid[i + 1][j];
|
||||
} else {
|
||||
pyramid[i][j] += pyramid[i + 1][j + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return pyramid[0][0];
|
||||
}
|
||||
}
|
28
4kyu/remove_zeros/solution.js
Normal file
28
4kyu/remove_zeros/solution.js
Normal file
|
@ -0,0 +1,28 @@
|
|||
function swap(array, i, j) {
|
||||
let temporary = array[i];
|
||||
array[i] = array[j];
|
||||
array[j] = temporary;
|
||||
}
|
||||
|
||||
function removeZeros(array) {
|
||||
// Sort "array" so that all elements with the value of zero are moved to the
|
||||
// end of the array, while the other elements maintain order.
|
||||
// [0, 1, 2, 0, 3] --> [1, 2, 3, 0, 0]
|
||||
// Zero elements also maintain order in which they occurred.
|
||||
// [0, "0", 1, 2, 3] --> [1, 2, 3, 0, "0"]
|
||||
|
||||
// Do not use any temporary arrays or objects. Additionally, you're not able
|
||||
// to use any Array or Object prototype methods such as .shift(), .push(), etc
|
||||
|
||||
// the correctly sorted array should be returned.
|
||||
|
||||
for (let i = array.length - 2; i > -1; i--) {
|
||||
if (array[i] === 0 || array[i] === '0') {
|
||||
for (let j = i; j < array.length - 1 && array[j + 1] !== 0 && array[j + 1] !== '0'; j++) {
|
||||
swap(array, j, j + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
69
4kyu/route_calculator/solution.ts
Normal file
69
4kyu/route_calculator/solution.ts
Normal file
|
@ -0,0 +1,69 @@
|
|||
class Expression {
|
||||
private static readonly INVALID_REQUEST: string = "400: Bad request";
|
||||
|
||||
value: string;
|
||||
|
||||
l: Expression | null = null;
|
||||
r: Expression | null = null;
|
||||
|
||||
private splitBy(operation: string): boolean {
|
||||
let splitOperands = this.value.split(operation);
|
||||
if (splitOperands.length < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.value = operation;
|
||||
this.r = new Expression(splitOperands.pop());
|
||||
this.l = new Expression(splitOperands.join(operation));
|
||||
return true;
|
||||
}
|
||||
|
||||
constructor(expr: string) {
|
||||
this.value = expr;
|
||||
|
||||
for (let operation of "+-*$") {
|
||||
if (this.splitBy(operation)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public evaluate(): (number | string) {
|
||||
if (this.l === null && this.r === null) {
|
||||
// process constants
|
||||
if (![...this.value].every(c => "0123456789.".includes(c))) {
|
||||
return Expression.INVALID_REQUEST;
|
||||
}
|
||||
|
||||
const val = Number.parseFloat(this.value);
|
||||
return val;
|
||||
}
|
||||
|
||||
if (this.l === null || this.r === null || !("+-$*".includes(this.value))) {
|
||||
return Expression.INVALID_REQUEST;
|
||||
}
|
||||
|
||||
const left = this.l.evaluate();
|
||||
const right = this.r.evaluate();
|
||||
|
||||
if (typeof left !== "number" || typeof right !== "number") {
|
||||
return Expression.INVALID_REQUEST;
|
||||
}
|
||||
|
||||
let operation = null;
|
||||
switch (this.value) {
|
||||
case "+":
|
||||
return left + right;
|
||||
case "-":
|
||||
return left - right;
|
||||
case "$":
|
||||
return left / right;
|
||||
case "*":
|
||||
return left * right;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const calculate = (sum: string): (number | string) => {
|
||||
return new Expression(sum).evaluate();
|
||||
}
|
57
4kyu/simplistic_tcp_fsm/solution.cs
Normal file
57
4kyu/simplistic_tcp_fsm/solution.cs
Normal file
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class TCP {
|
||||
private static bool IsInitialized = false;
|
||||
private static Dictionary<string, Dictionary<string, string>> Transitions = new Dictionary<string, Dictionary<string, string>>();
|
||||
|
||||
private static void InitializeIfNeeded() {
|
||||
if (IsInitialized) {
|
||||
return;
|
||||
}
|
||||
IsInitialized = true;
|
||||
|
||||
var transitions = new List<(string, string, string)>() {
|
||||
("CLOSED", "APP_PASSIVE_OPEN" , "LISTEN"),
|
||||
("CLOSED", "APP_ACTIVE_OPEN" , "SYN_SENT"),
|
||||
("LISTEN", "RCV_SYN" , "SYN_RCVD"),
|
||||
("LISTEN", "APP_SEND" , "SYN_SENT"),
|
||||
("LISTEN", "APP_CLOSE" , "CLOSED"),
|
||||
("SYN_RCVD", "APP_CLOSE" , "FIN_WAIT_1"),
|
||||
("SYN_RCVD", "RCV_ACK" , "ESTABLISHED"),
|
||||
("SYN_SENT", "RCV_SYN" , "SYN_RCVD"),
|
||||
("SYN_SENT", "RCV_SYN_ACK" , "ESTABLISHED"),
|
||||
("SYN_SENT", "APP_CLOSE" , "CLOSED"),
|
||||
("ESTABLISHED", "APP_CLOSE" , "FIN_WAIT_1"),
|
||||
("ESTABLISHED", "RCV_FIN" , "CLOSE_WAIT"),
|
||||
("FIN_WAIT_1", "RCV_FIN" , "CLOSING"),
|
||||
("FIN_WAIT_1", "RCV_FIN_ACK" , "TIME_WAIT"),
|
||||
("FIN_WAIT_1", "RCV_ACK" , "FIN_WAIT_2"),
|
||||
("CLOSING", "RCV_ACK" , "TIME_WAIT"),
|
||||
("FIN_WAIT_2", "RCV_FIN" , "TIME_WAIT"),
|
||||
("TIME_WAIT", "APP_TIMEOUT" , "CLOSED"),
|
||||
("CLOSE_WAIT", "APP_CLOSE" , "LAST_ACK"),
|
||||
("LAST_ACK", "RCV_ACK" , "CLOSED"),
|
||||
};
|
||||
|
||||
foreach (var (fromState, byEvent, toState) in transitions) {
|
||||
var fromStateDictionary = Transitions.GetValueOrDefault(fromState, new Dictionary<string, string>());
|
||||
fromStateDictionary.Add(byEvent, toState);
|
||||
Transitions[fromState] = fromStateDictionary;
|
||||
}
|
||||
}
|
||||
|
||||
public static string TraverseStates(string[] events) {
|
||||
InitializeIfNeeded();
|
||||
|
||||
var state = "CLOSED"; // initial state, always
|
||||
|
||||
foreach (var ev in events) {
|
||||
state = Transitions
|
||||
.GetValueOrDefault(state, new Dictionary<string, string>())
|
||||
.GetValueOrDefault(ev, "ERROR");
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
}
|
46
4kyu/snail/solution.cs
Normal file
46
4kyu/snail/solution.cs
Normal file
|
@ -0,0 +1,46 @@
|
|||
using System;
|
||||
|
||||
public class SnailSolution {
|
||||
private static void Update(ref int dx, ref int dy) {
|
||||
int newDx = -dy, newDy = dx;
|
||||
dy = newDy;
|
||||
dx = newDx;
|
||||
}
|
||||
|
||||
public static int[] Snail(int[][] array) {
|
||||
if (array.Length == 1 && array[0].Length == 0) {
|
||||
return new int[] {};
|
||||
}
|
||||
|
||||
int[] result = new int[array.Length * array.Length];
|
||||
|
||||
int y = 0, x = 0;
|
||||
int dy = 0, dx = 1;
|
||||
|
||||
int left = -1, right = array.Length;
|
||||
int top = 0, bottom = array.Length;
|
||||
|
||||
for (var i = 0; i < result.Length; i++) {
|
||||
result[i] = array[y][x];
|
||||
|
||||
if (dx != 0 && x + dx <= left) {
|
||||
left++;
|
||||
Update(ref dx, ref dy);
|
||||
} else if (dx != 0 && x + dx >= right) {
|
||||
right--;
|
||||
Update(ref dx, ref dy);
|
||||
} else if (dy != 0 && y + dy <= top) {
|
||||
top++;
|
||||
Update(ref dx, ref dy);
|
||||
} else if (dy != 0 && y + dy >= bottom) {
|
||||
bottom--;
|
||||
Update(ref dx, ref dy);
|
||||
}
|
||||
|
||||
x += dx;
|
||||
y += dy;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
53
4kyu/sudoku_solution_validator/solution.cs
Normal file
53
4kyu/sudoku_solution_validator/solution.cs
Normal file
|
@ -0,0 +1,53 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
public class Sudoku {
|
||||
private static readonly int FULL = (~(((~0) >> 9) << 9)) << 1;
|
||||
|
||||
private static IEnumerable<(int, int)> Row(int row) {
|
||||
for (var col = 0; col < 9; col++) {
|
||||
yield return (row, col);
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<(int, int)> Column(int column) {
|
||||
for (var row = 0; row < 9; row++) {
|
||||
yield return (row, column);
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<(int, int)> Box(int k) {
|
||||
var row = 3 * (k / 3);
|
||||
var col = 3 * (k % 3);
|
||||
|
||||
for (var i = 0; i < 3; i++) {
|
||||
for (var j = 0; j < 3; j++) {
|
||||
yield return (row + i, col + j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Valid(int[][] board, IEnumerable<(int, int)> coordinates) {
|
||||
var encountered = 0;
|
||||
foreach (var (row, col) in coordinates) {
|
||||
if (board[row][col] == 0) {
|
||||
return false;
|
||||
} else if ((encountered & (1 << board[row][col])) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
encountered |= 1 << board[row][col];
|
||||
}
|
||||
|
||||
return encountered == FULL;
|
||||
}
|
||||
|
||||
public static bool ValidateSolution(int[][] board) {
|
||||
for (var i = 0; i < 9; i++) {
|
||||
if (!Valid(board, Row(i)) || !Valid(board, Column(i)) || !Valid(board, Box(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
29
4kyu/sum_by_factors/solution.rs
Normal file
29
4kyu/sum_by_factors/solution.rs
Normal file
|
@ -0,0 +1,29 @@
|
|||
use std::vec::Vec;
|
||||
|
||||
fn is_prime(n: i64) -> bool {
|
||||
match n {
|
||||
x if x % 2 == 0 => x == 2,
|
||||
_ => {
|
||||
let max_value = (n as f64).sqrt().ceil() as i64;
|
||||
(3..max_value + 1).step_by(2).all(|i| n % i != 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sum_of_divided(l: Vec<i64>) -> Vec<(i64, i64)> {
|
||||
let max_value = l.iter().max_by_key(|x| x.abs());
|
||||
|
||||
match max_value {
|
||||
Some(max_val) => (2..max_val.abs() + 1)
|
||||
.filter(|&i| is_prime(i) && l.iter().any(|x| x % i == 0))
|
||||
.map(|i| {
|
||||
(
|
||||
i,
|
||||
l.iter()
|
||||
.fold(0, |acc, &x| acc + if x % i == 0 { x } else { 0 }),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
None => vec![],
|
||||
}
|
||||
}
|
63
4kyu/sum_strings_as_numbers/solution.cs
Normal file
63
4kyu/sum_strings_as_numbers/solution.cs
Normal file
|
@ -0,0 +1,63 @@
|
|||
using System;
|
||||
|
||||
public static class Kata {
|
||||
public static string sumStrings(string a, string b) {
|
||||
var result = "";
|
||||
var i = a.Length - 1;
|
||||
var j = b.Length - 1;
|
||||
var remainder = 0;
|
||||
|
||||
while (i >= 0 && j >= 0) {
|
||||
var a_digit = a[i] - '0';
|
||||
var b_digit = b[j] - '0';
|
||||
var sum = a_digit + b_digit + remainder;
|
||||
|
||||
result = (sum % 10) + result;
|
||||
|
||||
if (sum >= 10) {
|
||||
remainder = sum / 10;
|
||||
} else {
|
||||
remainder = 0;
|
||||
}
|
||||
|
||||
i--;
|
||||
j--;
|
||||
}
|
||||
|
||||
while (i >= 0) {
|
||||
var a_digit = a[i] - '0';
|
||||
var sum = a_digit + remainder;
|
||||
|
||||
result = (sum % 10) + result;
|
||||
|
||||
if (sum >= 10) {
|
||||
remainder = sum / 10;
|
||||
} else {
|
||||
remainder = 0;
|
||||
}
|
||||
|
||||
i--;
|
||||
}
|
||||
|
||||
while (j >= 0) {
|
||||
var b_digit = b[j] - '0';
|
||||
var sum = b_digit + remainder;
|
||||
|
||||
result = (sum % 10) + result;
|
||||
|
||||
if (sum >= 10) {
|
||||
remainder = sum / 10;
|
||||
} else {
|
||||
remainder = 0;
|
||||
}
|
||||
|
||||
j--;
|
||||
}
|
||||
|
||||
if (remainder > 0) {
|
||||
result = remainder + result;
|
||||
}
|
||||
|
||||
return result.TrimStart('0');
|
||||
}
|
||||
}
|
29
4kyu/the_observed_pin/solution.cs
Normal file
29
4kyu/the_observed_pin/solution.cs
Normal file
|
@ -0,0 +1,29 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class Kata {
|
||||
private static Dictionary<char, string> Possible = new Dictionary<char, string>() {
|
||||
{ '1', "124"}, { '2', "1235" }, { '3', "236" },
|
||||
{ '4', "1457"}, { '5', "24568" }, { '6', "3569" },
|
||||
{ '7', "478"}, { '8', "57890" }, { '9', "689" },
|
||||
{ '0', "80" }
|
||||
};
|
||||
|
||||
public static List<string> GetPINs(string observed) {
|
||||
var result = new HashSet<string>() {
|
||||
""
|
||||
};
|
||||
|
||||
foreach (char observedDigit in observed) {
|
||||
var possibleDigits = Possible[observedDigit];
|
||||
|
||||
result = new HashSet<string>(
|
||||
result
|
||||
.Select(pin => possibleDigits.Select(d => pin + d))
|
||||
.Aggregate((acc, e) => acc.Union(e))
|
||||
);
|
||||
}
|
||||
|
||||
return result.ToList();
|
||||
}
|
||||
}
|
31
4kyu/twice_linear/solution.js
Normal file
31
4kyu/twice_linear/solution.js
Normal file
|
@ -0,0 +1,31 @@
|
|||
function dblLinear(n) {
|
||||
let values = [1];
|
||||
let seen = new Set(values);
|
||||
let index = 0;
|
||||
let length = 0;
|
||||
|
||||
while (length < n) {
|
||||
const x = values.shift();
|
||||
seen.delete(x);
|
||||
|
||||
const a = 2 * x + 1;
|
||||
const b = 3 * x + 1;
|
||||
|
||||
if (!seen.has(a)) {
|
||||
let i = index;
|
||||
|
||||
for (;i < values.length; i++)
|
||||
if (values[i] > a)
|
||||
break;
|
||||
values.splice(i, 0, a);
|
||||
seen.add(a);
|
||||
index = i;
|
||||
}
|
||||
|
||||
seen.add(b);
|
||||
values.push(b);
|
||||
length++;
|
||||
}
|
||||
console.log(values);
|
||||
return values[0];
|
||||
}
|
15
5kyu/buddy_pairs/solution.kt
Normal file
15
5kyu/buddy_pairs/solution.kt
Normal file
|
@ -0,0 +1,15 @@
|
|||
fun getSumOfDivisors(n: Long): Long =
|
||||
(1 until Math.sqrt(n.toDouble()).toLong() + 1).reduce {
|
||||
acc, e -> acc + if (n.rem(e) == 0.toLong()) e + n.div(e) else 0.toLong()
|
||||
}
|
||||
|
||||
fun buddy(start: Long, limit: Long): String {
|
||||
for (n in start..limit) {
|
||||
val m = getSumOfDivisors(n) - 1
|
||||
if (m > n && getSumOfDivisors(m) - 1 == n) {
|
||||
return "($n $m)"
|
||||
}
|
||||
}
|
||||
|
||||
return "Nothing"
|
||||
}
|
15
5kyu/calculating_with_functions/solution.js
Normal file
15
5kyu/calculating_with_functions/solution.js
Normal file
|
@ -0,0 +1,15 @@
|
|||
function zero(operand=null) { return (operand) ? operand(0) : 0; }
|
||||
function one(operand=null) { return (operand) ? operand(1) : 1; }
|
||||
function two(operand=null) { return (operand) ? operand(2) : 2; }
|
||||
function three(operand=null) { return (operand) ? operand(3) : 3; }
|
||||
function four(operand=null) { return (operand) ? operand(4) : 4; }
|
||||
function five(operand=null) { return (operand) ? operand(5) : 5; }
|
||||
function six(operand=null) { return (operand) ? operand(6) : 6; }
|
||||
function seven(operand=null) { return (operand) ? operand(7) : 7; }
|
||||
function eight(operand=null) { return (operand) ? operand(8) : 8; }
|
||||
function nine(operand=null) { return (operand) ? operand(9) : 9; }
|
||||
|
||||
function plus(right) { return (x) => x + right; }
|
||||
function minus(right) { return (x) => x - right; }
|
||||
function times(right) { return (x) => x * right; }
|
||||
function dividedBy(right) { return (x) => Math.floor(x / right); }
|
32
5kyu/common_denominators/solution.cs
Normal file
32
5kyu/common_denominators/solution.cs
Normal file
|
@ -0,0 +1,32 @@
|
|||
using System;
|
||||
|
||||
public class Fracts {
|
||||
public static string convertFrac(long[,] lst)
|
||||
{
|
||||
if (lst.GetLength(0) < 1) return "";
|
||||
long denominator = lst[0, 1];
|
||||
|
||||
string result = "";
|
||||
|
||||
for (int i = 0; i < lst.GetLength(0); i++) denominator = LeastCommonMultiple(denominator, lst[i, 1]);
|
||||
|
||||
for (int i = 0; i < lst.GetLength(0); i++)
|
||||
{
|
||||
long factor = denominator / lst[i, 1];
|
||||
result += String.Format("({0},{1})", lst[i, 0] * factor, lst[i, 1] * factor);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static long GreatestCommonDivisor(long a, long b)
|
||||
{
|
||||
if (b == 0) return a;
|
||||
else return GreatestCommonDivisor(b, a % b);
|
||||
}
|
||||
|
||||
public static long LeastCommonMultiple(long a, long b)
|
||||
{
|
||||
return a * b / GreatestCommonDivisor(a, b);
|
||||
}
|
||||
}
|
13
5kyu/convert_a_hex_string_to_rgb/solution.c
Normal file
13
5kyu/convert_a_hex_string_to_rgb/solution.c
Normal file
|
@ -0,0 +1,13 @@
|
|||
#include <stdio.h>
|
||||
|
||||
typedef struct {
|
||||
int r, g, b;
|
||||
} rgb;
|
||||
|
||||
rgb hex_str_to_rgb(const char *hex_str) {
|
||||
rgb result;
|
||||
|
||||
sscanf(hex_str, "#%2x%2x%2x", &result.r, &result.g, &result.b);
|
||||
|
||||
return result;
|
||||
}
|
10
5kyu/count_ip_addresses/solution.rs
Normal file
10
5kyu/count_ip_addresses/solution.rs
Normal file
|
@ -0,0 +1,10 @@
|
|||
fn parse_ip(ip_str: &str) -> u32 {
|
||||
ip_str
|
||||
.split(".")
|
||||
.map(|octet| octet.parse::<u32>().unwrap())
|
||||
.fold(0, |ip, octet| (ip << 8) | octet)
|
||||
}
|
||||
|
||||
pub fn ips_between(start: &str, end: &str) -> u32 {
|
||||
parse_ip(end) - parse_ip(start)
|
||||
}
|
57
5kyu/did_i_finish_my_sudokou/solution.js
Normal file
57
5kyu/did_i_finish_my_sudokou/solution.js
Normal file
|
@ -0,0 +1,57 @@
|
|||
function checkSet(set) {
|
||||
if (set.size != 9) {
|
||||
return false;
|
||||
} else {
|
||||
for (let num = 1; num <= 9; num++) {
|
||||
if (!set.has(num)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function doneOrNot(board) {
|
||||
const positive = "Finished!";
|
||||
const negative = "Try again!";
|
||||
|
||||
// Check rows
|
||||
for (let row of board) {
|
||||
row = new Set(row);
|
||||
if (!checkSet(row)) {
|
||||
return negative;
|
||||
}
|
||||
}
|
||||
|
||||
// Check columns
|
||||
for (let col = 0; col < 9; col++) {
|
||||
// Construct set for a column
|
||||
let column = new Set();
|
||||
for (let i = 0; i < 9; i++) {
|
||||
column.add(board[i][col]);
|
||||
}
|
||||
|
||||
if (!checkSet(column)) {
|
||||
return negative;
|
||||
}
|
||||
}
|
||||
|
||||
// Check boxes
|
||||
for (let i = 0; i < 9; i += 3) {
|
||||
for (let j = 0; j < 9; j += 3) {
|
||||
// Construct set of a box
|
||||
let box = new Set();
|
||||
for (let k = 0; k < 3; k++) {
|
||||
box.add(board[i + k][j]).add(board[i][j + k]).add(board[i + k][j + k]);
|
||||
}
|
||||
box.add(board[i + 2][j + 1]).add(board[i + 1][j + 2]);
|
||||
|
||||
if (!checkSet(box)) {
|
||||
return negative;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return positive;
|
||||
}
|
20
5kyu/directions_reduction/solution.hs
Normal file
20
5kyu/directions_reduction/solution.hs
Normal file
|
@ -0,0 +1,20 @@
|
|||
module Codewars.Kata.Reduction where
|
||||
import Codewars.Kata.Reduction.Direction
|
||||
|
||||
-- data Direction = North | East | West | South deriving (Eq)
|
||||
|
||||
areOpposite :: Direction -> Direction -> Bool
|
||||
areOpposite North South = True
|
||||
areOpposite South North = True
|
||||
areOpposite East West = True
|
||||
areOpposite West East = True
|
||||
areOpposite _ _ = False
|
||||
|
||||
folding :: Direction -> [Direction] -> [Direction]
|
||||
folding x [] = [x]
|
||||
folding x (y:rest) | areOpposite x y = rest
|
||||
| otherwise = x:y:rest
|
||||
|
||||
dirReduce :: [Direction] -> [Direction]
|
||||
dirReduce [] = []
|
||||
dirReduce directions = foldr folding [] directions
|
61
5kyu/esolang_interpreters_ii/solution.swift
Normal file
61
5kyu/esolang_interpreters_ii/solution.swift
Normal file
|
@ -0,0 +1,61 @@
|
|||
func interpreter(_ code: String, _ tape: String) -> String {
|
||||
func fromTape(stringTape: String) -> [Int] {
|
||||
return stringTape.map({ c in (c == "0") ? 0 : 1 })
|
||||
}
|
||||
|
||||
func toTape(intTape: [Int]) -> String {
|
||||
return intTape.reduce("", { x, b in x + (b == 0 ? "0" : "1") })
|
||||
}
|
||||
|
||||
func findComplement(direction: Int, startIndex: Int, l: Character, r: Character) -> Int {
|
||||
var depth = 0
|
||||
var i = startIndex
|
||||
|
||||
repeat {
|
||||
let c = code[code.index(code.startIndex, offsetBy: i)]
|
||||
|
||||
if c == l {
|
||||
depth += 1
|
||||
} else if c == r {
|
||||
depth -= 1
|
||||
}
|
||||
|
||||
i += direction
|
||||
} while depth != 0
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
var bits = fromTape(stringTape: tape)
|
||||
var i = 0
|
||||
|
||||
var codeIndex = 0
|
||||
while codeIndex >= 0 && codeIndex < code.count {
|
||||
switch code[code.index(code.startIndex, offsetBy: codeIndex)] {
|
||||
case ">":
|
||||
i += 1
|
||||
case "<":
|
||||
i -= 1
|
||||
case "*":
|
||||
bits[i] = (bits[i] + 1) % 2
|
||||
case "[":
|
||||
if bits[i] == 0 {
|
||||
codeIndex = findComplement(direction: 1, startIndex: codeIndex, l: "[", r: "]") - 1
|
||||
}
|
||||
case "]":
|
||||
if bits[i] != 0 {
|
||||
codeIndex = findComplement(direction: -1, startIndex: codeIndex, l: "]", r: "[")
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
codeIndex += 1
|
||||
|
||||
if i < 0 || i >= bits.count {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return toTape(intTape: bits)
|
||||
}
|
48
5kyu/greed_is_good/solution.cpp
Normal file
48
5kyu/greed_is_good/solution.cpp
Normal file
|
@ -0,0 +1,48 @@
|
|||
#include <map>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
std::map<int, int> process_dice(const std::vector<int>& dice) {
|
||||
std::map<int, int> freqs;
|
||||
|
||||
for (auto val : dice) {
|
||||
freqs[val]++;
|
||||
}
|
||||
|
||||
return freqs;
|
||||
}
|
||||
|
||||
int score(const std::vector<int>& dice) {
|
||||
const std::map<std::tuple<int, int>, int> options{
|
||||
{{3, 1}, 1000},
|
||||
{{3, 6}, 600},
|
||||
{{3, 5}, 500},
|
||||
{{3, 4}, 400},
|
||||
{{3, 3}, 300},
|
||||
{{3, 2}, 200}
|
||||
};
|
||||
|
||||
auto counts = process_dice(dice);
|
||||
auto total = 0;
|
||||
|
||||
for (auto has_changed = true; has_changed;) {
|
||||
has_changed = false;
|
||||
|
||||
for (const auto& [option, points] : options) {
|
||||
const auto& [count, die] = option;
|
||||
|
||||
if (counts[die] >= count) {
|
||||
counts[die] -= count;
|
||||
total += points;
|
||||
|
||||
has_changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
total += counts[1] * 100;
|
||||
total += counts[5] * 50;
|
||||
|
||||
return total;
|
||||
}
|
24
5kyu/halloween_sweets/solution.js
Normal file
24
5kyu/halloween_sweets/solution.js
Normal file
|
@ -0,0 +1,24 @@
|
|||
function pick(bags, scale) {
|
||||
if (bags.length == 1) {
|
||||
return bags[0];
|
||||
}
|
||||
|
||||
let sets = [];
|
||||
let sizeOfSet = bags.length / 3;
|
||||
|
||||
for (let i = 0; i < bags.length; i += sizeOfSet) {
|
||||
sets.push(bags.slice(i, i + sizeOfSet));
|
||||
}
|
||||
|
||||
switch (scale.weigh(sets[0], sets[1])) {
|
||||
case -1:
|
||||
return pick(sets[0], scale);
|
||||
break;
|
||||
case 0:
|
||||
return pick(sets[2], scale);
|
||||
break;
|
||||
case 1:
|
||||
return pick(sets[1], scale);
|
||||
break;
|
||||
}
|
||||
}
|
14
5kyu/human_readable_time/solution.cs
Normal file
14
5kyu/human_readable_time/solution.cs
Normal file
|
@ -0,0 +1,14 @@
|
|||
using System;
|
||||
|
||||
public static class TimeFormat
|
||||
{
|
||||
public static string GetReadableTime(int seconds)
|
||||
{
|
||||
var hours = seconds / 3600;
|
||||
seconds %= 3600;
|
||||
var minutes = seconds / 60;
|
||||
seconds %= 60;
|
||||
|
||||
return String.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
|
||||
}
|
||||
}
|
6
5kyu/i32_to_ipv4/solution.c
Normal file
6
5kyu/i32_to_ipv4/solution.c
Normal file
|
@ -0,0 +1,6 @@
|
|||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
|
||||
void uint32_to_ip(uint32_t ip, char *output) {
|
||||
sprintf(output, "%d.%d.%d.%d", (ip >> 24) & 0xFF, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF);
|
||||
}
|
46
5kyu/is_my_friend_cheating/solution.cpp
Normal file
46
5kyu/is_my_friend_cheating/solution.cpp
Normal file
|
@ -0,0 +1,46 @@
|
|||
#include <vector>
|
||||
#include <cmath>
|
||||
|
||||
class RemovedNumbers
|
||||
{
|
||||
static long long get_lower_bound(long long n);
|
||||
static long long get_complement(long long ax, long long n);
|
||||
|
||||
public:
|
||||
static std::vector<std::vector<long long>> removNb(long long n);
|
||||
};
|
||||
|
||||
long long RemovedNumbers::get_lower_bound(long long n)
|
||||
{
|
||||
return (long long)ceil((2 * n - n * n - n) / (-2 * n - 2.0));
|
||||
}
|
||||
|
||||
long long RemovedNumbers::get_complement(long long ax, long long n)
|
||||
{
|
||||
auto result = (0.5 * (n * n + n) - ax) / (ax + 1);
|
||||
|
||||
if (floor(result) == result)
|
||||
{
|
||||
return (long long)result;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::vector<long long>> RemovedNumbers::removNb(long long n)
|
||||
{
|
||||
std::vector<std::vector<long long>> result;
|
||||
|
||||
for (long long ax = get_lower_bound(n); ax <= n; ax++)
|
||||
{
|
||||
auto complement = get_complement(ax, n);
|
||||
if (complement != 0)
|
||||
{
|
||||
result.push_back({ax, complement});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
4
5kyu/maximum_subarray_sum/solution.kt
Normal file
4
5kyu/maximum_subarray_sum/solution.kt
Normal file
|
@ -0,0 +1,4 @@
|
|||
fun maxSequence(arr: List<Int>): Int =
|
||||
arr.scan(0) { k, it ->
|
||||
maxOf(k, 0) + it
|
||||
}.maxOrNull() ?: 0
|
12
5kyu/memoized_fibonacci/solution.py
Normal file
12
5kyu/memoized_fibonacci/solution.py
Normal file
|
@ -0,0 +1,12 @@
|
|||
fibonacci_memory = {}
|
||||
|
||||
def fibonacci(n):
|
||||
if n in [0, 1]:
|
||||
return n
|
||||
|
||||
if n not in fibonacci_memory:
|
||||
value = fibonacci(n - 1) + fibonacci(n - 2)
|
||||
fibonacci_memory[n] = value
|
||||
return value
|
||||
else:
|
||||
return fibonacci_memory[n]
|
13
5kyu/moving_zeros_to_the_end/solution.cs
Normal file
13
5kyu/moving_zeros_to_the_end/solution.cs
Normal file
|
@ -0,0 +1,13 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class Kata {
|
||||
public static int[] MoveZeroes(int[] arr) {
|
||||
var length = arr.GetLength(0);
|
||||
|
||||
var new_arr = arr.Where(x => x != 0).ToList();
|
||||
for (var i = length - new_arr.Count(); i > 0; i--) new_arr.Add(0);
|
||||
|
||||
return new_arr.ToArray();
|
||||
}
|
||||
}
|
86
5kyu/my_smallest_code_interpreter_bf/solution.rs
Normal file
86
5kyu/my_smallest_code_interpreter_bf/solution.rs
Normal file
|
@ -0,0 +1,86 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
fn find_left(instructions: &[u8], index: usize) -> usize {
|
||||
let mut result = index - 1;
|
||||
let mut count = 1;
|
||||
|
||||
while count != 0 {
|
||||
if instructions[result] == ']' as u8 {
|
||||
count += 1;
|
||||
} else if instructions[result] == '[' as u8 {
|
||||
count -= 1;
|
||||
}
|
||||
|
||||
result -= 1;
|
||||
}
|
||||
|
||||
result + 1
|
||||
}
|
||||
|
||||
fn find_right(instructions: &[u8], index: usize) -> usize {
|
||||
let mut result = index + 1;
|
||||
let mut count = 1;
|
||||
|
||||
while count != 0 {
|
||||
if instructions[result] == '[' as u8 {
|
||||
count += 1;
|
||||
} else if instructions[result] == ']' as u8 {
|
||||
count -= 1;
|
||||
}
|
||||
|
||||
result += 1;
|
||||
}
|
||||
|
||||
result - 1
|
||||
}
|
||||
|
||||
fn brain_luck(code: &str, input: Vec<u8>) -> Vec<u8> {
|
||||
let instructions = code.as_bytes();
|
||||
|
||||
let mut result = Vec::<u8>::new();
|
||||
let mut tape = HashMap::<i64, i16>::new();
|
||||
let mut i = 0;
|
||||
let mut tape_i = 0;
|
||||
let mut input_i = 0;
|
||||
|
||||
while i < instructions.len() {
|
||||
match instructions[i] as char {
|
||||
'>' => tape_i += 1,
|
||||
'<' => tape_i -= 1,
|
||||
'+' => {
|
||||
tape.insert(tape_i, (tape.get(&tape_i).unwrap_or(&0) + 1) % 256);
|
||||
()
|
||||
}
|
||||
'-' => {
|
||||
let new_value = tape.get(&tape_i).unwrap_or(&0) - 1;
|
||||
tape.insert(tape_i, if new_value < 0 { 255 } else { new_value });
|
||||
()
|
||||
}
|
||||
'.' => {
|
||||
result.push(*tape.get(&tape_i).unwrap_or(&0) as u8);
|
||||
()
|
||||
}
|
||||
',' => {
|
||||
tape.insert(tape_i, input[input_i] as i16);
|
||||
input_i += 1;
|
||||
()
|
||||
}
|
||||
'[' => {
|
||||
if *tape.get(&tape_i).unwrap_or(&0) == 0 {
|
||||
i = find_right(instructions, i);
|
||||
}
|
||||
()
|
||||
}
|
||||
']' => {
|
||||
if *tape.get(&tape_i).unwrap_or(&0) != 0 {
|
||||
i = find_left(instructions, i);
|
||||
}
|
||||
()
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
result
|
||||
}
|
16
5kyu/number_of_trailing_zeros_of_nf/solution.cs
Normal file
16
5kyu/number_of_trailing_zeros_of_nf/solution.cs
Normal file
|
@ -0,0 +1,16 @@
|
|||
using System;
|
||||
|
||||
public static class Kata
|
||||
{
|
||||
public static int TrailingZeros(int n)
|
||||
{
|
||||
var sum = 0.0;
|
||||
var max = Math.Floor(Math.Log(n)/Math.Log(5));
|
||||
|
||||
for (var i = 1; i <= max; i++) {
|
||||
sum += Math.Floor(n / Math.Pow(5, i));
|
||||
}
|
||||
|
||||
return (int) sum;
|
||||
}
|
||||
}
|
21
5kyu/perimeter_of_squares_in_a_rectangle/solution.rs
Normal file
21
5kyu/perimeter_of_squares_in_a_rectangle/solution.rs
Normal file
|
@ -0,0 +1,21 @@
|
|||
use std::vec::Vec;
|
||||
|
||||
fn fibonacci(n: u64) -> Vec<u64> {
|
||||
match n {
|
||||
0 => vec![1],
|
||||
1 => vec![1, 1],
|
||||
_ => {
|
||||
let mut result = vec![1, 1];
|
||||
|
||||
for i in 2..(n as usize + 1) {
|
||||
result.push(result[i - 1] + result[i - 2]);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn perimeter(n: u64) -> u64 {
|
||||
fibonacci(n).iter().fold(0, |acc, x| acc + 4 * x)
|
||||
}
|
16
5kyu/rgb_to_hex_conversion/solution.cs
Normal file
16
5kyu/rgb_to_hex_conversion/solution.cs
Normal file
|
@ -0,0 +1,16 @@
|
|||
public class Kata
|
||||
{
|
||||
public static int Constrain(int val, int min, int max) {
|
||||
if (val < min) return min;
|
||||
else if (val > max) return max;
|
||||
else return val;
|
||||
}
|
||||
|
||||
public static string Rgb(int r, int g, int b)
|
||||
{
|
||||
r = Constrain(r, 0, 255);
|
||||
g = Constrain(g, 0, 255);
|
||||
b = Constrain(b, 0, 255);
|
||||
return $"{r,2:X2}{g,2:X2}{b,2:X2}";
|
||||
}
|
||||
}
|
17
5kyu/rot13/solution.js
Normal file
17
5kyu/rot13/solution.js
Normal file
|
@ -0,0 +1,17 @@
|
|||
function rot13(message) {
|
||||
let result = "";
|
||||
|
||||
for (let character of message) {
|
||||
let val = character.charCodeAt();
|
||||
|
||||
if (val >= 97 && val <= 122) {
|
||||
result += String.fromCharCode(97 + (val - 97 + 13) % 26);
|
||||
} else if (val >= 65 && val <= 90) {
|
||||
result += String.fromCharCode(65 + (val - 65 + 13) % 26);
|
||||
} else {
|
||||
result += character;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
19
5kyu/scramblies/solution.cs
Normal file
19
5kyu/scramblies/solution.cs
Normal file
|
@ -0,0 +1,19 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class Scramblies {
|
||||
public static bool Scramble(string str1, string str2) {
|
||||
var list = new List<char>(str1.ToCharArray());
|
||||
list.Sort();
|
||||
|
||||
foreach (char letter in str2) {
|
||||
if (list.Contains(letter)) {
|
||||
list.Remove(letter);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
38
5kyu/simple_assembler_interpreter/solution.kt
Normal file
38
5kyu/simple_assembler_interpreter/solution.kt
Normal file
|
@ -0,0 +1,38 @@
|
|||
private fun constantOrRegister(token: String, regs: Map<String, Int>): Int =
|
||||
token.toIntOrNull() ?: regs.getOrDefault(token, 0)
|
||||
|
||||
fun interpret(program: Array<String>): Map<String, Int> {
|
||||
var result = mutableMapOf<String, Int>()
|
||||
var instruction = 0
|
||||
|
||||
while (instruction in program.indices) {
|
||||
val ops = program.elementAt(instruction).split(' ')
|
||||
|
||||
when (ops[0]) {
|
||||
"mov" -> {
|
||||
val value = constantOrRegister(ops[2], result)
|
||||
result.put(ops[1], value)
|
||||
}
|
||||
"inc" -> {
|
||||
val value = result.getOrDefault(ops[1], 0)
|
||||
result.put(ops[1], value + 1)
|
||||
}
|
||||
"dec" -> {
|
||||
val value = result.getOrDefault(ops[1], 0)
|
||||
result.put(ops[1], value - 1)
|
||||
}
|
||||
"jnz" -> {
|
||||
val diff = constantOrRegister(ops[2], result)
|
||||
val cond = constantOrRegister(ops[1], result)
|
||||
|
||||
if (cond != 0) {
|
||||
instruction = instruction + diff - 1
|
||||
}
|
||||
}
|
||||
else -> error("invalid instruction")
|
||||
}
|
||||
instruction++
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
9
5kyu/simple_pig_latin/solution.py
Normal file
9
5kyu/simple_pig_latin/solution.py
Normal file
|
@ -0,0 +1,9 @@
|
|||
def pig_it(text):
|
||||
result = ''
|
||||
|
||||
for word in text.split():
|
||||
if word in '.?!\',':
|
||||
result += word + ' '
|
||||
else:
|
||||
result += word[1:] + word[0] + 'ay '
|
||||
return result.strip()
|
62
5kyu/snakes_and_ladders/solution.cpp
Normal file
62
5kyu/snakes_and_ladders/solution.cpp
Normal file
|
@ -0,0 +1,62 @@
|
|||
#include <map>
|
||||
|
||||
class SnakesLadders
|
||||
{
|
||||
private:
|
||||
static std::map<int, int> sls;
|
||||
int positions[2];
|
||||
int player = 0;
|
||||
public:
|
||||
SnakesLadders(){
|
||||
positions[0] = positions[1] = 0;
|
||||
};
|
||||
std::string play(int die1, int die2)
|
||||
{
|
||||
if (positions[0] == 100 || positions[1] == 100) {
|
||||
return "Game over!";
|
||||
} else {
|
||||
positions[player] += die1 + die2;
|
||||
|
||||
if (positions[player] > 100) {
|
||||
positions[player] = 100 - positions[player] % 100;
|
||||
} else if (positions[player] == 100) {
|
||||
return "Player " + std::to_string(player + 1) + " Wins!";
|
||||
}
|
||||
|
||||
if (sls.find(positions[player]) != sls.end()) {
|
||||
positions[player] = sls[positions[player]];
|
||||
}
|
||||
|
||||
int p = player + 1;
|
||||
if (die1 != die2) {
|
||||
player = (player + 1) % 2;
|
||||
}
|
||||
|
||||
return "Player " + std::to_string(p) + " is on square " + std::to_string(positions[p - 1]);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
std::map<int, int> SnakesLadders::sls = {
|
||||
{ 2, 38},
|
||||
{ 7, 14},
|
||||
{ 8, 31},
|
||||
{15, 26},
|
||||
{16, 6},
|
||||
{21, 42},
|
||||
{28, 84},
|
||||
{36, 44},
|
||||
{46, 25},
|
||||
{49, 11},
|
||||
{51, 67},
|
||||
{62, 19},
|
||||
{64, 60},
|
||||
{71, 91},
|
||||
{74, 53},
|
||||
{78, 98},
|
||||
{87, 94},
|
||||
{89, 68},
|
||||
{92, 88},
|
||||
{95, 75},
|
||||
{99, 80},
|
||||
};
|
11
5kyu/sum_of_pairs/solution.py
Normal file
11
5kyu/sum_of_pairs/solution.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
def sum_pairs(ints, s):
|
||||
passed = {}
|
||||
|
||||
for num in ints:
|
||||
other = s - num
|
||||
if other in passed:
|
||||
return [other, num]
|
||||
else:
|
||||
passed[num] = True
|
||||
|
||||
return None
|
32
5kyu/the_clockwise_spiral/solution.cpp
Normal file
32
5kyu/the_clockwise_spiral/solution.cpp
Normal file
|
@ -0,0 +1,32 @@
|
|||
#include <vector>
|
||||
|
||||
static void next_diff(int &dy, int &dx) {
|
||||
int new_dx = -dy, new_dy = dx;
|
||||
dy = new_dy;
|
||||
dx = new_dx;
|
||||
}
|
||||
|
||||
std::vector<std::vector<int>> create_spiral(int n) {
|
||||
if (n < 1) {
|
||||
return {};
|
||||
}
|
||||
|
||||
auto result = std::vector<std::vector<int>>(
|
||||
static_cast<size_t>(n), std::vector<int>( static_cast<size_t>(n), 0 )
|
||||
);
|
||||
|
||||
int y = 0, x = 0;
|
||||
int dy = 0, dx = 1;
|
||||
for (int i = 1, max = n * n; i <= max; i++) {
|
||||
result[y][x] = i;
|
||||
|
||||
if (y + dy == n || y + dy < 0 || x + dx == n || x + dx < 0 || result[y + dy][x + dx] != 0) {
|
||||
next_diff(dy, dx);
|
||||
}
|
||||
|
||||
y += dy;
|
||||
x += dx;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
7
5kyu/the_hashtag_generator/solution.js
Normal file
7
5kyu/the_hashtag_generator/solution.js
Normal file
|
@ -0,0 +1,7 @@
|
|||
function generateHashtag (str) {
|
||||
const result = str.split(/\s+/igm).reduce((accum, word) =>
|
||||
accum + word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()
|
||||
, "#");
|
||||
|
||||
return (result.length > 140 || result == "#") ? false : result;
|
||||
}
|
71
5kyu/tic_tac_toe_checker/solution.js
Normal file
71
5kyu/tic_tac_toe_checker/solution.js
Normal file
|
@ -0,0 +1,71 @@
|
|||
function checkEmpty(board) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
for (let j = 0; j < 3; j++) {
|
||||
if (board[i][j] === 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkColumn(board, column) {
|
||||
for (let i = 1; i < 3; i++) {
|
||||
if (board[i - 1][column] !== board[i][column]) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return board[0][column];
|
||||
}
|
||||
|
||||
function checkRow(board, row) {
|
||||
for (let i = 1; i < 3; i++) {
|
||||
if (board[row][i - 1] !== board[row][i]) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return board[row][0];
|
||||
}
|
||||
|
||||
function checkDiagonal(board) {
|
||||
let leftToRight = true;
|
||||
let rightToLeft = true;
|
||||
for (let i = 1; i < 3; i++) {
|
||||
if (board[i - 1][i - 1] !== board[i][i]) {
|
||||
leftToRight = false;
|
||||
}
|
||||
if (board[i - 1][3 - i] !== board[i][2 - i]) {
|
||||
rightToLeft = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (leftToRight) {
|
||||
return board[0][0];
|
||||
} else if (rightToLeft) {
|
||||
return board[0][2];
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function isSolved(board) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const col = checkColumn(board, i);
|
||||
const row = checkRow(board, i);
|
||||
if (col != 0) {
|
||||
return col;
|
||||
} else if (row != 0) {
|
||||
return row;
|
||||
}
|
||||
}
|
||||
|
||||
const diagonal = checkDiagonal(board);
|
||||
if (diagonal != 0) {
|
||||
return diagonal;
|
||||
}
|
||||
|
||||
if (checkEmpty(board)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
11
5kyu/valid_parentheses/solution.py
Normal file
11
5kyu/valid_parentheses/solution.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
def valid_parentheses(string):
|
||||
opened = 0
|
||||
|
||||
for letter in string:
|
||||
if letter == '(':
|
||||
opened += 1
|
||||
elif letter == ')':
|
||||
opened -= 1
|
||||
if opened < 0:
|
||||
return False
|
||||
return opened == 0
|
54
5kyu/vector_class/solution.js
Normal file
54
5kyu/vector_class/solution.js
Normal file
|
@ -0,0 +1,54 @@
|
|||
class Vector {
|
||||
constructor(array) {
|
||||
this.values = array.slice(0);
|
||||
}
|
||||
|
||||
mathOperation(vector, f) {
|
||||
if (!vector || !(vector instanceof Vector) || this.values.length !== vector.values.length) {
|
||||
throw "invalid operation";
|
||||
}
|
||||
|
||||
let result = [];
|
||||
for (let i = 0; i < this.values.length; i++) {
|
||||
result.push(f(this.values[i], vector.values[i]));
|
||||
}
|
||||
|
||||
return new Vector(result);
|
||||
}
|
||||
|
||||
add(vector) {
|
||||
return this.mathOperation(vector, (t, o) => t + o);
|
||||
}
|
||||
|
||||
subtract(vector) {
|
||||
return this.mathOperation(vector, (t, o) => t - o);
|
||||
}
|
||||
|
||||
dot(vector) {
|
||||
return this.mathOperation(vector, (t, o) => t * o)
|
||||
.values.reduce((t, e) => t + e, 0);
|
||||
}
|
||||
|
||||
norm() {
|
||||
return Math.sqrt(this.dot(this));
|
||||
}
|
||||
|
||||
toString() {
|
||||
return `(${this.values.join(',')})`;
|
||||
}
|
||||
|
||||
equals(other) {
|
||||
if (!other || !(other instanceof Vector) || this.values.length !== other.values.length) {
|
||||
return false;
|
||||
} else if (other === this) {
|
||||
return true;
|
||||
} else {
|
||||
for (let i = 0; i < this.values.length; i++) {
|
||||
if (this.values[i] !== other.values[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
22
5kyu/weight_for_weight/solution.py
Normal file
22
5kyu/weight_for_weight/solution.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
def digit_sum(n):
|
||||
total = 0
|
||||
while n > 0:
|
||||
total += n % 10
|
||||
n //= 10
|
||||
return total
|
||||
|
||||
class Weight:
|
||||
def __init__(self, weight):
|
||||
self.weight = weight
|
||||
self.digit_sum = digit_sum(weight)
|
||||
|
||||
def __lt__(self, other):
|
||||
if self.digit_sum == other.digit_sum:
|
||||
return str(self.weight) < str(other.weight)
|
||||
return self.digit_sum < other.digit_sum
|
||||
|
||||
def __str__(self):
|
||||
return str(self.weight)
|
||||
|
||||
def order_weight(strng):
|
||||
return ' '.join(map(lambda e: str(e), sorted(map(lambda e: Weight(int(e)), strng.split()))))
|
15
5kyu/where_my_anagrams_at/solution.js
Normal file
15
5kyu/where_my_anagrams_at/solution.js
Normal file
|
@ -0,0 +1,15 @@
|
|||
function anagrams(word, words) {
|
||||
word = word.split('');
|
||||
word.sort();
|
||||
word = word.join('');
|
||||
|
||||
let result = [];
|
||||
for (let testedWord of words) {
|
||||
twSorted = testedWord.split('');
|
||||
twSorted.sort();
|
||||
if (word == twSorted.join(''))
|
||||
result.push(testedWord);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
24
5kyu/which_x_for_that_sum/solution.rs
Normal file
24
5kyu/which_x_for_that_sum/solution.rs
Normal file
|
@ -0,0 +1,24 @@
|
|||
fn solve_quadratic(a: f64, b: f64, c: f64) -> Option<(f64, f64)> {
|
||||
let d = b * b - 4.0 * a * c;
|
||||
|
||||
if d < 0.0 {
|
||||
None
|
||||
} else {
|
||||
Some(((-b + d.sqrt()) / (2.0 * a), (-b - d.sqrt()) / (2.0 * a)))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn solve(m: f64) -> f64 {
|
||||
match solve_quadratic(m, -2.0 * m - 1.0, m) {
|
||||
Some((left, right)) => {
|
||||
if left > 0.0 && left < 1.0 {
|
||||
left
|
||||
} else if right > 0.0 && right < 1.0 {
|
||||
right
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
16
6kyu/are_they_the_same/solution.js
Normal file
16
6kyu/are_they_the_same/solution.js
Normal file
|
@ -0,0 +1,16 @@
|
|||
function comp(array1, array2){
|
||||
let squares = [];
|
||||
for (let num of array1) {
|
||||
squares.push(num * num);
|
||||
}
|
||||
|
||||
if (!array2)
|
||||
return false;
|
||||
|
||||
for (let square of array2) {
|
||||
let index = squares.indexOf(square);
|
||||
if (index != -1) squares.splice(index, 1);
|
||||
}
|
||||
if (squares.length > 0) return false;
|
||||
else return true;
|
||||
}
|
12
6kyu/ball_upwards/solution.kt
Normal file
12
6kyu/ball_upwards/solution.kt
Normal file
|
@ -0,0 +1,12 @@
|
|||
package ball
|
||||
|
||||
val G = 9.81
|
||||
|
||||
fun maxBall(v0: Int): Int {
|
||||
val v = v0 * 5 / 18.0
|
||||
val maxT = v * 10 / G
|
||||
|
||||
return (0..maxT.toInt() + 1).maxBy {
|
||||
v * it / 10.0 - 0.5 * G * it * it / 100.0
|
||||
} ?: 0
|
||||
}
|
7
6kyu/bit_counting/solution.py
Normal file
7
6kyu/bit_counting/solution.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
def countBits(n):
|
||||
count = 0
|
||||
while n > 0:
|
||||
if n % 2 == 1:
|
||||
count += 1
|
||||
n //= 2
|
||||
return count
|
9
6kyu/bouncing_balls/solution.py
Normal file
9
6kyu/bouncing_balls/solution.py
Normal file
|
@ -0,0 +1,9 @@
|
|||
def bouncingBall(h, bounce, window):
|
||||
if h <= 0 or (bounce <= 0 or bounce >= 1) or window >= h:
|
||||
return -1
|
||||
|
||||
result = -1
|
||||
while h > window:
|
||||
h *= bounce
|
||||
result += 2
|
||||
return result
|
25
6kyu/build_tower/solution.js
Normal file
25
6kyu/build_tower/solution.js
Normal file
|
@ -0,0 +1,25 @@
|
|||
String.prototype.centerJustify = function(length, char) {
|
||||
let i = 0;
|
||||
let str = this;
|
||||
let toggle = true;
|
||||
while (i + this.length < length) {
|
||||
i++;
|
||||
if (toggle)
|
||||
str = str + char;
|
||||
else
|
||||
str = char + str;
|
||||
toggle = !toggle;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function towerBuilder(nFloors) {
|
||||
let floor = '*';
|
||||
const width = nFloors * 2 - 1;
|
||||
let result = [];
|
||||
for (let i = 0, count = 1; i < nFloors; i++, count += 2) {
|
||||
result.push(floor.centerJustify(width, ' '));
|
||||
floor += '**';
|
||||
}
|
||||
return result;
|
||||
}
|
30
6kyu/build_tower_advanced/solution.js
Normal file
30
6kyu/build_tower_advanced/solution.js
Normal file
|
@ -0,0 +1,30 @@
|
|||
String.prototype.centerJustify = function(length, char) {
|
||||
let i = 0;
|
||||
let str = this;
|
||||
let toggle = true;
|
||||
while (i + this.length < length) {
|
||||
i++;
|
||||
if (toggle)
|
||||
str = str + char;
|
||||
else
|
||||
str = char + str;
|
||||
toggle = !toggle;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function towerBuilder(nFloors, nBlockSz) {
|
||||
let floor = '';
|
||||
for (let i = 0; i < nBlockSz[0]; i++)
|
||||
floor += '*';
|
||||
const width = nFloors * 2 * nBlockSz[0] - nBlockSz[0];
|
||||
let result = [];
|
||||
for (let i = 0, count = 1; i < nFloors; i++, count += 2) {
|
||||
for (let j = 0; j < nBlockSz[1]; j++) {
|
||||
result.push(floor.centerJustify(width, ' '));
|
||||
}
|
||||
for (let j = 0; j < nBlockSz[0]; j++)
|
||||
floor += '**';
|
||||
}
|
||||
return result;
|
||||
}
|
19
6kyu/camelcase_method/solution.rs
Normal file
19
6kyu/camelcase_method/solution.rs
Normal file
|
@ -0,0 +1,19 @@
|
|||
fn camel_case(str: &str) -> String {
|
||||
let mut result = String::from("");
|
||||
|
||||
let mut was_space: bool = true;
|
||||
for character in str.chars() {
|
||||
if character.is_whitespace() {
|
||||
was_space = true;
|
||||
} else if character.is_alphabetic() {
|
||||
if was_space {
|
||||
result += &character.to_uppercase().to_string();
|
||||
was_space = false;
|
||||
} else {
|
||||
result += &character.to_lowercase().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.to_string()
|
||||
}
|
12
6kyu/cheat_or_you_shall_not_pass_easy/solution.c
Normal file
12
6kyu/cheat_or_you_shall_not_pass_easy/solution.c
Normal file
|
@ -0,0 +1,12 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
int solution()
|
||||
{
|
||||
// return the right answer here
|
||||
srand(0);
|
||||
int a = 0;
|
||||
int b = 1000;
|
||||
int result = rand() % (b - a) + a;
|
||||
srand(0);
|
||||
return result;
|
||||
}
|
42
6kyu/consecutive_strings/solution.java
Normal file
42
6kyu/consecutive_strings/solution.java
Normal file
|
@ -0,0 +1,42 @@
|
|||
class LongestConsec {
|
||||
public static String longestConsec(String[] strarr, int k) {
|
||||
int n = strarr.length;
|
||||
|
||||
// handle limits
|
||||
if (n == 0 || k <= 0 || k > n) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// determine lengths
|
||||
int[] lengths = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
lengths[i] = strarr[i].length();
|
||||
}
|
||||
|
||||
// calculate first index
|
||||
int maxIndex = 0, maxLength = 0;
|
||||
for (int i = 0; i < k; i++) {
|
||||
maxLength += lengths[i];
|
||||
}
|
||||
|
||||
// Check rest of the array
|
||||
int tmpLength = maxLength;
|
||||
for (int i = 1; i < n - k + 1; i++) {
|
||||
tmpLength += lengths[i + k - 1];
|
||||
tmpLength -= lengths[i - 1];
|
||||
|
||||
if (tmpLength > maxLength) {
|
||||
maxIndex = i;
|
||||
maxLength = tmpLength;
|
||||
}
|
||||
}
|
||||
|
||||
// Join the strings
|
||||
String result = "";
|
||||
for (int i = maxIndex; i < maxIndex + k; i++) {
|
||||
result += strarr[i];
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
13
6kyu/convert_string_to_camel_case/solution.js
Normal file
13
6kyu/convert_string_to_camel_case/solution.js
Normal file
|
@ -0,0 +1,13 @@
|
|||
function toCamelCase(str){
|
||||
if (str.indexOf('-') != -1) {
|
||||
str = str.split('-');
|
||||
} else {
|
||||
str = str.split('_');
|
||||
}
|
||||
|
||||
for (let i = 1; i < str.length; i++) {
|
||||
str[i] = str[i].charAt(0).toUpperCase() + str[i].substring(1);
|
||||
}
|
||||
|
||||
return str.join('');
|
||||
}
|
17
6kyu/count_the_smiley_faces/solution.cs
Normal file
17
6kyu/count_the_smiley_faces/solution.cs
Normal file
|
@ -0,0 +1,17 @@
|
|||
using System.Text.RegularExpressions;
|
||||
|
||||
public static class Kata
|
||||
{
|
||||
public static int CountSmileys(string[] smileys)
|
||||
{
|
||||
var count = 0;
|
||||
|
||||
var regex = new Regex(@"[:;][-~]?[D\)]");
|
||||
|
||||
foreach (string smiley in smileys) {
|
||||
if (regex.Match(smiley).Success) count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
24
6kyu/counting_duplicates/solution.rs
Normal file
24
6kyu/counting_duplicates/solution.rs
Normal file
|
@ -0,0 +1,24 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
fn count_duplicates(text: &str) -> u32 {
|
||||
let mut counts: HashMap<char, i32> = HashMap::new();
|
||||
|
||||
for character in text.to_lowercase().chars() {
|
||||
match counts.get_mut(&character) {
|
||||
None => {
|
||||
counts.insert(character, 1);
|
||||
{}
|
||||
},
|
||||
Some(x) => *x += 1
|
||||
}
|
||||
}
|
||||
|
||||
counts
|
||||
.iter()
|
||||
.fold(0, |total, (_, &count)|
|
||||
match count > 1 {
|
||||
true => total + 1,
|
||||
_ => total
|
||||
}
|
||||
)
|
||||
}
|
12
6kyu/create_phone_number/solution.js
Normal file
12
6kyu/create_phone_number/solution.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
function createPhoneNumber(numbers) {
|
||||
let result = '(';
|
||||
for (let i = 0; i < 10; i++) {
|
||||
result += numbers[i];
|
||||
if (i == 2) {
|
||||
result += ') ';
|
||||
} else if (i == 5) {
|
||||
result += '-';
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
18
6kyu/decode_the_morse_code/solution.rs
Normal file
18
6kyu/decode_the_morse_code/solution.rs
Normal file
|
@ -0,0 +1,18 @@
|
|||
mod preloaded;
|
||||
use preloaded::MORSE_CODE;
|
||||
// MORSE_CODE is `HashMap<String, String>`. e.g. ".-" -> "A".
|
||||
|
||||
fn decode_morse(encoded: &str) -> String {
|
||||
let mut result = String::new();
|
||||
|
||||
encoded.split(" ").map(|x| x.trim()).for_each(|x| {
|
||||
x.split_whitespace().for_each(|c| {
|
||||
result += MORSE_CODE.get(c).unwrap();
|
||||
});
|
||||
|
||||
result += " ";
|
||||
});
|
||||
|
||||
|
||||
String::from(result.trim())
|
||||
}
|
17
6kyu/delete_occurrences_if_occurs/solution.js
Normal file
17
6kyu/delete_occurrences_if_occurs/solution.js
Normal file
|
@ -0,0 +1,17 @@
|
|||
function deleteNth(arr, n) {
|
||||
const freqs = {};
|
||||
const result = [];
|
||||
|
||||
for (const element of arr) {
|
||||
if (!freqs[element]) {
|
||||
freqs[element] = 1;
|
||||
} else if (freqs[element] < n) {
|
||||
freqs[element]++;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
result.push(element);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
36
6kyu/design_a_simple_automaton/solution.cpp
Normal file
36
6kyu/design_a_simple_automaton/solution.cpp
Normal file
|
@ -0,0 +1,36 @@
|
|||
#include <map>
|
||||
#include <set>
|
||||
|
||||
class Automaton
|
||||
{
|
||||
std::set<int> F{2};
|
||||
const int initial_state = 1;
|
||||
|
||||
std::map<int, std::map<char, int>> transitions{
|
||||
{1, std::map<char, int>{
|
||||
{'0', 1}, {'1', 2}
|
||||
}
|
||||
},
|
||||
{2, std::map<char, int>{
|
||||
{'0', 3}, {'1', 2}
|
||||
}
|
||||
},
|
||||
{3, std::map<char, int>{
|
||||
{'0', 2}, {'1', 2}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
Automaton() {}
|
||||
|
||||
bool read_commands(const std::vector<char>& commands) {
|
||||
int state = initial_state;
|
||||
|
||||
for (const char c : commands) {
|
||||
state = transitions[state][c];
|
||||
}
|
||||
|
||||
return F.find(state) != F.end();
|
||||
}
|
||||
};
|
19
6kyu/does_my_number_look_big_in_this/solution.cs
Normal file
19
6kyu/does_my_number_look_big_in_this/solution.cs
Normal file
|
@ -0,0 +1,19 @@
|
|||
using System;
|
||||
|
||||
public class Kata {
|
||||
public static bool Narcissistic(int value) {
|
||||
var narcissistic = 0;
|
||||
var length = (int) Math.Log10(value + 0.5) + 1;
|
||||
var copyOfValue = value;
|
||||
|
||||
while (copyOfValue > 0) {
|
||||
narcissistic += (int) Math.Pow(copyOfValue % 10, length);
|
||||
copyOfValue /= 10;
|
||||
if (narcissistic > value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return narcissistic == value;
|
||||
}
|
||||
}
|
15
6kyu/duplicate_encoder/solution.java
Normal file
15
6kyu/duplicate_encoder/solution.java
Normal file
|
@ -0,0 +1,15 @@
|
|||
public class DuplicateEncoder {
|
||||
static String encode(String word) {
|
||||
word = word.toLowerCase();
|
||||
String result = "";
|
||||
for (int i = 0; i < word.length(); i++) {
|
||||
char character = word.charAt(i);
|
||||
if (word.indexOf(character) != word.lastIndexOf(character)) {
|
||||
result += ")";
|
||||
} else {
|
||||
result += "(";
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
23
6kyu/equal_sides_of_an_array/solution.cs
Normal file
23
6kyu/equal_sides_of_an_array/solution.cs
Normal file
|
@ -0,0 +1,23 @@
|
|||
public class Kata
|
||||
{
|
||||
public static int SumOfTheArray(int[] arr)
|
||||
{
|
||||
int sum = 0;
|
||||
for (int i = 0, max = arr.Length; i < max; sum += arr[i++]);
|
||||
return sum;
|
||||
}
|
||||
public static int FindEvenIndex(int[] arr)
|
||||
{
|
||||
int left, right;
|
||||
left = 0;
|
||||
right = SumOfTheArray(arr) - arr[0];
|
||||
for (int i = 1, max = arr.Length; i < max; i++)
|
||||
{
|
||||
left += arr[i - 1];
|
||||
right -= arr[i];
|
||||
if (left == right) return i;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
17
6kyu/esolang_interpreters_i/solution.swift
Normal file
17
6kyu/esolang_interpreters_i/solution.swift
Normal file
|
@ -0,0 +1,17 @@
|
|||
func interpreter(_ prog: String) -> String {
|
||||
var cell = 0
|
||||
var result = ""
|
||||
|
||||
for i in prog {
|
||||
switch i {
|
||||
case "+":
|
||||
cell = (cell + 1) % 256
|
||||
case ".":
|
||||
result += String(Character(Unicode.Scalar(cell)!))
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
12
6kyu/evil_autocorrect_prank/solution.js
Normal file
12
6kyu/evil_autocorrect_prank/solution.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
const REGEX = new RegExp("(^|[^a-z]+)(u|you+)($|[^a-z]+)", "gi")
|
||||
|
||||
function autocorrect(input){
|
||||
var result = input;
|
||||
|
||||
do {
|
||||
input = result;
|
||||
result = result.replace(REGEX, "$1your sister$3");
|
||||
} while (result != input);
|
||||
|
||||
return result;
|
||||
}
|
19
6kyu/fat_fingers/solution.py
Normal file
19
6kyu/fat_fingers/solution.py
Normal file
|
@ -0,0 +1,19 @@
|
|||
def fat_fingers(string):
|
||||
if string == "":
|
||||
return ""
|
||||
|
||||
result = ""
|
||||
caps = False
|
||||
|
||||
for letter in string[0:]:
|
||||
if letter == 'A' or letter == 'a':
|
||||
caps = not caps
|
||||
elif caps:
|
||||
if letter.isupper():
|
||||
result += letter.lower()
|
||||
else:
|
||||
result += letter.upper()
|
||||
else:
|
||||
result += letter
|
||||
|
||||
return result
|
12
6kyu/find_the_missing_letter/solution.java
Normal file
12
6kyu/find_the_missing_letter/solution.java
Normal file
|
@ -0,0 +1,12 @@
|
|||
public class Kata {
|
||||
public static char findMissingLetter(char[] array) {
|
||||
int last = (int)array[0];
|
||||
for (int i = 1; i < array.length; i++)
|
||||
if ((int)array[i] != last + 1) {
|
||||
return (char) (last + 1);
|
||||
} else {
|
||||
last++;
|
||||
}
|
||||
return (char) -1;
|
||||
}
|
||||
}
|
17
6kyu/find_the_missing_term_in_arith_prog/solution.py
Normal file
17
6kyu/find_the_missing_term_in_arith_prog/solution.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
def find_missing(sequence):
|
||||
# Relation => a_n - a_(n-1) = d
|
||||
|
||||
diffs = []
|
||||
|
||||
for i in range(len(sequence) - 1):
|
||||
diffs.append(sequence[i + 1] - sequence[i])
|
||||
|
||||
max_diff = diffs[0]
|
||||
|
||||
for index, diff in enumerate(diffs[1:], 1):
|
||||
if abs(diff) > abs(max_diff):
|
||||
return sequence[index] + max_diff
|
||||
elif abs(max_diff) > abs(diff):
|
||||
return sequence[0] + diff
|
||||
|
||||
raise ValueError()
|
28
6kyu/find_the_odd_int/solution.cs
Normal file
28
6kyu/find_the_odd_int/solution.cs
Normal file
|
@ -0,0 +1,28 @@
|
|||
using System;
|
||||
|
||||
namespace Solution
|
||||
{
|
||||
class Kata
|
||||
{
|
||||
public static int find_it(int[] seq)
|
||||
{
|
||||
Array.Sort(seq);
|
||||
|
||||
int count = 1;
|
||||
|
||||
for (int i = 1; i < seq.Length; i++)
|
||||
{
|
||||
if (seq[i] == seq[i - 1]) count++;
|
||||
else
|
||||
{
|
||||
if (count % 2 == 1) return seq[i - 1];
|
||||
else count = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (count % 2 == 1) return seq[seq.Length - 1];
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
16
6kyu/find_the_unique_number/solution.py
Normal file
16
6kyu/find_the_unique_number/solution.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
def find_uniq(arr):
|
||||
a = arr[0]
|
||||
count_a = 1
|
||||
b = None
|
||||
count_b = 0
|
||||
|
||||
for e in arr[1:]:
|
||||
if e != a:
|
||||
count_b += 1
|
||||
b = e
|
||||
else:
|
||||
count_a += 1
|
||||
if count_a < count_b:
|
||||
return a
|
||||
else:
|
||||
return b
|
23
6kyu/give_me_a_diamond/solution.swift
Normal file
23
6kyu/give_me_a_diamond/solution.swift
Normal file
|
@ -0,0 +1,23 @@
|
|||
func diamond(_ size: Int) -> String? {
|
||||
if size < 0 || size % 2 == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var result = ""
|
||||
var (count, diff) = (1, 2)
|
||||
|
||||
while count > 0 {
|
||||
print(count, diff)
|
||||
result += String(repeating: " ", count: (size - count) / 2)
|
||||
result += String(repeating: "*", count: count)
|
||||
result += "\n"
|
||||
|
||||
if count == size {
|
||||
diff = -2
|
||||
}
|
||||
|
||||
count += diff
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
27
6kyu/halloween_trick_or_treat/solution.js
Normal file
27
6kyu/halloween_trick_or_treat/solution.js
Normal file
|
@ -0,0 +1,27 @@
|
|||
function trickOrTreat(children,candies){
|
||||
if (candies.length != children) {
|
||||
return "Trick or treat!";
|
||||
}
|
||||
|
||||
let lastCount = -1;
|
||||
for (let packet of candies) {
|
||||
let count = 0;
|
||||
for (let e of packet) {
|
||||
if (e == "bomb") {
|
||||
return "Trick or treat!";
|
||||
} else if (e == "candy") {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (lastCount == -1) {
|
||||
lastCount = count;
|
||||
}
|
||||
|
||||
if (count < 2 || lastCount != count) {
|
||||
return "Trick or treat!";
|
||||
}
|
||||
}
|
||||
|
||||
return "Thank you, strange uncle!";
|
||||
}
|
35
6kyu/help_the_bookseller/solution.rs
Normal file
35
6kyu/help_the_bookseller/solution.rs
Normal file
|
@ -0,0 +1,35 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
fn stock_list(list_art: Vec<&str>, list_cat: Vec<&str>) -> String {
|
||||
if list_art.is_empty() || list_cat.is_empty() {
|
||||
return "".to_string();
|
||||
}
|
||||
|
||||
let mut map: HashMap<&str, i32> = HashMap::new();
|
||||
|
||||
// Initialize with zero values
|
||||
for cat in &list_cat {
|
||||
map.insert(cat, 0);
|
||||
}
|
||||
|
||||
// Iterate through art
|
||||
for art in &list_art {
|
||||
for cat in &list_cat {
|
||||
if art.starts_with(cat) {
|
||||
let v: Vec<&str> = art.split_terminator(' ').collect();
|
||||
let count: i32 = v[1].parse().unwrap();
|
||||
map.insert(cat, map[cat] + count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get result string
|
||||
list_cat
|
||||
.iter()
|
||||
.map(
|
||||
|category| format!("({} : {})", category, map[category])
|
||||
)
|
||||
.collect::<Vec<String>>()
|
||||
.as_slice()
|
||||
.join(" - ")
|
||||
}
|
13
6kyu/highest_scoring_word/solution.py
Normal file
13
6kyu/highest_scoring_word/solution.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
from functools import reduce
|
||||
|
||||
def high(x):
|
||||
x = x.split()
|
||||
h = reduce(lambda total, char: total + ord(char) - 96, x[0], 0)
|
||||
hw = x[0]
|
||||
|
||||
for word in x[1:]:
|
||||
total = reduce(lambda total, char: total + ord(char) - 96, word, 0)
|
||||
if total > h:
|
||||
h = total
|
||||
hw = word
|
||||
return hw
|
21
6kyu/ip_validation/solution.c
Normal file
21
6kyu/ip_validation/solution.c
Normal file
|
@ -0,0 +1,21 @@
|
|||
#include <stdio.h>
|
||||
|
||||
int is_valid_ip(const char * addr) {
|
||||
int seg[4];
|
||||
|
||||
if (sscanf(addr, "%d.%d.%d.%d", &seg[0], &seg[1], &seg[2], &seg[3]) != 4) return 0;
|
||||
|
||||
for (size_t i = 0; i < 4; i++) if (seg[i] <= 0 || seg[i] > 255) return 0;
|
||||
|
||||
int count = 0;
|
||||
|
||||
for (size_t i = 0; addr[i] != '\0'; i++)
|
||||
{
|
||||
if (addr[i] == '.') count++;
|
||||
if ((addr[i] == '.' && addr[i + 1] == '0') || addr[i] == ' ') return 0;
|
||||
}
|
||||
|
||||
if (count != 3) return 0;
|
||||
|
||||
return 1;
|
||||
}
|
28
6kyu/irreducible_sum_of_rationals/solution.rs
Normal file
28
6kyu/irreducible_sum_of_rationals/solution.rs
Normal file
|
@ -0,0 +1,28 @@
|
|||
fn gcd(mut a: i64, mut b: i64) -> i64 {
|
||||
while b != 0 {
|
||||
let t = b;
|
||||
b = a % b;
|
||||
a = t;
|
||||
}
|
||||
|
||||
a
|
||||
}
|
||||
|
||||
fn lcm(a: i64, b: i64) -> i64 {
|
||||
(a*b).abs() / gcd(a, b)
|
||||
}
|
||||
|
||||
fn sum_fracts(l: Vec<(i64, i64)>) -> Option<(i64, i64)> {
|
||||
if l.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let denom = l.iter().fold(1, |a, b| lcm(a, b.1));
|
||||
|
||||
let (num, den) = l.iter().fold((0, denom), |runner, frac|
|
||||
(runner.0 + (frac.0 * denom / frac.1), denom)
|
||||
);
|
||||
|
||||
let divisor = gcd(num, den);
|
||||
Some((num / divisor, den / divisor))
|
||||
}
|
16
6kyu/is_a_number_prime/solution.py
Normal file
16
6kyu/is_a_number_prime/solution.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
import math
|
||||
|
||||
def is_prime(num):
|
||||
if num <= 1:
|
||||
return False
|
||||
elif num == 2:
|
||||
return True
|
||||
elif num % 2 == 0:
|
||||
return False
|
||||
|
||||
bound = int(math.ceil(math.sqrt(num)))
|
||||
|
||||
for div in range(3, bound + 1, 2):
|
||||
if num % div == 0:
|
||||
return False
|
||||
return True
|
21
6kyu/length_of_missing_array/solution.cs
Normal file
21
6kyu/length_of_missing_array/solution.cs
Normal file
|
@ -0,0 +1,21 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class Kata {
|
||||
public static int GetLengthOfMissingArray(object[][] arrayOfArrays) {
|
||||
if (arrayOfArrays == null || arrayOfArrays.GetLength(0) < 2) return 0;
|
||||
var lengths = new HashSet<int>();
|
||||
|
||||
foreach (var array in arrayOfArrays) {
|
||||
if (array == null) return 0;
|
||||
var size = array.GetLength(0);
|
||||
if (size == 0) return 0;
|
||||
else lengths.Add(size);
|
||||
}
|
||||
|
||||
var max = lengths.Max();
|
||||
var min = lengths.Min();
|
||||
|
||||
return (int) (0.5 * (arrayOfArrays.GetLength(0) + 1) * (max + min) - lengths.Sum());
|
||||
}
|
||||
}
|
28
6kyu/linked_lists_length_count/solution.cpp
Normal file
28
6kyu/linked_lists_length_count/solution.cpp
Normal file
|
@ -0,0 +1,28 @@
|
|||
/* Node Definition
|
||||
struct Node {
|
||||
Node * next;
|
||||
int data;
|
||||
}
|
||||
*/
|
||||
|
||||
int Length(Node *head)
|
||||
{
|
||||
int count = 0;
|
||||
while (head != NULL) {
|
||||
count++;
|
||||
head = head->next;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int Count(Node *head, int data)
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
while (head != NULL) {
|
||||
if (head->data == data) count++;
|
||||
head = head->next;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
55
6kyu/lotto_6_aus_49/solution.cs
Normal file
55
6kyu/lotto_6_aus_49/solution.cs
Normal file
|
@ -0,0 +1,55 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
|
||||
public class LOTTO {
|
||||
private static Random r = new Random();
|
||||
|
||||
public static int[] NumberGenerator() {
|
||||
var result = new int[7];
|
||||
result[6] = 50;
|
||||
|
||||
for (var i = 0; i < 6; i++) {
|
||||
var number = 0;
|
||||
do {
|
||||
number = r.Next(1, 50);
|
||||
} while (result.Contains(number));
|
||||
result[i] = number;
|
||||
}
|
||||
Array.Sort(result);
|
||||
result[6] = r.Next(0, 10);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int CheckForWinningCategory(int[] checkCombination, int[] winningCombination) {
|
||||
var count = 0;
|
||||
var superzahl = checkCombination.Last() == winningCombination.Last();
|
||||
|
||||
for (var i = 0; i < 6; i++) {
|
||||
var index = Array.IndexOf(checkCombination, winningCombination[i]);
|
||||
if (index != -1 && index != 6) count++;
|
||||
}
|
||||
|
||||
var result = -1;
|
||||
|
||||
switch (count) {
|
||||
case 6:
|
||||
result = 2;
|
||||
break;
|
||||
case 5:
|
||||
result = 4;
|
||||
break;
|
||||
case 4:
|
||||
result = 6;
|
||||
break;
|
||||
case 3:
|
||||
result = 8;
|
||||
break;
|
||||
}
|
||||
|
||||
if (count == 2 && superzahl) result = 9;
|
||||
else if (superzahl && result != -1) result--;
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
10
6kyu/make_the_deadfish_swim/solution.hs
Normal file
10
6kyu/make_the_deadfish_swim/solution.hs
Normal file
|
@ -0,0 +1,10 @@
|
|||
module Kata.Deadfish (parse) where
|
||||
|
||||
parse :: String -> [Int]
|
||||
parse = snd . foldl exec (0, [])
|
||||
where exec (value, output) cmd = case cmd of
|
||||
'i' -> (value + 1, output)
|
||||
'd' -> (value - 1, output)
|
||||
's' -> (value * value, output)
|
||||
'o' -> (value, output ++ [value])
|
||||
_ -> (value, output)
|
7
6kyu/multiples_of_3_or_5/solution.hs
Normal file
7
6kyu/multiples_of_3_or_5/solution.hs
Normal file
|
@ -0,0 +1,7 @@
|
|||
module MultiplesOf3And5 where
|
||||
|
||||
sumOfMultiples :: Integer -> Integer -> Integer
|
||||
sumOfMultiples n upTo = div ((div (upTo - 1) n) * (n + (upTo - 1 - mod (upTo - 1) n))) 2
|
||||
|
||||
solution :: Integer -> Integer
|
||||
solution number = sumOfMultiples 3 number + sumOfMultiples 5 number - sumOfMultiples 15 number
|
16
6kyu/multiplication_table/solution.go
Normal file
16
6kyu/multiplication_table/solution.go
Normal file
|
@ -0,0 +1,16 @@
|
|||
package multiplicationtable
|
||||
|
||||
func MultiplicationTable(size int) [][]int {
|
||||
result := make([][]int, size);
|
||||
for i := 0; i < size; i++ {
|
||||
result[i] = make([]int, size);
|
||||
}
|
||||
|
||||
for i := 0; i < size; i++ {
|
||||
for j := 0; j < size; j++ {
|
||||
result[i][j] = (i + 1) * (j + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
20
6kyu/parabolic_arc_length/solution.rs
Normal file
20
6kyu/parabolic_arc_length/solution.rs
Normal file
|
@ -0,0 +1,20 @@
|
|||
fn len_curve_of<F>(f: F, from: f64, to: f64, n: i32) -> f64
|
||||
where
|
||||
F: Fn(f64) -> f64,
|
||||
{
|
||||
let dx = (to - from) / n as f64;
|
||||
let dx2 = dx * dx;
|
||||
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let left = f(from + i as f64 * dx);
|
||||
let right = f(from + (i + 1) as f64 * dx);
|
||||
|
||||
(dx2 + (left - right).abs().powf(2.0)).sqrt()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
pub fn len_curve(n: i32) -> f64 {
|
||||
len_curve_of(|x| x * x, 0.0, 1.0, n)
|
||||
}
|
7
6kyu/pascals_triangle/solution.hs
Normal file
7
6kyu/pascals_triangle/solution.hs
Normal file
|
@ -0,0 +1,7 @@
|
|||
module Codewars.Kata.PascalsTriangle where
|
||||
|
||||
pascalsRow :: Int -> [Int]
|
||||
pascalsRow n = scanl (\nCk k -> (nCk * (n - k)) `div` (k + 1)) 1 [0..n - 1]
|
||||
|
||||
pascalsTriangle :: Int -> [Int]
|
||||
pascalsTriangle n = concatMap pascalsRow [0..n - 1]
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue