Various Problems Flashcards

1
Q

Write a function sumTo(n) that sums all numbers up to n
Make 3 solutions

  1. Using a recursion
  2. Using a for loop.
  3. Using the arithmetic progression formula.
A
function sumTo1(n) {
  if (n <= 1) {
    return n;
  }

return sumTo1(n-1) + n;

}

function sumTo2(n) {
  let sum = 0;
  for (let i = 1; i <= n; i++) {
    sum += i;
  }
  return sum;
}
function sumTo3(n) {
  return (n/2) * (n + 1);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write a recursive function printList(list) that outputs list items one-by-one.

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};
A
function listPrinter(inputList) {
  console.log(inputList.value);
  if (inputList.next == null) {
    return;
  }
  listPrinter(inputList.next);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write a function printReverse List(list) that outputs list items one-by-one in reverse order.

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};
A
let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

function printReverseList(list) {

if (list.next) {
printReverseList(list.next);
}

alert(list.value);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write a loop function that outputs list items one-by-one in reverse order.

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};
A
let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};
function printReverseList(list) {
  let arr = [];
  let tmp = list;

while (tmp) {
arr.push(tmp.value);
tmp = tmp.next;
}

  for (let i = arr.length - 1; i >= 0; i--) {
    alert( arr[i] );
  }
}

printReverseList(list);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly