Generate a two dimensional array via LINQ - linq

I am trying to create a matrix of doubles, representing a correlation between entities.
Here's how I'm doing it via LINQ
double[][] correlationsRaw = (from e in entitiesInOrder
select
(from f in entitiesInOrder
select correlations.GetCorrelation(e, f)
).ToArray()).ToArray();
That works fine.
But what I want is a two dimensional array (double[,]), not a jagged array.
Obviously, I can write some nested for loop to convert one into the other.
But is there some elegant LINQ trick I can use here?

I don't think there's an easy way of directly returning a multidimensional array from a Linq query... however you could create a function that takes a jagged array and return a multidimensional array :
public T[,] JaggedToMultidimensional<T>(T[][] jaggedArray)
{
int rows = jaggedArray.Length;
int cols = jaggedArray.Max(subArray => subArray.Length);
T[,] array = new T[rows, cols];
for(int i = 0; i < rows; i++)
{
cols = jaggedArray[i].Length;
for(int j = 0; j < cols; j++)
{
array[i, j] = jaggedArray[i][j];
}
}
return array;
}
By the way, it could be an extension method, allowing you to use it in a Linq query...

Related

Simple Sort function not working. Suggestions?

void sort_records_by_id (int []indices, int []students_id )
{
for (int k = 1; k<students_id.length; k++)
{
for (int j = k; j>0 && students_id[j]<students_id[j-1]; j--)
{
int place_holder = indices[j];
indices[j] = indices [j-1];
indices[j-1] = place_holder;
}
}
}
Hi,
I have to create a function that is able to sort an array of integers, not by changing and rearranging its contents, but by changing the order of integers in another array of integers called indexes. So, I would have an array with a series of ids such as: Lets call this id" [#] represents index [0]10001 12001 212334 [3]14332 [4]999999 [5]10111
There is a corresponding array, with integer values [#] is the index Lets call this arr [0]0 11 [2}2 [3]3 [4]4 [5]5 So that they correspond to the indexes we have in the other array.
Now, we must change the order of "arr", such that the elements are in such an order that it corresponds to the order of indexes in array id in sorted order. Note, array id is not changed in any way.
So, we can print the ids to the console in ascending order, by using a for loop, the values of arr, and array id.
Please, I would really appreciate if you would be able to provide advice without creating a very complex function. I would just like to alter my existing function I created so that it works.
This is the output of my function so far:
Any input or suggestions would be greatly appreciated.
When indexing students_id array, don't use j and j-1, but instead of this -> indices[j] and indices[j-1]. Thanks to that, you will change order in indices array using students_id array to get values to comparison.
for (int j = k; j>0 && students_id[indices[j]]<students_id[indices[j-1]]; j--)
Also I would change loop into
void sort_records_by_id (int []indices, int []students_id )
{
for (int k = 1; k<students_id.length; ++k)
{
for (int j = 0; j<k; ++j)
{
if(students_id[indices[j]]>students_id[indices[j+1]]) {
int place_holder = indices[j];
indices[j] = indices [j+1];
indices[j+1] = place_holder;
}
}
}
}
The simplest bubble sort - that's what comes to my mind.

Nested For Loops Explanation Needed

Basically, in this program, I was instructed to create an array of random numbers and then sort them smallest to largest by bubble sorting with for loops. With a bunch of trial and error, my buddy and I were able to figure it out but I just took a look back at my code and honestly, it's very hard to comprehend.. I'm not too familiar with nested loops so if someone could explain how this method is working, that would be awesome. More specifically, what does the value j and i stand for.
public void sort() {
int val = 0;
for(int i = 0; i < myArray.length; i++) {
for(int j = 1; j < (myArray.length - i); j++) {
if(myArray[j-1] > myArray[j]) {
val = myArray[j-1];
myArray[j-1] = myArray[j];
myArray[j] = val;
}
}
}
}
Any answers are greatly appreciated, thanks guys/gals!
i and j are short with no inherent meaning other than to represent the index you are at in the array. The first for loop is so that the second loop and the sorting method are repeated for as many items are in the array. The second loop does the sorting.
if(myArray[j-1] > myArray[j]) { // Checks if the index `j` in the array is less than the one before it.
val = myArray[j-1]; // Temporarily stores the greater value.
myArray[j-1] = myArray[j]; // Swap the numbers.
myArray[j] = val; // Swap the numbers.
}

The type of exp must be an array type but it resolved to double?

I'm trying to structure MATRIX class by following these instructions;
Constructors: write three constructors
Taking a list of vectors as comma separated argument list and converting these vectors from the first to the last to a matrix (Vector is another class to be explained below) and constructing a matrix from these vectors either creating them as columns or rows of the matrix determined by another parameter. (if 0 treat them as raw vectors, if 1 treat these vectors as columns of the matrix)
Taking an integer and producing an Identity matrix of dimension determined by that integer.
The following methods are invoked over a matrix object and takes another matrix or any other relevant parameter(s) as needed.
Here is my matrix class;
package p1;
public class Matrix{
public double myArray[][];
public Matrix(int b,double...vectors) {
this.myArray=vectors;
double myArray[][] = new double[vectors.length][];
int row = vectors.length;
int column = vectors[0].length;
for (int i = 0; i < row; i++) {
myArray[i] = new double[column];
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if(b==0)
{
myArray[i][j] = vectors[i][j]; // ERROR HERE
}
else
{
myArray[j][i] = vectors[i][j]; // ERROR HERE
}
}
}
}
public Matrix(int d){
double myArray[][]=new double[d][d];
}
}
I've shown the errors in my code. I cannot integrate two vectors in one 2D array to make it equal to matrix.

Slickgrid Filtering without Dataview

Is it possible to filter a Slickgrid without using the DataView?
In case it isn't possible, how should the data array be structured in order to display correctly?
I don't have a working example atm. Thanks
Later edit:
After doing some more homework, a filterable datagrid is all about getting matching indexes in a nested array... to get a live sorted result-set that gets updated with grid.setData(filterData);grid render; one should do the following
function intersect(a, b) // find an intersection of 2 arrays (google result on SO
{
var ai=0, bi=0;
var a = a.sort();
var b = b.sort();
var result = new Array();
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
// given results sets are arrays of indexes matching search criteria
a = [1,2,3,4];
b = [2,3,4,5];
c = [3,4,5,6];
d = [4,5,6,7];
// should reunite in a nested array
array = [a,b,c,d];
// check intersections for each array[k] and array[k+1]
k = array[0];
for (var i = 0; i<array.length-1; i++){
k = intersect(k,array[i+1]);
}
console.log(k) // returns 4
// k array is the index array that
// is used to build filterData[i] = data[j]
// depends if id is stored in data or in case
// of a database, it is stored in data
// tested in firebug
// thanks
Filter the underlying data array and call grid.setData(filteredData).

Most efficient way to sort parallel arrays in a restricted-feature language

The environment: I am working in a proprietary scripting language where there is no such thing as a user-defined function. I have various loops and local variables of primitive types that I can create and use.
I have two related arrays, "times" and "values". They both contain floating point values. I want to numerically sort the "times" array but have to be sure that the same operations are applied on the "values" array. What's the most efficient way I can do this without the benefit of things like recursion?
You could maintain an index table and sort the index table instead.
This way you will not have to worry about times and values being consistent.
And whenever you need a sorted value, you can lookup on the sorted index.
And if in the future you decided there was going to be a third value, the sorting code will not need any changes.
Here's a sample in C#, but it shouldn't be hard to adapt to your scripting language:
static void Main() {
var r = new Random();
// initialize random data
var index = new int[10]; // the index table
var times = new double[10]; // times
var values = new double[10]; // values
for (int i = 0; i < 10; i++) {
index[i] = i;
times[i] = r.NextDouble();
values[i] = r.NextDouble();
}
// a naive bubble sort
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
// compare time value at current index
if (times[index[i]] < times[index[j]]) {
// swap index value (times and values remain unchanged)
var temp = index[i];
index[i] = index[j];
index[j] = temp;
}
// check if the result is correct
for (int i = 0; i < 10; i++)
Console.WriteLine(times[index[i]]);
Console.ReadKey();
}
Note: I used a naive bubble sort there, watchout. In your case, an insertion sort is probably a good candidate. Since you don't want complex recursions.
Just take your favourite sorting algorithm (e.g. Quicksort or Mergesort) and use it to sort the "values" array. Whenever two values are swapped in "values", also swap the values with the same indices in the "times" array.
So basically you can take any fast sorting algorithm and modify the swap() operation so that elements in both arrays are swapped.
Take a look at the Bottom-Up mergesort at Algorithmist. It's a non-recursive way of performing a mergesort. The version presented there uses function calls, but that can be inlined easily enough.
Like martinus said, every time you change a value in one array, do the exact same thing in the parallel array.
Here's a C-like version of a stable-non-recursive mergesort that makes no function calls, and uses no recursion.
const int arrayLength = 40;
float times_array[arrayLength];
float values_array[arrayLength];
// Fill the two arrays....
// Allocate two buffers
float times_buffer[arrayLength];
float values_buffer[arrayLength];
int blockSize = 1;
while (blockSize <= arrayLength)
{
int i = 0;
while (i < arrayLength-blockSize)
{
int begin1 = i;
int end1 = begin1 + blockSize;
int begin2 = end1;
int end2 = begin2 + blockSize;
int bufferIndex = begin1;
while (begin1 < end1 && begin2 < end2)
{
if ( values_array[begin1] > times_array[begin2] )
{
times_buffer[bufferIndex] = times_array[begin2];
values_buffer[bufferIndex++] = values_array[begin2++];
}
else
{
times_buffer[bufferIndex] = times_array[begin1];
values_buffer[bufferIndex++] = values_array[begin1++];
}
}
while ( begin1 < end1 )
{
times_buffer[bufferIndex] = times_array[begin1];
values_buffer[bufferIndex++] = values_array[begin1++];
}
while ( begin2 < end2 )
{
times_buffer[bufferIndex] = times_array[begin2];
values_buffer[bufferIndex++] = values_array[begin2++];
}
for (int k = i; k < i + 2 * blockSize; ++k)
{
times_array[k] = times_buffer[k];
values_array[k] = values_buffer[k];
}
i += 2 * blockSize;
}
blockSize *= 2;
}
I wouldn't suggest writing your own sorting routine, as the sorting routines provided as part of the Java language are well optimized.
The way I'd solve this is to copy the code in the java.util.Arrays class into your own class i.e. org.mydomain.util.Arrays. And add some comments telling yourself not to use the class except when you must have the additional functionality that you're going to add. The Arrays class is quite stable so this is less, less ideal than it would seem, but it's still less than ideal. However, the methods you need to change are private, so you've no real choice.
You then want to create an interface along the lines of:
public static interface SwapHook {
void swap(int a, int b);
}
You then need to add this to the sort method you're going to use, and to every subordinate method called in the sorting procedure, which swaps elements in your primary array. You arrange for the hook to get called by your modified sorting routine, and you can then implement the SortHook interface to achieve the behaviour you want in any secondary (e.g. parallel) arrays.
HTH.

Resources