Skip to content

Commit 89390c3

Browse files
committed
Optimize stage 1
1 parent 6c220ce commit 89390c3

File tree

3 files changed

+44
-160
lines changed

3 files changed

+44
-160
lines changed

Algorithms/Other/Luhn.cs

Lines changed: 18 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -10,62 +10,36 @@ namespace Algorithms.Other;
1010
/// </summary>
1111
public static class Luhn
1212
{
13-
/// <summary>
14-
/// Checking the validity of a sequence of numbers.
15-
/// </summary>
16-
/// <param name="number">The number that will be checked for validity.</param>
17-
/// <returns>
18-
/// True: Number is valid.
19-
/// False: Number isn`t valid.
20-
/// </returns>
13+
// Checking the validity of a sequence of numbers.
2114
public static bool Validate(string number) => GetSum(number) % 10 == 0;
2215

23-
/// <summary>
24-
/// This algorithm finds one missing digit.
25-
/// In place of the unknown digit, put "x".
26-
/// </summary>
27-
/// <param name="number">The number in which to find the missing digit.</param>
28-
/// <returns>Missing digit.</returns>
16+
// Finds one missing digit. In place of the unknown digit, put "x".
2917
public static int GetLostNum(string number)
3018
{
31-
var missingDigitIndex = number.Length - 1 - number.LastIndexOf("x", StringComparison.CurrentCultureIgnoreCase);
32-
var checkDigit = GetSum(number.Replace("x", "0", StringComparison.CurrentCultureIgnoreCase)) * 9 % 10;
33-
34-
// Case 1: If the index of the missing digit is even.
35-
if (missingDigitIndex % 2 == 0)
36-
{
37-
return checkDigit;
38-
}
39-
40-
var candidateDigit = checkDigit / 2;
41-
42-
// Case 2: if the index of the missing digit is odd and the candidate is valid.
43-
// Case 3: if the index of the missing digit is odd and we need the alternative.
44-
return Validate(number.Replace("x", candidateDigit.ToString())) ? candidateDigit : (checkDigit + 9) / 2;
19+
var missingDigitIndex = number.Length - 1 - number.LastIndexOf('x');
20+
var checkDigit = GetSum(number.Replace("x", "0")) * 9 % 10;
21+
22+
return missingDigitIndex % 2 == 0
23+
? checkDigit
24+
: Validate(number.Replace("x", (checkDigit / 2).ToString()))
25+
? checkDigit / 2
26+
: (checkDigit + 9) / 2;
4527
}
4628

47-
/// <summary>
48-
/// Computes the sum found by the Luhn algorithm.
49-
/// </summary>
50-
/// <param name="number">The number for which the sum will be calculated.</param>
51-
/// <returns>Sum.</returns>
29+
// Computes the sum found by the Luhn algorithm, optimized with Span.
5230
private static int GetSum(string number)
5331
{
5432
var sum = 0;
55-
for (var i = 0; i < number.Length; i++)
33+
var span = number.AsSpan();
34+
for (var i = 0; i < span.Length; i++)
5635
{
57-
var digit = number[i] - '0';
58-
digit = (i + number.Length) % 2 == 0
59-
? 2 * digit
60-
: digit;
61-
if (digit > 9)
62-
{
63-
digit -= 9;
64-
}
65-
36+
var c = span[i];
37+
if (c is < '0' or > '9') continue;
38+
var digit = c - '0';
39+
digit = (i + span.Length) % 2 == 0 ? 2 * digit : digit;
40+
if (digit > 9) digit -= 9;
6641
sum += digit;
6742
}
68-
6943
return sum;
7044
}
7145
}

DataStructures/BinarySearchTree/BinarySearchTree.cs

Lines changed: 10 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -15,88 +15,43 @@ namespace DataStructures.BinarySearchTree;
1515
/// <typeparam name="TKey">Type of key for the BST. Keys must implement IComparable.</typeparam>
1616
public class BinarySearchTree<TKey>
1717
{
18-
/// <summary>
19-
/// Comparer to use when comparing node elements/keys.
20-
/// </summary>
18+
// Comparer to use when comparing node elements/keys.
2119
private readonly Comparer<TKey> comparer;
2220

23-
/// <summary>
24-
/// Gets the root of the BST.
25-
/// </summary>
21+
// Gets the root of the BST.
2622
public BinarySearchTreeNode<TKey>? Root { get; private set; }
2723

28-
public BinarySearchTree()
29-
{
30-
Root = null;
31-
Count = 0;
32-
comparer = Comparer<TKey>.Default;
33-
}
24+
public BinarySearchTree() => (Root, Count, comparer) = (null, 0, Comparer<TKey>.Default);
3425

35-
public BinarySearchTree(Comparer<TKey> customComparer)
36-
{
37-
Root = null;
38-
Count = 0;
39-
comparer = customComparer;
40-
}
26+
public BinarySearchTree(Comparer<TKey> customComparer) => (Root, Count, comparer) = (null, 0, customComparer);
4127

42-
/// <summary>
43-
/// Gets the number nodes currently in the BST.
44-
/// </summary>
28+
// Gets the number nodes currently in the BST.
4529
public int Count { get; private set; }
4630

47-
/// <summary>
48-
/// Insert a key into the BST.
49-
/// </summary>
50-
/// <param name="key">The key to insert.</param>
51-
/// <exception cref="ArgumentException">
52-
/// Thrown if key is already in BST.
53-
/// </exception>
31+
// Insert a key into the BST.
5432
public void Add(TKey key)
5533
{
5634
if (Root is null)
57-
{
5835
Root = new BinarySearchTreeNode<TKey>(key);
59-
}
6036
else
61-
{
6237
Add(Root, key);
63-
}
64-
6538
Count++;
6639
}
6740

68-
/// <summary>
69-
/// Insert multiple keys into the BST.
70-
/// Keys are inserted in the order they appear in the sequence.
71-
/// </summary>
72-
/// <param name="keys">Sequence of keys to insert.</param>
41+
// Insert multiple keys into the BST.
7342
public void AddRange(IEnumerable<TKey> keys)
7443
{
7544
foreach (var key in keys)
76-
{
7745
Add(key);
78-
}
7946
}
8047

81-
/// <summary>
82-
/// Find a node with the specified key.
83-
/// </summary>
84-
/// <param name="key">The key to search for.</param>
85-
/// <returns>The node with the specified key if it exists, otherwise a default value is returned.</returns>
48+
// Find a node with the specified key.
8649
public BinarySearchTreeNode<TKey>? Search(TKey key) => Search(Root, key);
8750

88-
/// <summary>
89-
/// Checks if the specified key is in the BST.
90-
/// </summary>
91-
/// <param name="key">The key to search for.</param>
92-
/// <returns>true if the key is in the BST, false otherwise.</returns>
51+
// Checks if the specified key is in the BST.
9352
public bool Contains(TKey key) => Search(Root, key) is not null;
9453

95-
/// <summary>
96-
/// Removes a node with a key that matches <paramref name="key" />.
97-
/// </summary>
98-
/// <param name="key">The key to search for.</param>
99-
/// <returns>true if the removal was successful, false otherwise.</returns>
54+
// Removes a node with a key that matches key.
10055
public bool Remove(TKey key)
10156
{
10257
if (Root is null)

DataStructures/Timeline.cs

Lines changed: 16 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ this data structure can be used to represent an ordered series of dates or times
1212
330: Constantine move the capital to Constantinople.
1313
*/
1414

15-
using System.Collections;
1615

1716
namespace DataStructures;
1817

@@ -23,83 +22,39 @@ namespace DataStructures;
2322
/// <typeparam name="TValue">Value associated with a <see cref="DateTime" />.</typeparam>
2423
public class Timeline<TValue> : ICollection<(DateTime Time, TValue Value)>, IEquatable<Timeline<TValue>>
2524
{
26-
/// <summary>
27-
/// Inner collection storing the timeline events as key-tuples.
28-
/// </summary>
29-
private readonly List<(DateTime Time, TValue Value)> timeline = new();
25+
// Inner collection storing the timeline events as key-tuples.
26+
private List<(DateTime Time, TValue Value)> timeline = [];
3027

31-
/// <summary>
32-
/// Initializes a new instance of the <see cref="Timeline{TValue}"/> class.
33-
/// </summary>
34-
public Timeline()
35-
{
36-
}
28+
// Default constructor
29+
public Timeline() { }
3730

38-
/// <summary>
39-
/// Initializes a new instance of the <see cref="Timeline{TValue}"/> class populated with an initial event.
40-
/// </summary>
41-
/// <param name="time">The time at which the given event occurred.</param>
42-
/// <param name="value">The event's content.</param>
43-
public Timeline(DateTime time, TValue value)
44-
=> timeline = new List<(DateTime, TValue)>
45-
{
46-
(time, value),
47-
};
31+
// Constructor with initial event
32+
public Timeline(DateTime time, TValue value) => timeline = [(time, value)];
4833

49-
/// <summary>
50-
/// Initializes a new instance of the <see cref="Timeline{TValue}"/> class containing the provided events
51-
/// ordered chronologically.
52-
/// </summary>
53-
/// <param name="timeline">The timeline to represent.</param>
54-
public Timeline(params (DateTime, TValue)[] timeline)
55-
=> this.timeline = timeline
56-
.OrderBy(pair => pair.Item1)
57-
.ToList();
34+
// Constructor with provided events, ordered chronologically
35+
public Timeline(params (DateTime, TValue)[] timeline) => this.timeline = timeline.OrderBy(pair => pair.Item1).ToList();
5836

59-
/// <summary>
60-
/// Gets he number of unique times within this timeline.
61-
/// </summary>
62-
public int TimesCount
63-
=> GetAllTimes().Length;
37+
// Gets the number of unique times within this timeline.
38+
public int TimesCount => GetAllTimes().Length;
6439

65-
/// <summary>
66-
/// Gets all events that has occurred in this timeline.
67-
/// </summary>
68-
public int ValuesCount
69-
=> GetAllValues().Length;
40+
// Gets all events that has occurred in this timeline.
41+
public int ValuesCount => GetAllValues().Length;
7042

71-
/// <summary>
72-
/// Get all values associated with <paramref name="time" />.
73-
/// </summary>
74-
/// <param name="time">Time to get values for.</param>
75-
/// <returns>Values associated with <paramref name="time" />.</returns>
43+
// Get or set all values associated with a time
7644
public TValue[] this[DateTime time]
7745
{
7846
get => GetValuesByTime(time);
7947
set
8048
{
81-
var overridenEvents = timeline.Where(@event => @event.Time == time).ToList();
82-
foreach (var @event in overridenEvents)
83-
{
84-
timeline.Remove(@event);
85-
}
86-
49+
timeline.RemoveAll(@event => @event.Time == time);
8750
foreach (var v in value)
88-
{
8951
Add(time, v);
90-
}
9152
}
9253
}
9354

94-
/// <inheritdoc />
95-
bool ICollection<(DateTime Time, TValue Value)>.IsReadOnly
96-
=> false;
55+
bool ICollection<(DateTime Time, TValue Value)>.IsReadOnly => false;
9756

98-
/// <summary>
99-
/// Gets the count of pairs.
100-
/// </summary>
101-
public int Count
102-
=> timeline.Count;
57+
public int Count => timeline.Count;
10358

10459
/// <summary>
10560
/// Clear the timeline, removing all events.

0 commit comments

Comments
 (0)