Push index array - c#

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)

Related

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 }

What are jagged arrays good for? [duplicate]

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.

Array not displaying properly

This is homework assignment for school, but I'm begging for someone to just correct my code. I've been working at this for two days and I think I have everything worked out except I can't get it to work as a 2D Array, so I set this up temporarily just to try to figure things out, but I'm digging myself deeper into a hole I think.
The assignment requires that two dice be rolled 36,000 times and then the results for each sum be displayed on the right, and the sum of the two dice on the left, like this in a 2D array:
12 850
11 1020
10 1200
...
2 900
I've got the right column displaying correctly, but the left column won't display the sums, it just displays "System.Int32[]" a bunch of times.
Here's the code:
Random rand = new Random();
const int ARRAY_SIZE = 13;
const double DICE_ROLLS = 36000;
int sum = 0;
int die1 = 0;
int die2 = 0;
int[] sums = new int[ARRAY_SIZE];
int[] dice = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for (int i = 0; i < DICE_ROLLS; i++ )
{
die1 = rand.Next(1, 7);
die2 = rand.Next(1, 7);
sum = die1 + die2;
sums[sum] += 1;
}
for (int i = 2; i < sums.Length; i++)
{
Console.WriteLine("{0,2} {1,8}", dice, sums[i]);
}
In the spirit of the homework assignment, rather than fixing the code outright, I will try to explain the parts you need to fix, and let you do the actual fixing.
The primary issue in your code is that you are trying to print dice as the value for the left column of the output, rather than individual elements of dice (e.g. dice[i]).
Note, however, that you can't just use dice[i], because your dice array has fewer elements in it than the sums array. If you just replaced dice with dice[i] in your WriteLine() statement, you'd get an index-out-of-bounds exception.
IMHO, the best way to address this is to initialize sums with 11 elements instead of 13, and then when tracking the sums (i.e. in your first loop), subtract 2 from the actual sum value to get the index for the sums array:
sums[sum - 2] += 1;
Then in your second loop, you can safely just use i to index both arrays.
I hope that helps. Please feel free to ask for any clarifications and good luck with your assignment.
Since you'll be using a 2d array you'll want to do something like this:
var rand = new Random();
const double diceRolls = 36000;
var sums = new[,] {{2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}, {7, 0}, {8, 0}, {9, 0}, {10, 0}, {11, 0}, {12, 0}};
for (var i = 0; i < diceRolls; i++)
{
var die1 = rand.Next(1, 7);
var die2 = rand.Next(1, 7);
var sum = die1 + die2;
sums[sum - 2, 1] += 1;
}
for (var i = 0; i < sums.GetLength(0); i++)
{
Console.WriteLine("{0,2} {1,8}", sums[i, 0], sums[i, 1]);
}
Note 1: sum - 2. Since the array length is only 11 you need to subtract 2 from the dice value. (0-10 instead of 2-12).
Note 2: sums.GetLength(0). If you use sums.Length you'll get 22 since there actually are 22 elements in the array. You need to get the length for rank 0
Note 3: Since you're dealing with 2d arrays you'll have the sum of the dice roll in sum[i, 0] and the total count in sum[i, 1].

To find a sequence of one array into another array [closed]

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.
Improve this question
I have two array objects
int[] arr1= new int[] {1,2,5,6,7,9,3,5,6,7}
int[] arr2 = new int[] {5,6,7}
Now, how to find the no of occurrences of arr2 in arr1?
Perhaps not very elegant, but it should work.
This selects all subarrays in a having the same length of b, and checks how many are equal to b.
int[] a = {1, 2, 3, 4, 5};
int[] b = {2, 3};
int count = 0;
int bl = b.Length;
for (int i = 0; i <= a.Length - bl; i++)
{
var suba = a.Skip(i).Take(bl);
if (suba.SequenceEqual(b))
count++;
}
N.B.: this solution considers overlapping subarrays, therefore if a = {2, 2, 2} and b = {2, 2}, the count will be 2.
you may use arr2.Intersect(arr1).Count()
So in your case it will return 3, as 3 elements in arr2 are present in arr1.
If this is not what you're asking for, please clarify.
Use the intersect. This code snippet will solve your problem and print all duplicates, and show the count of each in arr1. Note that I am also using the Linq Distinct(), so that when looping common occurrences, I only check once and not more.
int[] arr1= new int[] {1,2,5,6,7,9,3,5,6,7};
int[] arr2 = new int[] {5,6,7};
var listCommon = arr1.AsEnumerable().Where(arr2.AsEnumerable().Contains);
foreach (var x in listCommon.Distinct()) {
var numberOfOccurencesInArr1 = arr1.Where(y => y == x).Count();
Console.WriteLine(x + " is : " + numberOfOccurencesInArr1.ToString() + " times in arr1");
}
Console.ReadLine();
See MSDN for more information; http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect(v=vs.110).aspx
The listCommon will be the number of common items in both arrays.
Try This
string result = string.Empty; ;
int[] arr1 = new int[] { 1, 2, 5, 6, 7, 9, 3, 5, 6, 7 };
int[] arr2 = new int[] { 5, 6, 7 };
int count = arr2.Intersect(arr1).Count();
if (count == arr2.Length)
{
result = "Found";
}
else
{
result = "Not Found";
}
If you want to count how many occurences of an integer of the second array are present in the first array then you could write
int[] arr1 = new int[] {1,2,5,6,7,9,3,5,6,7};
int[] arr2 = new int[] {5,6,7};
Dictionary<int, int> counter = new Dictionary<int, int>();
foreach(int x in arr1)
{
if(arr2.Contains(x))
{
if(counter.ContainsKey(x))
counter[x]++;
else
counter[x] = 1;
}
}
foreach(KeyValuePair<int, int> kvp in counter)
Console.WriteLine("Key=" + kvp.Key.ToString() + " is present " + kvp.Value.ToString() + " times");
int[] arr1 = new int[] { 1, 2, 5, 6, 7, 9, 3, 5, 6, 7 };
int[] arr2 = new int[] { 5, 6, 7 };
how to find the no of occurrences of arr2 in arr1?
If you are expecting the result to be 2. Since the 5,6,7 appears twice in the arr1
try this
var res = arr1.Where(x => arr2.Contains(x)).Count()/arr2.Count();
Try this one:
var results = (from a1 in arr1
join a2 in arr2
on a1 equals a2
group arr1 by a1 into Group
select new
{
Number = Group.Key,
Times = Group.Count()
});
foreach(var result in results)
Console.WriteLine(result.Number+" "+result.Times);
Please check this solution using the following fiddle .NET fiddle
You can use ToLookup on the ints in the first count which are also in the second array. Then you just have to take the min-count of all groups since that's the greatest intersection:
var subsetGroups = arr1.Where(i1 => arr2.Contains(i1)).ToLookup(i => i);
int minGroupCount = 0;
// check if all integers from the array are in the first at all
if(arr2.All(i => subsetGroups.Contains(i)))
{
minGroupCount = subsetGroups.Min(g => g.Count()); // 2
}
Note that this approach doesn't care about the order and it also doesn't care about the number of duplicates in the second array. This might be desired or not.
As you input is arrays you can use indexing to effectively count the number of occurrences of the subarrays in the main array:
var count = 0;
for (var i = 0; i < arr1.Length - arr2.Length + 1; i += 1) {
if (arr1[i] != arr2[0])
continue;
var isSubarray = true;
for (var j = 0; j < arr2.Length; ++j)
if (arr1[i + j] != arr2[j]) {
isSubarray = false;
break;
}
if (isSubarray)
count += 1;
}
The result will be 2 because 567 is found two times in 1256793567.
If the subarray can "overlap" itself (e.g. 11 in 111) all "overlaps" will be counted (e.g. the result will be 2 for this example). If that is not the intention you simply have to advance the index i at the end of the main loop to skip the found subarray.

Finding the last index of an array

How do you retrieve the last element of an array in C#?
LINQ provides Last():
csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();
5
This is handy when you don't want to make a variable unnecessarily.
string lastName = "Abraham Lincoln".Split().Last();
With C# 8:
int[] array = { 1, 3, 5 };
var lastItem = array[^1]; // 5
The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.
string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;
When declaring an array in C#, the number you give is the length of the array:
string[] items = new string[5]; // five items, index ranging from 0 to 4.
New in C# 8.0 you can use the so-called "hat" (^) operator! This is useful for when you want to do something in one line!
var mystr = "Hello World!";
var lastword = mystr.Split(" ")[^1];
Console.WriteLine(lastword);
// World!
instead of the old way:
var mystr = "Hello World";
var split = mystr.Split(" ");
var lastword = split[split.Length - 1];
Console.WriteLine(lastword);
// World!
It doesn't save much space, but it looks much clearer (maybe I only think this because I came from python?). This is also much better than calling a method like .Last() or .Reverse() Read more at MSDN
Edit: You can add this functionality to your class like so:
public class MyClass
{
public object this[Index indx]
{
get
{
// Do indexing here, this is just an example of the .IsFromEnd property
if (indx.IsFromEnd)
{
Console.WriteLine("Negative Index!")
}
else
{
Console.WriteLine("Positive Index!")
}
}
}
}
The Index.IsFromEnd will tell you if someone is using the 'hat' (^) operator
Use Array.GetUpperBound(0). Array.Length contains the number of items in the array, so reading Length -1 only works on the assumption that the array is zero based.
To compute the index of the last item:
int index = array.Length - 1;
Will get you -1 if the array is empty - you should treat it as a special case.
To access the last index:
array[array.Length - 1] = ...
or
... = array[array.Length - 1]
will cause an exception if the array is actually empty (Length is 0).
Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type to keep array's indexes from end:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
You can use this index to get last array value in any length of array. For example:
var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5
For more information check documentation
The following will return NULL if the array is empty, else the last element.
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
say your array is called arr
do
arr[arr.Length - 1]
Is this worth mentioning?
var item = new Stack(arr).Pop();
Array starts from index 0 and ends at n-1.
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
int length = arr.Length - 1; // starts from 0 to n-1
Console.WriteLine(length); // this will give the last index.
Console.Read();
}
static void Main(string[] args)
{
int size = 6;
int[] arr = new int[6] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < size; i++)
{
Console.WriteLine("The last element is {0}", GetLastArrayIndex(arr));
Console.ReadLine();
}
}
//Get Last Index
static int GetLastArrayIndex(int[] arr)
{
try
{
int lastNum;
lastNum = arr.Length - 1;
return lastNum;
}
catch (Exception ex)
{
return 0;
}
}
This is simplest and works on all versions.
int[] array = { 1, 3, 5 };
int last = array[array.Length - 1];
Console.WriteLine(last);
// 5

Categories