Home > Software engineering >  How to find combination of two values such that the ratio and sum of those is fixed to certain numbe
How to find combination of two values such that the ratio and sum of those is fixed to certain numbe

Time:10-26

How can I find all combination of two numbers such that the sum of the two values amount to tot_max <= 16 (max, less is allowable) and ratio between the two is rat=0.5.

Instance of such is:

V1 V2 ratio(V1/V2) sum
1  2   0.5          3.   OK
2  4   0.5          6.   OK
3  6   0.5          9.   OK
4  8   0.5         12.   OK
8  16  0.5         24.   NOT OK (over 16)

These two numbers (V1 and V2) should be integer and greater than 0.

How can I create a R code so that it can accommodate different values of tot_max and rat?

CodePudding user response:

This is a math problem and not necessarily programing

You have x y < 16 and x/y = 0.5 and x, y > 0. with these three two conditions, doing algebra gives you: 1 <= x <= 5 and y = 2x.

therefore:

x <- seq(5)
y <- 2*x
data.frame(x, y, sum = x y, ratio = x/y) 

  x  y sum ratio
1 1  2   3   0.5
2 2  4   6   0.5
3 3  6   9   0.5
4 4  8  12   0.5
5 5 10  15   0.5
 

CodePudding user response:

df <- expand.grid(V1=1:15, V2=1:15)
df <- df[ df$V1   df$V2 <= 16 & df$V1 / df$V2 == 0.5, ]
df
#>     V1 V2
#> 16   1  2
#> 47   2  4
#> 78   3  6
#> 109  4  8
#> 140  5 10
  • Related