Suppose we have two identical arrays {"A", "B", "C", "D", "E", "F"}. Is there a quick way to randomize the order of each that ensures when the two are lined up, the same letters are never at the same indices? (Obviously we can just generate a new index if it will cause a match but I'm wondering if there's a way that produces less repetition).
This works, and I think it is fairly easy to understand.
var source = new [] { "A", "B", "C", "D", "E", "F" };
var output1 = (string[])null;
var output2 = (string[])null;
var rnd = new Random();
Action shuffle = () =>
{
output1 = source.OrderBy(x => rnd.Next()).ToArray();
output2 = source.OrderBy(x => rnd.Next()).ToArray();
};
shuffle();
while (output1.Zip(output2, (o1, o2) => new { o1, o2 })
.Where(x => x.o1 == x.o2)
.Any())
{
shuffle();
}
You could do it in two steps with O(n) complexity.
[Step 1]
Shuffle just one array in a way that every letter changes its original position, something like this:
var rnd = new Random(0);
var x = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
for(int i = 0; i < x.Length; i++)
{
var j0 = (i == x[i] - 'A')? i + 1: i;
var j = rnd.Next(j0, x.Length);
// x[i] ⟷ x[j]
var t = x[i]; x[i] = x[j]; x[j] = t;
}
It ensures that the first and the second arrays are different in every position.
[Step 2]
Use Fisher–Yates shuffle for both arrays synchronously:
var y = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
for(int i = 0; i < x.Length; i++)
{
var j = rnd.Next(i, x.Length);
// x[i] ⟷ x[j]; y[i] ⟷ y[j]
var
t = x[i]; x[i] = x[j]; x[j] = t;
t = y[i]; y[i] = y[j]; y[j] = t;
}
It ensures randomization of both, keeping difference at every position.
My best advice would be to make your own randomizer method that takes 2 arguments: array to be shuffled and array that its not allowed to match.
Here is a quick example of a class that has 2 string arrays that it will be shuffling by calling (objectName).Shuffle();
public class ArrayShuffler {
public String[] arr1;
public String[] arr2;
public ArrayShuffler() {
arr1 = new String[] { "A", "B", "C", "D", "E", "F" };
arr2 = new String[] { "A", "B", "C", "D", "E", "F" };
}
public void Shuffle() {
shuffleArr(arr1);
shuffleArr(arr2, arr1);
}
/// <summary>
/// Can shuffle array, maching against a second array to prevent dublicates in same intex spot.
/// </summary>
/// <param name="arr">Array to be shuffled</param>
/// <param name="validate">Array to mach against</param>
private void shuffleArr(String[] arr, String[] validate = null) {
Random r = new Random();
int indx = 0;
while(indx < arr.Length){
int rIndx = r.Next(indx, arr.Length);
string tmp = arr[indx];
if(validate != null) { //Will only be performed if you specify an array to be matched against.
if(arr[rIndx] != validate[indx]) {
arr[indx] = arr[rIndx];
arr[rIndx] = tmp;
indx++;
}
else if(indx == arr.Length - 1) {
shuffleArr(arr, validate);
}
}
else { //Default operation
arr[indx] = arr[rIndx];
arr[rIndx] = tmp;
indx++;
}
}
}
}
Assuming you're trying to minimize the quantity of unnecessary re-rolls, and that it's the two results that must not match one another (permitting an output character at a particular index to match the character in the input at that index), I think I've got a solution for you.
The gist of it is that we build the resulting strings on-the-fly keeping track of which characters have not been picked in each list and temporarily removing the one we picked first for a particular index from the candidates we select from for the second one. I don't think this method has any bias to it, but I'm admittedly not an expert in that regard.
public void Shuffle(int seed)
{
char[] orig = { 'A', 'B', 'C', 'D', 'E', 'F' };
List<char> buffer1 = new List<char>();
List<char> buffer2 = new List<char>();
// Keep track of which indexes haven't yet been used in each buffer.
List<int> availableIndexes1 = new List<int>(orig.Length);
List<int> availableIndexes2 = new List<int>(orig.Length);
for (int i = 0; i < orig.Length; i++)
{
availableIndexes1.Add(i);
availableIndexes2.Add(i);
}
Random rand = new Random(seed);
// Treat the last 2 specially. See after the loop for details.
for (int i = 0; i < orig.Length - 2; i++)
{
// Choose an arbitrary available index for the first buffer.
int rand1 = rand.Next(availableIndexes1.Count);
int index1 = availableIndexes1[rand1];
// Temporarily remove that index from the available indices for the second buffer.
// We'll add it back in after if we removed it (note that it's not guaranteed to be there).
bool removed = availableIndexes2.Remove(index1);
int rand2 = rand.Next(availableIndexes2.Count);
int index2 = availableIndexes2[rand2];
if (removed)
{
availableIndexes2.Add(index1);
}
// Add the characters we selected at the corresponding indices to their respective buffers.
buffer1.Add(orig[index1]);
buffer2.Add(orig[index2]);
// Remove the indices we used from the pool.
availableIndexes1.RemoveAt(rand1);
availableIndexes2.RemoveAt(rand2);
}
// At this point, we have 2 characters remaining to add to each buffer. We have to be careful!
// If we didn't do anything special, then we'd end up with the last characters matching.
// So instead, we just flip up to a fixed number of coins to figure out the swaps that we need to do.
int secondToLastIndex1Desired = rand.Next(2);
int secondToLastIndex2Desired = rand.Next(2);
// If the "desired" (i.e., randomly chosen) orders for the last two items in each buffer would clash...
if (availableIndexes1[secondToLastIndex1Desired] == availableIndexes1[secondToLastIndex2Desired] ||
availableIndexes1[(secondToLastIndex1Desired + 1) % 2] == availableIndexes2[(secondToLastIndex2Desired + 1) % 2])
{
// ...then swap the relative order of the last two elements in one of the two buffers.
// The buffer whose elements we swap is also chosen at random.
if (rand.Next(2) == 0)
{
secondToLastIndex1Desired = (secondToLastIndex1Desired + 1) % 2;
}
else
{
secondToLastIndex2Desired = (secondToLastIndex2Desired + 1) % 2;
}
}
else if (rand.Next(2) == 0)
{
// Swap the last two elements in half of all cases where there's no clash to remove an affinity
// that the last element has for the last index of the output, and an affinity that the first
// element has for the second-to-last index of the output.
int t = secondToLastIndex1Desired;
secondToLastIndex1Desired = secondToLastIndex2Desired;
secondToLastIndex2Desired = t;
}
buffer1.Add(orig[availableIndexes1[secondToLastIndex1Desired]]);
buffer1.Add(orig[availableIndexes1[(secondToLastIndex1Desired + 1) % 2]]);
buffer2.Add(orig[availableIndexes2[secondToLastIndex2Desired]]);
buffer2.Add(orig[availableIndexes2[(secondToLastIndex2Desired + 1) % 2]]);
Console.WriteLine(new string(buffer1.ToArray()));
Console.WriteLine(new string(buffer2.ToArray()));
}
Note that if this were used for particularly long arrays, then the data moving from List<T>.Remove / List<T>.RemoveAt and the linear searching done by the former may not scale well.
Related
Alright, so I was trying to do a part of my program which just tallies all the numbers in a number (i'm good at translating polish mathematical arguments to english) and I wanted to implement a loop in which new variables are created, and those variables have names from a table array.
Here's the snippet of my code:
Random rand = new Random();
int[] a = { rand.Next(100,999), rand.Next(100, 999), rand.Next(100, 999), rand.Next(100, 999) }; // random numbers
int j = -1;
string[] inty = { "k", "l", "m", "n" }; // the array from which i want to extract variable names
for (int i = 0;i<=a.Length;i++) // loop
{
j++;
int inty[j] = new int(); // create a new int, where the name of the int is some letter from that array
Console.WriteLine(a[j]);
}
Console.ReadKey();
So that int that's supposed to be created in the loop should have a name from the next letters in that string array (inty). Does anyone have an idea on how to do this (or replace the code in another way)?
Sincerely,
some random dude on the internet.
You can use a Dictionary for this:
Random rand = new Random();
int[] a = { rand.Next(100,999), rand.Next(100, 999), rand.Next(100, 999), rand.Next(100, 999) }; // random numbers
string[] inty = { "k", "l", "m", "n" };
var variables = new Dictionary<string, int>();
for (int i = 0; i<a.Length; i++)
{
variables.Add(inty[i], a[i]);
Console.WriteLine(variables[inty[i]]);
}
//example using a variable
Console.WriteLine($"k: {variables["k"]}");
Console.ReadKey();
or:
Random rand = new Random();
int[] a = { rand.Next(100,999), rand.Next(100, 999), rand.Next(100, 999), rand.Next(100, 999) }; // random numbers
string[] inty = { "k", "l", "m", "n" };
var variables = new Dictionary<string, int>();
foreach (var item in a.Zip(inty, (i, n) => (i, n)))
{
variables.Add(item.i, item.n);
}
//example using a variable
Console.WriteLine($"k: {variables["k"]}");
Console.ReadKey();
Remember C# is strongly-typed. Variables must be declared to the compiler. If you want an identifier to be available as a variable in the IDE, it must be declared that way. Otherwise, you just use the name as data held in some other type.
If I understand your question... you may use the modulus function and a hashset maybe
HashSet<string> names = new HashSet<strings>();
for (int i = 0;i<=a.Length;i++)
{
j = j++ % 3; // Will give 0,1,2,0,1,2,0,1,2... or use ranbd.Next(0,4)
string forName = inty[j]; // Restricted to 0,1,2
string newName = $"{forName}{a[j]}";
if (! names.Contains(newName)
{
names.Add(newName);
Console.WriteLine("Name: {newName}");
}
else
{
Console.WriteLine("Ups!: {newName} already used!");
}
}
Okay i might not have explained it to the best of my ability but i'm a beginner and i would like to make a piece of code that does this :
you have a string and you need to find each vowel in it and multiply each vowel's position in the string by its position in the alphabet and add all the sums together
example : steve: has 2 vowels the first e's position is 3 and its position in the alphabet is 5. and the second's position in the alphabet and the string is 5
so the sum is 5*3 + 5*5 = 40
this is what i did . idk what to do now or how to approach it
var vowels = new char[] {'a', 'e', 'i', 'o', 'u', 'y', 'A','E','I', 'O', 'U','Y'};
var chars = new List<char>();
List<int> indexes = new List<int>();
Console.WriteLine("Write something : ");
var input = Console.ReadLine();
int index;
foreach (var vowel in vowels)
{
if (input.Contains(vowel))
{
index = input.IndexOf(vowel);
indexes.Add(index + 1);
chars.Add(vowel);
}
}
Consider this approach:
using System;
using System.Linq;
using System.Collections.Generic;
namespace Whatever
{
class Program
{
static void Main(string[] args)
{
var vowels = new Dictionary<string, int>(5, StringComparer.OrdinalIgnoreCase) { { "a", 1 }, { "e", 5 }, { "i", 9 }, { "o", 15 }, { "u", 21 } };
Console.WriteLine("Write something : ");
var input = Console.ReadLine();
var sum = input.Select((value, index) => new { value, index })
.Sum(x =>
{
vowels.TryGetValue(x.value.ToString(), out var multiplier);
return (x.index + 1) * multiplier;
});
Console.ReadLine();
}
}
}
The Select projects the original string as an anonymous type with the char and its index included.
The Sum checks if the string is a vowel - and if it is it multiplies the position (index + 1) by the position in the alphabet (from vowels).
vowels is case insensitive so that "A" and "a" are treated the same.
If the compiler complains about the out var then use:
int multiplier = 0;
vowels.TryGetValue(x.value.ToString(), out multiplier);
return (x.index + 1) * multiplier;
instead.
i figured it out right here
for (int i = 0; i < indexes.Count; i++)
{
sumofone += indexes[i] * (char.ToUpper(chars[i]) - 64);
}
You can do this (Reference is from here):
var vowels = new char[] { 'a', 'e', 'i', 'o', 'u' };
Console.WriteLine("Write something : ");
var input = Console.ReadLine().ToLower();
int total = 0;
for (int temp = 1; temp <= input.Length; temp++)
{
if (vowels.Contains(input[temp - 1]))
{
total += temp * (char.ToUpper(input[temp -1]) - 64);
}
}
Console.WriteLine("The length is " + total);
My task is to print words in an array in a rectangular frame. Like this:
*********
* Hello *
* World *
* in *
* a *
* Frame *
*********
I wrote a code witch works just fine, but I'm just curious - how can I do the same just with only one foreach cycle?
using System;
namespace RectangleAroundWords
{
class Program
{
public static void Main()
{
string[] words = new[] { "Hello", "World", "in", "a", "frame" };
int length = 0;
foreach (var item in words)
{
if (length < item.Length)
{
length = item.Length;
}
}
String tabs = new string('*', length + 4);
Console.WriteLine(tabs);
foreach (var item in words)
{
Console.WriteLine("* " + item.PadRight(length, ' ') + " *");
}
Console.WriteLine(tabs);
Console.ReadKey();
}
}
}
Although I think my first answer is the better approach in readability and best practices, it is possible to do this completley without any loop by using recursion (just to be a nit-picker ;-):
public static void Main()
{
string[] words = new[] { "Hello", "World", "in", "a", "frame" };
var output = Recurse(words);
String tabs = new string('*', output.Item2 + 4);
Console.WriteLine(tabs);
Console.WriteLine(output.Item1);
Console.WriteLine(tabs);
Console.ReadKey();
}
Tuple<string, int> Recurse(string[] words, int index = 0, int maxLength = 0)
{
maxLength = Math.Max(maxLength, words[index].Length);
if (index < words.Length - 1)
{
var output = Recurse(words, index + 1, maxLength);
maxLength = output.Item2;
return Tuple.Create(
string.Format("* {0} *{1}{2}", words[index].PadRight(maxLength), Environment.NewLine, output.Item1),
maxLength);
}
return Tuple.Create(
string.Format("* {0} *", words[index].PadRight(maxLength)),
maxLength);
}
Compare and decide yourself...
With this snippet you can get the maximum length without the first loop:
int length = words.Select(w => w.Length).Max();
or shorter:
int length = words.Max(w => w.Length);
Also I think it would be better to first create the complete output string by using the StringBuilder class:
string[] words = new[] { "Hello", "World", "in", "a", "frame" };
int length = words.Max(w => w.Length);
var sb = new StringBuilder();
String tabs = new string('*', length + 4);
sb.AppendLine(tabs);
foreach (var item in words)
{
sb.AppendFormat("* {0} *", item.PadRight(length));
sb.AppendLine();
}
sb.AppendLine(tabs);
Console.WriteLine(sb.ToString());
Console.ReadKey();
You'd have to create coordinates then calculate the character at each coordinate somehow.
You know the maximum height without looping (words.Length) so increment a pointer and take modulo and divisor by this height to give x,y coords. Continue until you don't find any character at the given coordinates.
string[] words = new[] { "Hello", "World", "in", "a", "frame" };
int height = words.Length + 4;
int row = 0;
int column = 0;
void Write(char c)
{
Console.SetCursorPosition(column, row);
System.Console.Write(c);
}
int i = 0;
int completedWordCount = 0;
int? lastColumn = null;
do
{
row = i % height;
column = i / height;
if (row == 0 || row == height - 1)
{
completedWordCount = 0;
Write('*');
}
if (column == 0 || column == lastColumn)
{
Write('*');
}
if (row > 1 && row < height - 2 && column > 1)
{
string word = words[row - 2];
if (column - 2 < word.Length)
{
Write(word[column - 2]);
}
else
{
completedWordCount++;
}
if (completedWordCount == words.Length && !lastColumn.HasValue)
{
lastColumn = column + 2;
}
}
i++;
} while ((!lastColumn.HasValue || column < lastColumn) || row != height - 1);
Not exactly a foreach, but only one 'iteration'.
Based on the question: "how can I do the same just with only one foreach cycle?"
At this point, I only see 2 options:
If the string list is inserted by the user (BEFORE YOUR CODE and does not comes from a DB table), just read the length of the input and keep it on a MaxLengthTillNow, and then you are ok with it.
Crappy solution: make the "rectangle" fixed with with 100 :P no matter what you will write inside, will be ok..... but this is probably not the purpose of your problem :)
In conclusion: all the linq/lambdas/func, etc... solutions ARE always using "loops" behind doors..... so, probably there is no answer for your question.
I am having trouble with a small bit of code, which in a random size array, with random number pairs, except one which has no pair.
I need to find that number which has no pair.
arLength is the length of the array.
but i am having trouble actually matching the pairs, and finding the one which has no pair..
for (int i = 0; i <= arLength; i++)
{ // go through the array one by one..
var number = nArray[i];
// now search through the array for a match.
for (int e = 0; e <= arLength; e++)
{
if (e != i)
{
}
}
}
I have also tried this :
var findValue = nArray.Distinct();
I have searched around, but so far, i haven't been able to find a method for this.
This code is what generates the array, but this question isn't about this part of the code, only for clarity.
Random num = new Random();
int check = CheckIfOdd(num.Next(1, 1000000));
int counter = 1;
while (check <= 0)
{
if (check % 2 == 0)
{
check = CheckIfOdd(num.Next(1, 1000000)); ;
}
counter++;
}
int[] nArray = new int[check];
int arLength = 0;
//generate arrays with pairs of numbers, and one number which does not pair.
for (int i = 0; i < check; i++)
{
arLength = nArray.Length;
if (arLength == i + 1)
{
nArray[i] = i + 1;
}
else
{
nArray[i] = i;
nArray[i + 1] = i;
}
i++;
}
You can do it using the bitwise operator ^, and the complexity is O(n).
Theory
operator ^ aka xor has the following table:
So suppose you have only one number without pair, all the pairs will get simplified because they are the same.
var element = nArray[0];
for(int i = 1; i < arLength; i++)
{
element = element ^ nArray[i];
}
at the end, the variable element will be that number without pair.
Distict will give you back the array with distinct values. it will not find the value you need.
You can GroupBy and choose the values with Count modulo 2 equals 1.
var noPairs = nArray.GroupBy(i => i)
.Where(g => g.Count() % 2 == 1)
.Select(g=> g.Key);
You can use a dictionary to store the number of occurrences of each value in the array. To find the value without pairs, look for a (single) number of occurrences smaller than 2.
using System.Linq;
int[] data = new[] {1, 2, 3, 4, 5, 3, 2, 4, 1};
// key is the number, value is its count
var numberCounts = new Dictionary<int, int>();
foreach (var number in data) {
if (numberCounts.ContainsKey(number)) {
numberCounts[number]++;
}
else {
numberCounts.Add(number, 1);
}
}
var noPair = numberCounts.Single(kvp => kvp.Value < 2);
Console.WriteLine(noPair.Key);
Time complexity is O(n) because you traverse the array only a single time and then traverse the dictionary a single time. The same dictionary can also be used to find triplets etc.
.NET Fiddle
An easy and fast way to do this is with a Frequency Table. Keep a dictionary with as key your number and as value the number of times you found it. This way you only have to run through your array once.
Your example should work too with some changes. It will be a lot slower if you have a big array.
for (int i = 0; i <= arLength; i++)
{
bool hasMatch = false;
for (int e = 0; e <= arLength; e++)
{
if (nArray[e] == nArray[i])//Compare the element, not the index.
{
hasMatch = true;
}
}
//if hasMatch == false, you found your item.
}
All you have to do is to Xor all the numbers:
int result = nArray.Aggregate((s, a) => s ^ a);
all items which has pair will cancel out: a ^ a == 0 and you'll have the distinc item: 0 ^ 0 ^ ...^ 0 ^ distinct ^ 0 ^ ... ^0 == distinct
Because you mentioned you like short and simple in a comment, how about getting rid of most of your other code as well?
var total = new Random().Next(500000) * 2 + 1;
var myArray = new int[total];
for (var i = 1; i < total; i+=2)
{
myArray[i] = i;
myArray[i -1] = i;
}
myArray[total - 1] = total;
Then indeed use Linq to get what you are looking for. Here is a slight variation, returning the key of the item in your array:
var key = myArray.GroupBy(t => t).FirstOrDefault(g=>g.Count()==1)?.Key;
One of my 'for the hell of it' projects I started yesterday was a Befunge interpreter. I have it working for the most part except for an edge case.
I got lazy and decided to read in a befunge program with this:
char[][] program = File.ReadAllLines(args[0]).Select(x => x.ToCharArray()).ToArray();
I knew I was creating more work for myself later, but I wanted to get to other parts and left it at that. Now it's later and I need to fix the fact that program is not rectangular. Let's say I had this befunge program:
v v <
#
> ^
The 1st and 3rd lines are 9 characters long, but the 2nd line is only 5. In the way I have my befunge interpreter set up, I will get an IndexOutOfBoundsException before the program terminates because after interpreting ^ as a change of direction I would try to access program[1][8] and program[1] is only 5 long. Instead of trying to catch the exception and dance around it, how could I create a char[,] using program and filling the extra characters with spaces?
I know I could just determine the length of the longest line, the number of lines, create the char[,] with those and copy them over, but I'm hoping for something a little simpler and more elegant. I am completely ok with throwing out the above line if a new approach is better.
Rather than re-creating the entire jagged array (assuming it could be rather large) you could just create a wrapper for it. That wrapper would be able to do the bounds checking and return some default value if it would be out of bounds rather than erroring.
public class Matrix<T>
{
public T[][] UnderlyingCollection {get;set;} //should probably be readonly and set in the constructor
public T DefaultValue {get;set;}
public T this[int i, int j]
{
get
{
if(UnderlyingCollection.Length > i && UnderlyingCollection[i].Length > j)
return UnderlyingCollection[i][j];
else
return DefaultValue;
}
set
{ /*TODO implement*/ }
}
}
Building on #AndreCalil's previous answer, this might be more performant, especially for large arrays of primitive types. Arrays of primitive types can be treated as a flat buffer of bytes, which can be useful in this sort of work (if you've got experience with assembler or C):
static void Main( string[] args )
{
string[][] jagged = new string[][] { new string[] { "alpha" , } ,
new string[] { "bravo" , "charlie" , } ,
new string[] { "delta" , "echo" , "foxtrot" , } ,
new string[] { "golf" , "hotel" , "india" , "juliet" , } ,
new string[] { "kilo" , "lima" , "mike" , "nancy" , "oscar" , } ,
} ;
string[,] rectangular = RectArrayFromJagged<string>( jagged ) ;
return;
}
public static T[,] RectArrayFromJagged<T>( T[][] a )
{
int rows = a.Length;
int cols = a.Max( x => x.Length );
T[,] value = new T[ rows , cols ] ;
value.Initialize() ;
if ( typeof(T).IsPrimitive )
{
int elementSizeInOctets = Buffer.ByteLength(value) / value.Length ;
for ( int i = 0 ; i < rows ; ++i )
{
int rowOffsetInOctets = i * cols * elementSizeInOctets ;
int rowLengthInOctets = a[i].Length * elementSizeInOctets ;
Buffer.BlockCopy( a[i] , 0 , value , rowOffsetInOctets , rowLengthInOctets ) ;
}
}
else
{
for ( int i = 0 ; i < rows ; ++i )
{
int rowLength = a[i].Length ;
for ( int j = 0 ; j < rowLength ; ++j )
{
value[i,j] = a[i][j] ;
}
}
}
return value ;
}
Man, I'm not sure if this is what you're looking for, but check this out:
public static class CharArrayExtension
{
public static char[,] FormatMatrix(this char[][] matrix)
{
int TotalColumns = matrix.Length;
int TotalLines = 0;
//Get the longest line of the current matrix
for (int column = 0; column < TotalColumns; column++)
{
int line = matrix[column].Length;
if (line > TotalLines)
TotalLines = line;
}
//Instantiate the resulting matrix
char[,] Return = new char[TotalColumns, TotalLines];
Return.Initialize();
//Retrieve values from the current matrix
for (int CurrentColumn = 0; CurrentColumn < TotalColumns; CurrentColumn++)
{
int MaxLines = matrix[CurrentColumn].Length;
for (int CurrentLine = 0; CurrentLine < MaxLines; CurrentLine++)
{
Return[CurrentColumn, CurrentLine] = matrix[CurrentColumn][CurrentLine];
}
}
return Return;
}
}
Usage:
char[] Length5 = new char[]{ 'a', 'b', 'c', 'd', 'e'};
char[] Length10 = new char[10];
char[][] Matrix = new char[2][];
Matrix[0] = Length5;
Matrix[1] = Length10;
char[,] FormattedMatrix = Matrix.FormatMatrix();
Any feedback will be appreciated.
UPDATE
Nicholas pointed out the performance issue. I was curious about it, so I made the following micro-weak-benchmarking:
char[] Length5 = new char[]{ 'a', 'b', 'c', 'd', 'e'};
char[] Length10 = new char[10];
char[][] Matrix = new char[2][];
Matrix[0] = Length5;
Matrix[1] = Length10;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 5000; i++)
{
char[,] FormattedMatrix = Matrix.FormatMatrix();
}
stopWatch.Stop();
Console.WriteLine(string.Format("Andre Calil: {0} ms", stopWatch.ElapsedMilliseconds));
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < 5000; i++)
{
char[,] FormattedMatrix = RectArrayFromJagged<char>(Matrix);
}
stopWatch.Stop();
Console.WriteLine(string.Format("Nicholas Carey: {0} ms", stopWatch.ElapsedMilliseconds));
Console.ReadLine();
I've run it multiple times, and the average results was:
Andre Calil: 3 ms
Nicholas Carey: 5 ms
I know that this is not a proper benchmarking, but looke like my solution isn't so bad in terms of performance after all.