This question already has answers here:
recursive string reverse function
(6 answers)
Closed 1 year ago.
I tried to reverse array with recursion method but somehow my code didn't show the right output.
static void Main(string[] args)
{
int[] arr = { 10, 20, 15, 40, 70, 60, 50, 80, 90, 25 };
ReverseArray(arr, arr.Length);
string output = PrintArray(arr);
Console.WriteLine(output);
}
static void ReverseArray(int[] V, int N)
{
int start = V.Length - N;
if (N > 1)
{
int temp = V[start];
V[start] = V[N - 1];
V[N - 1] = temp;
ReverseArray(V, N - 1);
}
}
static string PrintArray(int[] arr)
{
string temp = "";
foreach (int angka in arr)
{
temp += angka.ToString() + " ";
}
return temp;
}
I want the output showing this :
(25,90,80,50,60,70,40,15,20,10)
But my output is like this :
What's wrong with my code ?
You're reversing the array, but after you get past the midpoint you keep reversing. That means you're flipping values that have already been flipped.
Changing if (N > 1) to if (N > V.Length / 2) will fix the problem.
Hi use below logic it will work.
void reverse(int[] arr, int low, int high)
{
if (low < high)
{
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
reverse(arr, low + 1, high - 1);
}
}
Related
I have a List<object> which can contain either an integer value or another List<object>.
What I need to do, is to sum the values in the array, depending on its depth(If depth is 0, multiply by 0, if 1 then by 1 ... etc.)
Example array: [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
How it should be calculated: 5 + 2 + 2 * (7 - 1) + 3 + 2 * (6 + 3 * (-13 + 8) + 4) = 12
What I managed to get:
public class Program
{
public static List<object> TestCase1()
{
List<object> test = new List<object>(){
5,
2,
new List<object>(){
7, -1
},
3,
new List<object>(){
6,
new List<object>(){
-13, 8
},
4,
},
};
return test;
}
public static int ProductSum(List<object> array)
{
int depthCounter = 1;
int totalSum = 0;
int tempSum = 0;
for (int i = 0; i < array.Count; i++)
{
if (array[i] is IList<object>)
{
totalSum += tempSum * depthCounter;
tempSum = 0;
depthCounter++;
}
else
{
tempSum += (int)array[i];
}
}
return totalSum;
}
static void Main(string[] args)
{
Console.WriteLine("Result = " + ProductSum(TestCase1()));
}
}
The result from my code is
The problem that I have, is I don't see a way, that I could iterate through an array to calculate it ... Maybe there is a way to sort an array of objects in some way to simplify it?
The method should call itself ("recursive"), when it encounters a nested list. It should also take a depth parameter, keeping track of the depth. Every time you call the function recursively, you pass depth + 1 as the new depth. Whenever you count something, you multiply by depth.
public static int ProductSum(List<object> list) => ProductSum(list, 1);
public static int ProductSum(List<object> list, int depth)
{
var sum = 0;
foreach (var thing in list) {
if (thing is List<object> innerList) {
sum += ProductSum(innerList, depth + 1) * depth;
} else if (thing is int x) {
sum += x * depth;
}
}
return sum;
}
You should do it recusively:
public static int ProductSum(List<object> array, int depthCounter)
{
int totalSum = 0;
for (int i = 0; i < array.Count; i++)
{
if (array[i] is List<object>)
{
totalSum += ProductSum(array[i] as List<Object>, depthCounter + 1);
}
else
{
totalSum += (int)array[i] * depthCounter;
}
}
return totalSum;
}
You call it this way:
ProductSum(TestCase1(), 0);
But I don't get the number you calculated, though: If all depth 0 candidates are multiplied by 0, these are... 0! ;)
Maybe there are some rules for your application that I don't know, and that's the reason why the calculations differ, but in the code you see how recursions work.
i am trying to use an Interpolation Search algorithm to find a value and return it. (Which is what it does currently). I am trying to modify it so it returns a number which i can use to find the closest values to the inputted item if the item which was searched was not found within the array.
public static int InterSearch(double[] array, double data)
{
int size = array.Length;
int lo = 0;
int mid = -1;
int hi = array.Length - 1;
int index = -1;
int count = 0;
while (lo <= hi)
{
mid = (int)(lo + (((double)(hi - lo) / (array[hi] - array[lo])) * (data - array[lo])));
count++;
if (array[mid] == data)
{
index = mid;
break;
}
else
{
if (array[mid] < data)
lo = mid + 1;
else
hi = mid - 1;
}
}
return index;
}
You can use an aggregate that find the closest value.
this is a custom extension method but you get the idea.
public static double GetValueClosestTo(this List<double> values, double closestTo)
{
return values.Aggregate((x, y) => Math.Abs(x - closestTo) < Math.Abs(y - closestTo) ? x : y);
}
Let's say you have the following array {1, 5, 9.2, 6, 17} and you test the following number {6, 15, 5.2}. You will use the following code
var sourceArray = new [] {1, 5, 9.2, 6, 17}.ToList() // for simplicity i use a list
var closestToX = sourceArray.GetValueClosestTo(6); // this return 6
closestToX = sourceArray.GetValueClosestTo(15); // this return 17
closestToX = sourceArray.GetValueClosestTo(5.2); // this return 5
I am trying to do a simple coding challenge that requires me to do the following:
You are given n, return an array ans, composed in such way:
`ans = [n, n - 5, n - 10, ... , m, m + 5, ... , n - 5, n]`, where m stands for the first non-positive integer obtained by subtractions.
Try to solve it without any loop.
Example
For n = 25, the output should be
listWithoutLoop(n) = [25, 20, 15, 10, 5, 0, 5, 10, 15, 20, 25].
I have done this code:
int[] listWithoutLoop(int n)
{
List<int> test = new List<int>();
if (test.Count > 2 && test[test.Count - 1] == n)
return test.ToArray();
if (n <= 0)
{
test.Add(n + 5);
return listWithoutLoop(n + 5);
}
else
{
test.Add(n - 5);
return listWithoutLoop(n - 5);
}
}
But I keep getting a stack overflow when running it. Is recursion supported by c#? If so, how to prevent getting a stackoverflow exception when running it?
You must define the test list above the listWithoutLoop() method.
List<int> test = new List<int>();
int[] listWithoutLoop(int n)
{
....
}
To simplify, I splitted the function to add up and add down separately (it's always better to have simple and understandable code at all times)
static void Main()
{
int n = 20;
int interval = 5;
List<int> list = new List<int>();
AddDown(list, n, 0, interval);
AddUp(list, 0, n, interval);
int[] arrInt = list.ToArray();
}
static void AddDown(List<int> list, int currentNumber, int targetNumber, int interval)
{
if(currentNumber > targetNumber)
{
list.Add(currentNumber);
AddDown(list, currentNumber - interval, targetNumber, interval);
}
}
static void AddUp(List<int> list, int currentNumber, int targetNumber, int interval)
{
if (currentNumber <= targetNumber)
{
list.Add(currentNumber);
AddUp(list, currentNumber + interval, targetNumber, interval);
}
}
I found this example of a merge sort algorithm online on a tutorial webpage and I have been trying to understand ow the code implements the algorithm. The example i found uses recursion and a temporary array to sort the array of unsorted algorithms.
My query is in the final step of the process. When copying the elements of the temporary array into the original array to sort the array. why does the algorithm decrements the right attribute instead of incrementing the left attribute? when i incremented the left left value the algorithm does not work.
class Assignment1
{
static void Main(string[] args)
{
Console.WriteLine("Size of array:");
int n = Convert.ToInt16(Console.ReadLine());
int[] unsorted = new int[n];
for(int i = 0; i < n; i++)
{
Console.WriteLine("Enter a number:");
unsorted[i] = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("--------Sort---------");
Recursion_Sort(unsorted, 0, n - 1);
for (int i = 0; i < n; i++)
{
Console.WriteLine(unsorted[i]);
}
}
static public void Merge(int[] numbers, int left, int mid, int right, int n)
{
int[] tempArray = new int[n];
int i, lEnd, size, pos;
lEnd = mid - 1;
pos = left;
size = (right - left + 1);
while ((left <= lEnd) && (mid <= right))
{
if (numbers[left] <= numbers[mid])
{
tempArray[pos] = numbers[left];
pos++;
left++;
}
else
{
tempArray[pos] = numbers[mid];
pos++;
mid++;
}
}
while (left <= lEnd)
{
tempArray[pos] = numbers[left];
pos++;
left++;
}
while (mid <= right)
{
tempArray[pos] = numbers[mid];
pos++;
mid++;
}
Console.WriteLine(tempArray.Length);
for (i = 0; i < size; i++)
{
numbers[right] = tempArray[right];
right--;
}
}
static public void Recursion_Sort(int[] numbers, int left, int right)
{
int mid;
if (right > left)
{
mid = (right + left) / 2;
Recursion_Sort(numbers, left, mid);
Recursion_Sort(numbers, (mid + 1), right);
// we then merge the sorted sub arrays using the merge method
Merge(numbers, left, (mid + 1), right, numbers.Length);
}
}
}
left value is changing during merge and as you have code block
while (left <= lEnd)
{
//...
left++;
}
left will be finally assigned to lEnd + 1(the condition for ending while loop).
Otherwise right is not changing and is the last index of currently manipulated sequence.
Taking the risk of not answering the question like you want it, I would suggest LINQ. This is not merge sort in particular, but rather a concatenation of two arrays and then sorting.
If your array isn't so big that performance matters, you might want to go for this approach, because it's simple and less code (which is always good).
int[] arr1 = new[] { 1, 2, 3, 7, 8, 10 };
int[] arr2 = new[] { 4, 6, 9, 12, 15 };
int[] merged = arr1.Concat(arr2).OrderBy(n => n).ToArray();
Furthermore, I post this if it is interesting for others.
I've recently started learning C# (having learnt other languages) and I'm trying to create a function that generates the fibonacci sequence to the 'nth' term using a while loop and then returns the value of the 'nth' term.
My current code is this:
void fibonacci(int n)
{
int[] terms = { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Concat( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
My understanding of C# is very poor as visual studio is telling me that I can't use 'Concat' with int[] - I'm trying to append the array with the new values. Any help would be great.
Arrays in C# are fixed length.
If you want to use a variable length collection, use a strongly typed List<T> instead, which has an Add method:
int fibonacci(int n)
{
var terms = new List<int>{ 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
You can't append to an array. In .Net, arrays have constant size and you can't resize them after creation.
Instead, you should use List<int> and its Add() method.
You can for example use list and change your code to:
int fibonacci(int n)
{
List<int> terms = new List<int> { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add(terms[i-1] + terms[i-2]);
i += 1;
}
return terms[n];
}
You can't add items to an array as it has fixed length. Use List<int> instead of array
I'm surprised nobody mentioned fixing the array size.
Well, maybe I'm missing something, but you could do:
int[] FibonacciArray(int n)
{
int[] F = new int[n+1];
F[0] = 0;
F[1] = 1;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i - 1] + F[i - 2];
}
return F;
}
It's in average 2.5x faster than the version using a list.
But as often there is no free-lunch: the drawback is that your memory consumption is not smoothed: you pay upfront for all the memory you'll need.
Don't append values to an array. arrays have static size and you can't resize them after creation.
use
List<int> and its Add() method instead of array.
here is your solution for fibonacci series.
int fibonacci(int n)
{
var terms = new List<int>{ 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
also can be done like this :
class FibonacciSeries
{
static void Main(string[] args)
{
Console.WriteLine("Enter a num till which you want fibonacci series : ");
int val = Convert.ToInt32(Console.ReadLine());
int num1, num2;
num1 = num2 = 1;
Console.WriteLine(num1);
if (val > num2)
{
while (num2 < val)
{
Console.WriteLine(num2);
num2 += num1;
num1 = num2 - num1;
}
}
Console.ReadLine();
}
}
in your array format here is the solution
public int[] FibonacciSeriesArray(int num)
{
int[] arr = new int[num+1];
arr[0] = 0;
arr[1] = 1;
for (int startnum = 2; startnum <= num; startnum++)
{
arr[startnum] = arr[startnum - 1] + arr[startnum - 2];
}
return arr;
}
I would do it as a recursion, and not as a loop.
private static int fibonacci(int fib)
{
if (fib == 2 || fib == 1)
{
return 1;
}
else
{
return fibonacci(fib - 1) + fibonacci(fib - 2);
}
}
Here's a much more efficient way of finding fibonnaci numbers.
public static IEnumerable<double> FibList(int n)
{
for (int i = 1; i <= n; i++)
{
yield return Math.Round(Fib(i));
}
}
public static double Fib(double n)
{
double golden = 1.61803398875;
return (n == 0 || n == 1) ? 1 : (Math.Pow(golden, n) - Math.Pow(-golden, -n))/Math.Sqrt(5);
}