C# Array error "Unexpected symbol '{' " - c#

I declared some array then got an error thath said "Unexpected symbol '{' ".
int[] array ;
void Start () {
if (level == 1) {
array = { 1, 2, 3, 4, 5}; //error here
}else if (level == 2) {
array = { 1, 2, 3, 4, 5, 6, 7}; //error here
}else if (level == 3) {
array = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
}
}
I change above code to this
array [0] = 1;
array [1] = 2;
...
but i want a simpler one like the first code, how?

You can only use the above syntax at the time of declaration, you can't use it later.
If you want to use something similar than you can do:
array = new[] { 1, 2, 3, 4, 5};
or
array = new int[] { 1, 2, 3, 4, 5};
But, at the time of declaration you can do:
int[] array = { 1, 2, 3, 4, 5 }; //this should compile fine

You could use something like below :
array =new int[] { 1, 2, 3, 4, 5};
For initializing array

Related

Check if all elements from one array are in the second array c#

How can I check if all the elements from one array are in another array? I have a 2d array with 3 arrays in it,and I want to check all of those 3 arrays if they have all the elements from allnumbers. array1=allnumbers ? array2=allnumbers ? array1=allnumber2 ? I need to return true if at least one contains all the elements from allnumbers. I have the code bellow,but I need it not to contain more than 3 control flow statements.
// int[,][] array = {array1, array2, array3}
static bool CheckLine(int[,][] array)
{
const int maxL = 9;
bool result = false;
int[] allnumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (var singlearray in array)
{
int[] arr = singlearray;
int p = 0;
foreach (var num in allnumbers)
{
foreach (var arraynumber in singlearray)
{
if (arraynumber == num)
{
p++;
}
}
if (p == maxL)
{
result = true;
break;
}
}
}
return result;
}
If the values in your array are unique, and you don't care about the order they're in, this is a job for HashSet. (In other words, if your arrays contain sets of numbers you can treat them as sets.) Here's the basic outline of comparing sets.
var allnumbersSet = new HashSet<int>(allnumbers);
var allnumbers2Set= new HashSet<int>(allnumbers2);
if (allnumbersSet.IsSupersetOf(allnumbers2Set)) {
/* everything in allnumbers2 is also in allnumbers1 */
}
The people who put together DotNet did a really good job creating and optimizing those collection classes; you can use them with confidence to get good performance.
It seems, that you have two-dimensional jagged array. You can simplify your code by using Except and check the difference between allnumbers array and single row at every loop iteration.
static bool CheckLine(int[,][] array)
{
int[] allnumbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (var singlearray in array)
{
var diff = allnumbers.Except(singlearray);
if (!diff.Any())
{
return true;
}
}
return false;
}
If there is no elements in a difference, it'll mean that single item from source 2D array has all elements from allnumbers array.
Example of the usage
var array = new int[2, 2][];
array[0, 0] = new[] { 1, 2, 8 };
array[0, 1] = new[] { 3, 4, 5, 6 };
array[1, 1] = new[] { 3, 2, 1, 4, 5, 7, 6, 10, 9, 8 };
array[1, 0] = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
CheckLine(array);
The last two items satisfy the condition, execution will break and return true for { 3, 2, 1, 4, 5, 7, 6, 10, 9, 8 } array. Also don't forget to add using System.Linq directive at the top of file
Thank you for your help. I forgot to mention that I can use only "using System;"

Sort 2D array based on user provided indices

In python there is a functionality (numpy.take) to sort arrays within an array, for example if I have an array (3x3):
a = [[1, 2, 3],[7,9,10],[3, 5,6]]
and I have an array of set indices
indices = [2, 0, 1]
the result shall be
array([[ 3, 5, 6], [ 1, 2, 3], [ 7, 9, 10]]).
Are there any direct approach methods/ functions as these in C# where I can pass in a jagged array and produce the same output?
Not directly, but you can achieve the same thing with Linq
var a = new[] { new[] { 1, 2, 3 }, new[] { 7, 9, 10 }, new[] { 3, 5, 6 } };
var indices = new [] { 2, 0, 1 };
var sorted = indices.Select(i => a[i]).ToArray();
foreach(var s in sorted) Console.WriteLine(string.Join(", ", s));
Note this does not check that your indices are all in range.
You can do it easily with LINQ:
var a = new[] { new[] { 1, 2, 3 }, new[] { 7, 9, 10 }, new[] { 3, 5, 6 } };
var indices = new[] { 2, 0, 1};
var result = indices
.Select(i => a[i])
.ToArray();
Or .ToList() if you prefer lists.
There is also the Array.Sort(keys, values) - MSDN
var a = new[]
{
new[] {1, 2, 3},
new[] {7, 9, 10},
new[] {3, 5, 6}
};
var indices = new[] {2, 0, 1};
var sortedArray = a.SortEx(indices);
Where SortEx is
public static class Extensions
{
public static T[][] SortEx<T>(this T[][] source, int[] indices)
{
return indices.Select(index => source[index]).ToArray();
}
}
This assumes that the all the indices in the indices array are not out of bound in a.

Take the first five elements and the last five elements from an array by one query using LINQ

I have been recently asked by a co-worker: Is it possible just take the first five elements and the last five elements by one query from an array?
int[] someArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
What I've tried:
int[] someArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
var firstFiveResults = someArray.Take(5);
var lastFiveResults = someArray.Skip(someArray.Count() - 5).Take(5);
var result = firstFiveResults;
result = result.Concat(lastFiveResults);
Is it possible to just take the first five elements and the last five elements by one query?
You can use a .Where method with lambda that accepts the element index as its second parameter:
int[] someArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
int[] newArray = someArray.Where((e, i) => i < 5 || i >= someArray.Length - 5).ToArray();
foreach (var item in newArray)
{
Console.WriteLine(item);
}
Output:
0, 1, 2, 3, 4, 14, 15, 16, 17, 18
A solution with ArraySegment<> (requires .NET 4.5 (2012) or later):
var result = new ArraySegment<int>(someArray, 0, 5)
.Concat(new ArraySegment<int>(someArray, someArray.Length - 5, 5));
And a solution with Enumerable.Range:
var result = Enumerable.Range(0, 5).Concat(Enumerable.Range(someArray.Length - 5, 5))
.Select(idx => someArray[idx]);
Both these solution avoid iterating through the "middle" of the array (indices 5 through 13).
In case you are not playing code puzzles with your co-workers, but just want to create a new array with your criteria, I wouldn't do this with queries at all, but use Array.copy.
There are three distinct cases to consider:
the source array has fewer than 5 items
the source array has 5 to 9 items
the source array has 10 or more items
The third one is the simple case, as the first and last 5 elements are distinct and well defined.
The other two require more thought. I'm going to assume you want the following, check those assumptions:
If the source array has fewer than 5 items, you will want to have an array of 2 * (array length) items, for example [1, 2, 3] becomes [1, 2, 3, 1, 2, 3]
If the source array has between 5 and 9 items, you will want to have an array of exactly 10 items, for example [1, 2, 3, 4, 5, 6] becomes [1, 2, 3, 4, 5, 2, 3, 4, 5, 6]
A demonstration program is
public static void Main()
{
Console.WriteLine(String.Join(", ", headandtail(new int[]{1, 2, 3})));
Console.WriteLine(String.Join(", ", headandtail(new int[]{1, 2, 3, 4, 5, 6})));
Console.WriteLine(String.Join(", ", headandtail(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11})));
}
private static T[] headandtail<T>(T[] src) {
int runlen = Math.Min(src.Length, 5);
T[] result = new T[2 * runlen];
Array.Copy(src, 0, result, 0, runlen);
Array.Copy(src, src.Length - runlen, result, result.Length - runlen, runlen);
return result;
}
which runs in O(1);
If you are playing code puzzles with your co-workers, well all the fun is in the puzzle, isn't it?
It's trivial though.
src.Take(5).Concat(src.Reverse().Take(5).Reverse()).ToArray();
this runs in O(n).
Try this:
var result = someArray.Where((a, i) => i < 5 || i >= someArray.Length - 5);
This should work
someArray.Take(5).Concat(someArray.Skip(someArray.Count() - 5)).Take(5);
Try this:
int[] someArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
var firstFiveResults = someArray.Take(5);
var lastFiveResults = someArray.Reverse().Take(5).Reverse();
var result = firstFiveResults;
result = result.Concat(lastFiveResults);
The second Reverse() reorders the numbers so you won't get 18,17,16,15,14
Please try this:
var result = someArray.Take(5).Union(someArray.Skip(someArray.Count() - 5).Take(5));

Hi, I'm trying to make a percentage calculator. I have an array and I want to see the number of times each element occurs

I'm trying to make a percentage calculator. I have an array and I want to see the number of times each element occurs and then divide it by the total number of occurrences to get a percentage. So I want an output like:
*/ 1 = 12%
*/ 2 = 15%
...
int[] n1 = { 1, 2, 3, 4, 5, 6, 1, 2, 4, 5, 6, 3, 1, 2, 5, 6 };
int c = n1.Count();
Console.WriteLine ("the total number of " + c );
Dictionary<int, int> counts = n1.GroupBy (x => x).ToDictionary (g => g.Key, g => g.Count ());
Try something like this:
int[] n1 = { 1, 2, 3, 4, 5, 6, 1, 2, 4, 5, 6, 3, 1, 2, 5, 6 };
int c = n1.Count();
var keyValue = n1.GroupBy (n => n).Select (n=> new KeyValuePair<int,string>(n.Key,((decimal)n.Count()/(decimal)c).ToString("0.0%")));
Response:
Key = 1, Value = 18.8%
Key = 2, Value = 18.8%
Key = 3, Value = 12.5%
Key = 4, Value = 12.5%
Key = 5, Value = 18.8%
Key = 6, Value = 18.8%

Add item to a Jagged array

I have already looked at some array topics but I am still stumped.
I wish to add a new line to my jagged array - and am strugigng to get the syntax right..
int[][] intJaggedArray = new int[7][];
intJaggedArray[0] = new int[3] { 1, 1, 1 };
intJaggedArray[1] = new int[3] { 2, 2, 2 };
intJaggedArray[2] = new int[3] { 3, 3, 3 };
intJaggedArray[3] = new int[3] { 4, 4, 4 };
intJaggedArray[4] = new int[3] { 5, 5, 5 };
intJaggedArray[5] = new int[3] { 6, 6, 6 };
intJaggedArray[6] = new int[3] { 7, 7, 7 };
So now if i want to add
intJaggedArray[0] = new int[3] { 1, 1, 2 };
so the array ends up being as shown below how do I acheive it - thanks in advance - A noob from England. (And a big thanks in advance)
intJaggedArray[0] = new int[3] { 1, 1, 1 };
intJaggedArray[0] = new int[3] { 1, 1, 2 };
intJaggedArray[1] = new int[3] { 2, 2, 2 };
intJaggedArray[2] = new int[3] { 3, 3, 3 };
intJaggedArray[3] = new int[3] { 4, 4, 4 };
intJaggedArray[4] = new int[3] { 5, 5, 5 };
intJaggedArray[5] = new int[3] { 6, 6, 6 };
intJaggedArray[6] = new int[3] { 7, 7, 7 };
What do you want to do? Insert a line between 0 and 1? Or replace the existing line 0?
Your line :
intJaggedArray[0] = new int[3] { 1, 1, 2 };
simply replaces the existing line 0.
You can't insert a line in an array. To do so, use a list instead:
List<int[]> myList = new List<int[]>();
myList.Add(new int[] {...});
myList.Add(new int[] {...});
myList.Add(new int[] {...});
...
myList.Insert(1, new int[] {...});
Or if you want to replace the existing line, then simply:
You might want to create a collection or a List<int[]>
Then you could insert an item into it at a certain index.
List<int[]> x = new List<int[]>();
x.Insert(3, new int[3] { 1, 2, 3 });
If you want the initial list to be of a variable length, you cannot use an array. Use a List instead.
This should work:
List<int[]> intJaggedList = new List<int[]>();
intJaggedList.Add( new int[3] { 1, 1, 1 } );
intJAggedList.Add( new int[3] { 2, 2, 2 } );
...
Then to insert your new array:
intJaggedList.Insert( 1, new int[3] { 1, 1, 2 } );

Categories