Consider a sequence u where u is defined as follows:
u(0) = 1
is the first one in u.x
in u
, then
y = 2 * x + 1
and z = 3 * x + 1
must be in
u
too.Ex:
u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on…
Given parameter n
the function dbl_linear
(or dblLinear
…) returns the element u(n)
of
the ordered (with <) sequence u
(so, there are no
duplicates).
dbl_linear(10) should return 22
Focus attention on efficiency
library(tidyverse)
<- function(n) {
dblLinear <- 1
u <- 1
i <- 1
j while (length(u) < n + 1) {
<- 2 * u[i] + 1
y <- 3 * u[j] + 1
z if (y < z) {
length(u) + 1] <- y
u[<- i + 1
i else if (y > z) {
} length(u) + 1] <- z
u[<- j + 1
j else {
} length(u) + 1] <- y
u[<- i + 1
i <- j + 1
j
}
}+ 1]
u[n
}
library(testthat)
<- function(n, expected) {
testing <- dblLinear(n)
actual expect_equal(actual, expected)
}test_that("tests", {
testing(10, 22)
testing(20, 57)
testing(50, 175)
})
#> Test passed 🥳
function dblLinear(n) {
let u = [1], i = 0, j = 0; //two pointer
while (u.length < n + 1) {
let newTerm = Math.min(2 * u[i] + 1, 3 * u[j] + 1);
.push(newTerm)
uif (newTerm === 2 * u[i] + 1) i++;
if (newTerm === 3 * u[j] + 1) j++;
}return u[n];
}
console.log(dblLinear(10));
.exports = dblLinear; module
#> 22