Java Homework
Java Homework
1. (5 points) Write a function number-embed (ArrayList list) that returns the number of embedded lists in a given list. An element of a list is a character or a list itself. The required output is as follows: If list is (a b c), number-embed returns 0 If list is (1 (2) 3 (4 5 6)), number-embed returns 2 If list is (1 (2) 3 (4 (5 6))), number-embed returns 3 2. (15 points) Implement a version of set difference for lists called mydifference (ArrayList list1, ArrayList list2). Your function only needs to work for lists of characters. For example: If list1 is (a b c d) and list2 is (b d j), my-difference returns (a c) 3. (15 points) Write a recursive function occurrences (ArrayList list) that takes a list and returns a list that indicates how many times each 2 element appears, sorted by most common to least common (break ties any way you like). Dont forget that elements of a list may be lists too! The required output is as follows: If list is (a a b a c c d d), occurrences returns ((a 3) (c 2) (d 2) (b 1)) If list is (a a (b) a c c d (c (d)) (b) b d), occurrences returns ((a 3) ((b) 2) (c 2) (d 2) (b 1) ((c (d)) 1)) 4. (20 points) A palindrome reads the same backwards as forwards: for example, the phrase a man, a plan, a canal, Panama is a palindrome. Write a function my-palindrome (ArrayList list), that checks if the given list is a palindrome. Note that the function should work for lists that have an even or an odd number of elements. The lists will not have embedded lists. Look at the examples below: If list is (1 2 3 4 5 4 3 2 1), my-palindrome returns T If list is (a b b a), my-palindrome returns T If list is (1 2 3), my-palindrome returns F 5. (20 points) Define the function subsets (ArrayList list). It returns the list of all subsets of the elements in list. Note that the elements will be characters and will not be lists themselves. E.g., If list is (a b c), subsets returns (() (a) (b) (c) (a b) (b c) (a c) (a b c)) Note: The next problem is for graduate students only 6. (25 points; graduate students only) This is a three-part problem. (a) Write a function addvec (ArrayList list) that takes a single list of integers as input argument and returns the sum of the integers. (Assume the input list has only one level. Return 0 for an empty list.) 3 (b) Write a function vecmul (ArrayList list1, ArrayList list2) that will take as input two simple lists of integers. vecmul should multiply
these lists coordinate-wise as one would multiply vectors. If one list is longer than the other, the result should be as if the shorter were padded with ones. For example: If list1 is (2 3 4 5) and list2 is (1 4 5 2 14), vecmul returns (2 12 20 10 14) (c) Use addvec and vecmul to define an inner product function innprod (ArrayList list1, ArrayList list2) that multiplies the lists coordinate-wise and sums the resulting products. For example: If list1 is (1 2 3 4) and list2 is (7 8 9), innprod returns 54