Round robin algorithm in a loop - c++

How round-robin algorithm can be implemented that runs in a loop for ever?
for (int i = 0; ;i++){
roundRobinIndex = i % numberOfWorkers;
}
The problems with the way above is that integer overflow problem. It can also be implemented with checking the value of i:
for (int i = 0; ;i++){
roundRobinIndex = i % numberOfWorkers;
if i == maxNumber{
i = 0;
}
}
But this way seems ugly. Maybe there is more elegant way?

Why not ?
int numberOfWorkers = 10
int roundRobinIndex = numberOfWorkers - 1
while(true){
roundRobinIndex = (roundRobinIndex + 1) % numberOfWorkers
}
or with a for-loop
for (int i = 0; ;i = (i + 1) % numberOfWorkers){
roundRobinIndex = i;
}
We can now get rid of i

Avoiding any modulo call, we can do:
constexpr int nextRR(int curIdx, int sz) {
if(curIdx==sz-1) {
return 0;
}
return curIdx+1;
}
for (int rrIndex = 0;;rrIndex = nextRR(rrIndex, sz)) {
// use rrIndex here ...
}
This will be performance-wise more effective than any modulo-based solution, if the number of workers is not known at compile time.
Note that nextRR can also be written like this, to optimize even further for platforms where comparison with 0 is faster than a comparison with a variable:
constexpr int nextRR(int curIdx, int sz) {
if(curIdx==0) {
return sz-1;
}
return curIdx-1;
}

For completeness (I agree that pLopeGG's answer is more elegant) - your way would work perfectly well if you make i an unsigned int rather than int since the overflow is defined in the standard for unsigned overflows, but not signed.
ie
for (unsigned int i = 0; ;i++){
roundRobinIndex = i % numberOfWorkers;
}

Why not put the % into the loop?
for (int i = 0; ;++i, i %= numberOfWorkers)
{
}

Related

C++ functions, arrays, and pointers

There is already a lot about this but none solved my problem or maybe I just didn't understand the answers. I'm just simply trying to return an array from a function
Also, I am having to put all of my functions above the main function that also seems weird to me.
And here is what happens when I try to use pointers:
int * RookMoves(int startingPosition, bool isWhite, int theBoard[64]){
int startingPositionXY[2] = { startingPosition % 8, (startingPosition - (startingPosition % 8)) / 8 };
int possibleRookPositions[14];
int possiblePosXY[2];
int counter = 0;
for (int h = 0; h < 2; h++)
{
int counter2 = 1;
for (int j = 0; j < 2; j++)
{
counter2 *= -1;
for (int i = 1; i < 8; i++)
{
int other = startingPositionXY[h] + (i * counter2);
int hInverted = (h + abs(h - 1)) * abs(h - 1); // 0 + 1 * 1 = 1 but 1 + 0 * 0 = 0
if (other < 8 && other > -1)
{
possiblePosXY[h] = other;
possiblePosXY[hInverted] = startingPositionXY[hInverted];
int movesOneDim = possiblePosXY[0] + (possiblePosXY[1] * 8);
if (CalculateSameColor(isWhite, theBoard[movesOneDim])) {
possibleRookPositions[counter] = movesOneDim;
counter++;
if (CalculateEnemy(isWhite, theBoard[movesOneDim]))
{
break;
}
}
else
{
break;
}
}
else
{
break;
}
}
}
}
for (int i = counter; i < 14; i++) //simply changing any unused elements to -1 for later recognition
{
possibleRookPositions[i] = -1;
}
cout << sizeof(possibleRookPositions) / sizeof(possibleRookPositions[0]) << ' '; // returns 14 just as it should
return possibleRookPositions;
}
int main()
{
int testBoard[64];
for (int i = 0; i < 64; i++) {
testBoard[i] = 0;
}
int* arr = RookMoves(21, true, testBoard);
cout << sizeof(arr) / sizeof(arr[0]); //ouputs: 1, should be 14
}
by all things the web says the pointer one should work but it doesn't, it returns an array with a size of 1.
An array in C++, in “simple” code, is either std::vector or std::array. Those can be returned without any problem. I’d say your issue is that you are writing mostly C and calling it C++. C is IMHO much harder to get right for beginners - so use the fact that you got C++ available for your use!
The C-style arrays is something any professional C++ programmer of course fully understands, but whenever I’m forced to write code like that (due to what amounts to customer requirements), it almost never passes the tests on the first try. So don’t be too worried: even people who can write a compiler that could take this array code and produce assembly output still have trouble with getting it right to some extent. It’s unwieldy and it has almost no place in C++ of today.
I was trying to get sizeof from a pointer because I don't really understand how those work yet but all I needed to do was to use pointers but just initialize the array I was returning as "static." Thanks to MikeCAT

Adding 1 to an input int vector and returning the answer in vector again

#include <cmath>
#include <vector>
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int>result;
unsigned long long c =0,answer;
for (int i=0; i<digits.size(); i++){
c = pow(10, i)*(digits[digits.size()-1-i]) + c;
//cout<<"loop"<<endl;
}
answer = c+1;
while (answer){
result.insert(result.begin(),answer%10);
answer = answer/10;
}
return result;
}
};
I get an error for long vectors.
Ex: for testcase , [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
My code is giving output as [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,4,0,9]
last three digits are wrong
If someone asked you to add one to a large number, would you use the pow function? Obviously not. This is how you should write the function
vector<int> plusOne(const vector<int>& digits) {
vector<int> result = digits;
int carry = 1;
int i = digits.size() - 1;
while (i > 0 && carry) {
++result[i];
if (result[i] < 10)
carry = 0;
else
result[i] = 0;
--i;
}
if (carry)
result.insert(result.begin(), 1); // overflow, e.g. 9999 => 10000
return result;
}
Untested code.

How to count comparisons in selectionsort?

How to count comparisons in selectionsort?
terms:
when the statements you perform to find the maximum value is 'true'
then count comparison.
The value to get the maximum value is held at the first element in the array, not at random.
I try with C
variable count position change - no work
new variable 'first' , first=sort[MAX] insert first for loop, - no work
#include <stdio.h>
int main() {
int sort[10000], i, n, MAX, temp, count;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &sort[i]);
}
for (MAX = 0; MAX < n; MAX++)
for (i = MAX + 1; i < n; i++) {
if (sort[MAX] > sort[i]) {
count++;
temp = sort[MAX];
sort[MAX] = sort[i];
sort[i] = temp;
}
}
printf("%d ", count);
return 0;
}
Sample Input
10
0 7 1 6 7 7 6 6 5 4
Sample Output
17
EDIT: new code:
#include <stdio.h>
#define SWAP(x, y, temp) ( (temp)=(x), (x)=(y), (y)=(temp) )
int count = 0;
void selection_sort(int list[], int n) {
int i, j, least, temp;
for (i = 0; i < n - 1; i++) {
least = i;
for (j = i + 1; j < n; j++) {
if (list[j] < list[least]) {
least = j;
count++;
}
}
SWAP(list[i], list[least], temp);
}
}
int main() {
int list[10000], i, n;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &list[i]);
};
selection_sort(list, n);
printf("%d", count);
}
how about this? why this code didn't move too?
You aren't counting the right thing, this code
if(sort[MAX]>sort[i])
{
count++;
temp=sort[MAX];
sort[MAX]=sort[i];
sort[i]=temp;
}
counts the times that two numbers are swapped. But you want to count comparisons so it should be this
count++;
if(sort[MAX]>sort[i]) // this is what we are counting
{
temp=sort[MAX];
sort[MAX]=sort[i];
sort[i]=temp;
}
Another problem is that you don't give count an initial value of zero
int sort[10000],i,n,MAX,temp,count;
should be
int sort[10000],i,n,MAX,temp,count = 0;
how to count comparison selectionsort?
Your definition of the term is oddly worded, but it seems to be intended to focus on the essential comparisons of the algorithm, as opposed to comparisons performed incidentally for other purposes, or inside library functions. That is, in the implementation you present (whose correctness I do not evaluate), you're to count each evaluation of sort[MAX]>first, but not MAX<n or i<n.
You appear to be using variable count for that purpose, but you are counting only comparisons that evaluate to true. My interpretation of the problem, based both on the wording presented and on my general expectations for such a problem, is that every evaluation of sort[MAX]>first should be counted, regardless of the result. That would be achieved by lifting the expression count++ out of the if block, but leaving it inside the inner enclosing for loop.
Of course, as #john observes, you do need to initialize count to 0 before beginning to sort. You might luck into getting that by accident, but the initial value of a local variables without an initializer is indeterminate (at least) until a value is assigned.
i try with c variable count position change - no work
new variable 'first' , first=sort[MAX] insert first for loop, - no work
Even with the misplacement of your increment to count, if your sort were in fact working then you would expect to see some counts for most inputs. That you don't is a good sign that your sort in fact does not work correctly. I would suggest outputting also the the sorted results so that you can debug the details of the sort algorithm.
You could abstract out the comparison into a function or macro that also increments a counter. The macro approach could be
#define GT(x,y,counter) (counter++, (x) > (y) ? 1 : 0)
...
if ( GT( sort[MAX], sort[i], count ) == 1 )
{
// perform swap
}
whereas the function approach would be
int gt( int x, int y, int *counter )
{
(*counter)++;
if ( x > y )
return 1;
return 0;
}
...
if ( gt( sort[MAX], sort[i], &count ) == 1 )
{
// perform swap
}
You are counting the number of swaps, not the number of comparisons.
Here is a corrected without a global variable and a few extra checks:
#include <stdio.h>
#define SWAP(x, y, temp) ((temp) = (x), (x) = (y), (y) = (temp))
int selection_sort(int list[], int n) {
int count = 0;
int i, j, least, temp;
for (i = 0; i < n - 1; i++) {
least = i;
for (j = i + 1; j < n; j++) {
count++;
if (list[j] < list[least]) {
least = j;
}
}
SWAP(list[i], list[least], temp);
}
return count;
}
int main() {
int list[10000], i, n, count;
if (scanf("%d", &n) != 1 || n > 10000)
return 1;
for (i = 0; i < n; i++) {
if (scanf("%d", &list[i]) != 1)
return 1;
}
count = selection_sort(list, n);
printf("%d\n", count);
return 0;
}
Not however that your algorithm will always perform the same number of comparisons for any set of n values: n * (n - 1) / 2 comparisons, and since you do not test of i != least, it will perform n - 1 swaps.

Is there any method to organize "cycling" (looping) numbers in c++?

I need to have a cycle of limited number (0 to 3) in an infinite loop. So I use this code:
int moveOp = 0;
while (1) {
//some operations with moveOp here
moveOp++;
if(moveOp>3) {
moveOp = 0;
}
}
But maybe there is a method to have a data type with which increment operator jumps to zero without hand written condition?
This would work:
moveOp = (moveOp + 1) % N;
if your NUM is power of 2 you can use the bitfields as well
struct {
unsigned moveOp:2;
}m;
m.moveOp++;
for(int i = 0; ; i = (i + 1) % 4) {
// your code goes here
}
I think Modulus operator is what you are looking for.
Following is the sample how you can use it:
int moveOp = 0;
int Num = 4;
while (1) {
++moveOp;
moveOp = moveOp%Num;
}

How do you find multiplicity of a prime factor in a prime factorization of number?

I have to find multiplicity of smallest prime factor in all numbers till 10^7.I am using Sieve of Eratosthenes to find all the prime numbers. And there in a seperate array phi i am storing smallest prime factors of composite numbers.Here is my code for that
for(ull i=2;i<=m;i++)
{
if (check[i])
{
uncheck[i]=true;
for (ull k=i*i; k<=n; k+=i)
{
if(check[k]==true)
phi[k]=g;
check[k]=false;
}
}
}
Now i am running a loop till n and using a loop inside it to calculate it.
Here is code for that
for(ull i=4;i<=n;i++)
{
if(check[i]==false)
{
ull count=0;
ull l=i;
ull r=phi[i];
while(l%r==0)
{
l=l/r;
count++;
}
cout<<count<<'\n';
}
}
Is there any faster way to compute this?
Absolutely, you can do this without a loop.
c is probably at most 64 bits. It cannot contain any factor other than 1 more than 63 times. So instead of a loop, you write 63 nested if-statements.
For the case j == 2 your compiler may have some intrinsic functions that count trailing zero bits. If that is the case, then you handle that case separately and you need only 40 if's, because 3^41 > 2^64.
If you want to evaluate n such that jn = c, then recast the problem to
n = log(c) / log(j).
If n is an integer then your problem is solved.
Of course you need to consider floating point precision here; n might not be an exact integer, but close to one.
One alternative option, though not necessarily the most efficient, is to write a simple recursive function, such as this, assuming you are dealing with ints:
int recurseSubtract(int c, int j, int count){
if ((c==j)) {
return count + 1;
} else {
c = c-j;
subtract(c, j, count++);
}
}
int count = recurseSubtract(c,j,0);
However, see here for the pros and cons of loops vs. recursion.
Since you asked for the "multiplicity of smallest prime factor" you could easily use the same sieve approach to get multiplicity as you used to get the smallest factor.
for(ull i=2;i<=m;i++)
{
if (check[i])
{
uncheck[i]=true; // WHY??
ull k=i*i;
for (ull q=i; q<maxq; k=(q*=i))
for ( ; k<=n; k+=q)
{
if(check[k]==true)
phi[k]=g; // I copied 'g' from you, but didn't you mean 'i'?
if ( phi[k]==g )
count[k]++;
check[k]=false;
}
}
}
If you want to do a little better than that, the step of phi[k]==g and the some of the redundancy in check[k] access are needed only because q values are processed in forward sequence. It would be faster to work with q in reverse. Since q's are only easily computed in forward sequence and there are fairly few q's per i, the easiest way to process q backward would be to convert the loop over q into a recursive function (compute q on the way in and process it after the recursive call).
I found one simple rule but can not really describe in words. Here is another code calculating primenumbers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double f_power(double val, int exp);
int main(int argc,char* argv[]) {
int p[2];
int ctr = 0;
int ctr2 = 0;
int it_m = 0;
int it_1 = 0;
int it_2 = 0;
int it_c = 0;
int index = 3;
srand(time(NULL));
double t = clock();
double s = clock();
int prime = 2;
FILE *file;
file = fopen("ly_prime.txt", "w");
//f_power(2.0, 57885161)
for (it_m = 2; it_m <= 2000; it_m++) {
for (it_1 = it_m, ctr2 = 0, it_c = it_m; it_1 >= 2; it_1--) {
for (it_2 = it_1; it_2 >= 2; it_2--) {
if (it_1 * it_2 - it_c == 0) {
p[ctr % 2] = it_c;
if (ctr >= 1 && p[ctr % 2] - p[(ctr - 1) % 2] == 2) {
//prime[0] = (p[ctr % 2] - 1);
prime = (p[ctr % 2] - 1);
fprintf(stdout, "|%d _ i: %d _ %d\n", isPrime(prime),index, prime);
index++;
}
ctr++;
}
}
}
}
t = clock() - t;
fprintf(file, "|%d_ %d_ %d ", prime, index - 2, ctr);
}
double f_power(double val, int exp) {
int i = 0;
double help = val;
for(i = 1; i < exp; i++) {
val *= help;
}
return val;
}
int isPrime(int number)
{
int i = 2;
for(i=2; i < number; i++)
{
int leftOver=(number % i);
if (leftOver==0)
{
return 1;
break;
}
}
return 0;
}
perhaps it helps understanding, best regards