about summary refs log tree commit diff
path: root/users/wpcarro/scratch/deepmind/part_two/inflight-entertainment.ts
blob: d6da1db3d313935a9b662da2a57290c1d85fcada (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
function canTwoMoviesFillFlightBonus(
  xs: Array<number>,
  duration: number
): boolean {
  // Returns true if two movies exist that can fill the flight duration +/- 20
  // minutes.
  const seeking = {};

  for (let x of xs) {
    for (let i = 0; i < 40; i += 1) {
      if (seeking[x + i + 1]) {
        return true;
      }
    }
    for (let i = 1; i <= 20; i += 1) {
      seeking[duration - x - i] = true;
      seeking[duration - x + i] = true;
    }
  }

  return false;
}

function canTwoMoviesFillFlight(xs: Array<number>, duration: number): boolean {
  const seeking = {};

  for (let x of xs) {
    if (seeking[x]) {
      return true;
    } else {
      seeking[duration - x] = true;
    }
  }

  return false;
}

// Tests
let desc = "short flight";
let actual = canTwoMoviesFillFlight([2, 4], 1);
let expected = false;
assertEquals(actual, expected, desc);

desc = "long flight";
actual = canTwoMoviesFillFlight([2, 4], 6);
expected = true;
assertEquals(actual, expected, desc);

desc = "one movie half flight length";
actual = canTwoMoviesFillFlight([3, 8], 6);
expected = false;
assertEquals(actual, expected, desc);

desc = "two movies half flight length";
actual = canTwoMoviesFillFlight([3, 8, 3], 6);
expected = true;
assertEquals(actual, expected, desc);

desc = "lots of possible pairs";
actual = canTwoMoviesFillFlight([1, 2, 3, 4, 5, 6], 7);
expected = true;
assertEquals(actual, expected, desc);

desc = "not using first movie";
actual = canTwoMoviesFillFlight([4, 3, 2], 5);
expected = true;
assertEquals(actual, expected, desc);

desc = "only one movie";
actual = canTwoMoviesFillFlight([6], 6);
expected = false;
assertEquals(actual, expected, desc);

desc = "no movies";
actual = canTwoMoviesFillFlight([], 2);
expected = false;
assertEquals(actual, expected, desc);

function assertEquals(a, b, desc) {
  if (a === b) {
    console.log(`${desc} ... PASS`);
  } else {
    console.log(`${desc} ... FAIL: ${a} != ${b}`);
  }
}