newdevin
BAN USERpublic static char[] Reverse(char[] str)
{
if (str.Length == 0)
return new char[0];
else if (str.Length == 1)
return new char[1] { str[0] };
char[] res = new char[str.Length];
int si = 0;
int ei = 0;
for (int i = si; i < str.Length; i++, ei++)
{
if (str[i] != ' ')
{
continue;
}
else
{
res[i] = ' ';
for (int j = si; j < ei; j++)
{
res[j] = str[ei - 1 - (j - si)];
}
si = ei + 1;
}
}
if (ei >= str.Length)
ei = str.Length - 1;
if (si <= ei)
{
for (int j = si; j <= ei; j++)
{
res[j] = str[ei - (j - si)];
}
}
return res;
}
The above code is in C# and do not use any inbuilt string functions. It just manipulates the array items
- newdevin August 03, 2015public static List<int[]> CheckSum2(int[] arr, int res)
{
List<int[]> lst = new List<int[]>();
if (arr == null)
throw new ArgumentNullException();
if (arr.Length == 0)
{
// lst.Add(new int[] { });
return lst; ;
}
int[] inp = arr.Select(x => x).OrderBy(x => x).ToArray();//sorted
if (inp.Length == 0)
{
// lst.Add(new int[] { });
return lst; ;
}
for (int i = 0; i < inp.Length; i++)
{
int num1 = inp[i];
//if (num1 > res)
// break;
if (num1 == res)
{
lst.Add(new int[] { num1 });
continue;
}
int[] x = inp.Skip(i + 1).ToArray();
var rest = CheckSum2(x, res - num1);
foreach (int[] restNum in rest)
{
var a = new int[restNum.Length + 1];
a[0] = num1;
for (int j = 1; j < a.Length; j++)
{
a[j] = restNum[j - 1];
}
lst.Add(a);
}
}
return lst;
}
C# code.
This code will return a list of arrays with each array containing the list of number that adds to the given sum.
E.g. for a given array of {-1,0,1} if the given sum is 0, it will return {-1,0,1},{-1,1},{0}.
I haven't worked out the space/time complexity
Using c#
- newdevin August 03, 2015