Adding ints from to string to 2D array every Nth character - c#

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;
}
}

Related

Using Modulo instead of two loops

I'm new at programming in general and learning C# right now.
I just wrote a little programm where I have to step through an int[] in a specific pattern. The pattern is as follows:
Start at the last entry of the array (int i)
form the sum of i and (if avaible) the three entrys above (e.g. i += i-1 ... i += i-3)
Change i to i -= 4 (if avaible)
Repeat from step 2 until i = 0;
Therefore i wrote the following loop:
for (int i = intArray.Length - 1; i >= 0; i -= 4)
{
for (int a = 1; a <= 3; a++)
{
if (i - a >= 0)
{
intArray[i] += intArray[i - a];
intArray[i - a] = 0;
}
}
}
Now my new assignment is to change my code to only use 1 loop with the help of modulo-operations. I do understand what modulo does, but i can't figure out how to use it to get rid of the second loop.
Maybe somebody explain it to me? Thank you very much in advance.
While iterating over the array, the idea would be to use the modulo 4 operation to calculate the next index to which you will add the current value.
This should work with any array lengths:
for (int i = 0; i < intArray.Length; i++){
// we check how far away we are from next index which stores the sum
var offset = (intArray.Length - 1 - i) % 4;
if (offset == 0) continue;
intArray[i+offset] += intArray[i];
intArray[i] = 0;
}
iterating the array reversely makes it a bit more complicated, but what you wanted to get rid of inner loop with modulo is probably this:
var intArray = Enumerable.Range(1, 15).ToArray();
for (int i = 1; i < intArray.Length - 1; i ++)
{
intArray[i - (i % 4)] += intArray[i];
intArray[i] = 0;
}

Limit the array size 2D (C# UNITY)

Hello guys is it possible to limit the array size just like this example
Now i want only to show 6 of them.
What i have done so far is this
CustomClass
const int MAX = 104; // = 8 decks * 52 cards / 4cardsoneround
const int Y = 6;
int[,] arrayRoad = new int[Y, X];
public int[,] GetRoad(int x) {
arrayRoad = new int[x, 6];
return arrayRoad;
}
Now I'm displaying it on my MainClass like this
ScoreBoard bsb = new ScoreBoard();
private void Road()
{
bsb.makeRoad(history); // Road
int[,] arrayRoad = bsb.GetRoad(6); //<--- sample value 6
string s = "";
for (int y = 0; y < arrayRoad.GetLength(0); y++)
{
//just 27 for now
for (int x = 0; x < 28; x++)
{
s += string.Format("{0:D2}",arrayRoad[y, x]);
s += ".";
}
s += "\n";
}
Debug.Log(s);
}
The problem with this code is that it's giving me an Array out of index
Is this possible??
Updated
public int[,] GetRoad(int x = MAX,int y = Y) {
arrayRoad = new int[y, x];
return arrayRoad;
}
Where in my Max = 104 and Y = 6
int[,] arrayRoad = bsb.GetRoad(12,6); //12 rows and 6 in height
string s = "";
for (int y = 0; y < arrayRoad.GetLength(0); y++)
{
for (int x = 0; x < arrayRoad.GetLength(1); x++)
{
s += string.Format("{0:D2}",arrayRoad[y, x]);
s += ".";
}
s += "\n";
}
Debug.Log(s);
}
I have all this value earlier before i perform the update code
Now when i perform the updated code here's what I got
The expected result must be this
Inside of that black marker those twelve columns only must be shown because i declared on my
int[,] arrayRoad = bsb.GetRoad(12,6);
Note this:
public int[,] GetBigEyeRoad(int x) {
arrayRoad = new int[x, 6]; // <-------------
return arrayBigEyeRoad;
There you are fixing the length of the second dimension of the array to 6.
for (int x = 0; x < 28; x++)
{
s += string.Format("{0:D2}",arrayBigEyeRoad[y, x]); // <------------
There, you are trying to access indices up to 28 on the second dimension of the array. The Out of Range error comes from that.
What I did here was copy my old array to the new one just like this code below
int[,] arrayBigRoadResult = new int[6, x];
//copy manually the element references inside array
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < x; j++)
{
arrayBigRoadResult[i, j] = arrayBigRoad[i, j];
}
}
return arrayBigRoadResult;
then by calling it just like this
int[,] arrayRoad = bsb.GetRoad(12);
It would only display 12 columns and 6 rows :)

Finding Offset using double array and list 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

move the values from a normal array to a 2D array - What's wrong with this code?

Basically I'm working on an assignment and I need to move the values from a normal array to a 2D array. I have to take input to set the length of the aray. The 2d array will be a square array, so say 3 is input my array needs to be 3x3. I've made the 1D array size n*n, with n being what the user inputs. I'm getting an index out of rage exception but I've gone through the code and written out what I think the values of everything should be at each stage and can't find out what's causing it.
public static void createTwoD(int[,] twoDArray, int[] startArray, int arrayLength)
{
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
}
The line getting the exception is the last line in that method. I'm passing in a 2D array of size [n,n], a 1D array of size [n*n] and the just n. If you want to see any more of the code let me know.
The problem is in you lines:
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
arrayLength variable makes jump out of bounds on startArray. Note that both x and i are in range from 0 to arrayLength
If you know already dimensions of your 2d array, you can easily achieve this by (here I assume it 3x3):
var x = 0;
for (int i = 0; i < arrayLength; i++) {
if(i!= 0 && i % 3 == 0) ++x; // go to another row
twoDArray[i, x] = startArray[i];
}
I would start by adding the following to the start of your method. These document your assumptions about the dimensions of the arrays passed as arguments.
Debug.Assert(twoDArray.Rank == 2);
Debug.Assert(startArray.Rank == 1);
Debug.Assert(twoDArray.GetLength(0) == arrayLength);
Debug.Assert(twoDArray.GetLength(1) == arrayLength);
Debug.Assert(startArray.GetLength(0) == arrayLength * arrayLength);
maybe twoDArray issnt initilized correctly:
public static void createTwoD(int[,] twoDArray, int[] startArray, int arrayLength)
{
//twoDArray musst be initialized correctly, otherwise use:
twoDArray = new int[arrayLength][arrayLength];
for (int x = 0; x < arrayLength; x++)
for (int i = 0; i < arrayLength; i++)
twoDArray[i, x] = startArray[i * arrayLength + x];
}

How to Save a Multidimensional Array Index?

Basically my first task was to save the position of the '0' in an integer. Real simple with a standard array. This code loops through an array (Size: 8) until it locates the 0, then save that as the position. See code below:
p.s: n is a reference to an array saved somewhere else.
int position = 0;
this.nodesExpanded++;
// Loop through the array to get the position of where '0' is
for (int i = 0; i < n.getPuzzle().length; i++){
if (n.getPuzzle()[i] == 0){
position = i;
break;
}
}
My ultimate task was to make this possible for a multidimensional array (Size: [3, 3]). So here's what I've created thus far:
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
if (n.getPuzzle()[x,y] == 0)
{
**position = ;**
break;
}
}//end y loop
}//end x loop
So how do I go about saving an array reference to a location to a value?
'position' will need to be something other than int I'm guessing..
If you need more clarification be sure to comment, sorry in advance & thank you!
You can use a Tuple to store that position. Or you can create your own data structure.
Example: at the end you can see how to access tuple items.
var positions = new List<Tuple<int, int>>();
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
if (n.getPuzzle()[x,y] == 0)
{
positions.Add(new Tuple<int, int>(x,y));
break;
}
}//end y loop
}//end x loop
if(positions.Any())
{
var xpos = positions[0].Item1;
var ypos = positions[0].Item2;
}
I find a natural way to store a multidimensional array index is to use a single dimensional array whose size is the number of dimensions.
So if you have a object[,,] A and index int[] i you would index into A with the expression A[i[0],i[1],i[2]].
It works the same way as your one-dimensional array, but you have two position values to keep. I've used ints for the example, but you may want to use a custom structure or Tuple (as AD.Net) said.
int xpos = -1;
int ypos = -1;
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
if (n.getPuzzle()[x,y] == 0)
{
xpos = x;
ypos = y;
break;
}
}//end y loop
}//end x loop
if (!(xpos > -1 && ypos > -1)) ; // 0 was not found

Categories