Now that I am using recursion to calcuate the sum of numbers, I want to do something slightly different. The following is my code that will sum the numbers 1,2,3,4,5. How would I modify my code to place the numbers 1, 2, 3, 4, 5 into an array and then use it in the recursion method? I have tried so many different attempts and I am apparently missing something. I know that in the recursion method, that I want to use the Length property of the array to control it.
Susan
static void Main(string[] args)
{
Console.WriteLine(Sum(5));
Console.Read();
}
static int Sum(int value)
{
if (value > 0)
{
return value + Sum(value - 1);
}
else
{
return 0;
}
}
let seq = [1;2;3;4;5]
let rec samp nums =
match nums with
| [] -> 0
| h::t -> h + samp t
static int Sum(int[] a, int index = 0)
{
if (a[index] == a[a.Length - 1])
{
return a[a.Length - 1];
}
return a[index] + Sum(a, index + 1);
}
static void Main()
{
int[] arr = {1, 2, 3, 9, 15};
Console.WriteLine(Sum(arr));
}
I'm a beginner too but this is my solution and it works for me.
What about using a Stack?:
Stack<int> stack = new Stack<int>(new int [] {1,2,3,4,5});
Console.WriteLine(SumStack(stack));
public static int SumStack(Stack<int> input)
{
return input.Count > 0 ? input.Pop() + SumStack(input) : 0;
}
Sniff, sniff, smells like homework to me.
However, a hint. Adding all the elements of an array of length 'n' is the same as adding all the elements of an array of length 'n-1', then adding the value of element 'n'.
The result of adding all the elements of an array of length '1' is just the value of the one element
I believe that you need to pass the array and the index in your Sum function to control the recursivity.
Of if your no good with lambda expressions or you only have .net 2.0, this is simple enough;
static void Main(string[] args)
{
int[] myArray = new int[5] {1,2,3,4,5 };
Console.WriteLine(Sum1(myArray));
Console.Read();
}
private static int Sum1(int[] myArray)
{
if (myArray.Length > 0)
{
int lengthZeroAdjusted = myArray.Length - 1;
int element = myArray[lengthZeroAdjusted];
Array.Resize<int>(ref myArray, lengthZeroAdjusted);
return element + Sum1(myArray);
}
else
{
return 0;
}
}
You're wanting to perform an operation that is commonly referred to as "fold" a.k.a. "reduce".
Luckily, the .NET team did your (home)work for you!
static int sum(int[] values)
{
return values.Aggregate<int>((hd, tl) => hd + tl);
}
You can rewrite it for easier readability if you like. ;)
EDIT: usage example
int[] values = new int[]{1,2,3,4,5};
Console.WriteLine(sum(values));
Recursion essentially means doing the small part, and giving the larger part to somebody else.
Now if you have to 'n' elements of array, you ask somebody to give you sum of last n-1 elements,
and just first one yourself ... just handle the case where there is nothing to be done ...
a pseudo code would be :
sum array start_index = if ( start_index >= length(array) ) return 0
else return array[start_index] = sum array (start_index + 1)
print (sum array 0 )
Related
I want to convert int array to int so i can add them.
Example
int[] x = {1, 2, 3};
sum=x[0] + x[1] + x[2];
I have a loop for getting an input from user but i have to add all the values of every inputted.
Use the .Sum LINQ method:
var x = new int[] { 1, 2, 3 };
var sum = x.Sum(); // gives 6
Further info
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://www.csharp-examples.net/linq-sum/
You can do this in a number of ways.
first by making a loop yourself.
static int Sum(int[] array)
{
int sum = 0;
foreach (var item in array)
{
sum += item;
}
return sum;
}
static void Main()
{
int[] x = new int[] { 1, 2, 3 };
Console.Write(Sum(x).ToString());
}
second, using the Sum() method in the System.Linq library
using System.Linq;
////
int[] x = new int[] { 1, 2, 3 };
Console.Write(x.Sum());
thank you USEFUL for feedback if it worked for you
It is not really clear what the problem is. Your code seems fully functional, so it is difficult to know what you are really trying to achieve and what the underlying issue it.
But certainly a simple loop would work fine.
int sum = 0;
for(int loop=0; loop < x.Length; loop++)
{
sum += x[loop];
}
You can also do this via Linq (I see somebody else posted that example, so I won't repeat it).
I have an array of Foo objects. How do I remove the second element of the array?
I need something similar to RemoveAt() but for a regular array.
If you don't want to use List:
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
You could try this extension method that I haven't actually tested:
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
And use it like:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array.
I use this method for removing an element from an object array. In my situation, my arrays are small in length. So if you have large arrays you may need another solution.
private int[] RemoveIndices(int[] IndicesArray, int RemoveAt)
{
int[] newIndicesArray = new int[IndicesArray.Length - 1];
int i = 0;
int j = 0;
while (i < IndicesArray.Length)
{
if (i != RemoveAt)
{
newIndicesArray[j] = IndicesArray[i];
j++;
}
i++;
}
return newIndicesArray;
}
LINQ one-line solution:
myArray = myArray.Where((source, index) => index != 1).ToArray();
The 1 in that example is the index of the element to remove -- in this example, per the original question, the 2nd element (with 1 being the second element in C# zero-based array indexing).
A more complete example:
string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();
After running that snippet, the value of myArray will be { "a", "c", "d", "e" }.
This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize<T>:
public static void RemoveAt<T>(ref T[] arr, int index)
{
for (int a = index; a < arr.Length - 1; a++)
{
// moving elements downwards, to fill the gap at [index]
arr[a] = arr[a + 1];
}
// finally, let's decrement Array's size by one
Array.Resize(ref arr, arr.Length - 1);
}
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
Not exactly the way to go about this, but if the situation is trivial and you value your time, you can try this for nullable types.
Foos[index] = null
and later check for null entries in your logic..
Try below code:
myArray = myArray.Where(s => (myArray.IndexOf(s) != indexValue)).ToArray();
or
myArray = myArray.Where(s => (s != "not_this")).ToArray();
As usual, I'm late to the party...
I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.
Reference:
http://msdn.microsoft.com/en-us/library/bb311042.aspx
So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)
using System;
namespace FunctionTesting {
// The class doesn't matter, as long as it's static
public static class SomeRandomClassWhoseNameDoesntMatter {
// Here's the actual method that extends arrays
public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
T[] nArray = new T[oArray.Length - 1];
for( int i = 0; i < nArray.Length; ++i ) {
nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
}
return nArray;
}
}
// Sample usage...
class Program {
static void Main( string[] args ) {
string[] myStrArray = { "Zero", "One", "Two", "Three" };
Console.WriteLine( String.Join( " ", myStrArray ) );
myStrArray = myStrArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myStrArray ) );
/* Output
* "Zero One Two Three"
* "Zero One Three"
*/
int[] myIntArray = { 0, 1, 2, 3 };
Console.WriteLine( String.Join( " ", myIntArray ) );
myIntArray = myIntArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myIntArray ) );
/* Output
* "0 1 2 3"
* "0 1 3"
*/
}
}
}
Here's how I did it...
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.
private int[] removeFromArray(int[] array, int id)
{
int difference = 0, currentValue=0;
//get new Array length
for (int i=0; i<array.Length; i++)
{
if (array[i]==id)
{
difference += 1;
}
}
//create new array
int[] newArray = new int[array.Length-difference];
for (int i = 0; i < array.Length; i++ )
{
if (array[i] != id)
{
newArray[currentValue] = array[i];
currentValue += 1;
}
}
return newArray;
}
Here's a small collection of helper methods I produced based on some of the existing answers. It utilizes both extensions and static methods with reference parameters for maximum idealness:
public static class Arr
{
public static int IndexOf<TElement>(this TElement[] Source, TElement Element)
{
for (var i = 0; i < Source.Length; i++)
{
if (Source[i].Equals(Element))
return i;
}
return -1;
}
public static TElement[] Add<TElement>(ref TElement[] Source, params TElement[] Elements)
{
var OldLength = Source.Length;
Array.Resize(ref Source, OldLength + Elements.Length);
for (int j = 0, Count = Elements.Length; j < Count; j++)
Source[OldLength + j] = Elements[j];
return Source;
}
public static TElement[] New<TElement>(params TElement[] Elements)
{
return Elements ?? new TElement[0];
}
public static void Remove<TElement>(ref TElement[] Source, params TElement[] Elements)
{
foreach (var i in Elements)
RemoveAt(ref Source, Source.IndexOf(i));
}
public static void RemoveAt<TElement>(ref TElement[] Source, int Index)
{
var Result = new TElement[Source.Length - 1];
if (Index > 0)
Array.Copy(Source, 0, Result, 0, Index);
if (Index < Source.Length - 1)
Array.Copy(Source, Index + 1, Result, Index, Source.Length - Index - 1);
Source = Result;
}
}
Performance wise, it is decent, but it could probably be improved. Remove relies on IndexOf and a new array is created for each element you wish to remove by calling RemoveAt.
IndexOf is the only extension method as it does not need to return the original array. New accepts multiple elements of some type to produce a new array of said type. All other methods must accept the original array as a reference so there is no need to assign the result afterward as that happens internally already.
I would've defined a Merge method for merging two arrays; however, that can already be accomplished with Add method by passing in an actual array versus multiple, individual elements. Therefore, Add may be used in the following two ways to join two sets of elements:
Arr.Add<string>(ref myArray, "A", "B", "C");
Or
Arr.Add<string>(ref myArray, anotherArray);
I know this article is ten years old and therefore probably dead, but here's what I'd try doing:
Use the IEnumerable.Skip() method, found in System.Linq. It will skip the selected element from the array, and return another copy of the array that only contains everything except the selected object. Then just repeat that for every element you want removed and after that save it to a variable.
For example, if we have an array named "Sample" (of type int[]) with 5 numbers. We want to remove the 2nd one, so trying "Sample.Skip(2);" should return the same array except without the 2nd number.
First step
You need to convert the array into a list, you could write an extension method like this
// Convert An array of string to a list of string
public static List<string> ConnvertArrayToList(this string [] array) {
// DECLARE a list of string and add all element of the array into it
List<string> myList = new List<string>();
foreach( string s in array){
myList.Add(s);
}
return myList;
}
Second step
Write an extension method to convert back the list into an array
// convert a list of string to an array
public static string[] ConvertListToArray(this List<string> list) {
string[] array = new string[list.Capacity];
array = list.Select(i => i.ToString()).ToArray();
return array;
}
Last steps
Write your final method, but remember to remove the element at index before converting back to an array like the code show
public static string[] removeAt(string[] array, int index) {
List<string> myList = array.ConnvertArrayToList();
myList.RemoveAt(index);
return myList.ConvertListToArray();
}
examples codes could be find on my blog, keep tracking.
I need assistance with Combinations with Repetition. Have searched all over the net and although I found a few examples I can't understand them completely. My goal is simple a function (CombinationsWithRepetiion) receives list with items (in this case integer values) and length (that represents how long each combination can be) and returns a list containing the result.
List<int> input = new List<int>() {1, 2, 3}
CombinationsWithRepetition(input, length);
result:
length = 1: 1, 2, 3
length = 2: 11,12,13,21,22,23,31,32,33
length = 3: 111,112 ....
I hope someone helps me and thank you in advance!
recursion
Ok,
here is the C# version - I walk you through it
static IEnumerable<String> CombinationsWithRepetition(IEnumerable<int> input, int length)
{
if (length <= 0)
yield return "";
else
{
foreach(var i in input)
foreach(var c in CombinationsWithRepetition(input, length-1))
yield return i.ToString() + c;
}
}
First you check the border-cases for the recursion (in this case if length <= 0) - in this case the answer is the empty string (btw: I choose to return strings as you did not say what your really needed - should be easy to change).
In any other case you look at each input i and recursivley take the next-smaller combinations and just plug em together (with String-concatination because I wanted strings).
I hope you understand the IEnumerable/yield stuff - if not say so in the comments please.
Here is a sample output:
foreach (var c in CombinationsWithRepetition(new int[]{1,2,3}, 3))
Console.WriteLine (c);
111
112
113
...
332
333
converting numbers
The following uses the idea I sketched in the comment below and has no problems with stack-overflow exceptions (recursion might for big lenght) - this too assumes strings as they are easier to work with (and I can do a simple PadLeft to simplify things)
static String Convert(string symbols, int number, int totalLen)
{
var result = "";
var len = symbols.Length;
var nullSym = symbols [0];
while (number > 0)
{
var index = number % len;
number = number / len;
result = symbols [index] + result;
}
return result.PadLeft (totalLen, nullSym);
}
static IEnumerable<String> CombinationsWithRepetition(string symbols, int len)
{
for (var i = 0; i < Math.Pow(symbols.Length,len); i++)
yield return Convert (symbols, i, len);
}
string[] items = {"1", "2", "3"};
var query = from i1 in items
from i2 in items
from i3 in items
select i1 + i2 + i3 ;
foreach(var result in query)
Console.WriteLine(result);
Console.ReadKey();
I am solving this problem of rotating an array and got algorithm and code working
int[] Rotate(int[] ar,int k)
{
if (k <= 0 || k > ar.Length - 1)
return ar;
Reverse(ar, 0, k - 1);
Reverse(ar, k, ar.Length - 1);
Reverse(ar, 0, ar.Length - 1);
return ar;
}
void Reverse(int[] ar,int start, int end)
{
while (start < end)
{
int temp = ar[start];
ar[start] = ar[end];
ar[end] = temp;
start++;
end--;
}
}
Now I want to do this in LINQ and I got the below code, I think this can be done much better.
int[] Rotate(int[] ar,int k)
{
if (k <= 0 || k > ar.Length - 1)
return ar;
int[] ar1=ar.Take(k-1).Reverse().ToArray();
int[] ar2=ar.Skip(k - 1).Take(ar.Length - k+1).Reverse().ToArray();
int[] ar3 = ar1.Concat(ar2).Reverse().ToArray();
return ar3;
}
This is a well known algorithm from Programming pearls - http://books.google.com/books?id=kse_7qbWbjsC&lpg=PA14&ots=DfzTzQCSar&dq=rotate%20an%20array%20programming%20pearls&pg=PA14#v=onepage&q&f=false
And in general how to develop my LINQ skills, if I am given a programming problem, right now I am only thinking in for loops or foreach loops, how to think in terms of linq operators. I am reading C# 4.0 nutshell, other than practicing any advice?
I'm not sure why you've got all the reversals, to be honest. How about this:
int[] Rotate(int[] ar,int k)
{
if (k <= 0 || k > ar.Length - 1)
return ar;
return ar.Skip(k) // Start with the last elements
.Concat(ar.Take(k)) // Then the first elements
.ToArray(); // Then make it an array
}
Here's a short but complete program to demonstrate it:
using System;
using System.Linq;
class Test
{
static int[] Rotate(int[] ar,int k)
{
if (k <= 0 || k > ar.Length - 1)
return ar;
return ar.Skip(k) // Start with the last elements
.Concat(ar.Take(k)) // Then the first elements
.ToArray(); // Then make it an array
}
static void Main()
{
int[] values = { 1, 2, 3, 4, 5 };
int[] rotated = Rotate(values, 3);
Console.WriteLine(string.Join(", ", rotated));
}
}
Output: 4, 5, 1, 2, 3
EDIT: I've just noticed one major difference between my code and your original: yours modifies the original array - mine returns a new array with the rotated values. So would your LINQ code, but it means if you were testing my code with something that only looked at the original array, you wouldn't see the rotation.
LINQ is designed to work this way in general - it favours returning a new sequence over modifying an existing one.
Starting with your code:
int[] ar1=ar.Take(k-1).Reverse().ToArray();
int[] ar2=ar.Skip(k - 1).Take(ar.Length - k+1).Reverse().ToArray();
int[] ar3 = ar1.Concat(ar2).Reverse().ToArray();
Since you just want to get all of the remaining elements, the Take in the second line isn't needed.
ar1 and ar2 are just enumerated, so they don't need to be arrays. The ToArray calls aren't needed. With a bit of creative renaming thrown in, we have:
IEnumerable<int> revFirst = ar.Take(k-1).Reverse();
IEnumerable<int> revLast = ar.Skip(k-1).Reverse();
int[] ar3 = revFirst.Concat(revLast).Reverse().ToArray();
Now we have
rev ( rev(first) + rev(last) )
distributing the outer rev gives
rev ( rev(last) ) + rev ( rev(first) )
which is the same as
last + first
applying the same operations to the code gives
IEnumerable<int> first = ar.Take(k-1);
IEnumerable<int> last = ar.Skip(k-1);
int[] ar3 = last.Concat(first).ToArray();
which further simplifies to
int[] ar3 = ar.Skip(k-1).Concat(ar.Take(k-1)).ToArray();
and now we have Jon Skeet's answer so we must be done.
this is my solution
public int[] solution(int[] A, int K) {
// write your code in C# 6.0 with .NET 4.5 (Mono)
if (A.Length <= 1)
{
return A;
}
var rotate = K % A.Length;
var leftSide = A.Length - rotate;
var arr1 = A.AsParallel().Skip(leftSide).Take(rotate);
var arr2 = A.AsParallel().Take(leftSide);
return arr1.Concat(arr2).ToArray();
}
you can check my github. I also have some unit tests for other cases and other codidlity lessons and challenges
I have an array of Foo objects. How do I remove the second element of the array?
I need something similar to RemoveAt() but for a regular array.
If you don't want to use List:
var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();
You could try this extension method that I haven't actually tested:
public static T[] RemoveAt<T>(this T[] source, int index)
{
T[] dest = new T[source.Length - 1];
if( index > 0 )
Array.Copy(source, 0, dest, 0, index);
if( index < source.Length - 1 )
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
And use it like:
Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);
The nature of arrays is that their length is immutable. You can't add or delete any of the array items.
You will have to create a new array that is one element shorter and copy the old items to the new array, excluding the element you want to delete.
So it is probably better to use a List instead of an array.
I use this method for removing an element from an object array. In my situation, my arrays are small in length. So if you have large arrays you may need another solution.
private int[] RemoveIndices(int[] IndicesArray, int RemoveAt)
{
int[] newIndicesArray = new int[IndicesArray.Length - 1];
int i = 0;
int j = 0;
while (i < IndicesArray.Length)
{
if (i != RemoveAt)
{
newIndicesArray[j] = IndicesArray[i];
j++;
}
i++;
}
return newIndicesArray;
}
LINQ one-line solution:
myArray = myArray.Where((source, index) => index != 1).ToArray();
The 1 in that example is the index of the element to remove -- in this example, per the original question, the 2nd element (with 1 being the second element in C# zero-based array indexing).
A more complete example:
string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();
After running that snippet, the value of myArray will be { "a", "c", "d", "e" }.
This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize<T>:
public static void RemoveAt<T>(ref T[] arr, int index)
{
for (int a = index; a < arr.Length - 1; a++)
{
// moving elements downwards, to fill the gap at [index]
arr[a] = arr[a + 1];
}
// finally, let's decrement Array's size by one
Array.Resize(ref arr, arr.Length - 1);
}
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
Not exactly the way to go about this, but if the situation is trivial and you value your time, you can try this for nullable types.
Foos[index] = null
and later check for null entries in your logic..
Try below code:
myArray = myArray.Where(s => (myArray.IndexOf(s) != indexValue)).ToArray();
or
myArray = myArray.Where(s => (s != "not_this")).ToArray();
As usual, I'm late to the party...
I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.
Reference:
http://msdn.microsoft.com/en-us/library/bb311042.aspx
So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)
using System;
namespace FunctionTesting {
// The class doesn't matter, as long as it's static
public static class SomeRandomClassWhoseNameDoesntMatter {
// Here's the actual method that extends arrays
public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
T[] nArray = new T[oArray.Length - 1];
for( int i = 0; i < nArray.Length; ++i ) {
nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
}
return nArray;
}
}
// Sample usage...
class Program {
static void Main( string[] args ) {
string[] myStrArray = { "Zero", "One", "Two", "Three" };
Console.WriteLine( String.Join( " ", myStrArray ) );
myStrArray = myStrArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myStrArray ) );
/* Output
* "Zero One Two Three"
* "Zero One Three"
*/
int[] myIntArray = { 0, 1, 2, 3 };
Console.WriteLine( String.Join( " ", myIntArray ) );
myIntArray = myIntArray.RemoveAt( 2 );
Console.WriteLine( String.Join( " ", myIntArray ) );
/* Output
* "0 1 2 3"
* "0 1 3"
*/
}
}
}
Here's how I did it...
public static ElementDefinitionImpl[] RemoveElementDefAt(
ElementDefinition[] oldList,
int removeIndex
)
{
ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];
int offset = 0;
for ( int index = 0; index < oldList.Length; index++ )
{
ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
if ( index == removeIndex )
{
// This is the one we want to remove, so we won't copy it. But
// every subsequent elementDef will by shifted down by one.
offset = -1;
}
else
{
newElementDefList[ index + offset ] = elementDef;
}
}
return newElementDefList;
}
In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.
private int[] removeFromArray(int[] array, int id)
{
int difference = 0, currentValue=0;
//get new Array length
for (int i=0; i<array.Length; i++)
{
if (array[i]==id)
{
difference += 1;
}
}
//create new array
int[] newArray = new int[array.Length-difference];
for (int i = 0; i < array.Length; i++ )
{
if (array[i] != id)
{
newArray[currentValue] = array[i];
currentValue += 1;
}
}
return newArray;
}
Here's a small collection of helper methods I produced based on some of the existing answers. It utilizes both extensions and static methods with reference parameters for maximum idealness:
public static class Arr
{
public static int IndexOf<TElement>(this TElement[] Source, TElement Element)
{
for (var i = 0; i < Source.Length; i++)
{
if (Source[i].Equals(Element))
return i;
}
return -1;
}
public static TElement[] Add<TElement>(ref TElement[] Source, params TElement[] Elements)
{
var OldLength = Source.Length;
Array.Resize(ref Source, OldLength + Elements.Length);
for (int j = 0, Count = Elements.Length; j < Count; j++)
Source[OldLength + j] = Elements[j];
return Source;
}
public static TElement[] New<TElement>(params TElement[] Elements)
{
return Elements ?? new TElement[0];
}
public static void Remove<TElement>(ref TElement[] Source, params TElement[] Elements)
{
foreach (var i in Elements)
RemoveAt(ref Source, Source.IndexOf(i));
}
public static void RemoveAt<TElement>(ref TElement[] Source, int Index)
{
var Result = new TElement[Source.Length - 1];
if (Index > 0)
Array.Copy(Source, 0, Result, 0, Index);
if (Index < Source.Length - 1)
Array.Copy(Source, Index + 1, Result, Index, Source.Length - Index - 1);
Source = Result;
}
}
Performance wise, it is decent, but it could probably be improved. Remove relies on IndexOf and a new array is created for each element you wish to remove by calling RemoveAt.
IndexOf is the only extension method as it does not need to return the original array. New accepts multiple elements of some type to produce a new array of said type. All other methods must accept the original array as a reference so there is no need to assign the result afterward as that happens internally already.
I would've defined a Merge method for merging two arrays; however, that can already be accomplished with Add method by passing in an actual array versus multiple, individual elements. Therefore, Add may be used in the following two ways to join two sets of elements:
Arr.Add<string>(ref myArray, "A", "B", "C");
Or
Arr.Add<string>(ref myArray, anotherArray);
I know this article is ten years old and therefore probably dead, but here's what I'd try doing:
Use the IEnumerable.Skip() method, found in System.Linq. It will skip the selected element from the array, and return another copy of the array that only contains everything except the selected object. Then just repeat that for every element you want removed and after that save it to a variable.
For example, if we have an array named "Sample" (of type int[]) with 5 numbers. We want to remove the 2nd one, so trying "Sample.Skip(2);" should return the same array except without the 2nd number.
First step
You need to convert the array into a list, you could write an extension method like this
// Convert An array of string to a list of string
public static List<string> ConnvertArrayToList(this string [] array) {
// DECLARE a list of string and add all element of the array into it
List<string> myList = new List<string>();
foreach( string s in array){
myList.Add(s);
}
return myList;
}
Second step
Write an extension method to convert back the list into an array
// convert a list of string to an array
public static string[] ConvertListToArray(this List<string> list) {
string[] array = new string[list.Capacity];
array = list.Select(i => i.ToString()).ToArray();
return array;
}
Last steps
Write your final method, but remember to remove the element at index before converting back to an array like the code show
public static string[] removeAt(string[] array, int index) {
List<string> myList = array.ConnvertArrayToList();
myList.RemoveAt(index);
return myList.ConvertListToArray();
}
examples codes could be find on my blog, keep tracking.