about summary refs log tree commit diff
path: root/scratch/deepmind/part_two/merge-sorted-arrays.ts
blob: 2d478e0e37dea299355350068e55692adabc4c5c (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
function mergeArrays(xs: Array<number>, ys: Array<number>): Array<number> {
  let i = 0;
  let j = 0;
  const result = [];

  for (let q = 0; q < xs.length + ys.length; q += 1) {
    if (i === xs.length) {
      while (j < ys.length) {
        result.push(ys[j]);
        j += 1;
      }
    } else if (j === ys.length) {
      while (i < xs.length) {
        result.push(xs[i]);
        i += 1;
      }
    } else if (xs[i] < ys[j]) {
      result.push(xs[i]);
      i += 1;
    } else {
      result.push(ys[j]);
      j += 1;
    }
  }

  return result;
}

// Tests
let desc = "both arrays are empty";
let actual = mergeArrays([], []);
let expected = [];
assertDeepEqual(actual, expected, desc);

desc = "first array is empty";
actual = mergeArrays([], [1, 2, 3]);
expected = [1, 2, 3];
assertDeepEqual(actual, expected, desc);

desc = "second array is empty";
actual = mergeArrays([5, 6, 7], []);
expected = [5, 6, 7];
assertDeepEqual(actual, expected, desc);

desc = "both arrays have some numbers";
actual = mergeArrays([2, 4, 6], [1, 3, 7]);
expected = [1, 2, 3, 4, 6, 7];
assertDeepEqual(actual, expected, desc);

desc = "arrays are different lengths";
actual = mergeArrays([2, 4, 6, 8], [1, 7]);
expected = [1, 2, 4, 6, 7, 8];
assertDeepEqual(actual, expected, desc);

function assertDeepEqual(a: Array<number>, b: Array<number>, desc: string) {
  const aStr = JSON.stringify(a);
  const bStr = JSON.stringify(b);
  if (aStr !== bStr) {
    console.log(`${desc} ... FAIL: ${aStr} != ${bStr}`);
  } else {
    console.log(`${desc} ... PASS`);
  }
}