Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
int arraySum (int [] a, int n)
{
int sum = 0;
n = a.size();
for (int i = 1; i < n; i++)
sum += a[i];
return sum;
}
I want to convert this code from iterative to recursive.
C# Version:
int arraySum ( int [] a, int sum = 0, int i = 0 ) /*i = 0, technically means this code is logically different from yours, however it will count every element and is just a default :)*/
{
if( i < a.Length )
return arraySum( a, sum + a[i], ++i );
return sum;
}
You need:
1- Recursive definition like: sum(n) = n + sum(n-1)
2- You need to specify where should you stop so the recursion does not last forever.
for example: if (n == 0) return 0;
based on this you can code at any language.
C++ Example:
int arraySum (int a[], int n)
{
if(n==1)
return a[n-1];
else
return a[n-1] + arraySum (a, n-1);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I want to remove bytes from an array, I don't want to remove all bytes 0x6f I just want to remove two only of them. This is my code:
string msg = "gooooooal";
byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg);
byte[] newArray = oldArray.Where(b => b != 0x6f).ToArray();
You can first find the position and then remove them
byte[] oldArray = Encoding.GetEncoding(1256).GetBytes(msg);
int howManyToRemove = 2; //How many items to remove
var positions = new List<int>();
int lastPos = -1;
for (int i = 0; i < howManyToRemove; i++)
{
var position = Array.IndexOf(oldArray, (byte)0x6f,lastPos+1);
if (position == -1)
{
break;
}
lastPos=position;
positions.Add(position);
}
byte[] newArray = oldArray.Where((val, idx) => !positions.Contains(idx)).ToArray();
If I understood your problem then if want to delete two occurrences of the letter o from your string because the 0x6f ASCII value is 111 which is the letter o.
and for that, you are making the solution very complex.
if can simply do like this.
string s = "gooooooal";
string output = removeChar(s, 'o'); //output will be gooool
static string removeChar(string s,
char ch)
{
int count = 2;
for (int i = 0; i < s.Length; i++)
{
// If ch is found
if (s[i] == ch && count > 0)
{
s = s.Substring(0, i) +
s.Substring(i + 1);
count--;
}
}
return s;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want a code to generate sequence of Alphanumeric character like LLNNLLNNLL where L is the Letter and N is the number. For example if the length is 5 the sequence will be LLNNL and if the length is 6 the sequence will be LLNNLL and if 7 it would be LLNNLLN.
string alphabets = "ABCDEFGHIJKLMNPQRSTUVWX";
int length = model.VALUE_INT;
string result = "";
for (int i = 0; i < length; i++)
{
int next = _random.Next(23);
result += alphabets.ElementAt(next);
result += _randomNum.Next(1, 9);
}
This is what I have tried but condition is not fulfilling
For each position (value of i) of your output string you need to check if you need a character or an integer.
Since the pattern repeats every 4 positions, you can achieve this using the modulo operator:
for (int i = 0; i < length; i++)
{
switch (i % 4)
{
case 0:
case 1:
int next = _random.Next(23);
result += alphabets.ElementAt(next);
break;
case 2:
case 3:
result += _randomNum.Next(1, 9);
break;
}
}
Or another possibility: Add blocks of LLNN and then truncate the result to the needed length...
for (int i = 0; i <= (length/4); i++)
{
result += alphabets.ElementAt(_random.Next(23));
result += alphabets.ElementAt(_random.Next(23));
result += _randomNum.Next(1, 9);
result += _randomNum.Next(1, 9);
}
result = result.Substring(0,length);
If you want to improve these lines, you can use a StringBuilder
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm writing a SIMD library and trying to squeeze every bit of performance.
I'm already casting in-place the array into a Span<Vector<int>>, instead of creating new objects.
Target arrays are of large size (more than 1000 elements).
Is there a more efficient way of summing an array?
Ideas are welcome.
public static int Sum(int[] array)
{
Vector<int> vSum = Vector<T>.Zero;
int sum;
int i;
Span<Vector<int>> vsArray = MemoryMarshal.Cast<int, Vector<int>>(array);
for (i = 0; i < vsArray.Length; i++)
{
vSum += vsArray[i];
}
sum = Vector.Dot(vSum, Vector<int>.One);
i *= Vector<int>.Count;
for (; i < array.Length; i++)
{
sum += array[i];
}
return sum;
}
Your code is good. Only possible to improve by 4%, here's how:
// Test result: only 4% win on my PC.
[MethodImpl( MethodImplOptions.AggressiveInlining )]
static int sumUnsafeAvx2( int[] array )
{
unsafe
{
fixed( int* sourcePointer = array )
{
int* pointerEnd = sourcePointer + array.Length;
int* pointerEndAligned = sourcePointer + ( array.Length - array.Length % 16 );
Vector256<int> sumLow = Vector256<int>.Zero;
Vector256<int> sumHigh = sumLow;
int* pointer;
for( pointer = sourcePointer; pointer < pointerEndAligned; pointer += 16 )
{
var a = Avx.LoadVector256( pointer );
var b = Avx.LoadVector256( pointer + 8 );
sumLow = Avx2.Add( sumLow, a );
sumHigh = Avx2.Add( sumHigh, b );
}
sumLow = Avx2.Add( sumLow, sumHigh );
Vector128<int> res4 = Sse2.Add( sumLow.GetLower(), sumLow.GetUpper() );
res4 = Sse2.Add( res4, Sse2.Shuffle( res4, 0x4E ) );
res4 = Sse2.Add( res4, Sse2.Shuffle( res4, 1 ) );
int scalar = res4.ToScalar();
for( ; pointer < pointerEnd; pointer++ )
scalar += *pointer;
return scalar;
}
}
}
Here's a complete test.
To be clear, I don’t recommend doing what I wrote above. Not for the 4% improvement. Unsafe code is, well, unsafe. Your version will work without AVX2, and benefits from AVX512 if available, my optimized version gonna crash without AVX2, and won’t use AVX512 even if hardware supports it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
Please tell me how can I apply permutation and combination in C# console application and take values of N and r and calculate permutation and combination.
I just had a go doing this for fun, it's actually a little challenging as a naive implementation overflows long very quickly. I've included those in comments.
Equations
nPr = n! / (n - r)!
nCr = n! / r! (n - r)!
Implementaion
public static class PermutationsAndCombinations
{
public static long nCr(int n, int r)
{
// naive: return Factorial(n) / (Factorial(r) * Factorial(n - r));
return nPr(n, r) / Factorial(r);
}
public static long nPr(int n, int r)
{
// naive: return Factorial(n) / Factorial(n - r);
return FactorialDivision(n, n - r);
}
private static long FactorialDivision(int topFactorial, int divisorFactorial)
{
long result = 1;
for (int i = topFactorial; i > divisorFactorial; i--)
result *= i;
return result;
}
private static long Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
}
Usage
Console.WriteLine(PermutationsAndCombinations.nPr(10, 3));
Console.WriteLine(PermutationsAndCombinations.nCr(10, 3));
Prints:
720
120
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i have a problem with arrays or something missed in these text..
my program works every 500ms and i want to read first 4 double values and take average of these values and then get next 4 double values and so on... i write something about this and can you pls look on this??
if (u_dcbus_pv_act[i] > 0 && i != 0)
{
u_dcbus_pv = u_dcbus_pv_act[i];
p_dcbus_pv = p_dcbus_pv_act[i];
}
if (i >= 3)
{
for (int j = 0; j < 4; j++)
{
total_u += u_dcbus_pv;
total_p += p_dcbus_pv;
}
average_u = total_u / 4;
average_p = total_p / 4;
u_dcbus_target = average_u;
p_dcbus_pv_avg = average_p;
}
from what I understand of your description, I would do it something like this:
/* add current samples to totals */
total_u += u_dcbus_pv_act[i];
total_p += p_dcbus_pv_act[i];
/* every fourth tick, calc average and reset totals */
if (i % 4 == 0)
{
average_u = total_u / 4;
average_p = total_p / 4;
total_u = 0;
total_p = 0;
}
u_dcbus_target = average_u;
p_dcbus_pv_avg = average_p;
i++;