-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnclassifiedAlgorithms.cs
103 lines (91 loc) · 2.51 KB
/
UnclassifiedAlgorithms.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Linq;
namespace dojo
{
public static class UnclassifiedAlgorithms
{
public static bool IsPrime(int number)
{
if (number == 2 || number == 3)
{
return true;
}
else
{
var squareRoot = (int)Math.Floor((Math.Sqrt(number)));
for (var num = 3; num < squareRoot; num += 2)
{
if (number % num == 0)
{
return false;
}
}
return true;
}
}
public static int SumOfIndividualIntegerNumbers(int num)
{
var sum = 0;
while (num > 0)
{
sum += num % 10;
num /= 10;
}
return sum;
}
public static int MemoizeFib(int n)
{
if (n == 2 || n == 3)
{
return 1;
}
if (Cache.ContainsKey(n))
{
Console.WriteLine("from cache for " + n);
return Cache[n];
}
else
{
Console.WriteLine("calculating " + n);
Cache[n] = MemoizeFib(n - 1) + MemoizeFib(n - 2);
return Cache[n];
}
}
public static int FibSequence(int n)
{
if (n == 2 || n == 3)
{
return 1;
}
return FibSequence(n - 1) + FibSequence(n - 2);
}
public static int CalculateNumberOfBoats(IList<int> weights, int limit)
{
weights = weights.OrderBy(w => w).ToArray();
var leftPointer = 0;
var rightPointer = weights.Count - 1;
var boats = 0;
while (leftPointer <= rightPointer)
{
if (leftPointer == rightPointer)
{
boats++;
break;
}
if (weights[leftPointer] + weights[rightPointer] <= limit)
{
leftPointer++;
rightPointer--;
}
else
{
rightPointer--;
}
boats++;
}
return boats;
}
private static readonly Dictionary<int, int> Cache = new Dictionary<int, int>();
}
}