## Problem statement

Event EA and EB needs to be done every A sec and B sec. Always make sure EA occurs before EB if A and B are multiples of each other.## More explanation

Say EA need to occur every 2 sec and EB needs be occur every 5 sec.EA would occur at

2, 4, 6, 8, 10, 12, 14, 16, 18...

EB would occur at

5, 10, 15, 20, 25, 30, 35, 40,...

Hence combining both together

2 - EA occurs

4 - EA occurs

5 - EB occurs

6 - EA occurs

8 - EA occurs

10 - EA and EB occurs

12 - EA occurs

14 - EA occurs

15 - EB occurs

and so on

Hence we need to count things in irregular interval (2, 2, 1, 1, 2, 2, 2, 2, 1, 1 ...)

## Solution

#include <stdio.h> #define MAX_LIMIT 25 #define min(i,j) (((i) < (j)) ? (i) : (j)) int main() { int a = 2, b = 5; int ta = a, tb = b; int t = 0, x; for(t = 0; t < MAX_LIMIT; t = t + x) { x = min(ta - t, tb - t); x = (x == 0) ? min(a, b) : x; if((ta - t) < (tb - t)) { ta = ta + a; printf("do EA "); }else if((ta - t) > (tb - t)){ tb = tb + b; printf("do EB "); }else { ta = ta + a; tb = tb + b; printf("do EA and EB "); } printf("t is %d, interval is %d\n", t + x, x); } return 0; }

Output of above program is

do EA t is 2, interval is 2 do EA t is 4, interval is 2 do EB t is 5, interval is 1 do EA t is 6, interval is 1 do EA t is 8, interval is 2 do EA and EB t is 10, interval is 2 do EA t is 12, interval is 2 do EA t is 14, interval is 2 do EB t is 15, interval is 1 do EA t is 16, interval is 1 do EA t is 18, interval is 2 do EA and EB t is 20, interval is 2 do EA t is 22, interval is 2 do EA t is 24, interval is 2 do EB t is 25, interval is 1

## Understanding program

- MAX_LIMIT is a constant till which the counting would happen
- min(x,y) is the macro that would calculate the minimum value between x and y.
- ta would count total time in interval of a.
- tb would count total time in interval of b.
- x is the variable interval that was mentioned in More Explanation.
- Hopefully if else if part is self explanatory. (Just put words in code and it makes sense)

## Links

Next Article -

Previous Article - C Programming Challenge #08: Sort - insertion (binary search variant)

All Article - C Programming Challenge

## No comments :

## Post a Comment