keep 10% of an array?
hey! i have this huge list of arrays:
in my
public Vector3[] paths;
but i wanna kick out some of them. so that i keep 10% of that. how can i do this? i thought i can use a % operator (https://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx) like this:
optimizedpoints = new Vector3[paths.Length%10];
int j = 0;
for (int i = 0; i < paths.Length; i%=10) {
optimizedpoints[j] = paths[i];
j++;
}
but that seams to be wrong somehow? do someone know why?
i is not incremented at all and stays 0. the % works different than you expect. it gives you the rest of a division, so creating an array with length 100 % 10 gives you 0, because it works out evenly. you should initialize the array with $$anonymous$$atf.Round(Lenght * .9f) and run the for loop with I < that value and i++
The problem is you're trying to use modulo like it's magic, when it's really just a normal math operation.
Suppose you have 300 things in the array. 1/10th of that is 30. What math equation, that you already know, will turn 300 into 30? In the loop, if you start at 0 then want to go to 10, then 20 then 30; what math equation will turn 10 into 20, then turn 20 into 30, and so on?
Answer by spraw · Nov 14, 2016 at 05:00 PM
I used your code as the base:
void CreateNewArray()
{
int nStep = 10;
optimizedArray = new Vector3[originalArray.Length / nStep + 1];
int j = 0;
for (int i = 0; i < originalArray.Length; i += nStep)
{
optimizedArray[j] = originalArray[i];
j++;
}
}
I wouldn't do it like this, personally. I would just use Lists, so much more convenient. Like so:
void WithoutLinq()
{
int nStep = 10;
List<Vector3> optimizedList = new List<Vector3>();
for (int i = 0; i < originalArray.Length; i += nStep)
{
optimizedList.Add(originalArray[i]);
}
}
Or
void WithLinq()
{
//using System.Linq at the top of the class
int nStep = 10;
List<Vector3> optimizedList = originalArray.ToList().Where((x, i) => i % nStep == 0).ToList();
}
Your answer
Follow this Question
Related Questions
Percentage sign 2 Answers
Is it possible to use . Operator to access variables in classes in lists 1 Answer
Why does unity subtract ammunition per frame? 1 Answer
And/Or Operator C# 2 Answers