❔ C# Recursion Output problem
Here's a piece of code (formatted by benqbenq) in C# for finding the sum of triplets that are closest to 1. The code outputs the sum, but I want it to output the triplets that produced the sum. I'm a noob at C# and recursion is difficult, can anyone help?
int[] arr = new int[] { -1, 2, 1, -4 };
int target = 1;
int arrSize = arr.Length;
int minDiff = int.MaxValue;
int answer = 0;
FindClosestTriplet(
arr,
size: arrSize,
targetSum: target,
currentCount: 0,
currentSum: 0,
currentIndex: 0,
closestSum: ref answer,
minDifference: ref minDiff);
Console.WriteLine(answer);
static void FindClosestTriplet(int[] array, int size, int targetSum, int currentCount, int currentSum, int currentIndex, ref int closestSum, ref int minDifference)
{
// Return when reaching the end of the array
// If we have picked three elements so far, check if the sum is closest to our "targetSum"
if (currentIndex == size)
{
if (currentCount == 3)
{
int currentDifference = Math.Abs(targetSum - currentSum);
if (currentDifference < minDifference)
{
minDifference = currentDifference;
closestSum = currentSum;
}
}
return;
}
// Pick this number
FindClosestTriplet(array, size, targetSum, currentCount + 1, currentSum + array[currentIndex], currentIndex + 1, ref closestSum, ref minDifference);
// Don't pick this number
FindClosestTriplet(array, size, targetSum, currentCount, currentSum, currentIndex + 1, ref closestSum, ref minDifference);
}int[] arr = new int[] { -1, 2, 1, -4 };
int target = 1;
int arrSize = arr.Length;
int minDiff = int.MaxValue;
int answer = 0;
FindClosestTriplet(
arr,
size: arrSize,
targetSum: target,
currentCount: 0,
currentSum: 0,
currentIndex: 0,
closestSum: ref answer,
minDifference: ref minDiff);
Console.WriteLine(answer);
static void FindClosestTriplet(int[] array, int size, int targetSum, int currentCount, int currentSum, int currentIndex, ref int closestSum, ref int minDifference)
{
// Return when reaching the end of the array
// If we have picked three elements so far, check if the sum is closest to our "targetSum"
if (currentIndex == size)
{
if (currentCount == 3)
{
int currentDifference = Math.Abs(targetSum - currentSum);
if (currentDifference < minDifference)
{
minDifference = currentDifference;
closestSum = currentSum;
}
}
return;
}
// Pick this number
FindClosestTriplet(array, size, targetSum, currentCount + 1, currentSum + array[currentIndex], currentIndex + 1, ref closestSum, ref minDifference);
// Don't pick this number
FindClosestTriplet(array, size, targetSum, currentCount, currentSum, currentIndex + 1, ref closestSum, ref minDifference);
}