Skip to content
This repository was archived by the owner on Jan 14, 2025. It is now read-only.

Commit 305c9e0

Browse files
committed
Add twice linear
1 parent 95878d6 commit 305c9e0

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

codewars/201808/twice-linear.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2+
## Description
3+
4+
Consider a sequence u where u is defined as follows:
5+
6+
* The number u(0) = 1 is the first one in u.
7+
* For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
8+
There are no other numbers in u.
9+
* Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]
10+
11+
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...
12+
13+
Task: Given parameter n the function dbl_linear (or dblLinear...) returns the element u(n) of the ordered (with <) sequence u.
14+
15+
Example: dbl_linear(10) should return 22
16+
17+
Note: Focus attention on efficiency
18+
19+
**Kata's link**: [Twice linear](https://www.codewars.com/kata/twice-linear)
20+
21+
## Best Practices
22+
23+
**First:**
24+
```js
25+
function dblLinear(n) {
26+
var ai = 0, bi = 0, eq = 0;
27+
var sequence = [1];
28+
while (ai + bi < n + eq) {
29+
var y = 2 * sequence[ai] + 1;
30+
var z = 3 * sequence[bi] + 1;
31+
if (y < z) { sequence.push(y); ai++; }
32+
else if (y > z) { sequence.push(z); bi++; }
33+
else { sequence.push(y); ai++; bi++; eq++; }
34+
}
35+
return sequence.pop();
36+
}
37+
```
38+
39+
**Second:**
40+
```js
41+
function dblLinear(n) {
42+
43+
var u = [1], pt2 = 0, pt3 = 0; //two pointer
44+
45+
for(var i = 1;i<=n;i++){
46+
u[i] = Math.min(2* u[pt2] + 1, 3*u[pt3] + 1);
47+
if(u[i] == 2 * u[pt2] + 1) pt2++;
48+
if(u[i] == 3 * u[pt3] + 1) pt3++;
49+
}
50+
51+
return u[n];
52+
53+
}
54+
```

readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ Some best practices for practice questions on [codewars](http://www.codewars.com
66
Here is my codewars homepage: https://www.codewars.com/users/dwqs.
77

88
## Lists
9+
### 2018-08
10+
* [Twice linear](codewars/201808/twice-linear.md)
11+
912
### 2018-07
1013
* [parseInt reloaded](codewars/201807/parseint-reloaded.md)
1114
* [Return substring instance count](codewars/201807/substring-instance-count.md)

0 commit comments

Comments
 (0)