However we often struggle to apply them in real world. We face difficulties to refactor a piece of functionality to use the right patterns or to apply a good software development principle. Honestly it is not an easy job to do so. Is is not only difficult to find out which practices and patterns to use, it is also difficult to decide should we apply any pattern at all or not. Developers often get obsessed with patterns and practices and they try to apply them everywhere they can. We should remember that everything in life is trade off, so is with the patterns and practices. A pattern or practice not implemented correctly may complicate our software and make it hard to maintain. There are lot of factors because of which we can decide not to use design patterns like cost, effort, deadlines, business value and etc.

Patterns and practices are some of our few friends in software development that help us to produce quality software.

In this article we will analyze an example functionality and then we will refactor it to use strategy and factory patterns in order to make it open for extension and closed for modifications. Although for a simple functionality like in this article it may seem overwhelming to use this approach for more complicated and real world application it may be beneficial.

We will look at functionality that calculates a commission for money transactions based on different rules and conditions.

We will create a simple console app for that purpose. To make it look more like a real world software we will also use dependency injection container which we will install as a NuGet package from Unity.Microsoft.DependencyInjection.

Here are our Transaction class and TransactionType enumeration.

```
public class Transaction
{
public long Id { get; set; }
public decimal Amount { get; set; }
public TransactionType TransactionType { get; set; }
public DateTime? TransactionDateTime { get; set; }
}
public enum TransactionType
{
Sale,
Settlement,
Refund,
ChargeBack,
Void
}
```

In order to calculate commissions we will create commission entity which ideally should be stored in database but for the sake of simplicity we will create them in memory in this example.

```
public class Commission
{
public int Id { get; set; }
public decimal Percent { get; set; }
public decimal CommissionFixedAmount { get; set; }
public DateTime ValidUntil { get; set; }
}
```

Each commission has a validity date determined by ValidUntil property.

Then we have the following interface for a commission repository which is used to get the active commission based on transaction date.

```
public interface ICommissionRepository
{
Commission Get(DateTime date);
}
```

We will have two implementation of this interface one for regular commissions and one for commissions with transaction type Refund.

```
public class CommissionRepository : ICommissionRepository
{
// In real app get this information from DB
private readonly List<Commission> dbCommissions = new List<Commission>
{
new Commission
{
Id = 1,
Percent = 10.00m,
CommissionFixedAmount = 10.00m,
ValidUntil = new DateTime(2020, 12, 31)
},
new Commission
{
Id = 2,
Percent = 20.00m,
CommissionFixedAmount = 20.00m,
ValidUntil = new DateTime(2021, 12, 31)
}
};
public Commission Get(DateTime date)
{
return dbCommissions.OrderByDescending(c => c.ValidUntil).FirstOrDefault(c => date <= c.ValidUntil);
}
}
```

```
public class RefundCommissionRepository: ICommissionRepository
{
// In real world get this information from DB
private readonly List<Commission> dbCommissions = new List<Commission>
{
new Commission
{
Id = 3,
Percent = 1.00m,
CommissionFixedAmount = 1.00m,
ValidUntil = new DateTime(2020, 12, 31)
},
new Commission
{
Id = 4,
Percent = 2.00m,
CommissionFixedAmount = 2.00m,
ValidUntil = new DateTime(2021, 12, 31)
}
};
public Commission Get(DateTime date)
{
return dbCommissions.OrderByDescending(c => c.ValidUntil).FirstOrDefault(c => date <= c.ValidUntil);
}
}
```

The main functionality will be in CommissionCalculatorService where we will calculate a commission for a given transaction entity.

```
public interface ICommissionCalculatorService
{
decimal Calculate(Transaction transaction);
}
```

```
public class CommissionCalculatorService : ICommissionCalculatorService
{
private readonly ICommissionRepository commissionRepository;
private readonly ICommissionRepository refundCommissionRepository;
// In real world read those values from config or database
private const decimal DefaultCommissionPercent = 5.00m;
private const decimal BeforeScheduleCommissionPercent = 1.00m;
private readonly DateTime commissionScheduleStartDate = new DateTime(2000, 1, 1);
public CommissionCalculatorService(List<ICommissionRepository> commissionRepositories)
{
this.commissionRepository =
commissionRepositories.First(cr => cr.GetType() == typeof(CommissionRepository));
this.refundCommissionRepository =
commissionRepositories.First(cr => cr.GetType() == typeof(RefundCommissionRepository));
}
public decimal Calculate(Transaction transaction)
{
if (transaction == default(Transaction))
{
return 0.00m;
}
if (transaction.TransactionType == TransactionType.ChargeBack ||
transaction.TransactionType == TransactionType.Void)
{
return 0.00m;
}
if (!transaction.TransactionDateTime.HasValue)
{
return transaction.Amount * DefaultCommissionPercent / 100;
}
if (transaction.TransactionDateTime <= this.commissionScheduleStartDate)
{
return transaction.Amount * BeforeScheduleCommissionPercent / 100;
}
if (transaction.TransactionType == TransactionType.Refund)
{
var refundCommission = this.refundCommissionRepository.Get(transaction.TransactionDateTime.Value);
if (refundCommission == null)
{
return -1 * (transaction.Amount * DefaultCommissionPercent / 100);
}
return -1 * (transaction.Amount * refundCommission.Percent / 100 + refundCommission.CommissionFixedAmount);
}
var commission = this.commissionRepository.Get(transaction.TransactionDateTime.Value);
if (commission == null)
{
return transaction.Amount * DefaultCommissionPercent / 100;
}
return transaction.Amount * commission.Percent / 100 + commission.CommissionFixedAmount;
}
}
```

Take a moment to examine the logic for calculating the commission which depends on different properties of transaction entity.

We have the following rules for calculating commission:

- If transaction is null or it’s type is ChargeBack or Void then no commission is calculated
- If transaction does not have a TransactionDateTime then calculate default commission
- If transaction date is before commissionScheduleStartDate then calculate a commission based on BeforeScheduleCommissionPercent
- If transaction type is Refund then get the valid commission from RefundCommissionRepository and calculate the commission based on negative refund commission, however if there is no valid refund commission then calculate a negative default commission.
- If transaction type is Sale or Settlement then get the valid commission from CommissionRepository and calculate the commission based on retrieved commission, however if there is no valid commission then calculate default commission

This is the area that we are going to refactor. Imagine we start receiving more and more rules for calculating transaction commissions then each time we have to open this logic and modify it and at some point it may become really hard to understand and maintain with all those if statements and conditions.

Let’s see how we calculate commissions for transactions with different properties.

```
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<ICommissionCalculatorService, CommissionCalculatorService>();
container.RegisterType<ICommissionRepository, CommissionRepository>("Default");
container.RegisterType<ICommissionRepository, RefundCommissionRepository>("Refund");
var commissionCalculatorService = container.Resolve<ICommissionCalculatorService>();
List<Transaction> transactions = new List<Transaction>
{
null,
new Transaction
{
Id = 1,
Amount = 100m,
TransactionType = TransactionType.ChargeBack,
TransactionDateTime = new DateTime(2000, 2, 2)
},
new Transaction
{
Id = 2,
Amount = 100m,
TransactionType = TransactionType.Void,
TransactionDateTime = DateTime.Now
},
new Transaction
{
Id = 3,
Amount = 100m,
TransactionType = TransactionType.Sale
},
new Transaction
{
Id = 4,
Amount = 100m,
TransactionType = TransactionType.Sale,
TransactionDateTime = new DateTime(1999,12,15)
},
new Transaction
{
Id = 5,
Amount = 100m,
TransactionType = TransactionType.Refund,
TransactionDateTime = new DateTime(2021,8,15)
},
new Transaction
{
Id = 6,
Amount = 100m,
TransactionType = TransactionType.Refund,
TransactionDateTime = new DateTime(2022,8,15)
},
new Transaction
{
Id = 7,
Amount = 100m,
TransactionType = TransactionType.Sale,
TransactionDateTime = new DateTime(2021,8,15)
},
new Transaction
{
Id = 8,
Amount = 100m,
TransactionType = TransactionType.Sale,
TransactionDateTime = new DateTime(2022,8,15)
},
new Transaction
{
Id = 9,
Amount = 100m,
TransactionType = TransactionType.Settlement,
TransactionDateTime = new DateTime(2021,8,15)
},
new Transaction
{
Id = 10,
Amount = 100m,
TransactionType = TransactionType.Settlement,
TransactionDateTime = new DateTime(2022,8,15)
}
};
foreach (var transaction in transactions)
{
var commission = commissionCalculatorService.Calculate(transaction);
Console.WriteLine($"Commission for transaction with Id:{transaction?.Id} and amount:{transaction?.Amount} is {commission}");
}
}
```

We get the following commissions calculated

Imagine the logic for each commission calculation is separated and encapsulated in it’s own class/module.

By doing this we impose a single responsibility principle and also separation of concerns if you like. When we have an issue in a specific commission calculation we open one class and look for the problem there instead of struggling in a code with a lot of ifs and switches.

Also if we have a new commission calculation rule we won’t modify any existing strategy but we will add new class with the new calculation logic. It sounds like an open closed principle.

But who will decide which calculation strategy is going to be used. Here comes the factory, which will orchestrate the different strategies and return the correct strategy to calculate transaction commission.

Let’s start creating strategies for different commission calculations.

```
public class NoCommissionCalculator: ICommissionCalculatorService
{
public decimal Calculate(Transaction transaction)
{
return 0.00m;
}
}
```

This strategy will be used in cases where we have no commission.

```
public class DefaultCommissionCalculator: ICommissionCalculatorService
{
// In real world read this value from config or database
private const decimal DefaultCommissionPercent = 5.00m;
public decimal Calculate(Transaction transaction)
{
return transaction.Amount * DefaultCommissionPercent / 100;
}
}
```

This strategy is for default commission calculation.

```
public class BeforeScheduleCommissionCalculator : ICommissionCalculatorService
{
// In real world read this value from config or database
private const decimal BeforeScheduleCommissionPercent = 1.00m;
public decimal Calculate(Transaction transaction)
{
return transaction.Amount * BeforeScheduleCommissionPercent / 100;
}
}
```

This strategy is for cases where transaction date is earlier than CommissionScheduleStartDate.

```
public class RefundCommissionCalculator : ICommissionCalculatorService
{
private readonly ICommissionRepository refundCommissionRepository;
private readonly ICommissionCalculatorService defaultCommissionCalculatorService;
public RefundCommissionCalculator(
IEnumerable<ICommissionRepository> commissionRepositories,
IEnumerable<ICommissionCalculatorService> commissionCalculatorServices)
{
this.refundCommissionRepository = commissionRepositories.First(cr => cr.GetType() == typeof(RefundCommissionRepository));
this.defaultCommissionCalculatorService = commissionCalculatorServices.First(cc=>cc.GetType() == typeof(DefaultCommissionCalculator));
}
public decimal Calculate(Transaction transaction)
{
var refundCommission = this.refundCommissionRepository.Get(transaction.TransactionDateTime.Value);
if (refundCommission == null)
{
return -1 * this.defaultCommissionCalculatorService.Calculate(transaction);
}
return -1 * (transaction.Amount * refundCommission.Percent / 100 + refundCommission.CommissionFixedAmount);
}
}
```

This is the strategy for refund commission calculation. We inject the default commission calculator here as it is used to calculate default commission if we don’t find valid refund commission.

```
public class MainCommissionCalculator : ICommissionCalculatorService
{
private readonly ICommissionRepository commissionRepository;
private readonly ICommissionCalculatorService defaultCommissionCalculatorService;
public MainCommissionCalculator(
IEnumerable<ICommissionRepository> commissionRepositories,
IEnumerable<ICommissionCalculatorService> commissionCalculatorServices)
{
this.commissionRepository = commissionRepositories.First(cr => cr.GetType() == typeof(CommissionRepository));
this.defaultCommissionCalculatorService = commissionCalculatorServices.First(cc=>cc.GetType() == typeof(DefaultCommissionCalculator));
}
public decimal Calculate(Transaction transaction)
{
var commission = this.commissionRepository.Get(transaction.TransactionDateTime.Value);
if (commission == null)
{
return this.defaultCommissionCalculatorService.Calculate(transaction);
}
return transaction.Amount * commission.Percent / 100 + commission.CommissionFixedAmount;
}
}
```

This is the strategy for main commission calculation for transaction types Sale and Settlement. We inject the default commission calculator here as it is used to calculate default commission if we don’t find valid commission.

Now let’s look at the factory class that will orchestrate all those strategies and return the correct commission calculator.

```
public interface ICommissionCalculatorFactory
{
ICommissionCalculatorService CreateFor(Transaction transaction);
}
```

```
public class CommissionCalculatorFactory : ICommissionCalculatorFactory
{
// In real world read this value from config or database
private static readonly DateTime CommissionScheduleStartDate = new DateTime(2000, 1, 1);
private readonly IEnumerable<ICommissionCalculatorService> commissionCalculatorServices;
private readonly Func<Transaction, bool> isNoCommission = transaction =>
transaction == default(Transaction) || transaction.TransactionType == TransactionType.ChargeBack || transaction.TransactionType == TransactionType.Void;
private readonly Func<Transaction, bool> isDefaultCommission = transaction => !transaction.TransactionDateTime.HasValue;
private readonly Func<Transaction, bool> isBeforeScheduleCommission = transaction => transaction.TransactionDateTime <= CommissionScheduleStartDate;
private readonly Func<Transaction, bool> isRefundCommission = transaction => transaction.TransactionType == TransactionType.Refund;
private readonly Func<Transaction, bool> isMainCommission = transaction => true;
public CommissionCalculatorFactory(IEnumerable<ICommissionCalculatorService> commissionCalculatorServices)
{
this.commissionCalculatorServices = commissionCalculatorServices;
}
public ICommissionCalculatorService CreateFor(Transaction transaction)
{
Dictionary<Func<Transaction, bool>, ICommissionCalculatorService> commissionCalculators =
new Dictionary<Func<Transaction, bool>, ICommissionCalculatorService>
{
{ this.isNoCommission, this.commissionCalculatorServices.First(cs => cs.GetType() == typeof(NoCommissionCalculator)) },
{ this.isDefaultCommission, this.commissionCalculatorServices.First(cs => cs.GetType() == typeof(DefaultCommissionCalculator)) },
{ this.isBeforeScheduleCommission, this.commissionCalculatorServices.First(cs => cs.GetType() == typeof(BeforeScheduleCommissionCalculator)) },
{ this.isRefundCommission, this.commissionCalculatorServices.First(cs => cs.GetType() == typeof(RefundCommissionCalculator)) },
{ this.isMainCommission, this.commissionCalculatorServices.First(cs => cs.GetType() == typeof(MainCommissionCalculator)) }
};
return commissionCalculators.First(cc => cc.Key(transaction)).Value;
}
}
```

In the factory class we define all conditions as delegates and then construct a key value collection where the key is the delegate and the value is the corresponding commission calculator strategy.

We then simply return the commission calculator whose delegate returns true.

Let’s once again execute the main function and see how a commission is calculated for each transaction from our previous example above before the refactoring.

```
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<ICommissionCalculatorService, CommissionCalculatorService>();
container.RegisterType<ICommissionRepository, CommissionRepository>("Default");
container.RegisterType<ICommissionRepository, RefundCommissionRepository>("Refund");
container.RegisterType<ICommissionCalculatorFactory, CommissionCalculatorFactory>();
container.RegisterType<ICommissionCalculatorService, NoCommissionCalculator>("NoCommissionCalculator");
container.RegisterType<ICommissionCalculatorService, DefaultCommissionCalculator>("DefaultCommissionCalculator");
container.RegisterType<ICommissionCalculatorService, BeforeScheduleCommissionCalculator>("BeforeScheduleCommissionCalculator");
container.RegisterType<ICommissionCalculatorService, RefundCommissionCalculator>("RefundCommissionCalculator");
container.RegisterType<ICommissionCalculatorService, MainCommissionCalculator>("MainCommissionCalculator");
var commissionCalculatorFactory = container.Resolve<CommissionCalculatorFactory>();
List<Transaction> transactions = new List<Transaction>
{
null,
new Transaction
{
Id = 1,
Amount = 100m,
TransactionType = TransactionType.ChargeBack,
TransactionDateTime = new DateTime(2000, 2, 2)
},
new Transaction
{
Id = 2,
Amount = 100m,
TransactionType = TransactionType.Void,
TransactionDateTime = DateTime.Now
},
new Transaction
{
Id = 3,
Amount = 100m,
TransactionType = TransactionType.Sale
},
new Transaction
{
Id = 4,
Amount = 100m,
TransactionType = TransactionType.Sale,
TransactionDateTime = new DateTime(1999,12,15)
},
new Transaction
{
Id = 5,
Amount = 100m,
TransactionType = TransactionType.Refund,
TransactionDateTime = new DateTime(2021,8,15)
},
new Transaction
{
Id = 6,
Amount = 100m,
TransactionType = TransactionType.Refund,
TransactionDateTime = new DateTime(2022,8,15)
},
new Transaction
{
Id = 7,
Amount = 100m,
TransactionType = TransactionType.Sale,
TransactionDateTime = new DateTime(2021,8,15)
},
new Transaction
{
Id = 8,
Amount = 100m,
TransactionType = TransactionType.Sale,
TransactionDateTime = new DateTime(2022,8,15)
},
new Transaction
{
Id = 9,
Amount = 100m,
TransactionType = TransactionType.Settlement,
TransactionDateTime = new DateTime(2021,8,15)
},
new Transaction
{
Id = 10,
Amount = 100m,
TransactionType = TransactionType.Settlement,
TransactionDateTime = new DateTime(2022,8,15)
}
};
foreach (var transaction in transactions)
{
var commissionCalculator = commissionCalculatorFactory.CreateFor(transaction);
var commission = commissionCalculator.Calculate(transaction);
Console.WriteLine($"Commission for transaction with Id:{transaction?.Id} and amount:{transaction?.Amount} is {commission}");
}
}
```

You can see how we first register all strategies and then for each transaction we ask for a specific commission calculator and then calculate the commission. As expected the result is same as above.

We have refactored our logic to use different strategies for different commission calculations using patterns and principles like strategy, factory, open closed, separation of concerns and single responsibility.

]]>

As graphs can have cycles we should not visit any visited vertex twice. For this purpose the algorithm must know if a vertex is visited and it shouldn’t visit it again. To implement the algorithm usually a helper stack is used. Let’s have a look at an example to better understand how the algorithm works.

Let’s say that we have the simple graph above and we want to traverse the graph by starting from vertex A.

At this point we have traversed all the vertices in the graph, so the DFS algorithm finishes.

Lets first create a simple vertex class which will represent the vertices in a graph.

```
public class Vertex
{
public Vertex(string name)
{
this.Name = name;
}
public string Name { get; set; }
public bool IsVisited { get; set; }
}
```

Next let’s create a graph class that will implement DFS algorithm.

```
public class Graph
{
// Adjacency list which will keep the connections between vertices
private readonly Dictionary<Vertex, List<Vertex>> adjLists;
public Graph()
{
adjLists = new Dictionary<Vertex, List<Vertex>>();
}
// Add edge between src---->dest vertices
public void AddEdge(Vertex src, Vertex dest)
{
if (this.adjLists.ContainsKey(src))
{
this.adjLists[src].Add(dest);
}
else
{
this.adjLists.Add(src, new List<Vertex> { dest });
}
}
// Applying DFS algorithm and returning a list of traversed vertices
public List<Vertex> Dfs(Vertex source)
{
List<Vertex> result = new List<Vertex>();
Stack<Vertex> vertexStack = new Stack<Vertex>();
vertexStack.Push(source);
while (vertexStack.Count > 0)
{
var vertex = vertexStack.Pop();
vertex.IsVisited = true;
result.Add(vertex);
// Add all unvisited adjacency
//vertices of currently visited vertex
// into the stack
foreach (var v in this.adjLists[vertex])
{
if (!v.IsVisited)
{
vertexStack.Push(v);
}
}
}
return result;
}
}
```

Finally we will construct the graph from the example above and run the DFS algorithm on it to show the order in which the vertices will be visited.

```
static void Main(string[] args)
{
var graph = new Graph();
var vA = new Vertex("A");
var vB = new Vertex("B");
var vC = new Vertex("C");
var vD = new Vertex("D");
var vE = new Vertex("E");
graph.AddEdge(vA, vB);
graph.AddEdge(vA, vC);
graph.AddEdge(vA, vD);
graph.AddEdge(vB, vA);
graph.AddEdge(vC, vA);
graph.AddEdge(vC, vE);
graph.AddEdge(vD, vA);
graph.AddEdge(vE, vC);
var traversed = graph.Dfs(vA);
foreach (var t in traversed)
{
Console.Write($"{t.Name} ");
}
}
```

When we run the console app the result will be:

**A D C E B**

The time complexity of the DFS algorithm is `O(V + E)`

, where `V` is the number of vertices and E is the number of edges.

As graphs can have cycles we should not visit any visited vertex twice. For this purpose the algorithm must know if a vertex is visited and it shouldn’t visit it again. To implement the algorithm usually a helper queue is used. Let’s have a look at an example to better understand how the algorithm works.

Let’s say that we have the simple graph above and we want to traverse the graph by starting from vertex A.

At this point we have traversed all the vertices in the graph, so the BFS algorithm finishes.

Lets first create a simple vertex class which will represent the vertices in a graph.

```
public class Vertex
{
public Vertex(string name)
{
this.Name = name;
}
public string Name { get; set; }
public bool IsVisited { get; set; }
}
```

Next let’s create a graph class that will implement BFS algorithm.

```
public class Graph
{
// Adjacency list which will keep the connections between vertices
private readonly Dictionary<Vertex, List<Vertex>> adjLists;
public Graph()
{
adjLists = new Dictionary<Vertex, List<Vertex>>();
}
// Add edge between src---->dest vertices
public void AddEdge(Vertex src, Vertex dest)
{
if (this.adjLists.ContainsKey(src))
{
this.adjLists[src].Add(dest);
}
else
{
this.adjLists.Add(src, new List<Vertex> { dest });
}
}
// Applying BFS algorithm and returning a list of traversed vertices
public List<Vertex> Bfs(Vertex source)
{
List<Vertex> result = new List<Vertex>();
Queue<Vertex> vertexQueue = new Queue<Vertex>();
vertexQueue.Enqueue(source);
while (vertexQueue.Count > 0)
{
var vertex = vertexQueue.Dequeue();
vertex.IsVisited = true;
result.Add(vertex);
// Add all unvisited adjacency vertices of currently
// visited vertex into the queue
foreach (var v in this.adjLists[vertex])
{
if (!v.IsVisited)
{
vertexQueue.Enqueue(v);
}
}
}
return result;
}
}
```

Finally we will construct the graph from the example above and run the BFS algorithm on it to show the order in which the vertices will be visited.

```
static void Main(string[] args)
{
var graph = new Graph();
var vA = new Vertex("A");
var vB = new Vertex("B");
var vC = new Vertex("C");
var vD = new Vertex("D");
var vE = new Vertex("E");
graph.AddEdge(vA, vB);
graph.AddEdge(vA, vC);
graph.AddEdge(vA, vD);
graph.AddEdge(vB, vA);
graph.AddEdge(vC, vA);
graph.AddEdge(vC, vE);
graph.AddEdge(vD, vA);
graph.AddEdge(vE, vC);
var traversed = graph.Bfs(vA);
foreach (var t in traversed)
{
Console.Write($"{t.Name} ");
}
}
```

When we run the console app the result will be:

**A B C D E**

The time complexity of the BFS algorithm is `O(V + E)`

, where `V` is the number of vertices and E is the number of edges.

Recursion is the technique in which a function calls itself from within its own body.*You can find out more about what is recursion and see some examples in various programming languages, a good resource is this one.*

It is possible to achieve a recursion within a SQL query.

This is possible with the help of a CTE (common table expression). CTEs are representing a temporary named result set, generated by a query and defined within the execution scope of a SELECT, INSERT, UPDATE, DELETE or MERGE statement.

What that means is that if we want to have a temporary data-set structure, and we aim to use it just once directly after it is created, then the CTE is our best friend.

Furthermore, we are going to use it for the creation of a recursion.

Let’s visualize the technique with a concrete example.

We are going to implement a Fibonacci sequence with a recursive SQL query by using self-called CTE and return to the user the n-th number from the sequence. Sounds cool, right? OK, let’s jump in it.

*A refresher for those who have forgotten what are the Fibonacci numbers – the* *sequence starts with the numbers 0 and then 1 and every next number is equal to the sum of the previous two. So if we want to see the sequence of the first 6 elements it looks like this:*

`{ 0, 1, 2, 3, 5, 8 }`

And if we want to return the value of the n-th element (where n = 6 in our example), then it will be:

`8`

Now if we want to achieve that in SQL then we can wrap that in a function:

dbo.Fibonacci and have an input parameter that receives the length of the sequence – the count of the elements. At the end, our function will return the value of the last element.

Here is the implementation:

```
CREATE FUNCTION dbo.Fibonacci (@count int)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @result int;
;WITH cte_fibonacci(n, currentNum, nextNum)
AS
(
SELECT
0, 0, 1
UNION ALL
SELECT n + 1, nextNum, currentNum + nextNum
FROM cte_fibonacci
WHERE n < @count
)
SELECT @result = MAX(currentNum)
FROM cte_fibonacci
RETURN @result;
END;
GO
```

You can see that cte_fibonacci calls itself inside the SELECT query in its body.

Finally, let’s test our new function with the following query:

```
select dbo.Fibonacci(6) AS [Result]
```**Result**
**8**

]]>Let’s clarify what stable matching means with an example. Imagine we have two men and two women: Bob, Peter, Alice and Kate. Based on preference list we will try to match those couples.

Matching 1 is stable as Alice is Bob’s first choice and vice versa. Alice is also Peter’s first choice but Alice won’t leave Bob for Peter because she prefers Bob to Peter. Kate prefers Bob to Peter as well but Bob won’t leave Alice for Kate as he prefers Alice to Kate.

Matching 2 is not stable as Bob prefers Alice and Alice prefers Bob, so they will defect and chose each other so that Peter and Kate will remain stranded.

A stable matching is one that avoids such defects, this is called stability. In stable matching none of the matched candidate pairs wants to make a deal with each other and leave their assigned partners stranded.

This small scale of example shows that when we have equal number of candidates on each side with equal number of preferences the algorithm will generate a stable matching between all candidates and nobody will be left stranded. Lets’ explain how the algorithm works step by step, imagine we have the following couples each with their own preference list.

The men in the left side start to propose to women on the right side based on their preference list. Women on their side will either accept the proposal or reject it if they already have a better proposal from their preference list.

We complete the first iteration after all men try to make proposals to their first candidates in their lists. In the second iteration the men that don’ have any match and they still have left candidates on their lists try to propose to remaining candidates based on their priority.

After the second iteration we repeat the same step again.

At the end of third iteration we are on a situation where every man has a current match and no man can make a proposal to any women. The algorithm terminates either when every man has a match or the list of men’s candidates is exhausted.

Take into account that it is possible to have more than one stable matching and it is not guaranteed which one the algorithm will find.

One drawback of the algorithm is related to who benefits from the situation. Although the above example doesn’t show this case, the sides that make the proposals get their best candidates as possible from their preference list. On the other side the sides which are being proposed get their worst candidates as possible. So it matters who makes the proposals.

We will show a slightly different implementation which is object orientated. We will create a Candidate class with several methods required to implement the algorithm.

```
public class Candidate
{
private readonly List<Candidate> preferences;
private readonly string name;
public Candidate CurrentMatch { get; set; }
public Candidate(string name)
{
this.preferences = new List<Candidate>();
this.name = name;
}
public bool HasAnyPreferencesLeft()
{
return this.preferences.Any();
}
//Gets the first candidate from a not proposed candidates yet
public Candidate GetCandidateToPropose()
{
return preferences.FirstOrDefault();
}
public void AddPreferences(List<Candidate> preferenceList)
{
this.preferences.AddRange(preferenceList);
}
// Propose a match to a candidate
public void Propose(Candidate toCandidate)
{
// We can only propose if we haven't got a match already
if (CurrentMatch == null)
{
//Call receive proposal on the other candidate
toCandidate?.ReceiveProposal(this);
}
}
// Implement the logic for receiving proposal
public void ReceiveProposal(Candidate fromCandidate)
{
// If we don't have a match already accept the proposal
if (CurrentMatch == null)
{
this.AcceptProposal(fromCandidate);
}
else
{ // Check if the candidate sending the current proposal
// is not with higher priority in our preference list
if (preferences.IndexOf(fromCandidate) < preferences.IndexOf(this.CurrentMatch))
{
// So we have a better match then break the current match
CurrentMatch.BreakMatch(this);
// Accept the new proposal
this.AcceptProposal(fromCandidate);
}
else
{
// Reject the current proposal as we already have a better match
fromCandidate.BreakMatch(this);
}
}
}
public void AcceptProposal(Candidate fromCandidate)
{
// When a proposal is accepted link both candidates to each other
this.CurrentMatch = fromCandidate;
fromCandidate.CurrentMatch = this;
}
public void BreakMatch(Candidate fromCandidate)
{
// When breaking or rejecting a proposal then remove the candidate
// that broke or rejected the offer from list of preferences
this.preferences.Remove(fromCandidate);
this.CurrentMatch = null;
}
public override string ToString()
{
return this.name;
}
}
```

In the next step we will implement the algorithm and call it to find a stable matching for the example explained above.

```
class Program
{
static void Main(string[] args)
{
var bob = new Candidate("Bob");
var peter = new Candidate("Peter");
var alex = new Candidate("Alex");
var alice = new Candidate("Alice");
var kate = new Candidate("Kate");
var jane = new Candidate("Jane");
bob.AddPreferences(new List<Candidate> { alice, kate, jane });
peter.AddPreferences(new List<Candidate> { kate, alice, jane });
alex.AddPreferences(new List<Candidate> { alice, kate, jane });
kate.AddPreferences(new List<Candidate> { peter, bob, alex });
alice.AddPreferences(new List<Candidate> { bob, peter, alex });
jane.AddPreferences(new List<Candidate> { bob, peter, alex });
List<Candidate> men = new List<Candidate>
{
bob,
peter,
alex
};
List<Candidate> women = new List<Candidate>
{
alice,
kate,
jane
};
StableMatch(men);
PrintMatches(men);
}
private static void StableMatch(List<Candidate> candidates)
{
// execute the algorithm when there are candidates without matches
// and the candidate has items in his preference list
while (candidates.Any(c => c.HasAnyPreferencesLeft() && c.CurrentMatch == null))
{
foreach (var candidate in candidates)
{
candidate.Propose(candidate.GetCandidateToPropose());
}
}
}
private static void PrintMatches(List<Candidate> candidates)
{
foreach (var candidate in candidates)
{
Console.WriteLine($"{candidate} <---> {candidate.CurrentMatch}");
}
}
}
```

If we run the program above we will get the following result:

Bob <—> Alice

Peter <—> Kate

Alex <—> Jane

Time Complexity of Gale-Shapley Algorithm is O(n^{2})

You can read more about this algorithm here.

]]>- Take the input array and convert it to max heap by applying heapify operation on it.
- Take the root (first) element as it is the max element now and swap it with the last element in the array. Now the last element is the largest of all and it is in the correct place.
- Heapify the array again without already sorted elements at the end of the array because they are already in the correct position.
- Repeat steps 1 to 3 for all remaining elements in the unsorted imaginary sub array.

Let’s implement the steps explained above with a C# code.

First we will need a heapify method with which we are already familiar from our previous article.

```
private static void Heapify(int[] arr, int index, int length)
{
int largestInd = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
if (left < length && arr[left] > arr[largestInd])
{
largestInd = left;
}
if (right < length && arr[right] > arr[largestInd])
{
largestInd = right;
}
if (largestInd != index)
{
var temp = arr[index];
arr[index] = arr[largestInd];
arr[largestInd] = temp;
Heapify(arr, largestInd, length);
}
}
```

With a help of this method we will implement HeapSort method

```
private static void HeapSort(int[] arr)
{
var n = arr.Length;
//First convert the array to max heap
for (int i = n / 2 - 1; i >= 0; i--)
{
Heapify(arr, i, n);
}
// Starting from the last element
// swap last and first element as the
// first element will be always the max element
// then reduce the index (array size)
for (int j = n-1; j >= 0; j--)
{
int temp = arr[j];
arr[j] = arr[0];
arr[0] = temp;
// Heapify the remaining elements
// pay attention to j index we pass to Hepify method
Heapify(arr, 0, j);
}
}
```

Let’s now test our heapsort method

```
static void Main(string[] args)
{
int[] arr = { 25, 10, 40, 1, 15 };
HeapSort(arr);
PrintArr(arr);
Console.ReadLine();
}
private static void PrintArr(int[] arr)
{
string space = "";
foreach (var i in arr)
{
Console.Write(space + i);
space = ",";
}
Console.WriteLine("\n");
}
```

And the output is:

1,10,15,25,40

HeapSort has a complexity of O(nlog n) in all cases and it has O(1) space complexity as it operates on the same array all the time.

]]>Dijkstra’s algorithm is a greedy algorithm which in each step finds the best solution and when we sum those solutions we find the best solution in general. The algorithm doesn’t work for edges with negative weights so in this case is used another algorithm which is called Bellman–Ford algorithm.

Let’s create an example weighted graph and explain how the algorithm works.

Let’s say we want to find the shortest path from vertex A to vertex F.

Initially we assign infinite value to all vertices as we don’t know the shortest distance to them. We assign 0 to starting vertex A as distance to self is 0.

We take the starting vertex A and we mark it as visited and then we observe all connected vertices and if the value of the visited vertex plus weight of the edge to the neighbor vertex is smaller than current value of the neighbor vertex then we update the neighbor vertex’s value with the weight of the edge plus value of the current visited vertex.

So in our example the value of A is 0 and the distance to B is 1.0. The current value of B is infinity.

**(0 + 1.0) < infinity, then we update the value of B to 1.0**

The value of A is 0 and the distance to C is 2.0. The current value of C is infinity.

**(0 + 2.0) < infinity, then we update the value of C to 2.0**

The next step is to chose which vertex to visit. The key point here is to take vertex with minimum value from unvisited vertices. In our case this is vertex B which has value 1.0 and it is less than the value of vertex C which is 2.0. From implementation point of view this is the point where we use priority queue. We enqueue vertices in a priority queue and then when we need the vertex with min value we just call dequeue and we get the minimum vertex.

So now we are on vertex B. We repeat the same operations here. We need to check the values of all **unvisited** neighbor vertices and update them if the current value + edge weight to neighbor vertex is smaller than neighbor vertex’s value. Be careful not to perform this operation to the visited neighbors.

So in our case B is connected to A and D. As A is already visited we will observe only D.

D’s current value is infinity, B’s current value is 1.0 and distance to D is 6.5.

**(1.0 + 6.5) < infinity, then we update the value of D to 7.5**

In the next step we take the vertex with min value from unvisited vertices. In our case this is vertex C

C (2.0) < D (7.5)

C has the following neighbors: A, E, D. From those neighbors only D and E are unvisited so we only observe them.

D has a value of 7.5. C has value of 2.0 and distance to D is 0.5.

**(2.0 + 0.5) < 7.5, then we update the value of D to 2.5**

E has value of infinity. C has value of 2.0 and the distance to E is 10.5

**(2.0 + 10.5) < infinity, then we update the value of E to 12.5**

In the next step we take the unvisited vertex with minimum value which is D.

D(2.5) < E(12.5)

D has the following neighbors: C, E, F. From those neighbors only E and F are unvisited so we only observe them.

E has value of 12.5. D has value of 2.5 and the distance to E is 2.0

**(2.5 + 2.0) < 12.5, then we update the value of E to 4.5**

F has value of infinity, D has value of 2.5 and the distance to F is 0.5

**(2.5 + 0.5) < infinity, then we update the value of F to 3.0**

Next we take the vertex with minimum value from unvisited vertices which is F.

F(3.0) < E(4.5)

F has two neighbors: D and E. From those neighbors only E is unvisited so we observe only E.

E has value of 4.5. D has value of 3.0 and the distance to E is 1.0

**(3.0 + 1.0) < 4.5, then we update the value of E to 4.0**

We have only one vertex which is unvisited, we visit vertex E. As all neighbors of E are already visited we are done with the algorithm at this stage. All vertices are visited and they have assigned values.

Note that in this graph example we had to always update the values of neighbor vertices but take into account if:

**(current vertex’s value + distance from current to neighbor) > neighbor’s value **

we don’t update the neighbor vertex’s value.

So looking into the initial graph where we applied Dijkstra’s algorithm we can say that the shortest path from A to F is: A–> C–> D–> F and the total distance is 3.0.

Let’s have a look how we can implement Dijkstra’s algorithm with C# code. We we will use a priority queue which we explained in one of the previous articles here https://paircoders.com/2021/04/19/heap-priority-queue/

First we will create a Vertex class which will represent our vertices in the graph described above

```
public class Vertex : IComparable<Vertex>
{
// We could have defined Vertex<T>
// as generic to store any data inside
// it, as you would probably do in
// real world, here we miss it for
// simplicity
//public T Value { get; set; }
public string Name { get; set; }
public decimal Weight { get; set; }
public bool IsVisited { get; set; }
public Vertex Parent { get; set; }
public Vertex(string name)
{
this.Name = name;
}
public int CompareTo(Vertex other)
{
if (this.Weight < other.Weight)
return -1;
else if (this.Weight > other.Weight)
return 1;
else return 0;
}
}
```

We will keep a reference to the parent which last updated the current vertex’s value in order to be able to backtrack the shortest path for any given vertex.

Next we will create class Dijkstra

```
public class Dijkstra
{
private List<Vertex> vertices;
private decimal[][] adjMatrix;
public Dijkstra(decimal[][] graph, List<Vertex> vertices)
{
if (graph.Length != vertices.Count)
{
throw new InvalidOperationException("Mismatch between graph and vertices");
}
this.adjMatrix = graph;
this.vertices = vertices;
}
}
```

We use adjacency matrix to represent the graph, basically the two most popular approaches to represent a graph are adjacency matrix and adjacency list, you can learn more about this topic here https://www.geeksforgeeks.org/graph-and-its-representations/

Next we will add a method to Dijkstra class called ApplyDijkstra which will apply the algorithm.

```
private void ApplyDijkstra(int source)
{
PriorityQueue<Vertex> pq =
new PriorityQueue<Vertex>(PriroityQueueType.Min);
// Initialize all vertices with infinite value
foreach (var v in this.vertices)
{
v.Weight = decimal.MaxValue;
}
// Source vertex's distance to self is zero
this.vertices[source].Weight = 0.0m;
pq.Enqueue(this.vertices[source]);
while (pq.Count() > 0)
{
// get the vertex with minimum wight
// from unvisited vertices to process
var minVertex = pq.Dequeue();
minVertex.IsVisited = true;
var minVIndex = vertices.IndexOf(minVertex);
// Go trough all unvisited neighbors
// and try to update their weight
for (var i = 0; i < adjMatrix[minVIndex].Length; i++)
{
// if weight is zero no connection between two vertices
if (this.adjMatrix[minVIndex][i] == 0.0m) continue;
// we are interested only in unvisited vertices
if (this.vertices[i].IsVisited) continue;
// calculate neighbor's weight by
// adding current weight and distance to the neighbor
// from current vertex
var calculatedWeight = adjMatrix[minVIndex][i] + minVertex.Weight;
// if calculated distance/weight is less then
// we found better path so update the neighbor's weight
if (calculatedWeight < this.vertices[i].Weight)
{
this.vertices[i].Weight = calculatedWeight;
this.vertices[i].Parent = minVertex;
// Add neighbor to the queue to process it later
pq.Enqueue(this.vertices[i]);
}
}
}
}
```

With this method we traverse all vertices in vertices list and looking at the graph matrix we update the values of each vertex. Next we will add public method which takes source and destination parameters, applies the algorithm and then backtracks the shortest path from distance to source and last it returns an information about the shortest path and total distance.

```
public string PrintShortestPath(string sourceName, string destinationName)
{
// We miss guard clauses for simplicity
var sVert =
vertices.First(v => v.Name == sourceName);
int source =
vertices.IndexOf(sVert);
var dVert =
vertices.First(v => v.Name == destinationName);
int destination =
vertices.IndexOf(dVert);
// Calculate all vertices' weights
ApplyDijkstra(source);
var destinationVertex = vertices[destination];
// Using stack to backtrack the path from
// destination to source by iterating parents
Stack<Vertex> backTrackShortestPath = new Stack<Vertex>();
bool pathExists = false;
while (destinationVertex != null)
{
if (destinationVertex.Name == sourceName)
{
backTrackShortestPath.Push(destinationVertex);
pathExists = true;
break;
}
backTrackShortestPath.Push(destinationVertex);
destinationVertex = destinationVertex.Parent;
}
if (!pathExists)
{
return $"No path exists from vertex:{source} to vertex:{destination}";
}
StringBuilder shortestPath = new StringBuilder();
var currentWeightArrow = "";
while (backTrackShortestPath.Count > 0)
{
var currentVertex = backTrackShortestPath.Pop();
shortestPath.Append($"{currentWeightArrow}({currentVertex.Name})");
currentWeightArrow = "--->";
}
shortestPath.AppendLine("\nTotal " +
$"distance from vertex:{sourceName} " +
$"to vertex:{destinationName} is " +
$"{vertices[destination].Weight}");
return shortestPath.ToString();
}
```

Next let’s construct the graph we explained above and use the code above to find the shortest path

```
static void Main(string[] args)
{
List<Vertex> vertices = new List<Vertex>
{
new Vertex("A"),
new Vertex("B"),
new Vertex("C"),
new Vertex("D"),
new Vertex("E"),
new Vertex("F")
};
decimal[][] graph = {
new[] { 0.0m, 1.0m, 2.0m, 0.0m, 0.0m, 0.0m },
new[] { 1.0m, 0.0m, 0.0m, 6.5m, 0.0m, 0.0m },
new[] { 2.0m, 0.0m, 0.0m, 0.5m, 10.5m, 0.0m },
new[] { 0.0m, 6.5m, 0.5m, 0.0m, 2.0m, 0.5m },
new[] { 0.0m, 0.0m, 10.5m, 2.0m, 0.0m, 1.0m },
new[] { 0.0m, 0.0m, 0.0m, 0.5m, 1.0m, 0.0m }
};
var dijkstra = new Dijkstra(graph, vertices);
var shortestPath =
dijkstra.PrintShortestPath("A", "F");
Console.WriteLine("The shortest path:");
Console.WriteLine(shortestPath);
Console.ReadLine();
}
```

The result in the console is:

The algorithm’s time complexity is

`O(E Log V)`

E – number of edges

V – number of vertices.

With this we conclude our explanation about Dijkstra’s algorithm. You can read more about the topic here:

https://www.programiz.com/dsa/dijkstra-algorithm

https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/

]]>The properties of heap described above makes it easy to be implemented with an array data structure and most commonly the heap is implemented with an array data structure. Let’s see how we would show a min heap with an array.

Based on the above representation we can define several formulas in order to detect parent or child nodes of a given node based on the index of an array. Given n is the index of an array then:

**Parent node index = (n – 1) / 2**

Example: Take 5th index which is 32, so (5 – 1) / 2 = 2 which is 30 the parent node.

**Left child index = (2 * n) + 1**

Example: Take 2nd index which is 30, so (2 * 2) + 1 = 5 which is 32 the left child.

**Right child index = (2 * n) + 2**

Example: Take 2nd index which is 30, so (2 * 2) + 2 = 6 which is 52 the right child.

Heapifying is an operation which rearranges the elements of the heap so it satisfies the conditions of min or max heap based on the heap type. This operation is performed after adding or removing a node from the heap or/and priority queue although in priority queue we have only enqueue and dequeue based on the priority of the elements compared to regular queue.

This operation starts from first index of non-leaf node whose index is given by n / 2 – 1 where n is the size of the array. Each root, left child and right child is compared and if they don’t satisfy the heap property the nodes are swapped. The operation is repeated until we reach the root node with index 0. Let’s see with example how we will heapify a tree which does not satisfy min heap properties.

When we add item to the heap/priority queue we add it as last item to the tree and then we heapify the tree as described above.

When we dequeue / remove item from the tree we swap the item to be removed with the last item in the tree, the rightmost node. Then we remove the last item which became the item we wanted to remove after we made a swap in previous step. Finally we heapify the tree in order to satisfy the heap properties.

Let’s see how we can implement priority queue in C#. First we will define an enum which will define the queue type.

```
public enum PriroityQueueType
{
Min,
Max
}
```

Then we will define a PriorityQueue class and implement it’s methods.

```
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> items;
private PriroityQueueType PriroityQueueType;
public PriorityQueue(PriroityQueueType priroityQueueType)
{
this.items = new List<T>();
this.PriroityQueueType = priroityQueueType;
}
}
```

We use generic class where the type should implement IComparable in order to compare the items when we implement priority queue operations. Next let’s implement heapify method.

```
private void Heapify(int index)
{
int count = items.Count;
int largestOrSmallest = index;
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
//check if current node is larger or smaller than left child based on the queue type
//if true then assign left child index to variable largestOrSmallest in order to track it
if (leftIndex < count &&
((PriroityQueueType == PriroityQueueType.Min
&& items[largestOrSmallest].CompareTo(items[leftIndex]) > 0)
|| (PriroityQueueType == PriroityQueueType.Max
&& items[largestOrSmallest].CompareTo(items[leftIndex]) < 0)))
{
largestOrSmallest = leftIndex;
}
//check if largestOrSmallest node is larger or smaller than right child based on the queue type
//if true then assign right child index to variable largestOrSmallest in order to track it
if (rightIndex < count &&
((PriroityQueueType == PriroityQueueType.Min
&& items[largestOrSmallest].CompareTo(items[rightIndex]) > 0)
|| (PriroityQueueType == PriroityQueueType.Max
&& items[largestOrSmallest].CompareTo(items[rightIndex]) < 0)))
{
largestOrSmallest = rightIndex;
}
//if one of the child is larger or smaller than the root then we need to swap them
if (largestOrSmallest != index)
{
T temp = items[largestOrSmallest];
items[largestOrSmallest] = items[index];
items[index] = temp;
//As we swapped the root item with one of the children we need to recrsively heapify the subtrees
Heapify(largestOrSmallest);
}
}
```

Heapify method is the code representation of the heapify operation visually described above.

Next we will implement enqueue method where we add an item to the end of the queue and then we start heapifying the tree starting from index n/2-1 where n is the count of the elements in the queue.

```
public void Enqueue(T item)
{
if (items.Count == 0)
{
items.Add(item);
}
else
{
items.Add(item);
for (int i = items.Count / 2 - 1; i >= 0; i--)
{
Heapify(i);
}
}
}
```

We will implement helper method DeleteNode which will delete a node from the heap by given index of the element. We will afterwards use this method to easily implement Dequeue operation of priority queue. Delete method follows the visual steps described earlier in this article.

```
private void DeleteNode(int index)
{
if(index > items.Count-1) throw new IndexOutOfRangeException();
T temp = items[index];
items[index] = items[items.Count - 1];
items[items.Count - 1] = temp;
items.RemoveAt(items.Count - 1);
for (int i = items.Count / 2 - 1; i >= 0; i--)
{
Heapify(i);
}
}
```

Using this method to implement dequeue operation is really easy we just call it with index 0 which is the top item of the queue.

```
public T Dequeue()
{
if (items.Count == 0)
throw new InvalidOperationException("The priority queue is empty");
T topItem = items[0];
DeleteNode(0);
return topItem;
}
```

Finally we implement Peek which is just returning the top item.

```
public T Peek()
{
T topItem = items[0];
return topItem;
}
```

It is worth mentioning the algorithm complexity of binary heap and priority queue.

Peek – O(1)

Enqueue – O(log n)

Dequeue – O(log n)

With this we conclude the explanation of heap and priority queue.

You can read more about this topic here:

https://www.geeksforgeeks.org/priority-queue-set-1-introduction/

https://www.programiz.com/dsa/priority-queue

The purpose is to share little pieces of helpful practices and tricks that will make your work better and more pleasant.

Do you prefer listening to music while working?

If so – what kind of music?

Let me share my preferences on that topic.

I’ve felt that there are **two **working ** mood types**.

is when we have to come up with a solution for some complex problem, or when we have to think of a design problem, or we need to decide on the correct architectural approach, or solve a tricky puzzle, or find out an appropriate algorithm.

Basically – we have to involve a high level of concentration and a fair amount of thinking.

Let’s call that mood type – **Le Penseur** (*in French*),

or **The Thinker**.

is when we know what needs to be done, the approach has been discovered, we’ve already done the thinking work and now we need to implement it.

Let’s call that – **The Worker** mood type.

I pick my music based on the mood type I am currently at.

The most productive I am in **The Thinker** mood while I listen to more * calm *and

During this mood, I prefer to keep the volume at lower levels!

On the other hand, when I am in **The Worker** area I find it most appropriate and boosting my velocity when I play more dynamic, more… fast, and sometimes kind of aggressive music, which energizes me and pushes me to do the work and to enjoy it!

In those moments I play some **metal **songs with a fast rhythm, for example, “*Pantera*“, “*Sepultura*“, “*Soulfly*“, often I listen to death metal bands like “*In Flames*“, “*Edge Of Sanity*“, etc.

I also often play something more electronic like “*The Prodigy*” or even some psytrance – my favorite here is “*Infected Mushroom*“.

And on some occasions, the classical music helps here as well – like *Vagner *or *Beethoven*, or even something more modern like *Yann Tiersen*.

Often the volume is in higher levels on that mood.

Here is actual research on the topic, which kind of syncs with my feelings and conclusions:

“Kellogg reviews a vast body of research to extract a few notable findings. Among them is the role of background noise, which seems to fall on a bell curve of fecundity: High-intensity noise that exceeds 95 decibels disrupts performance on complex tasks but improves it on simple, boring tasks — noise tends to raise arousal level, which can be useful when trying to stay alert during mindless and monotonous work, but can agitate you out of creative flow when immersed in the kind of work that requires deliberate, reflective thought.”

https://www.brainpickings.org/2014/08/25/the-psychology-of-writing-daily-routine/

Of course, the music picks depend on your personal preferences, but the main connection is that:

**The Thinker** needs something **calm and harmonious**.**The Worker** wants **dynamics and energy**.

The purpose is to share little pieces of helpful practices and tricks that will make your work better and more pleasant.

Upgrade your working environment by surrounding yourself with easily accessible **helpers**. **Print **out some useful (*for you*) **content **that can be used as a quick reference.

Of course, you can store all of those **cheat sheets** in electronic format somewhere on your hard drive (or URL bookmarks).

However, I would advise you to have some **on paper.**

That way you will not search for the file and disturb your inertion.

The physical version has a *psychological aspect *as well. You know that a piece of particular knowledge is exactly somewhere in the space around you and you can have a look at it for a second. So you are going to make references to those “* extensions of your brain*” in an absolutely natural and even semi-unconscious way.

Let me share with you some **example **resources:

- https://www.bigocheatsheet.com/ –
**Algorithms complexities**cheat sheet. - https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet – Basic
**GIT**commands. **SQL Server:**

– https://cheatography.com/davechild/cheat-sheets/sql-server/ : Basics.

– https://tableplus.com/blog/2018/08/ms-sql-server-data-types-cheatsheet.html : Data types

– https://www.guru99.com/sql-cheat-sheet.html : More complete list.- https://cheatography.com/kstep/cheat-sheets/http-status-codes/ –
**HTTP status codes**. - https://docs.microsoft.com/en-us/visualstudio/ide/default-keyboard-shortcuts-in-visual-studio?view=vs-2019 –
**Visual Studi**keyboard shortcuts. - https://cheatography.com/davechild/cheat-sheets/regular-expressions/ –
**Regular expressions**.