Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 1A
- function compute_e(lst) {
- function helper_acc(xs, n, current){
- if(is_empty_list(xs)) {
- return current;
- } else {
- if (n % 2 === 0){
- 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
- } else {
- 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
- }
- }
- }
- const result = helper_acc(lst, 0, 0); //this gives the sum with weights
- return result % 10; //returns remainder upon division by 10.
- }
- compute_e(list(4,9,2,7,1,8,2,0,9,3,7,5)); //returns 1.
- //1B
- function add_e(lst) {
- return append(lst, list(compute_e(lst)));
- }
- //1C
- function get_index_of_largest(is, current_index, largest_so_far, index_of_largest_so_far){
- if(is_empty_list(is)){
- return index_of_largest_so_far;
- } else {
- if (head(is) > largest_so_far){
- return get_index_of_largest(tail(is), current_index + 1, head(is), current_index);
- } else {
- return get_index_of_largest(tail(is), current_index + 1, largest_so_far, index_of_largest_so_far);
- }
- }
- }
- function index_of_largest(is) {
- return get_index_of_largest(is, 0, -Infinity, NaN);
- }
- index_of_largest(list(42,34,65,22,5,19)); //returns 2
- //2A
- function get_index_of_largest(is, current_index, largest_so_far, index_of_largest_so_far){
- if(is_empty_list(is)){
- return index_of_largest_so_far;
- } else {
- if (head(is) > largest_so_far){
- return get_index_of_largest(tail(is), current_index + 1, head(is), current_index);
- } else {
- return get_index_of_largest(tail(is), current_index + 1, largest_so_far, index_of_largest_so_far);
- }
- }
- }
- function index_of_largest(is) {
- return get_index_of_largest(is, 0, -Infinity, NaN);
- }
- index_of_largest(list(42,34,65,22,5,19)); //returns 2
- //2B
- function remove_specified_element_from_tail(lst, n){
- if(length(lst) < n + 2) {
- return NaN;
- } else {
- const result = list_ref(tail(lst), n);//index of largest element specified in args
- const new_list = remove(result, tail(lst));//removes all elements that are equal to that element
- set_tail(lst, new_list);//mutate original list to set its tail to the new list
- return result;
- }
- }
- var example1 = list(1,2,3,4,5,6);
- remove_specified_element_from_tail(example1 , 3);
- example1;
Add Comment
Please, Sign In to add comment