How do I implement the number of rounds in this C++ code? - c++

int round;
int Starting_index;
int hop_count;
for( round = 0; round < gNumRounds; round++)
{
Starting_index[round] = gPasswordHash[0+round*4] * 256 + gPasswordHash[1+round*4];
hop_count [round] = gPasswordHash[2+round*4] * 256 + gPasswordHash[3+round*4];
if(hop_count == 0) hop_count = 0xFFFF;
}
gPasswordHash, gNumRounds are both global variables. The place where I'm getting an error is with setting the Starting_index[round] and hop_count[round] inside the for loop.
There may be something wrong with my Starting_index and hop_count declarations, but I'm unsure what that is.

You need to declare those variables as arrays, not single int.
int Starting_index[MAXROUNDS];
int hop_count[MAXROUNDS];

Starting_index and hop_count aren't declared as arrays, they're currently only ints. You also should be declaring and defining round inside the for loop declaration instead of earlier: 'for (int round = 0; round < gNumRounds; round++)'.
And I don't really know what you mean by 'if (hop_count == 0) hop_count = 0xFFFF;'.

Related

Is there a way to 'reset' a functions variables?

I recently made a function to compare an array of numbers to a single value which returns the closest value to the single value out of the array. This works perfectly well when you only use it only once but if I use it again in another instance of the code, It returns an unexpected value (usually the previous single value used before). Here is the function that I am using:
double closestval (double num1, int amountofnums, double *comps){
double storagecomps[amountofnums];
for (int i = 0; i < amountofnums; i++){
storagecomps[i] = {comps[i]};
/* Storing the array of numbers for later as I will be changing them */
}
double smallval = 0.0001; /* tiny value used to increment/decrement
values in the array to the comparison variable.*/
int_fast64_t compi [amountofnums]; /* this variable keeps track of how many times it needs to decrement/increment the values in the array to approach the variable*/
for (int i = 0; i < amountofnums; i++){
compi[i] = 0;
}
for (int i = 0; i <= amountofnums; i++){
while (comps[i] > num1){
comps[i] -= smallval;
compi[i]++;
}
while (comps[i] < num1){
comps[i] += smallval;
compi[i]++;
}
double recholder[3] = {10000000, 0,};
// This area finds the
for (int i = 0; i < amountofnums; i++){
if (compi[i] < recholder[0]){
recholder[0] = compi[i];
recholder [1] = i;
recholder[2] = storagecomps[i]; /* if the amount of iterations to approach the single variable is less than the previous record holder, it becomes the new one.
*/
}
}
return recholder[2];
}
I am relatively sure this is because (in one way or another) the variables in the function are not being redefined properly or at all. Much thanks if you can show me where I've gone wrong!
The problem isn't resetting the variables. The problem is that you are modifying the arguments passed to the function.
To prevent modifications you should use the const keyword:
double closestval (double num1, int amountofnums, const double *comps){
and then fix the errors the compilers throws at you.
If you do want to modify the comps inside the functions but not have it affect the values outside the functions then you should usestd::vector so you can pass them by value and the compiler will copy them:
double closestval (double num1, int amountofnums, std::vector<double> comps){
You should really do that anyway as you should forget all about C-style arrays till you are an expert.

Acessing/Adressing variables with strings and int in Arduino

There's already a question about adressing variables with strings in Arduino, but the answers given didn't apply to my problem.
I have multiple sensors (around 14 and the number might increase) connected to my Arduino, I also have relays, engines and RFIDs. I'm creating a function that checks if all of the sensors are active.
The idea is basically this:
#define Sensor_1 2
#define Sensor_2 3
#define Sensor_3 4
#define Sensor_4 5
#define Sensor_5 6
int checkSensors(){
int all_active = 0;
int num_sens = 5;
int n;
int active_sens = 0;
for(n= 1; n <= num_sens; n++) {
if( !digitalRead("Sensor_" + n)) {
active_sens= active_sens+ 1;
}
else {
all_active = 0;
return ( all_active);
}
}
if(active_sens== num_sens) {
all_active = 1;
return(all_active);
}
}
The problem is: I want to address the variable Sensor_n, but I can't find out a way to do it. The error message I get is referring to the digitalRead("Sensor_" + n ) command.
error: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}' [-fpermissive]
I already tried to use "Sensor_" in a String = "Sensor_", I've tried to force a typecast to uint8_t, but the error message says that it loses precision.
I also tried the .toCharArray command, but it failed as well.
Is there a way to access a variable through a string + int?
I'm more familiar with the "loose" variables in PHP, so this is giving me a lot of trouble.
There are a few issues with your code. First you can't get the value of a variable or a define by dynamically using a string that is the name of the variable. It doesn't work that way in C. The easiest approach is to use an array and then just index through it. To make this work well I've changed the for loop to count from 0 since the array is indexed starting at 0. I changed the all_active logic assuming that at some point later you are going to want to know how many sensors are active instead of just whether they are all active or not. If you don't want that, then your logic is also more complicated than needed. It could just return 1 at the end of the for loop since all must have passed the test to get there.
#define Sensor_1 2
#define Sensor_2 3
#define Sensor_3 4
#define Sensor_4 5
#define Sensor_5 6
int sensors[] = {Sensor_1, Sensor_2, Sensor_3, Sensor_4, Sensor_5};
int checkSensors(){
int all_active = 1;
int num_sens = 5;
int n;
int active_sens = 0;
for(n= 0; n < num_sens; n++){
if( !digitalRead(sensors[n])){
active_sens= active_sens+ 1;
}
else {
all_active = 0;
}
}
return all_active;
}
In C this line will not work
if( !digitalRead("Sensor_" + n))
you cannot build a string like this in C. Since you didn't post the function digitalRead() I presume it takes a char* type, here a string, which in C you could build like this
char senstr[50];
sprintf(senstr, "Sensor_%d", n);
...
if (!digitalRead(senstr)) { ...
As a side issue, please get used to iterating loops from 0. You add 1 to interface with humans.

Initializing An Array with a Variable Size

I am almost done with my code except I need help on two thing. Here is my code: Code. For the function below, I am trying to make it so that I can use the input of "n" to initialize my array, myBits, instead of a constant, which is currently 5.
My Other question is right below that. I am trying to switch all of the right most bits to "true". I wrote the for loop in "/* .....*/" but it doesn't seem to be working. Right above it, I do it long ways for C(5,4) ....(myBit[0] = myBit[1]....etc...... (I am using this to find r-combinations of strings).... and it seems to work. Any help would be appreciated!!
void nCombination(const vector<string> &Vect, int n, int r){
bool myBits[5] = { false }; // everything is false now
myBits[1] = myBits[2] = myBits[3] = myBits[4] = true;
/* for(int b = n - r - 1; b = n - 1; b++){
myBits[b] = true; // I am trying to set the r rightmost bits to true
}
*/
do // start combination generator
{
printVector(Vect, myBits, n);
} while (next_permutation(myBits, myBits + n)); // change the bit pattern
}
These are called variable length arrays (or VLAs for short) and they are not a feature of standard C++. This is because we already have arrays that can change their length how ever they want: std::vector. Use that instead of an array and it will work.
Use std::vector<bool>:
std::vector<bool> myBits(n, false);
Then you have to change your while statement:
while (next_permutation(myBits.begin(), myBits.end()));
You will also have to change your printVector function to take a vector<bool>& as the second argument (you won't need the last argument, n, since a vector knows its own size by utilizing the vector::size() function).
As to your program: If you're attempting to get the combination of n things taken r at a time, you will need to write a loop that initializes the last right r bools to true instead of hard-coding the rightmost 4 entries.
int count = 1;
for (size_t i = n-1; i >= 0 && count <= r; --i, ++count)
myBits[i] = true;
Also, you should return immediately from the function if r is 0.

Simple loop, which one I would get more performance and which one is recommended? defining a variable inside a loop or outside of it?

Variable outside of the loop
int number = 0;
for(int i = 0; i < 10000; i++){
number = 3 * i;
printf("%d",number);
}
or Variable inside of the loop
for(int i = 0; i < 10000; i++){
int number = 3 * i;
printf("%d",number);
}
Which one is recommended and which one is better in performance?
Edit:
This is just an example to exhibit what I mean, All I wanna know is if defining a variable inside a loop and outside a loop means the same thing , or there's a difference.
Time to learn something early: any optimization you could make on something like this will be irrelevant in the face of printf.
Printf will be very, very slow. You could quintuple the math and get no measurable speed decrease. It's just the nature of printing to the terminal.
As for your edited question, there is no difference defining it in the loop or out. Imagine that
for (i = 0; i < 500; i++) {
int a = i * 3;
}
is just the same as
int forloop::a; // This doesn't work, the idea is to show it just changes the scope
for (i = 0; i < 500; i++) {
a = i * 3;
}
They will produce identical code, unless you start needing to use that variable outside of the loop it is defined in, because it is defined in the local scope of the loop. So...more like this:
int forloop::a; // Still not valid code, just trying to show an explanation
namespace forloop {
for (i = 0; i < 500; i++) {
a = i * 3;
}
} // namespace forloop
If this is unclear please let me know I'll go into more detail or explain differently.
Do not bother you with performance at first: make it safe before everything.
I would just quote Scott Meyers (Effective C++) for your concern:
"Postpone declarations as far as you can".
Thus, the second pattern is safer.
Example:
int j = 0;
for(int i = 0; i < 10000; i++){
j = 3 * i;
printf("%d",j);
}
...
// Use of j out of control!!!
int k = j * 5;
Now with the second pattern:
for(int i = 0; i < 10000; i++){
int j = 3 * i;
printf("%d",j);
}
...
// j not declared at this point.
// You get informed of the mistake at compile time, which is far much better.
int k = j * 5;
You do have a C++ tag, and you mention "declaring a string" in the question. Therefore there might be a performance difference (and yes, the printf could swamp it). Declaring a non-simple variable means calling a constructor, which might mean a non-trivial amount of work. In that case, declaring it inside of the loop could be hiding significant work in what appears to be an innocent declaration.
In general, the answer is that if you really care about performance - and treating the sample code as only an example of the difference between two places to declare a variable - then for non-simple variables, it is better to declare it outside the loop, unless the semantics require a fresh version of a temporary at each iteration.
There are likely many other places first to look at if performance is an issue, but one consideration is always moving loop invariants out of loops, especially if it is much easier for you to tell that it is invariant than for the compiler. And what looks like a declaration, can, in C++, fall into that category.
If, for (silly) example, you have
int k = 43;
for ( int i = 0; i < N; ++i )
{
int j = 17 + k; // k was previously defined outside the loop, but doesn't change in it
l = j * j; // l was also declared outside the loop
}
any good optimizing compiler can recognize that k is constant, and that j is always assigned 60, and l is assigned 3600 N times, and the loop can simply be removed and replaced with a single assignment to l. Here k and j are both loop invariants.
But a not-quite-so-good compiler might miss even one link in that chain, and wind up creating the loop.
It gets harder for the compiler to figure things out when you have
Foo k( 43 ); // a class that takes an int argument to its constructor
for( int i = 0; i < N; ++i )
{
Bar j( k ); // a Bar takes an int argument, adds 17 and stores it.
l = j.squared();
}
Same invariants. Not as easy to detect without looking inside the workings of bar; and if the constructor and squared method aren't inline, we've just made it slower.
In this case, printf("%d", i * 3) would be better than defining the variable at all.
To answer your question and not nitpicking:
The difference between the 2 variants is, that you are declaring your variable number in different "variable environments" - by which I mean that the scope changes. A variable environment is given by your curly braces { ... }. Everytime you open a new curly brace like this { ... { ... } ... }, you declare a new variable environment inside the old one, which means, that if you declare numbers like so:
{ ... { int numbers; ... } ... }
this variable will only be visible or existent in the innermost environment. So
{ ... { int numbers; ... } ... do_something(numbers); ... }
will give a compiler error.
And to your concerns about performance: Neither variant is better performing. Most, if not all compilers will give the same assembly.

Template Sort In C++

Hey all, I'm trying to write a sort function but am having trouble figuring out how to initialize a value, and making this function work as a generic template. The sort works by:
Find a pair =(ii,jj)= with a minimum value = ii+jj = such at A[ii]>A[jj]
If such a pair exists, then
swap A[ii] and A[jj] else
break;
The function I have written is as follows:
template <typename T>
void sort(T *A, int size)
{
T min =453;
T temp=0;
bool swapper = false;
int index1 = 0, index2 = 0;
for (int ii = 0; ii < size-1; ii++){
for (int jj = ii + 1; jj < size; jj++){
if((min >= (A[ii]+A[jj])) && (A[ii] > A[jj])){
min = (A[ii]+A[jj]);
index1 = ii;
index2 = jj;
swapper = true;
}
}
}
if (!swapper)
return;
else
{
temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
sort(A,size);
}
}
This function will successfully sort an array of integers, but not an array of chars. I do not know how to properly initialize the min value for the start of the comparison. I tried initializing the value by simply adding the first two elements of the array together (min = A[0] + A[1]), but it looks to me like for this algorithm it will fail. I know this is sort of a strange type of sort, but it is practice for a test, so thanks for any input.
most likely reason it fails, is because char = 453 does not produce 453 but rather different number, depending what char is (signed versus unsigned). your immediate solution would be to use numerical_limits, http://www.cplusplus.com/reference/std/limits/numeric_limits/
you may also need to think about design, because char has small range, you are likely to overflow often when adding two chars.
The maximum value of any type is std::numeric_limits<T>::max(). It's defined in <limits>.
Also, consider a redesign. This is not a good algorithm. And I would make sure I knew what I was doing before calling my sort function recursively.
I haven't put too much time reading your algorithm, but as an alternative to std::numeric_limits, you can use the initial element in your array as the initial minimum value. Then you don't have to worry about what happens if you call the function with a class that doesn't specialize std::numeric_limits, and thus can't report a maximum value.