Array.ConvertAll() and ToArray() method, which is better? - c#

Which of the following method is better to read from console and storing it into Int array? Is there any difference between the 2?
int[][] s = new int[3][];
for(int i=0; i<elements.Length;i++)
{
s[i] = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
}
OR
int[][] s = new int[3][];
for (int i = 0; i < 3; i++) {
s[i] = Array.ConvertAll(Console.ReadLine().Split(' '), sTemp => Convert.ToInt32(sTemp));
}
Thanks in Advance!!!

Firstly these aren't equivalent, in one version you are using int.Parse(x) in another Convert.ToInt32(sTemp)
That aside, you have found a perfect example of how to do something more than one way... In programming you will find this a lot.
ConvertAll()
Converts an array of one type to an array of another type.
Select()
Projects each element of a sequence into a new form.
ToArray()
Creates an array from a IEnumerable.
Technically, in combination they produce the same thing, yet got about it in slightly different ways due to the fact they are part of slightly different areas of the BCL that have concerns in slightly different domains.
Personally i don't see ConvertAll used all that much these days as people are very familiar with LINQ and like to chain methods.
As to which is better for performance, we would have to write a lot of tests to figure this out, and it would come down to allocations verse speed per array size per platform. However, i feel the difference would be relatively indistinguishable in day to day, and my guess is you would be struggling to find very much performance difference at all at any significant sigma categorically.
In short, use what You like

Related

How can i write a program in c# which can calculate the square of index's numbers?

I am tryig to solve a algorithm example.
There will be a array.And i need to calculate the square of this arrays index numbers.
Output should be:"0-1-4-9-16-25-36-49-64-81" since the index numbers starts with 0-9.
I searched on the web.But i couldnt find anything.I think we need to declare an array like this:
int[] a = new int[10];
But i dont know what to do after that.Should we take input from user or not?
If anyone knows python, this is the python code:
from numpy import
indis = arrange(0,10)
for dizi in indis:
dizi=dizi**2
print(dizi, end=" ")
Thank you for your help.
for(int i=0; i<10; i++){
Console.WriteLine(i*i);
}
How about this - its more like the python
var sq = Enumerable.Range(0,9).Select(x=>x*x).ToArray();
foreach(var s in sq)
Console.WriteLine(s);
or maybe
var sq = Enumerable.Range(0,9).ToArray();
foreach(var s in sq)
Console.WriteLine(s*s);
this is even closer to the python
Since you obviously move from Python to C#, let's start with a bit of Python (probably the first time I write code with this language...).
Here, what I found out so far:
Python has no (built in) arrays. That NumPy thing must be a library of sorts.
The for loop of Python is quite restricted. "Normal" idioms do not exist.
But there is the rather obscure (unless Python is lazy like Haskell) range() thing, which may or may not be optimized away.
Because of 2., you do not clearly see the problem at hand and as such, you lack to see the obvious optimization when you transfer to C#. There (in C#), no one in their right mind would create a temporary data structure (e.g. an array) with a consecutive number of integers and then iterate over it. This would be wasteful and obscure on many levels.
So, with the restrictions of Python, trying to avoid the range() overhead, you would probably write:
def meh(arr):
i = 0
while i < len(arr):
print(i*i)
i = i + 1
Of course, the argument arr above would be a list, not an array because of 1.
And if you translate that bit of (optimized) code to C#, it looks something like:
void meh<T>(T[] arr) {
for (int i = 0; i < arr.Size; i++) {
print(i*i)
}
}

Does List<T>.Sort suffer worst case performance on sorted lists?

According to the docs List<T>.Sort uses the QuickSort algorithm. I've heard that this can exibit worst case performance when called on a pre-sorted list if the pivot is not chosen wisely.
Does the .NET implementation of QuickSort experience worst case behaviour on pre-sorted lists?
In my case I'm writing a method that's going to do some processing on a list. The list needs to be sorted in order for the method to work. In most usage cases the list will be passed already sorted, but it's not impossible that there will be some small changes to the order. I'm wondering whether it's a good idea to re-sort the list on every method call. Clearly though, I am falling into the premature optimization trap.
Edit: I've edited the question.
My question was badly asked I guess. It should really have been:
Does List<T>.Sort suffer worst case performance on sorted lists?
To which the answer appears to be "No".
I did some testing and it seems that sorted lists require fewer comparisons to sort than randomized lists: https://gist.github.com/3749646
const int listSize = 1000;
const int sampleSize = 10000;
var sortedList = Enumerable.Range(0,listSize).ToList();
var unsortedList = new List<int>(sortedList);
var sortedCount = 0;
sortedList.Sort((l,r) => {sortedCount++; return l - r;});
//sortedCount.Dump("Sorted");
// Returns: 10519
var totalUnsortedComparisons = 0;
for(var i = 0; i < sampleSize; i++)
{
var unsortedCount = 0;
unsortedList.Shuffle();
unsortedList.Sort((l,r) => {unsortedCount++; return l - r;});
totalUnsortedComparisons += unsortedCount;
}
//(totalUnsortedComparisons / sampleSize).Dump("Unsorted");
// Returns: 13547
Of course, #dlev raises a valid point. I should never have allowed myself to get into a situation where I was not sure whether my list was sorted.
I've switched to using a SortedList instead to avoid this issue.
Until you have hard metrics to make comparisons off of, you would be falling into the premature optimization trap. Run your code in a loop over 1000 times and gather time for execution using the two different methods to see which is faster and whether it makes a difference.
Choosing the right algorithm is not premature optimization.
When your list is already sorted or nearly so, it makes sense to use a stable sort. .NET ships with one, LINQ's OrderBy implementation. Unfortunately, it will copy your entire list several times, but copying is still O(N), so for a non-trivial list, that will still be faster.

C# linked lists

very basic question, but is there any ToArray-like function for c# linked lists that would return an array of only part of the elements in the linkedlist.
e.g.: let's say my list has 50 items and I need an array of only the first 20. I really want to avoid for loops.
Thanks,
PM
Use Linq?
myLinkedList.Take(20).ToArray()
or
myLinkedList.Skip(5).Take(20).ToArray()
You say you "really want to avoid for loops" - why?
If you're using .NET 3.5 (or have LINQBridge), it's really easy:
var array = list.Take(20).ToArray();
... but obviously that will have to loop internally.
Note that this will create a smaller array if the original linked list has fewer than 20 elements. It's unclear whether or not that's what you want.
Something is going to have to loop internally, sooner or later - it's not like there's going to be a dedicated CPU instruction for "navigate this linked list and copy a fixed number of pointers into a new array". So the question is really whether you do it or a library method.
If you can't use LINQ, it's pretty easy to write the equivalent code yourself:
int size = Math.Min(list.Count, 20);
MyType[] array = new MyType[size];
var node = list.First;
for (int i = 0; i < size; i++)
{
array[i] = node.Value;
node = node.Next;
}
That will actually be slightly more efficient than the LINQ approach, too, because it creates the array to be exactly the right size to start with. Yes, it uses a loop - but as I say, something's got to.
If you're using the LinkedList collection class (from System.Collections.Generic), you can use LINQ to get it:
var myArray = list.Take(20).ToArray();

Vectorising operators in C#

I spend much of my time programming in R or MATLAB. These languages are typically used for manipulating arrays and matrices, and consequently, they have vectorised operators for addition, equality, etc.
For example, in MATLAB, adding two arrays
[1.2 3.4 5.6] + [9.87 6.54 3.21]
returns an array of the same size
ans =
11.07 9.94 8.81
Switching over to C#, we need a loop, and it feels like a lot of code.
double[] a = { 1.2, 3.4, 5.6 };
double[] b = { 9.87, 6.54, 3.21 };
double[] sum = new double[a.Length];
for (int i = 0; i < a.Length; ++i)
{
sum[i] = a[i] + b[i];
}
How should I implement vectorised operators using C#? These should preferably work for all numeric array types (and bool[]). Working for multidimensional arrays is a bonus.
The first idea I had was to overload the operators for System.Double[], etc. directly. This has a number of problems though. Firstly, it could cause confusion and maintainability issues if built-in classes do not bahave as expected. Secondly, I'm not sure if it is even possible to change the behaviour of these built-in classes.
So my next idea was to derive a class from each numerical type and overload the operators there. This creates the hassle of converting from double[] to MyDoubleArray and back, which reduces the benefit of me doing less typing.
Also, I don't really want to have to repeat a load of almost identical functionality for every numeric type. This lead to my next idea of a generic operator class. In fact, someone else had also had this idea: there's a generic operator class in Jon Skeet's MiscUtil library.
This gives you a method-like prefix syntax for operations, e.g.
double sum = Operator<double>.Add(3.5, -2.44); // 1.06
The trouble is, since the array types don't support addition, you can't just do something like
double[] sum = Operator<double[]>.Add(a, b); // Throws InvalidOperationException
I've run out of ideas. Can you think of anything that will work?
Create a Vector class (actually I'd make it a struct) and overload the arithmentic operators for that class... This has probably been done already if you do a google search, there are numerous hits... Here's one that looks promising Vector class...
To handle vectors of arbitrary dimension, I'd:
design the internal array which would persist the individual floats for each of the
vectors dimension values an array list of arbitrary size,
make the Vector constructor take the dimension as an constructor parameter,
In the arithmentic operator overloads, add a validation that the two vectors being added, or subtracted have the same dimension.
You should probably create a Vector class that internally wraps an array and overloads the arithmetic operators. There's a decent matrix/vector code library here.
But if you really need to operate on naked arrays for some reason, you can use LINQ:
var a1 = new double[] { 0, 1, 2, 3 };
var a2 = new double[] { 10, 20, 30, 40 };
var sum = a1.Zip( a2, (x,y) => Operator<double>.Add( x, y ) ).ToArray();
Take a look at CSML. It's a fairly complete matrix library for c#. I've used it for a few things and it works well.
The XNA Framework has the classes you may be able to use. You can use it in your application like any other part of .NET. Just grab the XNA redistributable and code away.
BTW, you don't need to do anything special (like getting the game studio or joining the creator's club) to use it in your application.

working with incredibly large numbers in .NET

I'm trying to work through the problems on projecteuler.net but I keep running into a couple of problems.
The first is a question of storing large quanities of elements in a List<t>. I keep getting OutOfMemoryException's when storing large quantities in the list.
Now I admit I might not be doing these things in the best way but, is there some way of defining how much memory the app can consume?
It usually crashes when I get abour 100,000,000 elements :S
Secondly, some of the questions require the addition of massive numbers. I use ulong data type where I think the number is going to get super big, but I still manage to wrap past the largest supported int and get into negative numbers.
Do you have any tips for working with incredibly large numbers?
Consider System.Numerics.BigInteger.
You need to use a large number class that uses some basic math principals to split these operations up. This implementation of a C# BigInteger library on CodePoject seems to be the most promising. The article has some good explanations of how operations with massive numbers work, as well.
Also see:
Big integers in C#
As far as Project Euler goes, you might be barking up the wrong tree if you are hitting OutOfMemory exceptions. From their website:
Each problem has been designed according to a "one-minute rule", which means that although it may take several hours to design a successful algorithm with more difficult problems, an efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute.
As user Jakers said, if you're using Big Numbers, probably you're doing it wrong.
Of the ProjectEuler problems I've done, none have required big-number math so far.
Its more about finding the proper algorithm to avoid big-numbers.
Want hints? Post here, and we might have an interesting Euler-thread started.
I assume this is C#? F# has built in ways of handling both these problems (BigInt type and lazy sequences).
You can use both F# techniques from C#, if you like. The BigInt type is reasonably usable from other languages if you add a reference to the core F# assembly.
Lazy sequences are basically just syntax friendly enumerators. Putting 100,000,000 elements in a list isn't a great plan, so you should rethink your solutions to get around that. If you don't need to keep information around, throw it away! If it's cheaper to recompute it than store it, throw it away!
See the answers in this thread. You probably need to use one of the third-party big integer libraries/classes available or wait for C# 4.0 which will include a native BigInteger datatype.
As far as defining how much memory an app will use, you can check the available memory before performing an operation by using the MemoryFailPoint class.
This allows you to preallocate memory before doing the operation, so you can check if an operation will fail before running it.
string Add(string s1, string s2)
{
bool carry = false;
string result = string.Empty;
if (s1.Length < s2.Length)
s1 = s1.PadLeft(s2.Length, '0');
if(s2.Length < s1.Length)
s2 = s2.PadLeft(s1.Length, '0');
for(int i = s1.Length-1; i >= 0; i--)
{
var augend = Convert.ToInt64(s1.Substring(i,1));
var addend = Convert.ToInt64(s2.Substring(i,1));
var sum = augend + addend;
sum += (carry ? 1 : 0);
carry = false;
if(sum > 9)
{
carry = true;
sum -= 10;
}
result = sum.ToString() + result;
}
if(carry)
{
result = "1" + result;
}
return result;
}
I am not sure if it is a good way of handling it, but I use the following in my project.
I have a "double theRelevantNumber" variable and an "int PowerOfTen" for each item and in my relevant class I have a "int relevantDecimals" variable.
So... when large numbers is encountered they are handled like this:
First they are changed to x,yyy form. So if the number 123456,789 was inputed and the "powerOfTen" was 10, it would start like this:
theRelevantNumber = 123456,789
PowerOfTen = 10
The number was then: 123456,789*10^10
It is then changed to:
1,23456789*10^15
It is then rounded by the number of relevant decimals (for example 5) to 1,23456 and then saved along with "PowerOfTen = 15"
When adding or subracting numbers together, any number outside the relevant decimals are ignored. Meaning if you take:
1*10^15 + 1*10^10 it will change to 1,00001 if "relevantDecimals" is 5 but will not change at all if "relevantDecimals" are 4.
This method make you able to deal with numbers up doubleLimit*10^intLimit without any problem, and at least for OOP it is not that hard to keep track of.
You don't need to use BigInteger. You can do this even with string array of numbers.
class Solution
{
static void Main(String[] args)
{
int n = 5;
string[] unsorted = new string[6] { "3141592653589793238","1", "3", "5737362592653589793238", "3", "5" };
string[] result = SortStrings(n, unsorted);
foreach (string s in result)
Console.WriteLine(s);
Console.ReadLine();
}
static string[] SortStrings(int size, string[] arr)
{
Array.Sort(arr, (left, right) =>
{
if (left.Length != right.Length)
return left.Length - right.Length;
return left.CompareTo(right);
});
return arr;
}
}
If you want to work with incredibly large numbers look here...
MIKI Calculator
I am not a professional programmer i write for myself, sometimes, so sorry for unprofessional use of c# but the program works. I will be grateful for any advice and correction.
I use this calculator to generate 32-character passwords from numbers that are around 58 digits long.
Since the program adds numbers in the string format, you can perform calculations on numbers with the maximum length of the string variable. The program uses long lists for the calculation, so it is possible to calculate on larger numbers, possibly 18x the maximum capacity of the list.

Categories

Resources