Three More List Manipulation Exercises
October 14, 2016
We have three more list-manipulation exercises today, for those students midway through their beginning programming course who need practice with linked lists:
- Define a function that takes two lists, the second of which is a list of non-negative integers the same length as the first list, and returns a list of elements from the first list, in reverse order, each repeated a number of times as specified by the corresponding element of the second list.
- Rearrange the integers in a list so that all the odd numbers appear before all the even numbers, with both odd and even numbers in the same relative order in the output as they were in the input.
- Write a function that returns the nth item from the end of a list.
Your task is to write the three specified programs. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s a solution in Java.
Output:
My solution in clojure:
Output:
(t1 ‘(2 3 4 1) ‘(4 5 6 1)) => (1 1 1 1 4 4 4 4 4 3 3 3 3 3 3 2)
(t2 ‘(1 2 3 4 5 6 7 8)) => (1 3 5 7 2 4 6 8)
(t3 ‘(1 2 3 4 5 5 6 7) 3) => 5
Reblogged this on Computer geek.
@miguelpinia, it looks like we had different interpretations of task 1. I associated “reverse order” with the returned list. It looks like you associated “reverse order” with the input list.
Here’s the Clojure version of my interpretation, based on your code.
@V, are your functions intended to operate on Ruby Arrays? My interpretation of the problem was that ‘list’ refers to ‘linked list’ (based on the comment, “… practice with linked lists”), but after reading again I see that the tasks all say ‘list’, not ‘linked list’.
@miguelpinia There are no build-in linked lists in Ruby, so my implementation is intended for Arrays. I thought for this simple exercise LinkedList, List or Array could be used interchangeably.
@Daniel: It does mention “practice with linked lists” in the first line. Makes a nice exercise in pointer manipulation. Here’s C++ solutions to a couple of the previous set of exercises and the odd/even rearrangement problem: