I am looping through an array of strings, such as (1/12/1992 apple truck 12/10/10 orange bicycle). The array's length will always be divisible by 3. I need to loop through the array and grab the first 3 items (I'm going to insert them into a DB) and then grab the next 3 and so on and so forth until all of them have been gone through.
//iterate the array
for (int i = 0; i < theData.Length; i++)
{
//grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
}
Just increment i by 3 in each step:
Debug.Assert((theData.Length % 3) == 0); // 'theData' will always be divisible by 3
for (int i = 0; i < theData.Length; i += 3)
{
//grab 3 items at a time and do db insert,
// continue until all items are gone..
string item1 = theData[i+0];
string item2 = theData[i+1];
string item3 = theData[i+2];
// use the items
}
To answer some comments, it is a given that theData.Length is a multiple of 3 so there is no need to check for theData.Length-2 as an upperbound. That would only mask errors in the preconditions.
i++ is the standard use of a loop, but not the only way. Try incrementing by 3 each time:
for (int i = 0; i < theData.Length - 2; i+=3)
{
// use theData[i], theData[i+1], theData[i+2]
}
Not too difficult. Just increment the counter of the for loop by 3 each iteration and then offset the indexer to get the batch of 3 at a time:
for(int i=0; i < theData.Length; i+=3)
{
var item1 = theData[i];
var item2 = theData[i+1];
var item3 = theData[i+2];
}
If the length of the array wasn't garuanteed to be a multiple of three, you would need to check the upper bound with theData.Length - 2 instead.
Your for loop doesn't need to just add one. You can loop by three.
for(int i = 0; i < theData.Length; i+=3)
{
string value1 = theData[i];
string value2 = theData[i+1];
string value3 = theData[i+2];
}
Basically, you are just using indexes to grab the values in your array. One point to note here, I am not checking to see if you go past the end of your array. Make sure you are doing bounds checking!
This should work:
//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
//grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
var a = theData[i];
var b = theData[i + 1];
var c = theData[i + 2];
}
I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.
Here is a more general solution:
int increment = 3;
for(int i = 0; i < theData.Length; i += increment)
{
for(int j = 0; j < increment; j++)
{
if(i+j < theData.Length) {
//theData[i + j] for the current index
}
}
}
string[] friends = new string[4];
friends[0]= "ali";
friends[1]= "Mike";
friends[2]= "jan";
friends[3]= "hamid";
for (int i = 0; i < friends.Length; i++)
{
Console.WriteLine(friends[i]);
}Console.ReadLine();
Related
I have set up a spreadsheet program with a 26 by 26 grid of cell objects. I set up a method which processes a formula entered by the user. The user can enter, for example, =A1+A2 and the method checks the values of cells A1 and A2 and adds them together. For some reason, the value of the second cell is not being assigned to the array.
https://pasteboard.co/IqRO23M.png
The code continues the switch case statement for other operators but that's not important for this problem.
public static void ProcessBasicFormula(Cell selectedCell,Cell[,]
cell,string[] cellsInUse, char operatorInUse)
{
int[] valueOfCell = new int[cellsInUse.Length]; //valueOfCell and
cellInUse have same length
int counter = 0;
double answer = 0.0;
switch(operatorInUse)
{
case ('+'):
for (int i = 0; i < cellsInUse.Length; i++)
{
for (int j = 0; j < cellsInUse.GetLength(0); j++)
{
for (int k = 0; k < cellsInUse.GetLength(0); k++)
{
if (cellsInUse[i] == cell[j, k].CellID)
{
valueOfCell[counter] =Convert.ToInt32(cell[j,k].Text);
counter++;
}
}
}
}
answer = valueOfCell[0] + valueOfCell[1];
break;
I expect the values of the two cells to be added together but instead, I am getting the first value added by 0.
my assumptions are:
the cellsInUse array length is accurate
List item the cell value at index 1 is not zero
the new int[int] will initialize the array to zeros;
int[] valueOfCell = new int[cellsInUse.Length];
cellsInUse is one dimensional array;
string[] cellsInUse
the getLength(0) of one dimensional array is the same as .length
cellsInUse.length == 2 is true;
cellsInUse.GetLength(0) == 2 is true;
so the j and k loops are looping to 2.
I am assuming the first cell value was lucky enough to be in first subset of [2,2] cells.
should the cellsInUse.GetLength(0) be cell.GetLength(0) => j and cell.GetLength(1) => k
This thing that I'm writing should do the following: get as an input a number, then, that many kids' names, and that many grades. Then, assign each kid a number of coins, so that if their grade is bigger, than their neighbor's, they get more coins and vice versa. What I wrote is this:
string input = Console.ReadLine();
int n = Convert.ToInt32(input);
int i = 0;
string[] names = new string[n];
for (i = 0; i < n; i++)
{
names[i] = Console.ReadLine();
}
string[] gradeText = new string[n];
int[] grades = new int[n];
for (i = 0; i < n; i++)
{
gradeText[i] = Console.ReadLine();
grades[i] = Convert.ToInt32(gradeText[i]);
}
int[] minCoins = { 1, 2, 3 };
int[] coinArray = new int[n];
for (i = 1; i < n - 2; i++)
{
if (grades[0] > grades[1])
{
coinArray[0] = 3;
}
else
{
coinArray[0] = 1;
}
if (grades[i] > grades[i + 1] && grades[i] > grades[i - 1])
{
coinArray[i] = 3;
}
if (grades[i] > grades[i + 1] || grades[i] > grades[i - 1])
{
coinArray[i] = 2;
}
if (grades[i] < grades[i + 1] && grades[i] < grades[i - 1])
{
coinArray[i] = 1;
}
if (grades[n - 1] > grades[n - 2])
{
coinArray[n - 1] = 3;
}
else
{ coinArray[n - 1] = 1; }
}
for (i = 0; i < n; i++)
{
Console.WriteLine(names[i] + " " + coinArray[i]);
}
I know my loop is hella messed up, but any tips on how to fix it would be kindly appreciated!
Others here have already suggested how to deal with index out of bounds issues. So this is slight different approach to solving your problem.
It is very easy to see this as one problem and then try to resolve it all in one place but that isn't always the best solution.
Your for loop is trying to do quite a lot. Each iteration could have many checks to make. In addition you are making checks you have previously made.
Do I have a neighbour to the left.
Do I have a neighbour to the right.
Did I get a better grade than both neighbours.
Did I get a better grade than one neighbour.
Did I lose to both neighbours.
My advice would be to break this down into two separate tasks.
1, To calculate how many neighbours each person got a higher grade than.
string[] names = new string[]{"John", "Paul", "Ringo", "George"};
int[] grades = new[] {3, 4, 3,2};
int[] winnersandloser = new int[4];
for (int i = 1; i < grades.Length; i++) //note starting at position 1 so I dont need to handle index out of bounds inside the for loop
{
if (grades[i] > grades[i - 1])
{
winnersandloser[i]++;
}
else
{
winnersandloser[i - 1]++;
}
}
In the above code you should have an array with these values: {0,2,1,0}
0 = you lost to both neighbours
1 = you beat one neighbour
2 = well done you beat both neighbours
Then using this winnersandlosers array you can calculate how many coins to give each person. I'll leave that for you to do.
Update
If you require different behaviour for the first and last in the list of people you need to add the logic to your code for allocating coins.
An array gives each value and index value, starting from 0. So 0 points to the first value in you array. George is the 4th entry in the array but as the array index starts with 0 the index value is 3, you also get this from arrayname.Length - 1
So now when looping through the array to allocate coins we can add a check for the first and last positions in the array.
//allocating coins
for (int i = 0; i < winnersandloser.Length; i++)
{
if (i == 0 || i == winnersandloser.Length - 1)
{
//allocating rules for first and last
}
else
{
//allocating rules for everyone else
}
}
One common way to approach this kind of issue is to oversize your array by as many elements as you need to look ahead/look behind. Place you real elements in the "middle"1 of this array and suitable dummy values into the elements at the start/end that don't correspond to real entries. You pick the dummy values such that the comparisons work out how you need them to (e.g. often you'll put int.MinValue in the dummy elements at the start and int.MaxValue in the dummy elements at the end).
You then just enumerate the real elements in the array, but all of your computed look aheads/look behinds still correspond to valid indexes in the array.
1Sometimes you'll have uneven look ahead/look behind requirements so it may not be the true middle. E.g. say you need to be able to look behind one element and ahead 3 elements, and you want to process 20 elements. You then create an array containing 24 entries, put dummy values at index 0, 21, 22 and 23, and populate your real elements into indexes 1 - 20.
I have an array of velocity and I want to get an array of displacement.
To get displacement for each n,i need add speed[] from 0 to n,
So I'm trying to add first n numbers for each n in array speed[],n is the index of array start from 0.
for (i = 0; i < totalnumber; i++)
{
for (int k = 0; k < i; k++)
{
Xdis[i] += Xvelo[k];
Ydis[i] += Yvelo[k];
Zdis[i] += Zvelo[k];
}
}
the loop above works,but the problem is it takes too long(loop in loop)
my question is, is there any sum function in C# can handle this without use for loop?
like Xdis[i]=Xvelo.sum(i) or sth?
Why don't you use the results you already calculated? Instead of re-summing all the way up, just use the previous result:
for (i = 1; i < totalnumber; i++)
{
Xdis[i] = XDis[i-1] + Xvelo[i-1];
Ydis[i] = YDis[i-1] + Yvelo[i-1];
Zdis[i] = ZDis[i-1] + Zvelo[i-1];
}
I have this for loop. TicketList starts with 109 tickets. nColumns = 100. I calculate the number of rows I will need depending on the number of tickets. So in this case I need 2 rows. Row one will be full and row two will only have 9 entries. I have the loop below. It only runs one time for the NumOfRows and fills the first 100 and never loops.
What am I missing?
for (int j = 0; j < NumOfRows; j++)
{
for (int i = 0; i < nColumns; i++)
{
if (TicketList.Count() > 0)
{
t = rand.Next(0, TicketList.Count() - 1);
numbers[i, j] = TicketList[t];
TicketList.Remove(TicketList[t]);
}
}
}
Try changing your code to use a more LINQ-like, functional approach. If might make the logic easier. Something like this:
TicketList
.OrderBy(x => rand.Next())
.Select((ticket, n) => new
{
ticket,
j = n / NumOfRows,
i = n % NumOfRows
})
.ToList()
.ForEach(x =>
{
numbers[x.i, x.j] = x.ticket;
});
You may need to flip around x.i & x.j or use nColumns instead of NumOfRows - I wasn't sure what your logic was looking for - but this code might work better.
Other than a few poor choices, your loops appear to be fine. I would venture that NumOfRows is not being calculated correctly.
The expression NumOfRows = (TotalTickets + (Columns - 1)) / Columns; should calculate the correct number of rows.
Also, you should use the property version of Count rather than the Linq extension method and use IList<T>.RemoveAt() or List<T>.RemoveAt rather than Remove(TicketList[T]).
Using Remove() requires that the list be enumerated to locate the element to remove, which may not be the same index that you are targeting. Not to mention that you will scan 50% (on average) of the list for each Remove call, when you already know the correct index to remove.
The functional approach listed earlier seems like overkill.
I've attempted to replicate your issue, assuming certain facts about the various variables in use. The loop repeats the expected number of times.
static void TestMe ()
{
List<object> TicketList = new List<object>();
for (int index = 0; index < 109; index++)
TicketList.Add(new object());
var rand = new Random();
int nColumns = 100;
int NumOfRows = (TicketList.Count + (nColumns - 1)) / nColumns;
object[,] numbers;
int t;
numbers = new object[nColumns, NumOfRows];
for (int j = 0; j < NumOfRows; j++)
{
Console.WriteLine("OuterLoop");
for (int i = 0; i < nColumns; i++)
{
if (TicketList.Count > 0)
{
t = rand.Next(0, TicketList.Count - 1);
numbers[i, j] = TicketList[t];
TicketList.RemoveAt(t);
}
}
}
}
The problem that you are seeing must be the result of something that you have not included in your sample.
I am trying to add two lists in a loop by adding first index value of one list to the first index value of another list but both list are populating at run time after calculation issue is that how to track that list<> posses value at that index or not as shown below ,
Result[var]=first[var]+second[var]
complete code is give below,
List<double> Result = new List<double>();
for (int var = 0; var < 30; var++)
{
if (first[var] == null)
{
first[var] = 0;
}
if (second[var] == null)
{
second[var] = 0;
}
}
Result[var]=first[var]+second[var];
}
we do are not sure that both list may have value up to 10,15 .. index but i need if list one have 15 values and list two have 10 values then add two list in this way ,
A list[0]+B list[0]=
A list[1]+B list[1]=
A list[2]+B list[2]=
if it add
A list[11]+B list[11]=
then it add 0 from second list because it has only 10 values then how to validate b list[11] and use 0 if index 11 not exist in second list
one more thing list can have upto 30 values maximum not more then 30
You may need something like this (assuming that first and second are List):
List<double> Result = new List<double>();
for (int i = 0; i < 30; i++)
{
double firstVal = 0;
double secondVal = 0;
if (first.Count > i)
{
firstVal = first[i];
}
if (second.Count > i)
{
secondVal = second[i];
}
Result.Add(firstVal + secondVal);
}
If I understood correctly, you are trying to add two list values into another list. If one of the list is ended, consider the value as zero and continue till max available limit of either of the lists.
If so,
// assume i1, i2 are sources and i3 is result
int max = i1.Count>i2.Count?i1.Count:i2.Count;
for (int i = 0; i < max; i++)
{
i3[i] = (i1.Count > i ? i1[i] : 0) + (i2.Count > i ? i2[i] : 0);
}
// another varient:
for (int i = 0; i < i1.Count; i++)
{
i3[i] = i1[i] + (i2.Count > i ? i2[i] : 0);
}
for (int i = i1.Count; i < i2.Count; i++)
{
i3[i] = i2[i];
}