What are jagged arrays good for? [duplicate] - c#

What is a jagged array (in c#)? Any examples and when should one use it....

A jagged array is an array of arrays.
string[][] arrays = new string[5][];
That's a collection of five different string arrays, each could be a different length (they could also be the same length, but the point is there is no guarantee that they are).
arrays[0] = new string[5];
arrays[1] = new string[100];
...
This is different from a 2D array where it is rectangular, meaning each row has the same number of columns.
string[,] array = new string[3,5];

A jagged array is the same in any language, but it's where you have a 2+ dimensional array with different array lengths in the second and beyond array.
[0] - 0, 1, 2, 3, 4
[1] - 1, 2, 3
[2] - 5, 6, 7, 8, 9, 10
[3] - 1
[4] -
[5] - 23, 4, 7, 8, 9, 12, 15, 14, 17, 18

Although the best answer is chosen by the question owner but still I want to present the following code to make jagged array more clear.
using System;
class Program
{
static void Main()
{
// Declare local jagged array with 3 rows.
int[][] jagged = new int[3][];
// Create a new array in the jagged array, and assign it.
jagged[0] = new int[2];
jagged[0][0] = 1;
jagged[0][1] = 2;
// Set second row, initialized to zero.
jagged[1] = new int[1];
// Set third row, using array initializer.
jagged[2] = new int[3] { 3, 4, 5 };
// Print out all elements in the jagged array.
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.Write(innerArray[a] + " ");
}
Console.WriteLine();
}
}
}
The output will be
1 2
0
3 4 5
Jagged arrays are used to store data in rows of varying length.
For more information check this post at MSDN blog.

You can find more information here : http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Also :
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
or
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

A jagged array is one in which you declare the number of rows during declaration but you declare number of columns during run time or also by user choice,simply its mean when you want different number of columns in each JAGGED array is suitable in that case
int[][] a = new int[6][];//its mean num of row is 6
int choice;//thats i left on user choice that how many number of column in each row he wanna to declare
for (int row = 0; row < a.Length; row++)
{
Console.WriteLine("pls enter number of colo in row {0}", row);
choice = int.Parse(Console.ReadLine());
a[row] = new int[choice];
for (int col = 0; col < a[row].Length; col++)
{
a[row][col] = int.Parse(Console.ReadLine());
}
}

Jagged array is an array with other arrays contained within.
A jagged array is a array in which the number of rows is fixed but the number of column is not fixed.
Code for jagged array in C# for window form application
int[][] a = new int[3][];
a[0]=new int[5];
a[1]=new int[3];
a[2]=new int[1];
int i;
for(i = 0; i < 5; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 3; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 1; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
As you can see in the above program no of rows is fixed to 3, but the number of columns is not fixed. So we have taken three different value of columns i.e. 5, 3 and 1. The ListBox1 keyword used in this code is for the listbox that we will use in the window form to see the result by the click of button which will be also used in the window form. All the programming done here is on the button.

Jagged Array is multidimensional array with different different number of rows.

Related

C# array issue due to indexing of int

I am fairly new to this and trying to learn. I am struggling trying to make a loop to find the max value in an array. I am not sure what I am doing wrong. I have searched everywhere and seen several people do it the way i am but do not know what i am missing…
static void Main(string[] args)
{
int[] Numbs = new int[10];
Numbs[0] = 56;
Numbs[1] = 77;
Numbs[2] = 23;
Numbs[3] = 12;
Numbs[4] = 88;
Numbs[5] = 59;
Numbs[6] = 97;
Numbs[7] = 33;
Numbs[8] = 38;
Numbs[9] = 64;
string[] Names = new string[10] {"John", "George", "Henry", "Larry", "Bart", "Luke", "Tim",
"Frank", "Conor", "Joe"};
FindMax(Numbs[9],9);
}
static int FindMax(int arrayNumbs, int arrayNumbsLength)
{
int Greatest = -1;
for (int Count = 0; Count <= arrayNumbsLength; Count++)
if (arrayNumbs[Count] > Greatest)
{
Console.WriteLine(Count);
Greatest = arrayNumbs;
Console.WriteLine(Greatest);
}
return Greatest;
The most basic change would be:
static int FindMax(int[] arrayNumbs)
{
...
for (int Count = 0; Count < arrayNumbs.Length; Count++)
...
}
The rest is just fine. There are some ways to make it better, but I'm guessing this is a school assignment and you'll get there eventually.
I can see few things that are issues with your code:
Your method defines first parameter as an integer (int arrayNumbs), it should say int[] arrayNumbs since you're passing an array, not a single integer
in your function call FindMax(Numbs[9], 9) you pass an integer as the first argument instead of an array (which didn't give you an error since it's how you defined the method, see above). Second argument is a lie, your array's size is 10, not 9 (remember about first element having index [0])
Inside your method you want to assign the integer to your variable, not the whole array (which would give you an error). Should say Greatest = arrayNumbs[Count]
You can use a List() instead of the array type. A list is dynamic and will expand automatically. In the example below I create the numbs list and use LINQ to get the max value.
var numbs = new List<int>
{
56, 77, 23, 12, 88, 59, 97, 33, 38, 65
};
var max = numbs.Max();

Populating an array with elements [duplicate]

Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}

How do I delete all elements in an int array that exist in another int array?

In my C# program, I have an int array containing a set of integers and occasionally duplicates of those integers. I want to create an array that only contains the numbers that exist as duplicates in the initial array, but in itself contains no duplicates. Based on my newbie understanding of C# I thought that the following code would do the trick:
int a = 9;
int b = 6;
int c = 3;
int index = 0;
int[] mltpls = new int[a + b + c];
while (a > 0)
{
mltpls[index] = 2 * a;
a -= 1;
index += 1;
}
while(b > 0)
{
mltpls[index] = 3 * b;
b -= 1;
index += 1;
}
while(c > 0)
{
mltpls[index] = 5 * c;
c -= 1;
index += 1;
}
int[] mltpls_unique = mltpls.Distinct().ToArray();
int[] mltpls_dplcts = mltpls.Except(mltpls_unique).ToArray();
Console.WriteLine(mltpls_dplcts);
//EDIT
//By running the following code I can write out all numbers in "mltpls"
for (int i = 0; i < mltpls.Length; i++)
{
Console.Write(mltpls[i] + ", ");
}
/*If I try to run equivalent code for the "mltpls_dplcts" array nothing
only a blank line is displayed.*/
When I run this goal my the final result of my console application is a blank row. My interpretation of this is that the array mltpls_dplcts is empty or that I'm incorrectly going about printing the array.
How do get only the duplicate values from an array?
My interpretation of this is that the array mltpls_dplcts is empty or that I'm incorrectly going about printing the array.
Both interpretations are correct
Distinct will return every item that is at least once present in mltps. If you now apply Except you get nothing because all items that are in mltpls_unique are also present in mltps. The items in the array are compared by value, so for Except it does not matter whether a number occurs multiple times in the other array. If it is there once it will not return the number. So you get an empty array.
Furthermore you cannot simply shove an entire array into Console.WriteLine. Either use a loop or String.Join to print the content:
Console.WriteLine(String.Join(" ",mltpls_dplcts));
Solution: You can solve it using a good old loop approach ;)
int[] mltpls_unique = mltpls.Distinct().ToArray();
// The amount of duplicates is the difference between the original and the unique array
int[] mltpls_dplcts = new int[mltpls.Length-mltpls_unique.Length];
int dupCount = 0;
for (int i = 0; i < mltpls.Length; i++)
{
for (int j = i+1; j < mltpls.Length; j++)
{
if (mltpls[i] == mltpls[j])
{
mltpls_dplcts[dupCount] = mltpls[i];
dupCount++;
}
}
}
Output: 18 12 10 6 15
You cannot print the array directly. You need to loop and print one by one:
foreach (var element in mltpls_dplcts)
{
Console.WriteLine(element);
}
You can get array of distinct duplicates like this:
var duplicates = mltpls.GroupBy(o => o)
.Where(g => g.Count() > 1)
.Select(g => g.First()).ToArray();
To get new array that contains only the elements from the original one that are not in the second array you can use:
var newArr = mltpls.Except(duplicates).ToArray();
It is not proper way to find duplicates. You can determine the duplicates by using GroupBy and print them to console like this;
var mltpls_dplcts = mltpls.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToArray();
foreach (var duplicate in mltpls_dplcts)
{
Console.WriteLine(duplicate);
}
Also, If it isn't must to use Array for you, I suggest you to use List<int>.
Updated question from OP:
How do get only the duplicate values from an array?
var arr1 = new[] {1, 2, 4, 4, 5, 5, 5, 5, 6, 7, 1};
var duplicates = arr1.ToLookup(_ => _, _ => _).Where(_ => _.Count()>1).Select(_ => _.Key).ToArray();
// duplicates is now { 1, 4, 5 }
Original question from OP:
How do I delete all elements in an int array that exist in another int array in C#?
var arr1 = new[] {1, 2, 4, 5, 6, 7};
var arr2 = new[] {4, 5};
var hash = new HashSet<int>(arr1);
hash.ExceptWith(arr2);
var filteredArray = hash.ToArray();
// filteredArray is now { 1, 2, 6, 7 }

Push index array

I'm sure there's a word for what I,m looking for but since I don't know it I can't find the answear to my problem, what I have is a jagged array of double and I want the value at index 0 to be the value of index 1 same for the index 1 going to the 2 until the end of the array and the last index being pish to the index 0
Example :
Original
private double[][] array = { {1, 2, 3, 4}, {5, 6, 7, 8}, ...}
Become (After the modification)
I know it's seems I'm redeclaring the array that's not the point, it's just to show you what it should be after.
private double[][] array = { {4, 1, 2, 3}, {8, 5, 6, 7}, ...}
EDIT
If you know the word or somethings about what I'm looking for, could you say so in the comment I will delete the question and look further into it
This is usually called rotating. You can achieve it a for-loop, but note that since your rotating to the right, it's easier to work your way from back to front, like this:
for(var i = 0; i < array.Length; i++)
{
var len = array[i].Length;
if (len > 1) {
var last = array[i][len - 1];
for(var j = len - 1; j > 0; j--)
{
array[i][j] = array[i][j - 1];
}
array[i][0] = last;
}
}
You could easily use a List of Queue instead of a jagged array. Below an example of how your jagged array could look like and how to move elements:
var queues = new List<Queue<double>>();
//first queue (1,2,3,4)
var queue = new Queue<double>();
queue.Enqueue(4);
queue.Enqueue(3);
queue.Enqueue(2);
queue.Enqueue(1);
queues.Add(queue);
//second queue (5,6,7,8)
var queue2 = new Queue<double>();
queue.Enqueue(8);
queue.Enqueue(7);
queue.Enqueue(6);
queue.Enqueue(5);
queues.Add(queue2);
//an example of how to "rotate"
var lastItem = queues[0].Dequeue(); // (1,2,3)
queues[0].Enqueue(lastItem); // (4,1,2,3)

Multidimensional array init without pre-existing values?

How can we initialize a multidimensional array without pre-existing values? Only the third one is correct, but it works with pre-existing values. I would like my multidimensional array to contain 10 or 20 values, and add them later on with numbers[y][x] :
int[][] numbers = new int[10][];
//List<int[]> numbers = new List<int[]>();
//int[10][]{ new int[]{}};
//correct : { new int[] {1, 2}, new int[] {3, 4, 5} };
numbers[0][0] = 58;
Would you know how to do this? (I don't know if [,] is the same as [][] by the way)
Thanks
Would you know how to do this? (I don't know if [,] is the same as [][] by the way)
there are not the some as int[][] test = new int[10][]; is called a jagged array (array of arrays) and int[,] is a fixed array
just declare your array as the following
int[,] test = new int[10,30];
test[0,1] = 10;
test[1,2] = 20;
You can try initiating values this way, it is one way to create jagged-array
int[][] test = new int[10][];
test[0] = new int[20];
test[1] = new int[30];
test[2] = new[] { 3, 4, 5 };
test[0][1] = 10;
test[1][2] = 20;

Categories