How do I go about writing a method to create a populated nxn matrix like so:
int[,] Matrix(int n) or int[][] Matrix(int n) for example for n = 5:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
One solution is this:
static int[,] Matrix(int n)
{
if (n < 0)
throw new ArgumentException("n must be a positive integer.", "n");
var result = new int[n, n];
int level = 0,
counter = 1;
while (level < (int)Math.Ceiling(n / 2f))
{
// Start at top left of this level.
int x = level,
y = level;
// Move from left to right.
for (; x < n - level; x++)
result[y, x] = counter++;
// Move from top to bottom.
for (y++, x--; y < n - level; y++)
result[y, x] = counter++;
// Move from right to left.
for (x--, y--; x >= level; x--)
result[y, x] = counter++;
// Move from bottom to top. Do not overwrite top left cell.
for (y--, x++; y >= level + 1; y--)
result[y, x] = counter++;
// Go to inner level.
level++;
}
return result;
}
Here are the resultant matrices (n between 1 and 6) printed to console:
This can be achieved in this MSDN Example.
Google Search Results
// 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 } } };
// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);
// Getting the total count of elements or the length of a given dimension.
var allLength = array3D.Length;
var total = 1;
for (int i = 0; i < array3D.Rank; i++) {
total *= array3D.GetLength(i);
}
System.Console.WriteLine("{0} equals {1}", allLength, total);
// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12
// 12 equals 12
Related
I wonder if it is possible to implement a general Julia\Matlab alike View function in C# that would work for arrays of any dimensions (eg [,,] and [,,,]) as they do it in array slicer\mover view. So I wonder if there is a library that provides similar functionality for CSharp multidimentional arrays or how to implement it in C#?
The solution is twofold:
Use a wrapper class that holds a reference to the master array
Use the Array base class to make it polymorphic
Wrapper
class View<T>
{
private readonly Array array;
private readonly int dim;
private readonly int slice;
public View(Array array, int dim, int slice)
{
this.array = array;
this.dim = dim;
this.slice = slice;
}
public T this[params int[] indexes]
{
get { return (T)array.GetValue(BaseIndexesFor(indexes)); }
set { array.SetValue(value, BaseIndexesFor(indexes)); }
}
private int[] BaseIndexesFor(int[] indexes)
{
if (indexes.Length != array.Rank - 1) throw new ArgumentException("indexes");
int i_index = 0;
int[] baseIndexes = new int[array.Rank];
for (int i = 0; i < baseIndexes.Length; i++)
{
baseIndexes[i] = (i == dim) ? slice : indexes[i_index++];
}
return baseIndexes;
}
}
2D example
var A = new int[,]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
/* View(Array array, int dim, int slice)
*
* For 2 dimensional array:
* dim=0 -> rows
* dim=1 -> columns
*/
// From second dimension slice index 1
// Or simply, take column with index 1
var B = new View<int>(A, 1, 1);
B[2] = 0;
Console.WriteLine(A[2, 1]); // 0
3D examples
var C = new int[,,]
{
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
},
{
{ 11, 12, 13 },
{ 14, 15, 16 },
{ 17, 18, 19 }
},
{
{ 21, 22, 23 },
{ 24, 25, 26 },
{ 27, 28, 29 }
}
};
/* From first dimension slice index 2
* { 21, 22, 23 },
* { 24, 25, 26 },
* { 27, 28, 29 }
*/
var D = new View<int>(C, 0, 2);
D[1, 1] = 0;
Console.WriteLine(C[2, 1, 1]); // 0
/* From third dimension slice index 0
* { 1, 4, 7 },
* { 11, 14, 17 },
* { 21, 24, 27 }
*/
var E = new View<int>(C, 2, 0);
E[2, 0] = 0;
Console.WriteLine(C[2, 0, 0]); // 0
How to write function to got new B array but put multiple 3 elements of array A..
int[] a = new int[] {1,2,3,4,5,6,7,8,9,10};
b0 = a1,a2,a3
b1 = a4,a5,a6
b2 = etc...
ONLY if you aren't allowed to use Linq...
int[] a = new int[] {1,2,3,4,5,6,7,8,9,10};
int[,] b;
if(a.Length % 3 != 0)
{
b = new int[a.Length/3+1,3];
}
else
{
b = new int[a.Length/3, 3];
}
for(int i = 0; i< a.Length;i++)
{
b[i/3,i%3] = a[i];
}
Well if you cannot use LINQ than simple for loop in an extension method can do the trick :
public static int[][] GetChunks(int[] array, int chunkSize)
{
if(array.Length < chunkSize)
{
throw new ArgumentOutOfRangeException("chunkSize");
}
var result = new List<int[]>(array.Length / chunkSize);
for (var i = 0; i < array.Length; i += chunkSize)
{
var chunk = new int[chunkSize + i < array.Length ? chunkSize : (array.Length - i - 1)];
for (var j = 0; j < chunk.Length; j++)
{
chunk[j] = array[i + j];
}
result.Add(chunk);
}
return result.ToArray();
}
Example of usage :
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[][] chunksOfFixedSize = GetChunks(nums, 3);
Console.WriteLine("Number of chunks : " + chunksOfFixedSize.Length);
Console.WriteLine("Second element at 3rd chunk is : " + chunksOfFixedSize[2][1]);
Output :
Number of chunks : 4
Second element at 3rd chunk is : 8
P.S.
If you prefer to have different variables per each array you could simply do something like :
var b = chunksOfFixedSize[0];
var c = chunksOfFixedSize[1];
var d = chunksOfFixedSize[2];
Linq solution:
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int size = 3;
// Array of 3 items arrays
int[][] result = Enumerable
.Range(0, a.Length / size + (a.Length % size == 0 ? 0 : 1))
.Select(index => a
.Skip(index * size)
.Take(size)
.ToArray())
.ToArray(); // if you want array of 3-item arrays
Test
String report = String.Join(Environment.NewLine,
result.Select(chunk => String.Join(", ", chunk)));
// 1, 2, 3
// 4, 5, 6
// 7, 8, 9
// 10
Console.Write(report);
Here is a solution where you get the exact lengths in the arrays:
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// if the length % 3 is zero, then it has length / 3 values
// but if it doesn't go without rest, the length of the array in the first dimention is + 1
int[][] b = new int[((a.Length % 3 == 0) ? a.Length / 3 : a.Length / 3 + 1)][];
for (int i = 0; i < b.Length; i++)
{
// the length of the second dimension of the array is the 3 if it goes throught 3
// but if it has rest, then the length is the rest
b[i] = new int[(i + 1) * 3 <= a.Length ? 3 : a.Length % 3];
int[] bTemp = new int[b[i].Length];
for (int j = 0; j < b[i].Length; j++)
{
bTemp[j] = a[i * 3 + j];
}
b[i] = bTemp;
}
And this is the result of b
The simplest and ugliest way would be
var a = new int[] {1,2,3,4,5,6,7,8,9,10};
var b0 = new int[] {a[0], a[1], a[2]};
var b1 = new int[] {a[3], a[4], a[5]};
otherwise
int[][] b = new int[a.Length][];
b[0] = a;
by the use of a two dimensional array, you can just select whatever array you want and assign it.
I am trying to keep all the combinations (5C1, 5C2, 5C3, 5C4, 5C5) of 1,2,3,4,5 into individual array. So I need to create dynamic array using for loop in c#.
Say for example,
Here n = 5 and r = 1 to 5.
if r = 1 then
My array will be single dimensional array, when r = 2 then it will be two dimensional array, when r = 3 then three dimensional, when r = 4 then four dimensional array and it will e continued up to end of 5.
My code is given below
string[] ShipArrayObj;
public frmResult( string[] ShipArray )
{
InitializeComponent();
ShipArrayObj = ShipArray;
}
private void frmResult_Load(object sender, EventArgs e)
{
string[] arr = ShipArrayObj;
int n = ShipArrayObj.Count();
for (int r = 1; r <= n; r++)
{
StoreCombination(arr, n, r);
richTextBox1.Text = richTextBox1.Text + "/";
}
}
void StoreCombination(string[] arr, int n, int r)
{
string[] data = new string[r];
createCombination (arr, data, 0, n - 1, 0, r);
}
private void createCombination(string[] arr, string[] data, int start, int end, int index, int r)
{
if (index == r)
{
int j = 0;
for (j = 0; j < r; j++)
richTextBox1.Text = richTextBox1.Text + data[j].ToString();//Where I want to set array to keep combination values
return;
}
int i = 0;
for (i = start; i <= end && end - i + 1 >= r - index; i++)
{
data[index] = arr[i];
CreateCombination(arr, data, i + 1, end, index + 1, r);
}
}
I am storing all the combination into a Rich Text Box, but want to keep into array. If anybody help me then I will be grateful to you.
If you're used to something like Java then multidimensional arrays are a little different in syntax in C#.
Here's a page describing how to do them in C#. Here's a snippet from said page:
// 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 } } };
If you're interested in different combinations of things with a fixed number of them, something like this should be all you need.
If you're interested in different combinations of things with a dynamic number of them, something like this should be all you need.
(Unless you're trying to optimize performance, it's better to be readable/expressive, generally speaking.)
You may need to consider whether or not order matters (un-ordered set vs. ordered list). I would assume it doesn't from your code (in which case sorting is good to eliminate "duplicates"), but I can't tell for sure.
Here's a good example that's easy to read and modify for variations and isn't so bad for small numbers:
// -1, 0, ..., 5
var choices = Enumerable.Range(-1, 6);
var possibleChoices =
from a in choices
from b in choices
from c in choices
from d in choices
from e in choices
select (IEnumerable<int>)new [] { a, b, c, d, e };
// Remove -1's because they represent not being in the choice.
possibleChoices =
possibleChoices.Select(c => c.Where(d => d >= 0));
// Remove choices that have non-unique digits.
possibleChoices =
possibleChoices.Where(c => c.Distinct().Count() == c.Count());
// Sort the choices to indicate order doesn't matter
possibleChoices =
possibleChoices.Select(c => c.OrderBy(d => d));
// Remove duplicates
possibleChoices =
possibleChoices.Select(c => new
{
Key = string.Join(",", c),
Choice = c
}).
GroupBy(c => c.Key).
Select(g => g.FirstOrDefault().Choice);
foreach (var choice in possibleChoices) {
Console.Out.WriteLine(string.Join(", ", choice));
}
Output:
0
1
2
3
4
0, 1
0, 2
0, 3
0, 4
1, 2
1, 3
1, 4
2, 3
2, 4
3, 4
0, 1, 2
0, 1, 3
0, 1, 4
0, 2, 3
0, 2, 4
0, 3, 4
1, 2, 3
1, 2, 4
1, 3, 4
2, 3, 4
0, 1, 2, 3
0, 1, 2, 4
0, 1, 3, 4
0, 2, 3, 4
1, 2, 3, 4
0, 1, 2, 3, 4
This is probably a little more dense to understand, hard-coded to this specific variation of combination and involves recursion but is a bit more generic/isn't hard-coded to 5 (and took 0.047s on dotnetfiddle.net instead of 0.094s). It's also completely lazy/IEnumerable.
public static void Main()
{
var possibleChoices = Choose(5);
foreach (var choice in possibleChoices) {
Console.Out.WriteLine(string.Join(", ", choice));
}
}
public static IEnumerable<IEnumerable<int>> Choose(int max)
{
var remaining = Enumerable.Range(0, max);
return ChooseRecursive(remaining, Enumerable.Empty<int>());
}
public static IEnumerable<IEnumerable<int>> ChooseRecursive(IEnumerable<int> remaining, IEnumerable<int> chosen)
{
yield return chosen;
foreach (var digit in remaining)
{
var choices = ChooseRecursive(
remaining.Where(d => d > digit),
chosen.Concat(new [] { digit })
);
foreach (var choice in choices)
{
yield return choice;
}
}
}
Output:
0
0, 1
0, 1, 2
0, 1, 2, 3
0, 1, 2, 3, 4
0, 1, 2, 4
0, 1, 3
0, 1, 3, 4
0, 1, 4
0, 2
0, 2, 3
0, 2, 3, 4
0, 2, 4
0, 3
0, 3, 4
0, 4
1
1, 2
1, 2, 3
1, 2, 3, 4
1, 2, 4
1, 3
1, 3, 4
1, 4
2
2, 3
2, 3, 4
2, 4
3
3, 4
4
I have an array of integers intx[]:
int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
I need to find the first two digits which their sum is equal to 10.
Here's the code:
Output should like (4 and 6).
Output should like (3 and 7).
Output should like (2 and 8).
Output should like (1 and 9).
public string Test()
{
int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int i, j = intx.Length-1;
string s = "";
for (i = 0; i < 4; i++)
{
if ((intx[i] + intx[j - 1]) == 10)
{
s = (intx[i].ToString() + " and " + intx[j - 1].ToString());
}
j--;
}
return s;
}
You could use LINQ:
int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var twoDigitsSumEquals10 = intx
.SelectMany((i1, index) =>
intx.Skip(index + 1)
.Select(i2 => Tuple.Create(i1, i2)))
.Where(t => t.Item1 + t.Item2 == 10);
SelectMany builds a cartesian product between all ints in the array and all ints in the array with a greater index than the first(to prevent repetition).
Test:
foreach (var x in twoDigitsSumEquals10)
Console.WriteLine(string.Join(",", x));
Output:
(1, 9)
(2, 8)
(3, 7)
(4, 6)
or only the first with "and" between like (1 and 9):
var firstCombi = twoDigitsSumEquals10.First();
Console.Write("({0} and {1})", firstCombi.Item1, firstCombi.Item2);
Update: here's the same without LINQ:
List<Tuple<int, int>> pairs = new List<Tuple<int, int>>();
for (int i = 0; i < intx.Length - 1; i++)
{
for (int ii = i + 1; ii < intx.Length; ii++)
{
if(i + ii == 10)
pairs.Add(Tuple.Create(i, ii));
}
}
You don't do anything with s you just re assign it. Try adding the results to a list and return the list
public List<string> Test()
{
int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int j = intx.Length-1;
List<string> result = new List<string>();
for (int i = 0; i < 4; i++)
{
if ((intx[i] + intx[j - 1]) == 10)
{
result.Add(intx[i].ToString() + " and " + intx[j--].ToString());
}
}
return result;
}
foreach(string s in Test())
Console.WriteLine(s);
To just return the first, then exit the loop early
public string Test()
{
int[] intx = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int j = intx.Length-1;
for (int i = 0; i < 4; i++)
{
if ((intx[i] + intx[j - 1]) == 10)
{
return (intx[i].ToString() + " and " + intx[j--].ToString());
}
}
return "";
}
I have a ten element array of integers. I want to sum the elements by group, so for instance I want to add the value at element 0 with the value at element 1, then with the value at element 2, then 3, and so on through to element 9, then add the value at element 1 with the value at 2,3, through to 9 until every group of 2 values has been added together and stored in a variable. I then want to repeat the process with groups of 3, groups of 4, of 5, all the way through to group of 10. Each resultant total being stored in a separate variable. Thus far the only way I can figure out how to do it is thus :-
int i = 0;
int p = 1;
int q = 2;
int r = 3;
while (i < NumArray.Length - 3)
{
while (p < NumArray.Length - 2)
{
while (q < NumArray.Length-1)
{
while (r < NumArray.Length)
{
foursRet += NumArray[i] + NumArray[p] + NumArray[q]+ NumArray[r];
r++;
}
q++;
r = q + 1;
}
p++;
q = p + 1;
r = q + 1;
}
i++;
p = i + 1;
q = i + 2;
r = i + 3;
}
The above is an example of summing groups of 4.
I was wondering if anyone could be kind enough to show me a less verbose and more elegant way of achieving what I want. Many thanks.
Because everything is better with LINQ*:
using System; // Output is below
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var inputArray = Enumerable.Range(0, 10).ToArray();
var grouped =
from Buckets in Enumerable.Range(1, inputArray.Length)
from IndexInBucket in Enumerable.Range(0, inputArray.Length / Buckets)
let StartPosInOriginalArray = IndexInBucket * Buckets
select new
{
BucketSize = Buckets,
BucketIndex = StartPosInOriginalArray,
Sum = inputArray.Skip(StartPosInOriginalArray).Take(Buckets).Sum()
};
foreach (var group in grouped)
{
Debug.Print(group.ToString());
}
Console.ReadKey();
}
}
} // SCROLL FOR OUTPUT
{ BucketSize = 1, BucketIndex = 0, Sum = 1 }
{ BucketSize = 1, BucketIndex = 1, Sum = 2 }
{ BucketSize = 1, BucketIndex = 2, Sum = 3 }
{ BucketSize = 1, BucketIndex = 3, Sum = 4 }
{ BucketSize = 1, BucketIndex = 4, Sum = 5 }
{ BucketSize = 1, BucketIndex = 5, Sum = 6 }
{ BucketSize = 1, BucketIndex = 6, Sum = 7 }
{ BucketSize = 1, BucketIndex = 7, Sum = 8 }
{ BucketSize = 1, BucketIndex = 8, Sum = 9 }
{ BucketSize = 1, BucketIndex = 9, Sum = 10 }
{ BucketSize = 2, BucketIndex = 0, Sum = 3 }
{ BucketSize = 2, BucketIndex = 2, Sum = 7 }
{ BucketSize = 2, BucketIndex = 4, Sum = 11 }
{ BucketSize = 2, BucketIndex = 6, Sum = 15 }
{ BucketSize = 2, BucketIndex = 8, Sum = 19 }
{ BucketSize = 3, BucketIndex = 0, Sum = 6 }
{ BucketSize = 3, BucketIndex = 3, Sum = 15 }
{ BucketSize = 3, BucketIndex = 6, Sum = 24 }
{ BucketSize = 4, BucketIndex = 0, Sum = 10 }
{ BucketSize = 4, BucketIndex = 4, Sum = 26 }
{ BucketSize = 5, BucketIndex = 0, Sum = 15 }
{ BucketSize = 5, BucketIndex = 5, Sum = 40 }
{ BucketSize = 6, BucketIndex = 0, Sum = 21 }
{ BucketSize = 7, BucketIndex = 0, Sum = 28 }
{ BucketSize = 8, BucketIndex = 0, Sum = 36 }
{ BucketSize = 9, BucketIndex = 0, Sum = 45 }
{ BucketSize = 10, BucketIndex = 0, Sum = 55 }
*Not everything is better with LINQ
If I understand you correctly you have an array of numbers with length n. You want to pick all combinations of m numbers from this. You then want to sum all these combinations and finally compute the sum of these sums.
For instance given n = 6 numbers you can pick m = 4 elements in 15 different ways (the numbers are indices in the array of numbers):
0 1 2 3
0 1 2 4
0 1 3 4
0 2 3 4
1 2 3 4
0 1 2 5
0 1 3 5
0 2 3 5
1 2 3 5
0 1 4 5
0 2 4 5
1 2 4 5
0 3 4 5
1 3 4 5
2 3 4 5
If n < 32 (no more than 31 numbers in your array) you can efficiently generate the indices using 32 bit arithmetic. The following function is based on Gosper's hack:
IEnumerable<UInt32> GetIndexBits(Int32 m, Int32 n) {
unchecked {
var i = (UInt32) (1 << m) - 1;
var max = (UInt32) (1 << n);;
while (i < max) {
yield return i;
var u = (UInt32) (i & -i);
var v = u + i;
i = v + (((v ^ i)/u) >> 2);
}
}
}
With m = 4 and n = 6 this function will generate these numbers (displayed in binary form):
001111
010111
011011
011101
011110
100111
101011
101101
101110
110011
110101
110110
111001
111010
111100
You can then create the sum using LINQ:
var m = 4;
var numbers = new[] { 1, 2, 3, 4, 5, 6 };
var sum = GetIndexBits(4, numbers.Length)
.Select(
bits => Enumerable
.Range(0, numbers.Length)
.Where(i => ((1 << i) & bits) != 0)
)
.Select(indices => indices.Sum(i => numbers[i]))
.Sum();
With the provided input the sum will be 210 which is the same result as foursRet in the question when NumArray contains the numbers 1 to 6.