Brute Force Method Explained And Applied In C#

Brute Force method

 
In this article, I will be showing an implementation of my favorite method, the brute force method, to implement a compound interest calculation in a web calculator project.

What is the brute force method?

 
The brute force method means finding your way into the desired solution as quickly as possible, "no matter" what. If you break your problem, you will have basically these parts,
  1. Input: the data that you are going to receive in order to get into the desired result;
  2. Algorithm: here is where we turn the input into the output and that is where the brute force is applied, applying an algorithm that can lead towards the desired solution;
  3. Output: the desired solution.

Benefits of using brute force

  • Can be applied to any language;
  • Can improve your code quality if you apply a code clean-up afterward;
  • Reduces the learning curve for new programming languages;
  • Overall faster deliverables;

Disadvantages of using brute force

 
Most disadvantages are due to bad usage, like,
  • Bad quality code if the code clean-up is not done;
  • Bugs if not tested correctly;
  • Performance issues if the performance issue was not considered while finding the solution; 

Brute force method in action

 
Base
 
I will use one of my previous articles as a base to show an implementation of the brute force method in action, you may access the previous article here.
 
The Problem: Calculate Compound Interest
 
We are going to add an option to calculate compound interest in the .NET Core Web Calculator. 
 
The user input is going to be,
  1. Initial Value
  2. Period of time
  3. Interest rate based on each period
Example
  • Initial Value: 1000;
  • Period of time: 10 months;
  • Interest Rate: 2% per month;
  • Result: 1218.93
The Brute Force Method Explained And Applied In C#
 
This example above is going to be used later as unit testing.
 

The Solution: Brute Force in action

 
The article base
 
The Brute Force Method Explained And Applied In C#
 
Adding new items into the project
 
Let's start adding a new folder, called business, and a class inside it.:
 
The Brute Force Method Explained And Applied In C#
 
Add a new class as the model for the input/output,
 
I included the same reference as used to describe the formula, in the 3.3.1 section of this article, at their properties display value 
  1. namespace NetCoreCalculator.Models  
  2. {  
  3.     public class CompoundInterestModel  
  4.     {  
  5.         [Display( Name = "Result - A" )]  
  6.         public double Result { getset; }  
  7.   
  8.         [Display( Name = "Initial Investment - P" )]  
  9.         public double Investment { getset; }  
  10.   
  11.         [Display( Name = "Interest Rate - r" )]  
  12.         public double InterestRate { getset; }  
  13.   
  14.         [Display( Name = "Period of Time - n" )]  
  15.         public int TimePeriod { getset; }  
  16.   
  17.     }  
  18. }  
Add a new View for the Compound Interest calculation,
  1. @model NetCoreCalculator.Models.CompoundInterestModel  
  2.   
  3. @{  
  4.     ViewData["Title"] = "Thiago Vivas";  
  5. }  
  6.   
  7. <h2>Compound Interest Calculation</h2>  
  8.   
  9. <hr />  
  10. <div class="row">  
  11.     <div class="col-md-4">  
  12.         <form asp-action="CompoundInterest">  
  13.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  14.             <div class="form-group">  
  15.                 <label asp-for="Investment" class="control-label"></label>  
  16.                 <input asp-for="Investment" class="form-control" />  
  17.                 <span asp-validation-for="Investment" class="text-danger"></span>  
  18.             </div>  
  19.             <div class="form-group">  
  20.                 <label asp-for="InterestRate" class="control-label"></label>  
  21.                 <input asp-for="InterestRate" class="form-control" />  
  22.                 <span asp-validation-for="InterestRate" class="text-danger"></span>  
  23.             </div>  
  24.             <div class="form-group">  
  25.                 <label asp-for="TimePeriod" class="control-label"></label>  
  26.                 <input asp-for="TimePeriod" class="form-control" />  
  27.                 <span asp-validation-for="TimePeriod" class="text-danger"></span>  
  28.             </div>             
  29.             <div class="form-group">  
  30.                 <label asp-for="Result" class="control-label"></label>  
  31.                 <input disabled="disabled" asp-for="Result" class="form-control" />  
  32.             </div>  
  33.             <div class="form-group">  
  34.                 <input type="submit" value="Calculate" class="btn btn-default" />  
  35.             </div>  
  36.         </form>  
  37.     </div>  
  38. </div>  
  39.   
  40. @section Scripts {  
  41.     @{await Html.RenderPartialAsync( "_ValidationScriptsPartial" );}  
  42. }  
Modify the home controller in order to access the new view,
  1. namespace NetCoreCalculator.Controllers  
  2. {  
  3.     public class HomeController : Controller  
  4.     {  
  5.         [HttpGet]  
  6.         public IActionResult Index()  
  7.         {  
  8.             return View();  
  9.         }  
  10.   
  11.         [HttpPost]  
  12.         public IActionResult Index( Operation model )  
  13.         {  
  14.             if ( model.OperationType == OperationType.Addition )  
  15.                 model.Result = model.NumberA + model.NumberB;  
  16.             return View( model );  
  17.         }  
  18.   
  19.         [HttpPost]  
  20.         public IActionResult CompoundInterest( CompoundInterestModel model )  
  21.         {  
  22.             return View( model );  
  23.         }  
  24.   
  25.         [HttpGet]  
  26.         public IActionResult CompoundInterest()  
  27.         {  
  28.             return View();  
  29.         }  
  30.     }  
  31. }  
Algorithm breakdown
 
The formula,
 
A = P (1 + r) (n)

Where,

A = the future value of the investment/loan, including interest. Our result
P = the principal investment amount 
r = the interest rate 
n = the number of times that interest is compounded

Algorithm base
  1. Calculate n * t;
  2. Calculate 1 + r/n
  3. Calculate the (result from number 2)  ^ (the result from number 1)
  4. Calculate P * (result from number 3)
Applying the algorithm using the brute force method
 
First, let's organize our method signatures and connect our front-end to our back-end,
 
P.S.: The method and variable names do not matter yet.
 
Right now, I think that we only need to send the result as output and the model as input. Here we have the signature of the method, 
  1. public static class Calculation  
  2. {  
  3.     public static double doesNotMatter( CompoundInterestModel model )  
  4.     {  
  5.         return 0;  
  6.     }  
  7. }  
And here, our controller,
  1. public class HomeController : Controller  
  2.   {  
  3.       [HttpGet]  
  4.       public IActionResult Index()  
  5.       {  
  6.           return View();  
  7.       }  
  8.   
  9.       [HttpPost]  
  10.       public IActionResult Index( Operation model )  
  11.       {  
  12.           if ( model.OperationType == OperationType.Addition )  
  13.               model.Result = model.NumberA + model.NumberB;  
  14.           return View( model );  
  15.       }  
  16.   
  17.       [HttpPost]  
  18.       public IActionResult CompoundInterest( CompoundInterestModel model )  
  19.       {  
  20.           model.Result = Calculation.doesNotMatter( model );  
  21.           return View( model );  
  22.       }  
  23.   
  24.       [HttpGet]  
  25.       public IActionResult CompoundInterest()  
  26.       {  
  27.           return View();  
  28.       }  
  29.   }  
Now, let's apply our algorithm in the doesNotMatter method. And this is the result,
  1. public static class Calculation  
  2. {  
  3.     public static double doesNotMatter( CompoundInterestModel model )  
  4.     {  
  5.         var asdasd = model.TimePeriod;  
  6.         var sdoad = 1 + ( (model.InterestRate / 100) / model.TimePeriod );  
  7.         var asdasds = Math.Pow( sdoad, asdasd );  
  8.         var owee = asdasds * model.Investment;  
  9.         return owee;  
  10.     }  
  11. }  
Testing the result
 
This is a very important step, let's test our result with our previous example,
 
Example
  • Initial Value: 1000;
  • Period of time: 10 months;
  • Interest Rate: 2% per month;
  • Value addition: 100 per month;
  • Result: 2313,89
 The Brute Force Method Explained And Applied In C#
 
The result is completely different from what we expected, so let's fix it,
 
The Brute Force Method Explained And Applied In C#
 
After fixing the formula, this is the method which matches with the expected result:
 
The Brute Force Method Explained And Applied In C#
 
Code clean-up
 
Now, it is time to adjust our variables and methods so they may have the right name for their purpose. In the end, you must look into your code and be proud of it, having in your mind that anything else is necessary to make your code readable and reusable.
 
Organize your methods
 
That's the final result, which must make sense now,
  1. public static class Calculation  
  2.    {  
  3.        public static double CalculateCompoundInterest( CompoundInterestModel model )  
  4.        {  
  5.            var asdasd = model.TimePeriod;  
  6.            var sdoad = 1 + GetPercentValue( model.InterestRate );  
  7.            var asdasds = Math.Pow( sdoad, model.TimePeriod );  
  8.            var owee = asdasds * model.Investment;  
  9.            return owee;  
  10.        }  
  11.   
  12.        private static double GetPercentValue( double number )  
  13.        {  
  14.            return number / 100;  
  15.        }  
  16.    }  
Organize your variables
 
Now revise your variables and rename them according to their purpose,
  1. public static class Calculation  
  2. {  
  3.     public static double CalculateCompoundInterest( CompoundInterestModel model )  
  4.     {  
  5.         var initialInvestment = model.TimePeriod;  
  6.         var interestRateCalculation = 1 + GetPercentValue( model.InterestRate );  
  7.         var powerResult = Math.Pow( interestRateCalculation, model.TimePeriod );  
  8.         return powerResult * model.Investment;  
  9.     }  
  10.   
  11.     private static double GetPercentValue( double number )  
  12.     {  
  13.         return number / 100;  
  14.     }  
  15. }  
Comment your code 
 
That's a very important step, go through your code and comment as much as possible,
  1. /// <summary>  
  2.   /// Calculates mathematics formulas  
  3.   /// </summary>  
  4.   public static class Calculation  
  5.   {  
  6.       /// <summary>  
  7.       /// Calculates the compound interest based in a given model  
  8.       /// Formula: A = P (1 + r) (n)  
  9.       /// </summary>  
  10.       /// <param name="model">Model with input data to calculate</param>  
  11.       /// <returns>The result of the operation</returns>  
  12.       public static double CalculateCompoundInterest( CompoundInterestModel model )  
  13.       {  
  14.           // P  
  15.           var initialInvestment = model.TimePeriod;  
  16.   
  17.           // 1 + r  
  18.           var interestRateCalculation = 1 + GetPercentValue( model.InterestRate );  
  19.   
  20.           // (1 + r) (n)  
  21.           var powerResult = Math.Pow( interestRateCalculation, model.TimePeriod );  
  22.   
  23.           // P (1 + r) (n)  
  24.           return powerResult * model.Investment;  
  25.       }  
  26.   
  27.       /// <summary>  
  28.       /// Converts the given percentage in a double number  
  29.       /// Result = number / 100  
  30.       /// </summary>  
  31.       /// <param name="number">Percentage to convert to number</param>  
  32.       /// <returns>The number related to the given percentage</returns>  
  33.       private static double GetPercentValue( double number )  
  34.       {  
  35.           return number / 100;  
  36.       }  
  37.   }  
Re-test your result 
 
In order to guarantee that you did not break anything, you must run 100% of your tests again. 
 
The Brute Force Method Explained And Applied In C# 
 
Congratulations, you have successfully applied the brute force method using .NET Core.


Similar Articles