How can I add a single Integer to an Integer Array?
if (valuesHigherThanAverage.Length == 0) valuesHigherThanAverage[valuesHigherThanAverage.Length] = arrayGetal;
else valuesHigherThanAverage[valuesHigherThanAverage.Length + 1] = arrayGetal;
I have this code and I have also tried with for or foreach loop but it doesn't worked. And I need to use an INT[] and may not use an List.
You can't add a new item in an array, you have to create a new array with size+1, copy all existing values, and then set the last item value.
An easier way is to use a List<int>, which will automatically resize if you run out of space. Calling the Add method suffices then.
Here a sample of an array resizing algorithm (Array.Resize could automate this, but this is just to show you how it should work):
int[] oldItems = new int[] { 1, 2, 3 };
int[] newItems = new int[oldItems.Length * 2];
for (int i = 0; i < oldItems.Length; i++)
{
newItems[i] = oldItems[i];
}
newItems[oldItems.Length + 1] = 4;
The array is not designed to be extended as new elements are added. You will need to call Array.Resize(Of T) to increase the size but this is will be quite inefficient.
Data types more in line for what you want to do is List<T>.
You cannot change the size of array like valuesHigherThanAverage.Length + 1. It has fixed size. You are crossing the upper bound of the array.
You can create a new Array with the length of the old array + 1.
public static int[] AddIntToArray(int[] sourceArray, int addValue)
{
int[] newArray = new int[sourceArray.Length + 1];
Array.Copy(sourceArray, newArray, sourceArray.Length);
newArray[newArray.Length] = addValue;
return newArray;
}
I have the following code. It's roughly analogous in concept to the python reshape function. It successfully loads 1-dimensional data into a multi-dimensional array, the dimensions of which are not known until runtime. For example {209,64,64,3}. I have to iterate over the 1-dimensional data and create the correct indexes for each dimension of the array.
private void InitializeData()
{
var imageData = ImageData.Load(txtFileName.Text); // one dimensional array
var dimensions = txtDimensions.Text.Split(',').Select(d => int.Parse(d)).ToArray(); // e.g., {-1,64,64,3}
int elements = 1;
foreach (var dim in dimensions.Skip(1))
{
elements *= dim;
}
dimensions[0] = imageData.Length / elements; // {209,64,64,3}
// create multipliers
var multipliers = new int[dimensions.Length - 1];
for (var dimension = 1; dimension < dimensions.Length; dimension++)
{
var multiplier = 1;
for (var followingdimension = dimension; followingdimension < dimensions.Length; followingdimension++)
{
multiplier *= dimensions[followingdimension];
}
multipliers[dimension - 1] = multiplier;
}
// load data
var dataArray = Array.CreateInstance(typeof(int), dimensions);
var indexes = new int[dimensions.Length];
for (var imageDataIndex = 0; imageDataIndex < imageData.Length; imageDataIndex++)
{
indexes[0] = imageDataIndex / multipliers[0];
indexes[dimensions.Length - 1] = imageDataIndex % multipliers[multipliers.Length - 1];
for (var multiplier = 1; multiplier < dimensions.Length - 1; multiplier++)
indexes[multiplier] = (imageDataIndex / multipliers[multiplier]) % dimensions[multiplier];
dataArray.SetValue(imageData[imageDataIndex], indexes);
}
}
Is there a faster or more elegant way of doing this? I do realize those are two different things. I'll do bench-marking on the elegant suggestions, but I'd still like to see them. Because this is just too ugly to look at and was too painful to write to be the best way.
Note (Please)
The data may not always be image data, so I am not looking for bitmap operations. That just happens here but it's not necessarily a typical case. And, my goal is not to get a bitmap, but an array.
I have a partial answer thanks to How to reshape an Array in c#
The code can be replaced with just this:
var imageData = ImageData.Load(txtFileName.Text); // one dimensional array
// e.g., {209,64,64,3}
var dimensions = txtDimensions.Text.Split(',').Select(d => int.Parse(d)).ToArray();
int elements = 1;
foreach (var dim in dimensions.Skip(1))
{
elements *= dim;
}
dimensions[0] = imageData.Length / elements;
// load data
var dataArray = Array.CreateInstance(typeof(int), dimensions);
Buffer.BlockCopy(imageData, 0, dataArray, 0, imageData.Length * sizeof(int));
I would be surprised if there's a faster way to do the actual load then Buffer.BlockCopy, or a simpler one. It turns out whatever dimensional form your original data is in, BlockCopy handles it as long as you can specify your target dimensions as part of a target array.
I'll keep looking for ways to further refine the rest of the original code.
I have this 2D Array which is giving me a Array index is out of range, problem. What is the cause of this problem and how can i solve this ?
EDIT: Yep, sorry about that. I will include what i will want to do here:
So im trying to make jagged array which.
So i have a number of platforms, numOfPlatforms
I want to go through them, and each platform has its Size which is randomXSize.
And now, i want mark a point in each platform which is every 0.5, thats why i made
(randomXSize - 0.5)
But i don't know how many times i will need to do that for so i made
randomXSizeSegments = randomXSize * 2;
To calculate how many 0.5 will be for each randomXSize.
So in other words,
If the first platform '0' has a randomXSize of 3
I want the array randomXSizeSegments to be looking like this
randomXSizeSegments[1][0] = 3
randomXSizeSegments[0][1] = 2.5
randomXSizeSegments[0][2] = 2
randomXSizeSegments[0][3] = 1.5
randomXSizeSegments[0][4] = 1
randomXSizeSegments[0][5] = 0.5
randomXSizeSegments[0][6] = 0
And if second platform '1' has a randomXSize of 7
I want the array randomXSizeSegments to be looking like this
randomXSizeSegments[1][0] = 7
randomXSizeSegments[1][1] = 6.5
randomXSizeSegments[1][2] = 6
randomXSizeSegments[1][3] = 5.5
randomXSizeSegments[1][4] = 5
randomXSizeSegments[1][5] = 4.5
randomXSizeSegments[1][6] = 4
randomXSizeSegments[1][7] = 3.5
randomXSizeSegments[1][8] = 3
randomXSizeSegments[1][9] = 2.5
randomXSizeSegments[1][10] = 2
randomXSizeSegments[1][11] = 1.5
randomXSizeSegments[1][12] = 1
randomXSizeSegments[1][13] = 0
void Debugging_One() {
for(int a = 0; a < numOfPlatforms; a = a + 1) {
randomXPosSegments = new int[a][];
randomXSizeSegments = randomXSize * 2;
//Debug.Log(a);
//Debug.Log(randomXSizeSegments);
for(int b = 0; b < randomXSizeSegments; b = b + 1) {
// randomXPosSegments[a][b] = 0;
randomXPosSegments[a] = new int[] {(int)(randomXSize - 0.5)};
//Debug.Log(b);
}
}
}
In the first iteration of your outer for-loop, randomXPosSegments = new int[a][] creates an "empty" array since a = 0. When you then try to access the "0th" (i.e. first) element of that array, it throws that exception since there isn't a position [0] to access.
To create an array with one element, you need to declare it to have a size of 1:
var singleElementArray = new int[1];
singleElementArray[0] = 42;
Debug.WriteLine(singleElementArray[0]); // Prints '42'
If you give it a size of 0. There isn't a "0th" position that exists to assign to:
var singleElementArray = new int[0];
singleElementArray[0] = 42; // Throws IndexOutOfRangeException
I'm not sure how to help you solve this since you haven't explained what you are trying to accomplish and existing code doesn't make sense (e.g. you have an iterator b you never use, you keep on setting randomXPosSegments[a] to a new empty array).
Edit:
A few things first:
To store decimal values like 0.5, randomXPosSegments will need to be an array of double instead of int. We also need to create this outside the loop, or we'll keep creating a new empty array on each iteration. Like wise, you need to initialize randomXPosSegments[a] outside the inner for-loop or you'll just reset it each time.
I created a GetRandomXSize() function, since right now it's value never changes.
Inside the inner for-loop, I'm using randomXSize - (0.5 * b) to get values like 7, 6.5, .... b will start off as 0, so on the first iteration, it will just be randomXSize. Then it'll subtract a 0.5 for each time it's been through the loop.
To get 0 as the last result inside the jagged array, I had to change the condition on the inner for-loop to b <= randomXSizeSegments and make sure I initialize it to be big enough to fit the results (notice the +1 in new double[randomXSizeSegments + 1]).
Here's the code that works for me.
var randomXPosSegments = new double[numOfPlatforms][];
for(int a = 0; a < numOfPlatforms; a = a + 1) {
var randomXSize = GetRandomXSize();
var randomXSizeSegments = randomXSize * 2;
randomXPosSegments[a] = new double[randomXSizeSegments + 1];
for(int b = 0; b <= randomXSizeSegments; b = b + 1) {
randomXPosSegments[a][b] = randomXSize - (0.5 * b);
}
}
Hi i am working on Grade Calculation. My problem here is if the length of string array is longer that int array it works skipping the last 2 grades.
ex:
int[] unit = new int[] {1,-3,3,4};
string[] letter_grade = new string[] {"A", "B","B","W","D","F"};
but if length of int array longer than that of string array its not working its throwing error Index was outside the bounds of the array.
int[] unit = new int[] {1,-3,3,4,5,6,7};
string[] letter_grade = new string[] {"A", "B","B"};
so my question how do i make it work for both??
int length = unit.Length;
int no_units = length;
double totalGrade_Points = 0.0;
int totalno_units = 0;
totalGPA = 0;
for (int i = 0; i < unit.Length; i++)
{
entrygot = findGpaListentry(letter_grade[i]); //Index was outside the bounds of the array.
if (entrygot != null)
{
//some code calculation
}
}
For array indexing you must have starting and stopping condition defined very well. For accessing two arrays either they must be equal or they are compared under certain valid conditions. Have a look at this:
for(int i=0;i<unit.length;i++){
entrygot = findGpaListentry(letter_grade[i]);// only if letter_grade is valid under all values of i i.e unit.length
}
// either you have to check as if;
if(lenght_of_letter_grade < i-1)
//then access
entrygot = findGpaListentry(letter_grade[i]);
You can't just check if the array item is null, because you would be out of the bounds of the array and you will get an exception before the null check occurs.
I would check the length of the array on each iteration...
for (int i = 0; i < unit.Length; i++)
{
if (currentArray.Length < i - 1) { break; }
// other code...
}
I think in your case, the number of elements will never be large hence performance wont be an issue. So I think you should be using a List instead of an array. With an array you will have to be insert checks each time some logic changes or you add other functionalities.
foreach loop is best for your scenerio.
foreach (string s in letter_grade)
{
entrygot = findGpaListentry(s);
if (entrygot != null)
{
//some code calculation
}
}
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
For those who have used PHP, here's what I'm trying to do in C#:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).
Using Linq's method Concat makes this simple
int[] array = new int[] { 3, 4 };
array = array.Concat(new int[] { 2 }).ToArray();
result
3,4,2
If you're writing in C# 3, you can do it with a one-liner:
int[] terms = Enumerable.Range(0, 400).ToArray();
This code snippet assumes that you have a using directive for System.Linq at the top of your file.
On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what that code would look like:
List<int> terms = Enumerable.Range(0, 400).ToList();
Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add() like this:
terms.Add(1337);
By 2019 you can use Append, Prepend using LinQ in just one line
using System.Linq;
and then in NET 6.0:
terms = terms.Append(21);
or versions lower than NET 6.0
terms = terms.Append(21).ToArray();
Answers on how to do it using an array are provided here.
However, C# has a very handy thing called System.Collections
Collections are fancy alternatives to using an array, though many of them use an array internally.
For example, C# has a collection called List that functions very similar to the PHP array.
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
Using a List as an intermediary is the easiest way, as others have described, but since your input is an array and you don't just want to keep the data in a List, I presume you might be concerned about performance.
The most efficient method is likely allocating a new array and then using Array.Copy or Array.CopyTo. This is not hard if you just want to add an item to the end of the list:
public static T[] Add<T>(this T[] target, T item)
{
if (target == null)
{
//TODO: Return null or throw ArgumentNullException;
}
T[] result = new T[target.Length + 1];
target.CopyTo(result, 0);
result[target.Length] = item;
return result;
}
I can also post code for an Insert extension method that takes a destination index as input, if desired. It's a little more complicated and uses the static method Array.Copy 1-2 times.
Based on the answer of Thracx (I don't have enough points to answer):
public static T[] Add<T>(this T[] target, params T[] items)
{
// Validate the parameters
if (target == null) {
target = new T[] { };
}
if (items== null) {
items = new T[] { };
}
// Join the arrays
T[] result = new T[target.Length + items.Length];
target.CopyTo(result, 0);
items.CopyTo(result, target.Length);
return result;
}
This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.
You have to allocate the array first:
int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
terms[runs] = value;
}
int ArraySize = 400;
int[] terms = new int[ArraySize];
for(int runs = 0; runs < ArraySize; runs++)
{
terms[runs] = runs;
}
That would be how I'd code it.
C# arrays are fixed length and always indexed. Go with Motti's solution:
int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.
List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
terms.Add(runs);
}
Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.
You can't just add an element to an array easily. You can set the element at a given position as fallen888 outlined, but I recommend to use a List<int> or a Collection<int> instead, and use ToArray() if you need it converted into an array.
If you really need an array the following is probly the simplest:
using System.Collections.Generic;
// Create a List, and it can only contain integers.
List<int> list = new List<int>();
for (int i = 0; i < 400; i++)
{
list.Add(i);
}
int [] terms = list.ToArray();
one approach is to fill an array via LINQ
if you want to fill an array with one element
you can simply write
string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();
furthermore, If you want to fill an array with multiple elements you can use the
previous code in a loop
//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array
foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}
Array Push Example
public void ArrayPush<T>(ref T[] table, object value)
{
Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
table.SetValue(value, table.Length - 1); // Setting the value for the new element
}
int[] terms = new int[10]; //create 10 empty index in array terms
//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case
for (int run = 0; run < terms.Length; run++)
{
terms[run] = 400;
}
//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}
Console.ReadLine();
/*Output:
Value in index 0: 400
Value in index 1: 400
Value in index 2: 400
Value in index 3: 400
Value in index 4: 400
Value in index 5: 400
Value in index 6: 400
Value in index 7: 400
Value in index 8: 400
Value in index 9: 400
*/
If you don't know the size of the Array or already have an existing array that you are adding to. You can go about this in two ways. The first is using a generic List<T>:
To do this you will want convert the array to a var termsList = terms.ToList(); and use the Add method. Then when done use the var terms = termsList.ToArray(); method to convert back to an array.
var terms = default(int[]);
var termsList = terms == null ? new List<int>() : terms.ToList();
for(var i = 0; i < 400; i++)
termsList.Add(i);
terms = termsList.ToArray();
The second way is resizing the current array:
var terms = default(int[]);
for(var i = 0; i < 400; i++)
{
if(terms == null)
terms = new int[1];
else
Array.Resize<int>(ref terms, terms.Length + 1);
terms[terms.Length - 1] = i;
}
If you are using .NET 3.5 Array.Add(...);
Both of these will allow you to do it dynamically. If you will be adding lots of items then just use a List<T>. If it's just a couple of items then it will have better performance resizing the array. This is because you take more of a hit for creating the List<T> object.
Times in ticks:
3 items
Array Resize Time: 6
List Add Time: 16
400 items
Array Resize Time: 305
List Add Time: 20
I will add this for a another variant. I prefer this type of functional coding lines more.
Enumerable.Range(0, 400).Select(x => x).ToArray();
You can't do this directly. However, you can use Linq to do this:
List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();
If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf. Like:
List<int> termsLst = terms.ToList();
for (int runs = 0; runs < 400; runs++)
{
termsLst.Add(runs);
}
terms = termsLst.ToArray();
Note: don't miss adding 'using System.Linq;' at the begaining of the file.
This seems like a lot less trouble to me:
var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();
Just a different approach:
int runs = 0;
bool batting = true;
string scorecard;
while (batting = runs < 400)
scorecard += "!" + runs++;
return scorecard.Split("!");
int[] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
static void Main(string[] args)
{
int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
/*output each array element value*/
for (j = 0; j < 5; j++)
{
Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
}
Console.ReadKey();/*Obtains the next character or function key pressed by the user.
The pressed key is displayed in the console window.*/
}
/*arrayname is an array of 5 integer*/
int[] arrayname = new int[5];
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}
To add the list values to string array using C# without using ToArray() method
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
list.Add("five");
string[] values = new string[list.Count];//assigning the count for array
for(int i=0;i<list.Count;i++)
{
values[i] = list[i].ToString();
}
Output of the value array contains:
one
two
three
four
five
You can do this is with a list. here is how
List<string> info = new List<string>();
info.Add("finally worked");
and if you need to return this array do
return info.ToArray();
Here is one way how to deal with adding new numbers and strings to Array:
int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];
do
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Enter Name");
names[i] = Convert.ToString(Console.ReadLine());
Console.WriteLine($"The Name is: {names[i]}");
Console.WriteLine($"the index of name is: {i}");
Console.WriteLine("Enter ID");
ids[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"The number is: {ids[i]}");
Console.WriteLine($"the index is: {i}");
}
} while (names.Length <= 10);