You may feel weird about what I'm asking, but it's true, convert 1 two-dimensional array into 2 one-dimensional arrays.
That was what my teacher asked, and he said he would give a perfect point for whoever answers this (I think, tricky) question. I would happy to convert any 2 or n-dimensional array into one one-dimensional array. But he said 2, so I think there must be something to do with the second array. And, he didn't tell what type of array (int, String or object), so I assume it must be done with any kind of 2-dimensional array.
This is what I will answer him if no one here figure out what he wants: Convert into a 1-dimensional array, and leave the second null (or let it have no element). But I don't think it's a good answer for such a tricky question.
EDIT: Here is my teacher question, word-by-word (he just ask at the end of the session in voice, not in the textbook, as a bonus question(with... a nice bonus reward)): Given a 2-dimensional array, convert it into two 1-dimensional arrays.
I don't know if [][] in Java and C# considered 2-dimensional array, but C# does have [, ], which is 2-dimensional array. We are studying computer algorithm, with no target IDE or language.
EDIT2: I emailed him, and he refused to give additional information (he said it was unfair for others if I have more information than them), and he didn't give any comments about jagged array idea. The only useful thing in his reply: Let [][] be considered 2-dimensional array.
I'll bite. It's possible to flatten the entire two-dimensional array into the first of the two one-dimensional arrays by simply reading and writing consistently. I.e. store row 1 then row 2, etc. sequentially in that first array. Whenever you move to the next row, store the index of that next cell (of the first one dimensional array) in the second one-dimensional array, which would essentially become a row index table.
As Jon Skeet said above, this isn't a very well-specified question; perhaps with clarified information, we could better help you.
If I understand your question properly
it's easy m8...
it's only an algorithm question.. not a programming language specific...
you can do it like this:
one array holds the values
second array holds the keys
try to find a workaround in the second array to know what keys you've got..
For example:
array_1: v0 v1 v2 null v3 v4 v5 null v6 v7 v8 null
array_2: 0 1 2 newR 0 1 2 newR 0 1 2 newR
You can represent it in one array as well... but you need a specific algorithm to figure out when you are located on Y of the matrix.
The problem is that you won't access the data instantly from memory.. this is why there are bi-dimensional arrays
Another way:
keep in array 1 the values
keep in the second array the keys as string like in the following example:
array1: value1 value2 value3 value4 value5
array2: 0,0 0,1 1,0 1,1 2,0
there are a lot of algorithms but I don't think you will find better than bi-dimensional arrays...
When you look after them you will have less performance.. ofc.. unless you keep them in hashtables.. hashing 0,0 and added as key in a hashtable and add the specified value to that key. then you will look for key "0,0"...
Flatten the 2-d array in either row-major or column-major order, storing it in one of the 1-d arrays. Store the shape {n, m} of the array in the other 1-d integer array. Given the indices for an element in the 2-d array of values, you can use the shape to calculate the index in the 1-d array of values.
The two representations are isomorphic, and both allow looking up the values in constant time. It's also similar to how a 2-d array is represented in memory.
I guess you want to transform you 2-demension array (typed RelevantType[,]) into 2 arrays (typed SomeTypeA[] and SomeTypeB[]) without losing any information?
It's not very difficult:
Have the first array be of type RelevantType[], the second one of type int[], copy the content of your 2-dimensionnal array into the first one and its first indices into the second one, and you're done.
Related
I would like to ask if there is a data structure or some sort of dictionary that would help me to solve this problem.
First I create array of arrays of int.
11,32,21,10;
455,476,465,454;
11,32,476,455;
...
10,32,21,11;
Besides that I am adding points to separate array of arrays
Pt11,Pt32,Pt21,Pt10;
Pt455,Pt476,Pt465,Pt454;
Pt11,Pt32,Pt476,Pt455;
...
Pt10,Pt32,Pt21,Pt11;
Is there a way to create a dictionary to add array of points by name, and the name is array of integers - 10,32,21,11 - .
But the problem I have, is that I want to add to the same dictionary point array if name is mixed - 11,32,21,10.
So dictionary would point to the same collection - if I call 10,32,21,11 or 11,32,21,10. In other words 10,32,21,11 and 11,32,21,10 is the same name because elements are just ordered differently.
I do not know if it clear as I mixing several things:
1. Is it possible to create at least a dictionary whose name is an array?
2. Then if yes it probably would not point to the same points array if I add elements dictionary.Add(10,32,21,11, pt[]); dictionary.Add(11,32,21,10, pt[]);
I have the following DataTable
ItemNumber Quantity Order
1 2 3
4 3 8
7 7 9
I would like to load first two columns into 2 dimensional array. If it is not possible, at least I would like to get first column into 1 dimension array.
Of course, I can write a loop, but I wonder if it is possible to avoid loops.
Regards,
You won't necessarily be able to avoid loops in the technical sense, but you could write something like this:
DataTable table = ...;
return table.Rows.Cast<DataRow>().Select(c => new[] { c[0], c[1] });
That's an array of arrays, rather than a multidimensional array. But from what I've seen multidimensional arrays seem to be phased out as standard practice in most applications. You might also want to parse each row in that Select to being some actual type.
If you leave this as an IEnumerable<>, it will not need to loop more than the once that you use it, but if you're reading at random points a lot (using the indexer, or what have you), you might want to append .ToArray(). That decision depends on how you're using it. As a general rule, it's nice to write code that doesn't depend on random access like that, since then you don't have to read from the DataTable more than once per record.
This question already has answers here:
Array versus List<T>: When to use which?
(16 answers)
Closed 9 years ago.
I am not asking about the difference between array and list in general, I'm just asking about the difference between them in this scenario.
I have one Array. The array index is a dynamic value, and I have one integer List.
int DynamicValue=20 ;//It's any values should be coming from database or anywhere
int[DynamicValue] array1=new int[DynamicValue];//Array declaration
List<int> list1=New List<int>();//List declaration
Now I create one for loop to add values to Array and List:
//First add values in array
for(i=0;i<DynamicValue;i++)
{
array1[i]=i;
}
//Then add the values to list
for(i=0;i<DynamicValue;i++)
{
list1.Add(i);
}
Now what is this difference between the above codes ?
My questions are:
Array is type safe and also defined the index size. So why do many peoples like Lists in this scenario? (I know it's useful for generics coding, but I'm asking for this scenario)
The array for loop is not accruing any boxing and unboxing, So why would we need List?
Which for loop (Array or List) is best in this scenario ?
Which for loop will give good performance (I think both of for loops are good, because this code does not attempt any boxing and unboxing and also this codes is type safe. But I'm not sure at this time which one is better) ?
When you create an array you specify the size. When you create your list you do not (you can provide an initial capacity with an overload of the constructor).
So when you create the array you say it needs memory for the size of 20 int objects. But when you create the List it has no size reserved for the ints.
List<int> list = new List<int>();
Console.WriteLine(list.Capacity);
//Output: 0
Then when you use the loop to add items to the array the size of the array remains 20. But when you use the loop for the list the list sees there is no room. So it creates room for 4 items (check list.Capacity after first add). Then when the capacity is full the list will double its capacity. Now it is 8. Then again 16, then again 32. So in the end your list reserved room in memory for 32 int objects.
The array only reserved 20 so in total the array is better memory wise.
Further more, performance wise, array is also a little faster. I refer to this SO answer: https://stackoverflow.com/a/454923/637425
To adress some of your questions:
Many people don't like to work with indexes. You can make mistakes very easily (especially for starting programmers). Indexes are zero based etc etc... But if you could just call .Add() you don't have to worry about index. So it is a bit of convenience for most people to use List
You don't need list... See answer 1.
See my large story... Array is a bit better memory wise.
Both give good performance and you wont notice any difference. When you start using larger lists/arrays then it becomes interesting. For something with the size of 20 there is just not much performance gain.
I have a code that looks like (more or less) :
public void INeedHolidaysNow(double[,]){
//... Code to take a break from coding and fly to Hawaii
}
double[][] WageLossPerVacationDay = new double[10][5];
INeedHolidays(WageLossPerVacationDay); // >>throws the Exception in the Title
I found the solution on this post which consists in looping rather thant trying a savage cast
So my question is : WHY ? what happens behind the scenes in the memory allocation that prevents what may seem - at least at first glance, to be a feasible cast ? I mean structurally, both expression seem to be quite identic. What is it that I am missing here ?
EDIT:
I have to use "double[ ][ ]" as it is provided by an external library.
One is a jagged array, the other is one big block.
double[][] is an array that contains arrays of double. Its form is not necessarily rectangular. In c terms its similar to a double**
double[,] is just one big block of memory, and it is always rectangular. In c terms it's just a double* where you use myArray[x+y*width] to access an element.
One is called multidimensional array (double[*,*]) and other is called jagged array (double[][]).
Here is a good discussion over differences between them.
What is differences between Multidimensional array and Array of Arrays in C#?
Quite simply, [,] arrays (2D arrays) and [][] arrays (jagged arrays) aren't the same.
A [,] array can be visually represented by a rectangle (hence it's also known as a rectangular array), while a [][] array is a 1D array that contains other 1D arrays.
It wouldn't make much sense to be able to cast one to the other.
You should define your double array like this:
double[,] WageLossPerVacationDay = new double[3, 5];
Then it should work!
hth
My requirement is to find a duplicate number in an array of integers of length 10 ^ 15.
I need to find a duplicate in one pass. I know the method (logic) to find a duplicate number from an array, but how can I handle such a large size.
An array of 10^15 of integers would require more than a petabyte to store. You said it can be done in a single pass, so there's no need to store all the data. But even reading this amount of data would take a lot of time.
But wait, if the numbers are integers, they fall into a certain range, let's say N = 2^32. So you only need to search at most N+1 numbers to find a duplicate. Now that's feasible.
You can use a BitVector array with length = 2^(32-5) = 0x0800000
This has a bit for each posible int32 number.
Note: easy solution (BitArray) do´nt support adecuate constructor.
BitVector32[] bv = new BitVector32[0x8000000];
int[] ARR = ....; // Your array
foreach (int I in ARR)
{
int Element = I >> 5;
int Bit = I & 0x1f;
if (bv[Element ][Bit])
{
// Option for First Duplicate Found
}
else
{
bv[I][Bit] = true;
}
}
You'll need a different data structure. I suspect the requirement isn't really to use an array - I'd hope not, as arrays can only hold up to Int32.MaxValue elements, i.e. 2,147,483,647... much less than 10^15. Even on a 64-bit machine, I believe the CLR requires that arrays have at most that many elements. (See the docs for Array.CreateInstance for example - even though you can specify the bounds as 64-bit integers, it will throw an exception if they're actually that big.)
Now, if you can explain what the real requirement is, we may well be able to suggest alternative data structures.
If this is a theoretical problem rather than a practical one, it would be helpful if you could tell us those constraints, too.
For example, if you've got enough memory for the array itself, then asking for 2^24 bytes to store which numbers you've seen already (one bit per value) isn't asking for much. This is assuming the values themselves are 32-bit integers, of course. Start with an empty array, and set the relevant bit for each number you find. If you find you're about to set one that's already set, then you've found the first duplicate.
You can declare it in the normal way: new int[1000000000000000]. However this will only work on a 64-bit machine; the largest you can expect to store on a 32-bit machine is a little over 2GB.
Realistically you won't be able to store the whole array in memory. You'll need to come up with a way of generating it in smaller chunks, and checking those chunks individually.
What's the data in the array? Maybe you don't need to generate it all in one go. Or maybe you can store the data in a file.
You cannot declare an array of size greater than Int32.MaxValue (2^31, or approx. 2*10^9), so you will have to either chain arrays together or use a List<int> to hold all of the values.
Your algorithm should really be the same regardless of the array size. The best time complexity you'll get has got to be (ideally) O(n) of course.
Consider the following pseudo-code for the algorithm:
Create a HashSet<int> of capacity equal to the range of numbers in your array.
Loop over each number in the array and check if it already exists in the hashset.
if no, add it to the hashset now.
if yes, you've found a duplicate.
Memory usage here is far from trivial, but if you want speed, it will do the job.
You don't need to do anything. By definition, there will be a duplicate because 2^32 < 10^15 - there aren't enough numbers to fill a 10^15 array uniquely. :)
Now if there is an additional requirement that you know where the duplicates are... thats another story, but it wasn't in the original problem.
question,
1) is the number of items in the array 10^15
2) or can the value of the items be 10^15?
if it is #1:
where are you pulling the nummbers from? if its a file you can step through it.
are there more than 2,147,483,647 unique numbers?
if its #2:
a int64 can handle the number
if its #1 and #2:
are there more than 2,147,483,647 unique numbers?
if there are less then 2,147,483,647 unique numbers you can use a List<bigint>