Guest User

Untitled

a guest
Nov 13th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. // 1A
  2. function compute_e(lst) {
  3. function helper_acc(xs, n, current){
  4. if(is_empty_list(xs)) {
  5. return current;
  6. } else {
  7. if (n % 2 === 0){
  8. return helper_acc(tail(xs), n + 1, current + head(xs)); //if index is even (so number is at odd i), just add it to the sum
  9. } else {
  10. return helper_acc(tail(xs), n + 1, current + head(xs) * 3); //if index is odd (so number is at even i), multiply by 3 and then add to sum
  11. }
  12. }
  13. }
  14. const result = helper_acc(lst, 0, 0); //this gives the sum with weights
  15. return result % 10; //returns remainder upon division by 10.
  16. }
  17.  
  18. compute_e(list(4,9,2,7,1,8,2,0,9,3,7,5)); //returns 1.
  19.  
  20. //1B
  21.  
  22. function add_e(lst) {
  23. return append(lst, list(compute_e(lst)));
  24. }
  25.  
  26. //1C
  27. function get_index_of_largest(is, current_index, largest_so_far, index_of_largest_so_far){
  28. if(is_empty_list(is)){
  29. return index_of_largest_so_far;
  30. } else {
  31. if (head(is) > largest_so_far){
  32. return get_index_of_largest(tail(is), current_index + 1, head(is), current_index);
  33. } else {
  34. return get_index_of_largest(tail(is), current_index + 1, largest_so_far, index_of_largest_so_far);
  35. }
  36. }
  37. }
  38.  
  39. function index_of_largest(is) {
  40. return get_index_of_largest(is, 0, -Infinity, NaN);
  41. }
  42.  
  43. index_of_largest(list(42,34,65,22,5,19)); //returns 2
  44.  
  45. //2A
  46.  
  47. function get_index_of_largest(is, current_index, largest_so_far, index_of_largest_so_far){
  48. if(is_empty_list(is)){
  49. return index_of_largest_so_far;
  50. } else {
  51. if (head(is) > largest_so_far){
  52. return get_index_of_largest(tail(is), current_index + 1, head(is), current_index);
  53. } else {
  54. return get_index_of_largest(tail(is), current_index + 1, largest_so_far, index_of_largest_so_far);
  55. }
  56. }
  57. }
  58.  
  59. function index_of_largest(is) {
  60. return get_index_of_largest(is, 0, -Infinity, NaN);
  61. }
  62.  
  63. index_of_largest(list(42,34,65,22,5,19)); //returns 2
  64.  
  65. //2B
  66.  
  67. function remove_specified_element_from_tail(lst, n){
  68. if(length(lst) < n + 2) {
  69. return NaN;
  70. } else {
  71. const result = list_ref(tail(lst), n);//index of largest element specified in args
  72. const new_list = remove(result, tail(lst));//removes all elements that are equal to that element
  73. set_tail(lst, new_list);//mutate original list to set its tail to the new list
  74. return result;
  75. }
  76. }
  77.  
  78. var example1 = list(1,2,3,4,5,6);
  79. remove_specified_element_from_tail(example1 , 3);
  80. example1;
Add Comment
Please, Sign In to add comment