Arduino - For Loop with Array not working - arduino

I have a problem with for loops and an array in Arduino IDE.
test1 does not work
test2 does work
test3 does work
How can I get test1 to work?
void test1(){
for(int i=1; i<5; i++) {
individualPixels[i]==1;
}
}
void test2(){
individualPixels[1]=1;
individualPixels[2]=1;
individualPixels[3]=1;
individualPixels[4]=1;
}
}
void test3(){
for(int i=1; i<5; i++) {
Serial.println(individualPixels[i]); //prints out 0 4 times
}
}

You're not actually assigning anything in test1, you're testing
for equality (individualPixels[i]==1 should be individualPixels[i] = 1, note the single equality sign).
Also, as other commenters mentioned, C/C++ uses zero based indexing.

C/C++ uses zero indexed arrays, so your for loops in test1 and test3 should look like this:
for(int i=0; i<4; i++) {
individualPixels[i]==1;
}
Test2 has an unmatched bracket and the array indexes should start at zero:
void test2(){
individualPixels[0]=1;
individualPixels[1]=1;
individualPixels[2]=1;
individualPixels[3]=1;
//} this shouldn't be here
}

The for loops start with i = 1 that should be 0 as an element in an array can be accessed with an index from 0 to size-1. An array with 4 elements can be accessed as follows:
array[0] --- first element
array[1] --- second element
array[2] --- third element
array[3] --- fourth element
Apart from that, the first for loop (that doesn't work) used the == operator, which checks if two variables are equal and then returns a boolean as a result. Instead you should use a single = that will set the value.
The second test has an extra } ,which should be removed
I suggest you to start actually learning programming, for example by reading a (e)book, as you will teach yourself bad habits (accessing arrays in a wrong way), which may work, but may not be efficient.

Thanks very much to all of you.
I have a large array with 60 indexes and want to set some of them 1 with a for loop. The "==" was the main problem. It's working now like I want it to:
void test1(){
for(int i=1; i<5; i++) {
individualPixels[i]=1;
}
}
void test2(){
individualPixels[1]=1;
individualPixels[2]=1;
individualPixels[3]=1;
individualPixels[4]=1;
}
void test3(){
for(int i=1; i<5; i++) {
Serial.println(individualPixels[i]); //prints out 0 4 times
}
}

Related

Exception in thread "main" java.lang.StackOverflowError at Solution.recur(File.java:58)

class Solution{
ArrayList subsetSums(ArrayList arr, int N){
int sum=0;
ArrayList<Integer> temparr = new ArrayList<>();
for(int i=1;i<=arr.size();i++)
{
for(int j = 0; i < arr.size()-i+1 ; j++)
temparr.add(recur(arr,i,j,sum));
}
return temparr;
}
int recur(ArrayList<Integer> arr,int i,int j,int sum)
{
int index = j;
int len = i;
int Sum = sum;
if(len==0)
{
return Sum;
}
Sum += arr.get(index);
return recur(arr,len--,index++,Sum);
}
}
,,,
I'm getting stack overflow error in 'return recur(arr,len--,index++,Sum);'
'''
I think, the main problem here (see comments for potential other problems) is the way you are trying to pass changed arguments to the recursive invocation:
recur(arr,len--,index++,Sum)
Actually this will call recur with the unchanged values of len and index because the operators ++ and -- (when written on the right side of a variable) are defined to return the original value of the variable and then update the variable's value.
Use (I would prefer this)
recur(arr, len-1, index+1, Sum)
or (okay, but the assignment is not needed)
recur(arr, --len, ++index, Sum)
to actually pass the modified value to the function.
Java has a recursion limit. The way to fix this is replace the recursion with a loop. (Or change the function so it does not recur as much. Infinite loops are a problem just as infinite recursion is).
A few tips for the future:
Google the documentation for errors
State the language with a tag in posts
Don't use formatting of line 1
Debug with print statements

Random Values from a variable set of entries in a vector

i have a problem which is the following:
i have for example 4 objects. One object is randomly selected to do a certain action. E.g. if object 1 does an action, the other 3 objects do nothing.
So, i have a vector of these objects.
vector{object1,object2, object3, object4}
In the beginning, i can easily randomly select one object with vector[random].
And here comes the problem: An object can also "die" meaning the object should not be part of the random-step anymore.
For example, if object2 dies, if want to random between 1,3,4 and let the 2 out.
Is this possible somehow? (using C++)
Thanks!
I was just under the shower and thought about it.. i think i found a workaround for this. Pseudo-Code:
vector<figure> all_figure_types;
vector<figure> all_figure_types_alive;
for (int i = 0; i < 5; i++) {
all_figure_types.push_back(generate_random_number(1,10));
}
all_figure_types_alive.clear();
for (int i = 0; i < all_figure_types.size(); i++) {
if (all_figure_types[i].is_alive) {
all_figure_types_alive.push_back(all_figure_types[i]);
}
}
int start = 0;
int end = all_figure_types_alive.size();
int random_num = generate_random_number(start, end);
int object_type = all_figure_types_alive[random_num].type;
If there is a nicer version without resetting this helping-construct all_figure_types_alive, let me know would be nice to hear!

Appending to / removing elements from vector while iterating over said vector [duplicate]

What is the idiomatic way to iterate (read) over the first half of the vector and change the structure of the second half of the vector depending on the first? This is very abstract but some algorithms could be boiled down to this problem. I want to write this simplified C++ example in Rust:
for (var i = 0; i < vec.length; i++) {
for (var j = i + 1 ; j < vec.length; j++) {
if (f(vec[i], vec[j])) {
vec.splice(j, 1);
j--;
}
}
}
An idiomatic solution of this generic problem will be the same for Rust and C, as there's no constraints which would allow simplification.
We need to use indexes because vector reallocation will invalidate the references contained by the iterators. We need to compare the index against the current length of the vector on each cycle because the length could be changed. Thus an idiomatic solution will look like this:
let mut i = 0;
while i < v.len() {
let mut j = i + 1;
while j < v.len() {
if f(v[i], v[j]) {
v.splice(j, 1);
} else {
j += 1;
}
}
i += 1;
}
Playground link
While this code covers the general case, it is rarely useful. It doesn't capture specifics, which are usually inherent to the problem at hand. In turn, the compiler is unable to catch any errors at compile time. I don't advise writing something like this without considering another approaches first.

Arduino - Writing int array with for loop doesn't work

I am a college student so I'm still learning a lot. I ran into something interesting while making a project. I have this segment of code that works when it isn't placed in a for loop, but doesn't work when it is. I just want to understand why. Here is my code:
void setup() {
Serial.begin(9600);
int a[8];
for(int i=0;i<8;i++) {
a[i]=pow(2,i);
}
for(int i=0;i<8;i++) {
Serial.print(a[i]);
}
}
void loop() {
}
Here is the same code written without the first for loop (where the data gets written into the array):
void setup() {
Serial.begin(9600);
int a[8];
a[0]=pow(2,0);
a[1]=pow(2,1);
a[2]=pow(2,2);
a[3]=pow(2,3);
a[4]=pow(2,4);
a[5]=pow(2,5);
a[6]=pow(2,6);
a[7]=pow(2,7);
for(int i=0;i<8;i++) {
Serial.print(a[i]);
}
}
void loop() {
}
The first code outputs:
1
2
3
7
15
31
63
127
While the second code outputs:
1
2
4
8
16
32
64
128
Does anybody know? I really want to know why.
You are experiencing floating point round off. 2^4 will actually give you a value closer to 15.9999 and when this is assigned to an int, it truncates the decimal to 15. I would suggest doing bit shift operations when using powers of 2, such that:
for(int i=0;i<8;i++)
{
a[i]=(1 << i);
}
If you want to read up on bit shifting, look here.
If you want to know more about the floating point round off, look here.
Additionally if you wanted just a quick fix to your code closer to what you have, I believe this will also work:
for(int i=0;i<8;i++)
{
a[i]= (int) round( pow(2, i) );
}
This will round the floating result properly before casting it to an int.

How to get a QVector<T> from a QVector<QVector<T>>?

I've got a QVector of QVector. And I want to collect all elements in all QVectors to form a new QVector.
Currently I use the code like this
QVector<QVector<T> > vectors;
// ...
QVector<T> collected;
for (int i = 0; i < vectors.size(); ++i) {
collected += vectors[i];
}
But it seems the operator+= is actually appending each element to the QVector. So is there a more time-efficent usage of QVector or a better suitable type replace QVector?
If you really need to, then I would do something like:
QVector< QVector<T> > vectors = QVector< QVector<T> >();
int totalSize = 0;
for (int i = 0; i < vectors.size(); ++i)
totalSize += vectors.at(i).size();
QVector<T> collected;
collected.reserve(totalSize);
for (int i = 0; i < vectors.size(); ++i)
collected << vectors[i];
But please take note that this sounds a bit like premature optimisation. As the documentation points out:
QVector tries to reduce the number of reallocations by preallocating up to twice as much memory as the actual data needs.
So don't do this kind of thing unless you're really sure it will improve your performance. Keep it simple (like your current way of doing it).
Edit in response to your additional requirement of O(1):
Well if you're randomly inserting it's a linked list but if you're just appending (as that's all you've mentioned) you've already got amortized O(1) with the QVector. Take a look at the documentation for Qt containers.
for (int i = 0; i < vectors.size(); ++i) {
for(int k=0;k<vectors[i].size();k++){
collected.push_back(vectors[i][k]);
}
}
outer loop: take out each vector from vectors
inner loop: take out each element in the i'th vector and push into collected
You could use Boost Multi-Array, this provides a multi-dimensional array.
It is also a 'header only' library, so you don't need to separately compile a library, just drop the headers into a folder in your project and include them.
See the link for the tutorial and example.

Resources