Advertisement
Normantas

Find All combination with desired value

Mar 26th, 2020
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 KB | None | 0 0
  1. public static List<string> FindCombination(int range, int searchValue)
  2.         {
  3.             List<string> output = new List<string>();
  4.             loop(1,1,"1");
  5.             return output;
  6.             void loop(long value, int iteration, string takenPath)
  7.             {
  8.                 if (iteration == range && value == searchValue) //Escape from recursion when we reach the final number (itteration)
  9.                 {
  10.                     output.Add($"{takenPath} = {value}");
  11.                 }
  12.                 else if (iteration < range)
  13.                 {
  14.                     iteration += 1; //the next number
  15.                     loop(value + iteration, iteration, takenPath + " + " + iteration); //add the number
  16.                     loop(value - iteration, iteration, takenPath + " - " + iteration); //subtract the number
  17.  
  18.                     //adds the number to the end of the current number, example: 1 and 2 => 12, 4 and 5 => 45
  19.                     if (value > 0)
  20.                         loop(value * 10 + iteration, iteration, takenPath + iteration.ToString());
  21.                     else
  22.                         loop(value * 10 - iteration, iteration, takenPath + iteration.ToString());
  23.                 }
  24.             }
  25.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement