Related
I can not understand the difference between the declaration with array initialization in the first case and the second
int[] array = new int[3] { 1, 2, 3 };
int[] secondArray = { 1, 2, 3 };
They seem to do the same thing, maybe they work differently?
The is no difference in the result between the two show lines shown:
int[] array = new int[3] { 1, 2, 3 };
int[] secondArray = { 1, 2, 3 };
However, there are practical differences between new int[n] {...} syntax and {...}:
Implicit type is not available for the alternative array initialiser:
var a1 = new int[3] { 1, 2, 3 }; // OK
var a2 = { 1, 2, 3 }; // Error: Cannot initialize an implicitly-typed variable with an array initializer
// BTW. You can omit the size
var a3 = new int[] { 1, 2, 3 }; // OK
With the alternative syntax you cannot specify the size, it's always inferred.
var a1 = new int[100]; // Array with 100 elements (all 0)
int[] a2 = { }; // Array with no elements
There is no difference in the compiled code between the two lines.
The second one is just a shortcut. Both statements have the same result. The shorter variant just wasn't available in early versions of C#.
The first one uses 3 as a array size explictly, the 2nd one size is inferred.
This might be work if you dont want to initialize the values.
There is no difference between this two array initialization syntaxes in terms how they will be translated by the compiler into IL (you can play with it at sharplab.io) and it is the same as the following one:
int[] thirdArray = new int[] { 1, 2, 3 };
The only difference comes when you are using those with already declared variable, i.e. you can use 1st and 3rd to assign new value to existing array variable but not the second one:
int[] arr;
arr = new int[3] { 1, 2, 3 }; // works
// arr = { 1, 2, 3 }; // won't compile
arr = new int[] { 1, 2, 3 }; // works
I have two arrays, one singular and the other 2 dimensional.
int[][] array1 = {
new int [] {1, 22, 3, 44, 5, 66},
new int [] {11, 22, 33, 44, 55, 66},
new int [] {1, 2, 3, 4, 5, 6},
};
int[] array2 = new int[] {1, 2, 3, 5, 66}
I need to create a loop which searches the array1 for both the 2nd last digits in array2, so it would return how many times an array with array1 contains both 5 and 66, which is 1, as the other two only contain 1 of each number.
I already managed to write a function which returns how many times array2 as a whole exists in array1, this new function is effectively a refinement of that.
for (int a = 0; a < array1[i].Length; a++)
{
for (int b = 0; b < array2.Length; b++)
{
if (array2[c] == array1[a][b])
count++;
temp[b] = array1[a][b];
}
}
I feel all would be needed to search for just the last two digits is a slight change to this function, I tried to add in another loop but that didn't work either. How would I go about doing this? I'm using loops and not Contains for a reason since i'm still learning the basics.
The one thing is not clear in question that, does it matter which position the two digits occur in the 2D array?
If ithis is not the case, then you can use Intersect() which produces the set intersection of two sequences by using the default equality comparer to compare values:
var result = array1.Count(x => x.Intersect(array2.Reverse().Take(2)).Count() == 2);
If you have paid an attention we have used this line, for getting last two elements of array1:
array1.Reverse().Take(2);
.NET Fiddle
Additional:
If you want to find if last two elements of arrays in 2D array is equal to last two elements of array1, then you can try LINQ solution:
var result = array1.Count(x=> x.Reverse().Take(2).SequenceEqual(array2.Reverse().Take(2)));
Explanation of used extension methods:
Reverse() inverts the order of the elements in a sequence.
Take() returns a specified number of contiguous elements from the start of a sequence.
SequenceEqual() determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
After getting last two elements of both arrays, we will use SequenceEqual() to determine if both arrays are equal.
var res = array1.Where((x) => (x.Contains(array2.Last()) && x.Contains(array2[array2.Length - 2]))).Count();
Explaination:
array1.Where takes every subarray of array1 and filters the ones that
meet a certain condition. The condition being every subarray of
array1 contains the last && next-to-last element of array2.The
Count() methods returns the number of subarrays that meet the
conditions
You can create an array of target values and then count the number of times that the intersection of that array with each subarray in the 2D array contains all the items in the target array:
using System;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
[STAThread]
private static void Main()
{
int[][] array1 =
{
new [] {1, 22, 3, 44, 5, 66},
new [] {11, 22, 33, 44, 55, 66},
new [] {1, 2, 3, 4, 5, 6},
new [] {1, 66, 3, 4, 5, 6} // This one has the target items out of order.
};
int[] array2 = {1, 2, 3, 5, 66};
// Extract the targets like this; it avoids making a copy
// of array2 which occurs if you use IEnumerable.Reverse().
int[] targets = {array2[array2.Length - 2], array2[array2.Length - 1]};
// Count the number of times that each subarray in array1 includes
// all the items in targets:
int count = array1.Count(array => array.Intersect(targets).Count() == targets.Length);
Console.WriteLine(count);
}
}
}
I've just started learning C#, I'm good PHP developer and I'm trying to build a basic blackjack app for practice, I'm lost because arrays in PHP and arrays in C# are so different
I'm wondering how I can have the following array which is written in PHP to C#
$array = array("first_array" => array(), "second_array" => array());
I tried the following but it doesn't really seem to work
string[] array = ["first_array" => string[], "second_array" => string[]];
If anyone could help me or guide me, I'd be grateful.
To declare a multi-dimensional string array in C#, it's a simple matter of writing this:
string[,] array = new string[4,4];//size of each array here
Initializing an array is done in the same way as it is in C(++), using curly brackets:
string[,] array = new string[,] { {"index[0][0]", "index[0][1]"}, {"index[1][0]", "index[1][1]"} };
basic tut on arrays in C# here
But you're not creating an array, you're using strings as keys, meaning you need a Dictionary:
Dictionary<string, string[]> dictionary = new Dictionary<string, string[]> {
{"first_array", new string[4]},
{"second_array", new string[4]}
};
In case of a Dictionary, owing to its declaration being quite verbose, it's quite common to see code that relies on C#'s implicit typing to abreviate things a bit:
var dictionary = new Dictionary<string, string[]> {
{"first_array", new string[4]},
{"second_array", new string[4]}
};
more on Dictionary here
Update:
Because you'd like to be able to append strings to the arrays as you go along (ie: you don't know the length of the array when you create it), you can't really use a regular string array. You'll have to use a dictionary of string lists:
var dictionary = new Dictionary<string, List<string>> {
"first_list", new List<string>() { "first string", "second string" },
"second_list", new List<string>() { "first string", "second string" }
};
So now, bringing it all together, and some examples of how you can add strings to lists, and add lists to the dictionary:
//add string to list in dictionary:
dictionary["first_list"].Add("third string");
//suppose we have an array, how to add to the dictionary?
string[] some_array = new string[2] {"string1", "string2"};
//simply initialize list using array of strings
var temp_list = new List<string>(some_array);
//add new key to dictionary
dictionary.Add("new_list", temp_list);
docs on the List<T> class
Note:
Arrays can be resized, so it is possible to use an array instead of a list, but in this case, it's better to use a list. Lists are designed to be resized, arrays are not the best tool for the job
I dont know very much about C#, but that's not the way that works. string[] in C# and in most programming languages indicates an array of strings. You may want to use Dictionary<string key, string[] array> to do that. Don't know if the Dictionary in C# is the same as HashMap in Java, but as I recall, it's the same.
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
{ "five", "six" } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
for more example http://msdn.microsoft.com/tr-tr/library/2yd9wwz4.aspx
C# is a static typed language, so its arrays can't contain elements of different types.
Your PHP array is a hash actually, so you can use .NET's hash, i.e. Dictionary.
But if your object has only two fixed fields "first_array" and "second_array", then it's better to use the simple class, like this:
public class MyObject
{
public string[] first;
public string[] second;
}
For simple pairs you can use tuples also:
var pair = new Tuple<string[], string[]>({"aa", "bb"}, {"cc", "dd"});
var first = pair.Item1;
var second = pair.Item2;
From: http://msdn.microsoft.com/en-us/library/2s05feca.aspx
Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:
int[][] jaggedArray3 =
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
What does it mean?
Why is it ok to omit new in:
int[] arrSimp = { 1, 2, 3 };
int[,] arrMult = { { 1, 1 }, { 2, 2 }, { 3, 3 } };
but not possible in:
int[][,] arrJagg = {new int[,] { { 1, 1} }, new int[,] { { 2, 2 } }, new int[,] { { 3, 3 } } };
First off, what a coincidence, an aspect of your question is the subject of my blog today:
http://ericlippert.com/2013/01/24/five-dollar-words-for-programmers-elision/
You've discovered a small "wart" in the way C# classifies expressions. As it turns out, the array initializer syntax {1, 2, 3} is not an expression. Rather, it is a syntactic unit that can only be used as part of another expression:
new[] { 1, 2, 3 }
new int[] { 1, 2, 3 }
new int[3] { 1, 2, 3 }
new int[,] { { 1, 2, 3 } }
... and so on
or as part of a collection initializer:
new List<int> { 1, 2, 3 }
or in a variable declaration:
int[] x = { 1, 2, 3 };
It is not legal to use the array initializer syntax in any other context in which an expression is expected. For example:
int[] x;
x = { 1, 2, 3 };
is not legal.
It's just an odd corner case of the C# language. There's no deeper meaning to the inconsistency you've discovered.
In essence the answer is "because they (meaning the language designers) choose not to.To quote from Eric Lippert:
The same reason why every unimplemented feature is not implemented:
features are unimplemented by default. In order to become implemented
a feature must be (1) thought of, (2) designed, (3) specified, (4)
implemented, (5) tested, (6) documented and (7) shipped.
More technically there is a good reason to it and that's the definition of jagged arrays compared to 1-dimension and multi-dimension arrays.
A one or more dimension arrays can be expressed in plain English as a X dimension array of T where a jagged array has to be expressed as an Array of arrays of T. In the second case, there is a loose coupling between the inner array and the outer arary. That is, you can assign a new array to a position within the outer array whereas a x dimension array is fixed.
Now that we know that Jagged arrays are very different from multi-dimensional arrays in their implementation, we can also assume why there is a different level of integrated support for the 2. It's certainly not impossible to add support, just a question of demand and time.
(as a teaser, why only add support for jagged arrays? how about your own custom types?)
I know that they are used to store data, but I have a difficult time understanding exactly how to use them in a program.
In addition, I found this site with a tetris clone tutorial (the actual tutorial is missing). It uses arrays, but I can't really make sense of how it works.
Here's an example of the code -
public int[, ,] TShape = new int[4, 4, 2]
{
{{1, 0}, {0, 1}, {1, 1}, {2, 1}},
{{1, 0}, {0, 1}, {1, 1}, {1, 2}},
{{0, 0}, {1, 0}, {2, 0}, {1, 1}},
{{0, 0}, {0, 1}, {1, 1}, {0, 2}}};
Could it be that I'm looking too hard into this, or perhaps there's something I'm not grasping about it?
It would be clearer if formatted this way:
public int[, ,] TShape = new int[4, 4, 2]
{
{ {1, 0}, // <- this is int[2]
{0, 1},
{1, 1},
{2, 1} }, // <- the last four lines are an int[4,2]
{ {1, 0},
{0, 1},
{1, 1},
{1, 2} }, // <- another int[4,2]
{ {0, 0},
{1, 0},
{2, 0},
{1, 1} }, // <- third int[4,2]
{ {0, 0},
{0, 1},
{1, 1},
{0, 2} } // <- fourth and last int[4,2]
}; // <- The whole thing is int[4, 4, 2]
"Well I've been having a hard time
understanding how to use arrays. I
know they are used for storing data,
but I have yet to find any resource
that gives a clearer explanation than
that."
I'll try to give you an analogy: array is to programming like a file cabinet is to an office. The only difference is that a file cabinet is restricted to what it can hold: i.e. files... the only restriction for arrays is that it must hold items of the same type, but the actual type of the item can be nearly anything. Arrays can not only hold data, but objects, other arrays, other containers, etc.
So what can you do with an array in programming? Well a LOT of stuff! Let's look at several examples:
Financial: an array can hold the stock prices for today.
Gaming: an array can hold the 3D models that are used on a level.
Military: an array can hold all of the targets identified by a targeting system.
etc...
The main purpose of arrays is to contain various things and allow us to iterate over them. For example:
// Financial
int[] stockPrices = new int[4]{ 15, 14, 18, 16 }; // contains four prices
foreach( int price in stockPrices )
{
MakeTransaction(price);// calls a function that makes a transaction at the price: e.g. buy/sell
}
// Gaming
3DModel[] gameModels = new 3DModel[4]{ new Tank(), new Truck(), new Soldier(), new Building()}; // contains 3D models
foreach( 3DModel model in gameModels )
{
model.Draw();// calls a function of each 3DModel that draws the model on the screen
}
// Military
Target[] targets = new Target[4]{ new Tank(), new Helicopter(), new APC(), new Truck()}; // contains targets
foreach( Target target in targets )
{
Attack(target);// calls an attack function which initiates an attack on each target
}
The possibilities are endless! Arrays are a subset of containers and containers are an integral part of programming. Does that help?
Straight from the horse's mouth: http://msdn.microsoft.com/en-us/library/system.array.aspx
Those details will come in handy after you have gone through online tutorials such as this http://www.functionx.com/csharp/Lesson21.htm
Imagine you have 10 boxes. Now you want to clearly tell someone which box you are talking about. So you assign numbers to them, from 0 to 9. What you have now is an array of boxes, defined as:
box[ 10 ]
The number in the brackets tells you, how many of them are there. By default they are numbered from 0 to 9 (some languages allow to change this, but lets skip that for now). So if you are talking about the fifth box, its box[ 4 ] (since we index from 0!). Now imagine you open the box and see that there are five balls in it. This defines an array:
box[ 10 ][ 5 ]
A two dimensional array. How do you tell your friend which ball do you want to talk about? Again, you number them, this time from 0 to 4. How do you specify say the third ball in the seventh box? Simple: box[ 6 ][ 2 ]. And so on. Hope that helps.
In your question, you're stating the Tetris game which uses an array. That is a good use of arrays in whatever language you're using.
You have to see the Tetris play yard as the array. Let's say this play yard is a 20 spaces on the X axis, and 100 spaces on the Y axis. What tells you whether you have a piece on a space, is when you have the integer value 1, and you get an integer value of 0 for empty spaces. We then get:
var tetrisPlayYard = new int[20][100];
You now have to initialize each positions of the board to 0 in order to mark them as empty spaces, so no pieces have ever been placed already.
for(int xAxisIndex = 0; xAxisIndex < tetrisPlayYard.GetLength(0); ++xAxisIndex )
for (int yAxisIndex = 0; yAxisIndex < tetrisPlayYard.GetLength(1); ++ yAxisIndex)
tetrisPlayYard[xAxisIndex][yAxisIndex] = 0;
We now know that no pieces is on board as each array's positions are set to 0.
Then, when we place, let's say a four spaces straight line horizontally at the bottom-right of the board, we would then have to address 4 spaces, and set their values to 1 to indicate there is a piece on these spaces.
tetrisPlayYard[19][99] = 1;
tetrisPlayYard[18][99] = 1;
tetrisPlayYard[17][99] = 1;
tetrisPlayYard[16][99] = 1;
This tells that you have a four spaces straight line. Your algorithm should work around this logic to display the bars, the cubes, etc. while playing the game.
In conclusion, use arrays whenever a finite space is known, and that you know that it won't be required to resize it dynamically. Otherwise, a Collection should be used.