Finding Offset using double array and list C# - c#

Im trying to find the offset(difference between the array elements) of an array of double..The formula for my offset calculation is Offset= ((double[x+1]-double[x])*33)..
The problem I encounter is I cant seem to display the offsetX. What am I doing wrong here ?
Is there an easier way to do this ?
Here are my codes :
//double[] test is an infinite array containing double values that are passed from the Client to Server via UDP
//example : double[] test={1.11,2.344,3.45,4.54,....,......,....}
//Partial codes on the Server side to calculate and display offset
List<double> array = new List<double>();
//Im trying to store just the elements of postion 0,3,6..from the double []test into list array
//ignore array1[] and array2[]
for (int j = 0; j < test.Length;)
{
array.Add(test[j]); j++;
array1.Add(test[j]); j++;
array2.Add(test[j]); j++;
}
double[] gg = array.ToArray();
//Finding the offset
for (int i = 0, j = 1; i < gg.Length - 1; i++, j++)
{
offsetX.Add(gg[j] - gg[i]);
offsetX[i] = Math.Round(offsetX[i], 1);
offsetX[i] = (offsetX[i] * 33);
}
Console.Write( "OffsetX:" + string.Join(",", offsetX) +"/n");

The method below just iterates over the arrays adding the offsets during the initial iteration of the list
List<double> array = new List<double>() { 1.11,2.344,3.45,4.54 };
var offsets = new List<double>();
for (int i = 1; i < array.Count; i++)
offsets.Add(array[i] - array[i-1]);
This results in the offsets of:
Offsets: 1.234,1.106,1.09

Related

Adding ints from to string to 2D array every Nth character

What I am trying to do here is populate a 2d array from a text file. For sake of simplicity, I will keep this short and show you my problem. I have this following string:
string numbers = "11121314151617181920";
I would like to add this to an array every 2 Chars, so the array would appear and output:
11,12,13,14,15,16,17,18,19,20
I have gone about this using the Substring method available in c#. This is my code:
int[,] numArray = new int[1, 10];
for (int x = 0; x < 10; x++)
{
while (i != 20)
{
numArray[0, x] = int.Parse(numbers.Substring(i, 2));
i += 2;
}
}
Edit: The output of this code gives me:
20000000000
My desired output is:
11,12,13,214,15,16,17,18,19,20
Solved it! I had the for loop in the wrong spot:
while (i != 20)
{
for (int x = 0; x < 10; x++)
{
numArray[0, x] = int.Parse(numbers.Substring(i, 2));
i += 2;
}
}

Reverse int array return wrong element

Here is a simple method in C# to reverse the element of the array. For instance, if I input {1,2,3,4} the result should be {4,3,2,1}.
public int[] reverse(int[] array)
{
int[] new_array = new int[array.Length];
for (int i = 0; i < array.Length-1; i++)
{
new_array[i] = array[array.Length-1 - i];
}
return new_array;
}
However, when I run it and give an input as {1,2,3,4}, it result in {4,3,2,0}, why does the last element become 0 instead of 1?
Issue exists here for (int i = 0; i < array.Length-1; i++).
You have to use <= if you are comparing it with Length-1 or use < sign with Length
Try this code.
public int[] reverse(int[] array)
{
int[] new_array = new int[array.Length];
for (int i = 0; i < array.Length; i++)
{
new_array[i] = array[array.Length-1 - i];
}
return new_array;
}
The problem you are having is that you are checking the array length and subtracting one.
for (int i = 0; i < array.Length - 1; i++)
This says if I is less than the length of your array minus one. There for you will never check the last element in your array.
This may be slightly easier to understand. I am basically running my for loop backwards and keeping a counter for both the new array and the original one.
var array = new int[] { 1, 2, 3, 4 };
int[] new_array = new int[array.Length];
for (int i = array.Length -1, n=0 ; i >= 0 ; i--,n++)
{
new_array[n] = array[i];
}
you can use Linq Instead of Writing Too many lines of code
Using
using System.Linq;
To Reverse Array
var reverse = array.Reverse();
Or
int[] reverse = array.Reverse().ToArray();
You don't need array.Length-1 because this will go beyond the index of array so only array.Length is enough.
int[] array = new int[4] { 4, 3, 2, 1 };
int[] new_array = new int[array.Length];
for (int i = 0; i< array.Length; i++)
{
new_array[i] = array[(array.Length - 1) - i];
}
Try this:
for (int i = array.Length - 1,j=0; i >= 0; i--,j++)
{
new_array[j] = array[i];
}

How to build a large 2d array out of many smaller 2d arrays

I am trying to work towards a
512 x 512 (262144 elements)
I currently have a
List<double[,]> data;
Dimensions are:
4096 x [8 , 8] (262144 elements)
The 2d array I am working towards is square.
List<List<float>> newList = new List<List<float>(); //working towards
I have tried something along the lines of:
for (int i = 0; i < Math.Sqrt(data.Count); i++ ) {
List<float> row = new List<float>();
foreach (double[,] block in data) {
for (int j = 0; j < 8; j++) {
row.Add(block[i,j]); //i clearly out of range
}
}
newList.Add(row);
}
What I was trying to do there was to brute force my way and add up every row (which is 8 in length) and then add the large rows to the newList.
I believe you can do that in the following way
var newList = new List<List<float>>();
for (int i = 0; i < 512; i++)
{
var innerList = new List<float>();
for (int j = 0; j < 512; j++)
{
int x =(i/8)*64 + (j/8);
int y = i % 8;
int z = j % 8;
innerList.Add(data[x][y,z]);
}
newList.Add(innerList);
}
Basically you have 64x64 of your 8x8 blocks. So the (i,j) coordinate of the larger 512x512 structure translate in the following ways. First to determine the 8x8 block you have to figure out the row and column of the 64x64 structure of blocks by dividing the i and j by the size of the block (8) then you multiply the row (i/8) by the number of block in a row (64) and add the column (j/8). For the y and z it's simpler because you know that its just a matter of the remainder of i and j when divided by 8 (i%8) and (j%8).

C# Resorting an array in a unique way

I am wanting to create multiple arrays of ints(in C#). However they all must have a unique number in the index, which no other array has that number in that index. So let me try show you what I mean:
int[] ints_array = new int[30];
for (int i = 0; i < ints_array.Count(); i++)
ints_array[i] = i;
//create a int array with 30 elems with each value increment by 1
List<int[]> arrayList = new List<int[]>();
for(int i = 0; i < ints_array.Count(); i++)
arrayList.Add(ints_array[i]. //somehow sort the array here randomly so it will be unique
So I am trying to get the arrayList have 30 int[] arrays and each is sorted so no array has the same int in the same index as another.
Example:
arrayList[0] = {5,2,3,4,1,6,7,8,20,21... etc }
arrayList[1] = {1,0,5,2,9,10,29,15,29... etc }
arrayList[2] = {0,28,4,7,29,23,22,17... etc }
So would this possible to sort the array in this unique kind of way? If you need anymore information just ask and ill fill you in :)
Wouldn't it be easier to create the arrays iteratively using an offset pattern?
What I mean is that if you created the first array using 1-30 where 1 is at index 0, the next array could repeat this using 2-30 where 2 is at index 0 and then wrap back to 1 and start counting forward again as soon as you go past 30. It would be an easy and repeatable way to make sure no array shared the same value/index pair.
You can do it like that:
List<int[]> arrayList = new List<int[]>();
Random rnd = new Random();
for (int i = 0; i < ints_array.Length; i++)
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
var isDuplicate = arrayList.Any(x => x.SequenceEqual(ints_array));
if (isDuplicate)
{
while (arrayList.Any(x => x.SequenceEqual(ints_array)))
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
}
}
arrayList.Add(ints_array);
}
I think, this wouldn't be so efficient for bigger numbers than 30.But in this case it shouldn't be a problem, in my machine it takes 7 milliseconds.
Jesse's idea would be best unless you needed a pure random pattern. In that case I would recommend generating a random number, checking all your previous arrays, and then placing it in an array if it did not match any other arrays current index. Otherwise, generate a new random number until you find a fresh one. Put that into a loop until all your arrays are filled.
Use a matrix (2D-array). It is easier to handle than a list of arrays. Create a random number generator. Make sure to initialize it only once, otherwise random number generator may create bad random numbers, if created in too short time intervals, since the slow PC-clock might not have ticked in between. (The actual time is used as seed value).
private static Random random = new Random();
Create two helper arrays with shuffeled indexes for rows and columns:
const int N = 30;
int[] col = CreateUniqueShuffledValues(N);
int[] row = CreateUniqueShuffledValues(N);
Then create and initialize the matrix by using the shuffeled row and column indexes:
// Create matrix
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[row[i], col[j]] = (i + j) % N;
}
}
The code uses these two helper methods:
private static int[] CreateUniqueShuffledValues(int n)
{
// Create and initialize array with indexes.
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
// Shuffel array using one variant of Fisher–Yates shuffle
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm
for (int i = 0; i < n; i++) {
int j = random.Next(i, n);
Swap(array, i, j);
}
return array;
}
private static void Swap(int[] array, int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
int size = 10;
// generate table (no duplicates in rows, no duplicates in columns)
// 0 1 2
// 1 2 0
// 2 0 1
int[,] table = new int[size, size];
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
table[y, x] = (y + x) % size;
// shuffle rows
Random rnd = new Random();
for (int i = 0; i < size; i++)
{
int y1 = rnd.Next(0, size);
int y2 = rnd.Next(0, size);
for (int x = 0; x < size; x++)
{
int tmp = table[y1, x];
table[y1, x] = table[y2, x];
table[y2, x] = tmp;
}
}
// shuffle columns
for (int i = 0; i < size; i++)
{
int x1 = rnd.Next(0, size);
int x2 = rnd.Next(0, size);
for (int y = 0; y < size; y++)
{
int tmp = table[y, x1];
table[y, x1] = table[y, x2];
table[y, x2] = tmp;
}
}
// sample output
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
Console.Write("{0} ", table[y, x]);
Console.WriteLine();
}

filling multidimensional array with unique numbers in C#

I'm trying to write a code that will fill array with unique numbers.
I could write the code separately for 1, 2 and 3 dimensional arrays but number of for cycles grow to "infinity".
this is the code for 2D array:
static void fillArray(int[,] array)
{
Random rand = new Random();
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = rand.Next(1, 100);
for (int k = 0; k < j; k++)
if (array[i, k] == array[i, j])
j--;
}
}
print_info(array);
}
Is it possible to do something like this for n-dimensional arrays?
My approach is to start with a 1-d array of unique numbers, which you can shuffle, and then slot into appropriate places in your real array.
Here is the main function:
private static void Initialize(Array array)
{
var rank = array.Rank;
var dimensionLengths = new List<int>();
var totalSize = 1;
int[] arrayIndices = new int[rank];
for (var dimension = 0; dimension < rank; dimension++)
{
var upperBound = array.GetLength(dimension);
dimensionLengths.Add(upperBound);
totalSize *= upperBound;
}
var singleArray = new int[totalSize];
for (int i = 0; i < totalSize; i++) singleArray[i] = i;
singleArray = Shuffle(singleArray);
for (var i = 0; i < singleArray.Length; i++)
{
var remainingIndex = i;
for (var dimension = array.Rank - 1; dimension >= 0; dimension--)
{
arrayIndices[dimension] = remainingIndex%dimensionLengths[dimension];
remainingIndex /= dimensionLengths[dimension];
}
// Now, set the appropriate cell in your real array:
array.SetValue(singleArray[i], arrayIndices);
}
}
The key in this example is the array.SetValue(value, params int[] indices) function. By building up the correct list of indices, you can use this function to set an arbitrary cell in your array.
Here is the Shuffle function:
private static int[] Shuffle(int[] singleArray)
{
var random = new Random();
for (int i = singleArray.Length; i > 1; i--)
{
// Pick random element to swap.
int j = random.Next(i); // 0 <= j <= i-1
// Swap.
int tmp = singleArray[j];
singleArray[j] = singleArray[i - 1];
singleArray[i - 1] = tmp;
}
return singleArray;
}
And finally a demonstration of it in use:
var array1 = new int[2,3,5];
Initialize(array1);
var array2 = new int[2,2,3,4];
Initialize(array2);
My strategy assigns sequential numbers to the original 1-d array to ensure uniqueness, but you can adopt a different strategy for this as you see fit.
You can use Rank property to get the total number of dimentions in your array
To insert use SetValue method
In the first two for loops you are analysing the array properly (i and j go from the start to the end of the corresponding dimension). The problem comes in the most internal part where you introduce a "correction" which actually provokes an endless loop for j.
First iteration:
- First loop: i = 0;
- Second loop: j = 0;
- Third loop: j = -1
Second iteration
- First loop: i = 0;
- Second loop: j = 0;
- Third loop: j = -1
. etc., etc.
(I start my analysis in the moment when the internal loop is used for the first time. Also bear in mind that the exact behaviour cannot be predicted as far as random numbers are involved. But the idea is that you are making the j counter back over and over by following an arbitrary rule).
What you want to accomplish exactly? What is this last correction (the one provoking the endless loop) meant to do?
If the only thing you intend to do is checking the previously stored values, you have to rely on a different variable (j2, for example) which will not affect any of the loops above:
int j2 = j;
for (int k = 0; k < j2; k++)
if (array[i, k] == array[i, j2])
j2--;

Categories