Lists and Arrays Practice

 

Copyright to whomever owns it. I just provide my solutions to them.

For, While, Arrays

Easy

Question 1

Obtain sum of an array

function sum_array(arr){
    const len = array_length(arr);
    let res = 0;
    for(let i = 0; i < len; i = i + 1){
        res = res + arr[i];
    }
    return res;
}

Question 2

Implement accumulate with each accumulated answer being stored in the array

xs = [1,2,3];
f(plus, 0, xs);
xs;
//returns [1,3,6]; 

Filter for arrays

function filter_array(f, arr){
    const res = [];
    for(let i = 0; i < array_length(arr); i = i + 1){
        if(f(arr[i])){
            res[array_length(res)] = arr[i];
        } else {}
    }
    for(let i = array_length(res); i < array_length(arr); i = i + 1){
        res[i] = 0;
    }
    for(let i = 0; i < array_length(arr); i = i + 1){
        arr[i] = res[i];
    }
    return arr;
}
function acc_arr(f, init, arr){
    arr[0] = f(arr[0], init);
    for(let i = 1; i < array_length(arr); i = i + 1){
        arr[i] = f(arr[i], arr[i-1]);
    }
    return arr;
}

Question 3

Star pyramid using while/for

*
**
***
function star_py(n){
    let res = "\n";
    for(let i = 1; i <= n; i = i + 1){
        for(let j = 1; j <= i; j = j + 1){
            res = res + '*';
        }
        res = res + '\n';
    }
    display(res);
}

Question 4 (from 2014 finals)

Given number_of_rows, and number_of_columns, and func make a 2D array where elements at A[r][c] are func(r,c).

function make_arr(f, row, col){
    let res = [];
    for(let i = 0; i < row; i = i + 1){
        res[i] = [];
        for(let j = 0; j < col; j = j + 1){
            res[i][j] = f(i, j);
        }
    }
    return res;
}

Question 5 (from 2014 finals)

Write a function flip that inverts the contents of an image (image is a 2D array)

[[1,2,3],
 [4,5,6]]

Turns into

[[6,5,4],
 [3,2,1]]
function flip(arr){
    const res = [];
    const rows = array_length(arr);
    const cols = rows === 0 ? 0 : array_length(arr[0]);
    for(let i = 0; i < rows; i = i + 1){
        res[i] = [];
        for(let j = 0; j < cols; j = j + 1){
            res[i][j] = arr[rows-i-1][cols-j-1];
        }
    }
    return res;
}

Medium

Question 1

Quick sort partition Given an array [6,8,5,7,1,4,9,2], rewrite the array such that the anything less than the first member is written in front while anything greater than the first member is at the back.

Output: [6,4,2,5,1,8,9,7]

function qsp(arr){
    const piv = arr[0];
    const len = array_length(arr);
    const res = [piv];
    let left = 1;
    let right = len - 1;
    for(let i = 1; i < len; i = i + 1){
        if(arr[i] < piv){
            res[left] = arr[i];
            left = left + 1;
        } else {
            res[right] = arr[i];
            right = right - 1;
        }
    }
    return res;
}
qsp([6,8,5,7,1,4,9,2]);

Question 2

Stock prices (By Avenger Rahul) Source Academy

Given a list of stock prices, find the maximum profit you can get in ONE transaction (buy and sell once only)

e.g. list(100, 180, 260, 310, 40, 535, 695)

answer is 695 - 40 = 655

For the above example, you buy the stock when its price is 40 and sell at 695.

Remember, the stocks in the list are arranged by day! You cannot buy a stock from a later day and sell it earlier :O

e.g. list(655,40,100,30)

answer is 100 - 40 = 60

If you simply take max - min, you will get 655-30 which is wrong!

Can you solve this problem in O(n)?

function maxStockPrice(lst) {
    const arr = [];
    function h(lst){
        if(!is_empty_list(lst)){
            arr[array_length(arr)] = head(lst);
            h(tail(lst));
        } else {}
    }
    h(lst);
    //pair(min, max_profit)
    arr[0] = [arr[0], 0];
    for(let i = 1; i < array_length(arr); i = i + 1){
        const cur = arr[i];
        arr[i] = arr[i-1];
        if(arr[i-1][0] > cur){
            arr[i][0] = cur;
        } else {}
        if(cur - arr[i-1][0] > arr[i-1][1]){
            arr[i][1] = cur - arr[i-1][0];
        } else {}
    }
    return arr[array_length(arr)-1][1];
}
maxStockPrice(list(100, 180, 260, 310, 40, 535, 695));

Question 3

Prime numbers (idea from Avenger David K)

function all_primes_below_x(x) {
	//your code here
}

// all_primes_below_x(10);
// returns list (2, 3, 5, 7)
// length(all_primes_below_x(1000));
// returns 168
function all_primes_below_x(x) {
	//your code here
	let res = list();
	let ok = true;
	for(let i = 2; i < x; i = i + 1){
	    ok = true;
	    for(let j = 2; j <= math_sqrt(i); j = j + 1){
	        if(i % j === 0){
	            ok = false;
	            break;
	        } else { }
	    }
	    if(ok){
	        res = append(res, list(i));
	    } else {}
	}
// 	return res;
	
	function h(low, ans){
	    if(low > x){
	        return ans;
	    } else {
	        let ok = true;
	        for(let i = 2; i <= math_sqrt(low); i = i + 1){
	            if(low % i === 0){
	                ok = false;
	                break;
	            } else {}
	        }
	        if(ok){
	            return h(low+1, append(ans, list(low)));
	        } else {
	            return h(low+1, ans);
	        }
	    }
	}
	
	return h(2, []);
}

Question 4

Given a 2D array of size n by n, obtain the greatest possible ab+cd from 4 numbers in a diagonal (a,b,c,d are in order of the diagonal) (idea from Project Euler)

function getGreatest(arr){
    const n = array_length(arr);
    if(n < 4){
        error("wrong!");
    } else {
        function getDiag(x, y){
            return arr[x][y] + arr[x+1][y+1] + arr[x+2][y+2] + arr[x+3][y+3];
        }
        let greatest = 0;
        for(let i = 0; i < n-3; i = i + 1){
            for(let j = 0; j < n-3; j = j + 1){
                if(i === 0 && j === 0){
                    greatest = getDiag(i,j);
                } else {
                    const ans = getDiag(i,j);
                    greatest = (ans > greatest ? ans : greatest);
                }
            }
        }
        return greatest;
    }
}

function gen(x,y){
    let res = "[";
    let cnt = 1;
    for(let i = 0; i < x; i = i + 1){
        res = res + '[';
        for(let j = 0; j < y; j = j + 1){
            if(j !== y-1){
                res = res + cnt + ',';
            } else {
                res = res + cnt;
            }
            cnt = cnt + 1;
        }
        if(i !== x-1){
            res = res + '],';
        } else {
            res = res + ']';
        }
    }
    res = res + ']';
    return res;
}

getGreatest([[ 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]]);

Difficult

Question 1

Largest possible contiguous sum in O(n^3), O(n^2), and O(n)

Obtain the largest possible sum of substring in an array [1,-1,3,-5,3,9,-6,2,0,3,8,-7]

The answer is 3 + 9 + (-6) + 2 + 0 + 3 + 8 = 19

function f(arr){
    //pair[max_with_current, max]
    //max_with_current = max(last_max_with_current + current, current);
    let dp = [];
    for(let i = 0; i < array_length(arr); i = i + 1){
        if(i === 0){
            dp[i] = pair(arr[i], arr[i]);
        } else {
            const with_last = head(dp[i-1]) + arr[i];
            const max_with_cur = with_last > arr[i] ? with_last : arr[i];
            const max = max_with_cur > tail(dp[i-1]) ? max_with_cur : tail(dp[i-1]);
            dp[i] = pair(max_with_cur, max);
        }
    }
    return tail(dp[array_length(arr)-1]);
}

f([1,-1,3,-5,3,9,-6,2,0,3,8,-7]);

List Processing and Recursion Revision

Questions from Avenger Thomas

Try to write recursive and iterative functions for the following:

Question 1

f(g, n, a) = a + g(a) + g(g(a)) + ... + g(g(...g(a)...))

function f(g,n,a){
    if(n === 0){
        return a;
    } else {
        return a+accumulate((x,y)=>x+y, 0, map(t=>g(t), f(g,n-1,a)));
    }
}
function ff(g,n,a){
    function h(x, ans, last){
        if(x > n){
            return ans;
        } else {
            const cur = g(last);
            return h(x+1, ans+cur, cur);
        }
    }
    return h(0, 0, a);
}

Question 2

// equals(a, b) = checks if two lists/pairs/list of pairs/list of lists/whatever
// have the same contents. e.g.
/*
equals(
    pair(2, list(1, 2, 4, pair(3, pair(2, 3)))),
    pair(2, list(1, 2, 4, pair(3, pair(2, 3))))) === true
*/
function e(a,b){
    if(is_empty_list(a) || is_empty_list(b)){
        return is_empty_list(a) && is_empty_list(b);
    } else if((!is_pair(a))&&(!is_pair(b))){
        return a === b;
    } else {
        return e(head(a), head(b)) && e(tail(a), tail(b));
    }
}
function ee(a,b){
    function h(res){
        //todo
    }
}

Question 3

// gospelistze(lst) = converts each number into a list containing
// that many copies of that number.
// list(2, list(3, 4)) --> list(list(2, 2), list(list(3, 3, 3), list(4, 4, 4, 4)))
function f(lst){
    function make_list(x, n, res){
        if(n === 0){
            return res;
        } else {
            return make_list(x, n-1, pair(x, res));
        }
    }
    if(is_empty_list(lst)){
        return [];
    } else if(is_list(lst)){
        return pair(f(head(lst)), f(tail(lst)));
    } else {
        return make_list(lst, lst, []);
    }
}

Practice Questions

Question 1

First, implement tail_n_times(xs, n) to execute tail(tail(...tail(xs))) for n times Second, implement f(xs, n) that returns the last n elements of a list xs.

function tail_n_times(xs, n){
    function h(cnt, res){
        if(cnt >= n){
            return res;
        } else {
            return h(cnt+1, tail(res));
        }
    }
    return h(0, xs);
}
function last_n(xs, n){
    const len = length(xs);
    return tail_n_times(xs, len-n);
}

Question 2

Write two_d_map, a function that performs f on 2D list.

function two_d_map(f, xss) {
	//your code here
}

// two_d_map(times_two, list(list(1,2,3),
                          list(4,5,6),
                          list(7,8,9)));

//returns list(list(2,4,6),
               list(8,10,12),
               list(14,16,18)));
function two_d_map(f, xs){
    if(is_empty_list(xs)){
        return [];
    } else {
        return pair(map(f, head(xs)), two_d_map(f, tail(xs)));
    }
}

two_d_map(t=>t*2, list(list(1,2,3),
                          list(4,5,6),
                          list(7,8,9))
);

Question 3

Write snake that converts list(list(1,2,3), list(4,5,6), list(7,8,9)) to list(1,2,3,6,5,4,9,8,7).

function snake(xs){
    function helper(ls, n, ans){
        if(is_empty_list(ls)){
            return ans;
        } else {
            if(n === 1){
                return helper(tail(ls), 0, append(ans, head(ls)));
            } else {
                return helper(tail(ls), 1, append(ans, reverse(head(ls))));
            }
        }
    }
    return helper(xs, 1, []);
}

snake(list(list(1,2,3), list(4,5,6), list(7,8,9)));

Question 4 (from 2016 PE)

num-of-matches

function num_of_matches(a, b){
    function in_list(n, xs){
        if(is_empty_list(xs)){
            return false;
        } else {
            if(head(xs) === n){
                return true;
            } else {
                return in_list(n, tail(xs));
            }
        }
    }
    if(is_empty_list(a)){
        return 0;
    } else {
        if(in_list(head(a), b)){
            return 1 + num_of_matches(tail(a), b);
        } else {
            return num_of_matches(tail(a), b);
        }
    }
}

num_of_matches(list(1,2,3,4),list(1,2,3));

Question 5 (from 2013 paper)

Table for Two Write a function that outputs a list of pairings for n people, n is a positive even integer.

all_pairings(4) = list(list(pair(3, 1), pair(2, 4)), list(pair(1, 2), pair(3, 4)), list(pair(2, 3), pair(1, 4)));
function all_pairings(n) {
    function _map(f, xs) {
        function h(lst, ans) {
            if (is_empty_list(lst)) {
                return ans;
            } else {
                return h(tail(lst), pair(f(head(lst)), ans));
            }
        }
        return h(reverse(xs), []);
    }

    function list_gen(x, ans) {
        if (x === 0) {
            return ans;
        } else {
            return list_gen(x - 1, pair(x, ans));
        }
    }

    function h(lst) {
        if (is_empty_list(lst)) {
            return list([]);
        } else {
            return accumulate(append,
                [],
                _map(
                    x =>
                    (_map(t => pair(head(x), t), h(tail(x)))),
                    _map(
                        x =>
                        pair(pair(head(lst), x), filter(t => t !== x, tail(lst))),
                        tail(lst))));
        }
    }
    return h(list_gen(n, []));
}

all_pairings(6);

More Practice

Question 1 (from 2015 PE)

Sublist replace - must not modify original list.

Use tail_n_times and is_prefix_of (xs, ys) which returns true if list(a,b,c) is prefix of list(a,b,c,d,e,f)

sublist-replace

function tail_n_times(xs, n){
    function h(cnt, res){
        if(cnt >= n){
            return res;
        } else {
            return h(cnt+1, tail(res));
        }
    }
    return h(0, xs);
}
function is_prefix_of(xs, ys){
    if(is_empty_list(xs)){
        return true;
    } else {
        if(is_empty_list(ys)){
            return false;
        } else {
            if(head(xs) === head(ys)){
                return is_prefix_of(tail(xs), tail(ys));
            } else {
                return false;
            }
        }
    }
}
function sublist_replace(a, b, c){
    // replace all a with b in c
    const lenA = length(a);
    const lenB = length(b);
    let res = [];
    function h(xs){
        if(is_empty_list(xs)){
            return undefined;
        } else if(is_prefix_of(a, xs)){
            res = append(res, b);
            h(tail_n_times(xs, lenA));
        } else {
            res = append(res, list(head(xs)));
            h(tail(xs));
        }
    }
    h(c);
    return res;
}

Question 2 (from 2017 midterm)

Rucer Puzzle

Rucer-puzzle

function solvable(xs, n){
    const len = length(xs);
    function h(cur, rem){
        if(cur === len-1){
            return true;
        } else if(rem <= 0){
            return false;
        } else {
            const now = list_ref(xs, cur);
            if(!(cur + now < len||cur - now >= 0)){
                return false;
            } else if(cur + now < len){
                // can walk right
                return h(cur + now, rem-1);
            } else if(cur - now >= 0){
                // can walk left
                return h(cur - now, rem-1);
            } else { }
        }
    }
    return h(0, n);
}
// solvable(list(6,1,3,5,2,2,4,3),3);
// solvable(list(3,5,8,4,2,7,1,6),3);

Question 3

reorder

function ref_head(xs, n){
    if(n === 0){
        return xs;
    } else {
        return ref_head(tail(xs), n-1);
    }
}

function swap(a, b, xs){
    const t = list_ref(xs, a);
    set_head(ref_head(xs, a), list_ref(xs, b));
    set_head(ref_head(xs, b), t);
}

function reorder(lst){
    const len = length(lst);
    for(let i = 0; i < len/2 - 1; i = i + 1){
        for(let j = i; j <= len-2; j = j + 2){
            swap(j, j+1, lst);
        }
    }
    swap(len/2 - 1, len/2, lst);
    return lst;
}

const a = list(1,2,3,4,5,6,7,8);
reorder(a);

Question 4

rotate

function rotate(lst, k){
    if(k === 0){
        return lst;
    } else {
        return rotate(append(tail(lst), list(head(lst))), k-1);
    }
}

High-precision addition

Implement a high-precision addition library using lists in Source.

// Question 1
// Convert a list of numbers to a number
function list_to_number(lst){
    function helper(xs, ans){
        if(is_empty_list(xs)){
            return ans;
        } else {
            return helper(tail(xs), ans*10 + head(xs));
        }
    }
    return helper(lst, 0);
}
display(list_to_number(list(1,2,3)));
// Convert a list of numbers to a string representing that number
function _list_to_string(lst){
    if(is_empty_list(lst)){
        return "";
    } else {
        return (""+head(lst)) + _list_to_string(tail(lst));
    }
}
display(_list_to_string(list(1,2,3,4)));
// Convert a single digit character to a number
function digit(x){
    return x === '0'
                ? 0
                : x === '1'
                ? 1
                : x === '2'
                ? 2
                : x === '3'
                ? 3
                : x === '4'
                ? 4
                : x === '5'
                ? 5
                : x === '6'
                ? 6
                : x === '7'
                ? 7
                : x === '8'
                ? 8
                : x === '9'
                ? 9
                : -1;
}
// Convert a string representing number to a list representing the same
function string_to_list(str){
    function array_drop(arr, n){
        const res = [];
        for(let i = n; i < arr.length; i = i + 1){
            res[res.length] = arr[i];
        }
        return res;
    }
    if(is_empty_list(str)){
        return [];
    } else {
        return pair(digit(str[0]), string_to_list(array_drop(str, 1)));
    }
}
display(string_to_list("123"));
// Convert pair("+", lst) or pair("-", lst) to a number with sign
function signed_number(x){
    return head(x) === "+" 
        ? list_to_number(tail(x)) 
        : -1 * list_to_number(tail(x));
}
display(signed_number(pair("-", list(1,2,3))));
// Add a single digit number to a number represented by a list
function add_single(n, lst){
    if(is_empty_list(lst)){
        return list(n);
    } else if(n === 0){
        return lst;
    } else {
        const rev = reverse(lst);
        const t = head(rev) + n;
        if(t < 10){
            return reverse(pair(t, tail(rev)));
        } else {
            return append(add_single(1, reverse(tail(rev))), list(t%10));
        }
    }
}
display(add_single(1, list(1,2,9)));
display(add_single(1, list(1,9,9)));
// Add two lists rep of numbers together, return list rep of their sum
function add(xs, ys){
    if(is_empty_list(ys)){
        return xs;
    } else {
        const ys_rightmost = head(reverse(ys));
        const ys_rem = reverse(tail(reverse(ys)));
        const xs_add_single = add_single(ys_rightmost, xs);
        const xs_last = head(reverse(xs_add_single));
        const xs_res_head = reverse(tail(reverse(xs_add_single)));
        return append(add(xs_res_head, ys_rem), list(xs_last));
    }
}
display(add(list(1,2,3), list(1,2,7)));
display(add(list(1,2,3), list(0)));
// Take to strings of number a and b, output their sum
// a and b can be up to 1000 digits long
function high_pres_add(a, b){
    return _list_to_string(add(string_to_list(a), string_to_list(b)));
}
display(high_pres_add("123","127"));

Least possible edits

// Get the least possible "edits" to change string m to string n
// By "edit" we mean add, delete or replace, one character at a time

function min_edit(m, n){
    const min = (x,y) => x < y ? x : y;
    const lenm = length(m);
    const lenn = length(n);
    if(is_empty_list(m)){
        return lenn;
    } else if(is_empty_list(n)){
        return lenm;
    } else {
        if(head(m) === head(n)){
            return min_edit(tail(m), tail(n));
        } else {
            return 1 + min(min_edit(m, tail(n)),min(min_edit(tail(m), n), min_edit(tail(m), tail(n))));
        }
    }
}

const a = list('s','a','t','u');
const b = list('b','u');
min_edit(a,b);

Count cycles

In lecture, you saw how we can create arbitrary cyclical data structures using set_head and set_tail. In this question, we will go one step further. Write a procedure count_cycles that takes mutable data structure (consisting of pair boxes) and counts the number of directed cycles in the data structure. Because head and tail pointers have direction, a directed cycle exists when it is possible to come back to the same pair pair by following some non_zero path of car or cdr pointers. The following are some examples:
Images
A directed cycle is a sequence of links such that the node at the start of the first link is the same as the node at the destination of the last link and there are no repeated links and nodes in the sequence. For example, in the following pair structure, there are altogether 4 directed cycles: (l_a,l_c), (l_a,l_d), (l_b,l_c), and (l_b,l_d).
Images2
**Sample execution:** ```js var test_case1 = pair(1, 1); count_cycles(test_case1); // returns 0; var test_case2 = pair(1, pair(2, 0))); count_cycles(test_case2); // returns 0; var test_case3 = pair(1, pair(2, 0)); set_tail(tail(test_case3), test_case3); count_cycles(test_case3); // returns 1; var a = pair([], []); set_head(a, a); var test_case4 = pair(a, a); count_cycles(test_case4); // returns 1; var c = pair([], []); var test_case5 = pair(c,c); set_head(c, test_case5); set_tail(c, test_case5); count_cycles(test_case5); // returns 4; var test_case6 = pair(true, true); var help4 = pair(true, true); set_head(test_case6, help4); set_tail(test_case6, test_case6); set_head(help4, test_case6); set_tail(help4, help4); count_cycles(test_case6); // returns 3; ``` ```js function count_cycles(xs){ let count = 0; function helper(ys, enc){ if(is_empty_list(ys) || !is_array(ys) || !is_empty_list(filter(x => x === ys, enc))){ return 0; } else { enc = pair(ys, enc); let left = false; let right = false; if(!is_empty_list(filter(x => x === head(ys), enc))){ display('l'); count = count + 1; left = true; } else {} if(!is_empty_list(filter(x => x === tail(ys), enc))){ display('r'); count = count + 1; right = true; } else {} if(!left){ helper(head(ys), enc); } else {} if(!right){ helper(tail(ys), enc); } else {} } } helper(xs, []); return count; } // Test 1 // const a = pair(1,1); // const b = pair(1,1); // set_head(a,b); // set_tail(a,b); // set_head(b,a); // set_tail(b,a); // count_cycles(a); // Test 2 // count_cycles(list(1,2)); // Test 3 // const a = pair(1,1); // set_head(a,a); // count_cycles(a); // Test 4 // const a = pair(1,1); // const b = pair(1,1); // set_head(a,b); // set_tail(a,a); // set_head(b,a); // set_tail(b,b); // count_cycles(a); // Test 5 const a = pair(1,1); const b = pair(1,[]); set_head(b,b); set_head(a,b); set_tail(a,b); count_cycles(a); ``` ## List operation template ```js // member() function that matches a list // however, it returns the remaining head also function is_member_list(xs, ys){ function is_prefix(xs, ys){ if(is_empty_list(xs)){ return true; } else if(length(xs) > length(ys)){ return false; } else { if(head(xs) === head(ys)){ return is_prefix(tail(xs), tail(ys)); } else { return false; } } } function helper(xs, ys, left){ if(is_empty_list(xs)){ return pair(reverse(left), ys); } else if(length(xs) > length(ys)){ return pair(reverse(left), []); } else { if(is_prefix(xs, ys)){ return pair(reverse(left), ys); } else { return helper(xs, tail(ys), pair(head(ys), left)); } } } return helper(xs, ys, []); } is_member_list(list(1,2),list(2,2,1,2,3,4)); // return pair(take(xs, n), drop(xs, n)) function take_drop(xs, n){ function helper(left, right, n){ if(n === 0){ return pair(reverse(left), right); } else { return helper(pair(head(right), left), tail(right), n-1); } } return helper([], xs, n); } take_drop(list(1,2,3),1); // find the nth head of a list xs function head_ref(xs, n){ if(n === 0){ return xs; } else { return head_ref(tail(xs), n-1); } } // set the nth element of a list xs to x function set_n(xs, n, x){ set_head(head_ref(xs, n), x); } const a = list(1,2,3,4); set_n(a, 2, 5); a; // copy a list xs function copy_list(xs){ return map(x => x, xs); } ``` ### Make election ```js function make_elections(parties){ const p = []; let stations = 0; while(!is_empty_list(parties)){ const obj = {name: head(parties), votes: 0}; p[p.length] = obj; parties = tail(parties); } function switcher(cmd){ if(cmd === "create_polling_station"){ return make_station(); } else if(cmd === "count_votes"){ let res = []; for(let i = 0; i < p.length; i = i + 1){ res = append(res, list(pair(p[i].name, p[i].votes))); } return res; } else if(cmd === "num_station"){ return stations; } else { error('Invalid command!'); } } function make_station(){ const v = []; stations = stations + 1; for(let i = 0; i < p.length; i = i + 1){ const obj = {name: p[i].name, votes: 0}; v[v.length] = obj; } // display(stringify(v)); function switcher(cmd){ if(is_empty_list(cmd) || !is_list(cmd)){ error('wrong'); } else if(head(cmd) === "count_votes"){ let res = []; for(let i = 0; i < v.length; i = i + 1){ res = append(res, list(pair(v[i].name, v[i].votes))); } return res; } else if(head(cmd) === "vote"){ let ok = false; for(let i = 0; i < v.length; i = i + 1){ if(head(tail(cmd)) === v[i].name){ ok = true; v[i].votes = v[i].votes + 1; p[i].votes = p[i].votes + 1; break; } else { continue; } } if(!ok) { error('Spoilt vote!'); } else { } } else { error('wrong'); } } return switcher; } return switcher; } // Punters say it will happen year end _ what say you. var ge_2010 = make_elections(list("pap", "wp", "sdp")); //Neutral ward var ang_mo_kio_station = ge_2010("create_polling_station"); //Opposition ward var hougang_station = ge_2010("create_polling_station"); //PAP stronghold var marine_parade_station = ge_2010("create_polling_station"); // ge_2010("stuff"); // returns "Invalid command" ge_2010("num_station"); //returns 3 //Here comes Voting Day! ang_mo_kio_station(list('vote','pap')); ang_mo_kio_station(list('vote','pap')); ang_mo_kio_station(list('vote','pap')); ang_mo_kio_station(list('vote','pap')); display(ang_mo_kio_station(list('count_votes'))); hougang_station(list('vote','wp')); display(hougang_station(list('count_votes'))); //And the final count! ge_2010("count_votes"); //returns list(("pap", 9),("wp", 7), ("sdp", 2)) ```