Recursive Reverse List - c++

I need to write an algorithm called reverseNodes that takes a RefToNode as a parameter and recuriveley reverses the list the header i came up with was
Algorithm reverse (rList)
reverves elementsin a list
Pre: rList :: a referance to a list to be reversed
Post: elements in rList are reversed
if ( rList !=NULL)
reverseNodes (rList -> head)
return
I need to find a way to write this is psuedocode and find the time complexity

Sometimes it is easier to create some un-formal algorithm gibberish, if you start
with the idea expressed clearly. Then, obfuscate and verbalize until you have something, your professor will happily accept.
So, lets start with our general idea of the algorithm:
let rec fold folder acc l =
match l with
| [] -> acc
| x::xs -> fold folder (folder acc x) xs
let prepend l e = e :: l
let revlist l = fold prepend [] l
...and start to verbalize:
let result = empty list
let l = the list we want to reverse
if l is the empty list, goto 7
let head = l.front, l = l.pop_front()
result.push_front head
goto 3
l = result
The steps 3..6 can be easily expressed as a recursive function:
void loop(list& l, list& result)
{
if( l.is_empty()) return;
auto head = l.front();
l.pop_front();
result.push_front(head);
loop(l,result);
}
As we want to create the illusion of in-place.reversal, our reverse_list function is
void reverse_list( list& l )
{
list result;
loop( l, result);
l = result;
}
Alternate solution
We can also do it in another way:
let rec revlist1 l =
match l with
| [] -> l
| x::xs -> (revlist1 xs) # [x]
This basically states, that the reversed list is the front element of the original list appended to the reverse of the rest.
Translating the algorithm to gibberish form yields:
Node* reverse_list1( Node* list )
{
if( list == NULL) return NULL; // reverse of empty list is empty list.
if( list->next == NULL ) // last element in list?
return list; // the reverse of a list with 1 element is the same.
else
{
Node* head = list;
Node* tail = list->next;
head->next = NULL;
Node* end_of_reverse_tail = tail; // the first will be the last...
Node * result = reverse_list1(tail);
end_of_reverse_tail->next = head;
return result;
}
}
Note, that this is not a tail recursive solution.

Related

F# Recursive function for adding even list elements

I have a problem, namely, I would like to turn the following code into a recursive function for adding even list elements, but unfortunately I do not know how much ...
let even = List.filter(fun x -> x%2=0)[1..100]
let sum = List.length even
printfn "Even: %A sum: %d " even sum
Thank you for any help!
You can use pattern matching to check if the first element in your list is even,
and if so, to add it into accumulator list and call the same method on the rest of the list. In case the element is odd - just call the same method for the rest of the list without adding anything to accumulator. When list is empty - return the accumulator and you will have list of just even numbers.
let rec getEven (input : int list) (acc: int list) =
match input with
| head :: tail when head % 2 = 0 -> (getEven tail (head :: acc))
| head :: tail when head % 2 = 1 -> (getEven tail (acc))
| _ -> acc
let even = getEven [1..10] []
let sum = List.sum even
Function above will produce:
val getEven : input:int list -> acc:int list -> int list
val even : int list = [10; 8; 6; 4; 2]
val sum : int = 30
P.S. to calculate sum of the elements, you should use List.sum instead of List.length that will return you the number of elements in list.
Also note, that you can calculate sum of even elements in getEven function, storing not the list of even elements, but their sum.

How to use fold on an elaborate function in ocaml

As the title suggests, I want to use fold. If I understand correctly, it it used to apply a function to every item in a list. That's what I want to do with my function, but I don't know how to format it.
Here is the function I want to use with fold :
let pairing list =
let rec aux counter length paired list = match list with
| [] -> paired
| [head] -> paired
| head :: head' :: tail -> if counter = length then aux (counter-1) length ((head, head) :: paired) (head :: head' :: tail) else aux counter length ((head, head') :: paired) (head' :: tail)
in List.rev(aux (List.length(listheads list)) (List.length(listheads list)) [] (listheads list));;
What it does is it returns a list of all the items in the list paired together.
For example, if my list is [3;4;2], it should return
[(3,3); (3,4); (3,2); (4,3); (4,4); (4,2); (2,3); (2,4); (2,2)]
What it returns at the moment is only [(3,3); (3,4); (3,2)], because the function only applies to the first item of the list.
Here are all the helper functions :
let rec member list x = match list with
| [] -> false
| head :: tail -> head = x || member tail x
let head_list list =
let rec aux l1 list = match list with
| [] -> l1
| (x,y) :: tail -> aux (x :: l1) tail
in List.rev (aux [] list);;
let head'_list list =
let rec aux l2 list = match list with
| [] -> l2
| (x,y) :: tail -> aux (y :: l2) tail
in List.rev (aux [] list);;
let listheads list =
let rec aux returnlist l1 l2 = match l1 with
| [] -> returnlist
| head :: tail -> if member l2 head = true && member returnlist head = false then aux (head :: returnlist) tail l2 else aux returnlist tail l2
in List.rev(aux [] (head_list list) (head'_list list));;
What listheads does is it will take my original list (say [(3,4); (4,2); (2,3); (4,7); (9,4)]), use head_list and head'_list in order to determine which integers are both in head and head' position in the tuple, and put them in the list (in the case I gave, [3;4;2]).
I know that fold takes a function, an empty list and a list as arguments, but I don't know how to use pairing with fold.
Your code need to make a double pass on the list
let pairing l =
let second_pass x acc y = ...... in
let first_pass acc el = ....... in
List.fold_left first_pass [] l |> List.rev
The first pass function should call the second pass function, and the second pass function will create the pair element. Free to you for completing the code of the two functions.
Here the result I have :
utop # pairing [3 ; 4 ; 2];;
- : (int * int) list =
[(3, 3); (3, 4); (3, 2); (4, 3); (4, 4); (4, 2); (2, 3); (2, 4); (2, 2)]
It's very difficult to answer your question because there's no clean place to add a fold to get the result you want.
It might be more fruitful just to debug your code. It seems to me you're using your counter backwards. Its initial value is the length of the list and it is decremented for each recursive call. But your test for termination tests against the length of the list. It seems to me you should be testing against 0 (or possibly 1).
If you have a function f that does something interesting to a value, and you have a list of the values, you can use List.map to get a list of the values of f applied to each element of the list. You don't need a fold for that.
The purpose of a fold is to compute thing other than just a list of the function values. For examle, if each call to f makes a list of values, you could use a fold to keep concatenating these lists into a longer list.
Let's say f makes a value x into a list [x; x]. Then you can create a (reversed) doubled list something like this:
let f x = [x; x]
let double l =
let aux sofar x = f x # sofar in
List.fold_left aux [] l
# double [1;2;3];;
- : int list = [3; 3; 2; 2; 1; 1]
You could possibly follow this pattern if you can come up with a function like f that transforms a value into a list. If you define f inside your outer function it will have access to the initial list.

Delete the ith element of a list

Write a function that deletes the ith element of a list. If the length of the list is less than i, return the list.
This is the output wanted:
- deleteIth([1,2,3,4,5,6],3);
val it = [1,2,4,5,6] : int list
- deleteIth([1,2,3,4,5,6],7);
val it = [1,2,3,4,5,6] : int list
Here's my code:
fun deleteIth (L, i) =
let
(* Deletes the element of a list at ith index *)
fun delete (nil, i, position) = nil
| delete (x::xs, i, position) = if i = position then xs else
x :: delete (xs, i, position + 1)
in
if i >= 0 andalso i < length L then delete (L, i, 0) else L
end;
note: the line x :: delete (xs, I, position + 1) should be right after the else in the previous line the line wrap made me show the code this way. Sorry for that.
But my code out puts
- deleteIth([1,2,3,4,5,6],3);
val it = [1,2,3,5,6] : int list
- deleteIth([1,2,3,4,5,6],7);
val it = [1,2,3,4,5,6] : int list
I would appreciate the help thanks.
Since you've got your expected results, here's a shorter version that only traverses the list once, and never beyond the element to remove.
(length must traverse the entire list to determine its length. It's possibly the least useful list function.)
The general case, k > 1 and the list is not empty:
To remove the k:th element, remove element k-1 from the tail of the list, then add the head of the original list to the result.
Base cases:
Removing element 1 from a list produces the tail of the list.
Removing anything from the empty list produces the empty list.
The case where the list is shorter than k will terminate when it reaches the empty list.
Like this:
fun delete_ith ([], k) = []
| delete_ith (x::xs, 1) = xs
| delete_ith (x::xs, k) = x :: delete_ith (xs, k - 1)

function parameter errors in Standard ML

I am trying to implement a function treeToString that uses this data type:
datatype Tree = LEAF of string | NODE of Tree list;
and this tree:
val L1a = LEAF "a"
val L1b = LEAF "b"
val L1c = LEAF "c"
val L2a = NODE [L1a, L1b, L1c]
val L2b = NODE [L1b, L1c, L1a]
val L3 = NODE [L2a, L2b, L1a, L1b]
val L4 = NODE [L1c, L1b, L3]
val L5 = NODE [L4]
The function takes an argument like treeToString L5 which will output the string ((cb((abc)(bca)ab)))
The problem is I cannot figure out the correct way to differentiate between when the function takes in a LEAF or a NODE type. I wrote the code below to try and test this but I am getting errors. Anyone know the syntax in order to get this to work? Once I get the parameters down, the actual recursion should be easy.
(* treeToString *)
fun treeToString(LEAF str) = str
| treeToString(NODE h::t) =
h;
This function is what I used to get it working. Just needed to add parenthesis around my arguments
fun treeToString f Node = let
fun helperFun (LEAF(v)) = [f v]
| helperFun (NODE(h::t)) = ["("] # List.concat (map helperFun(h::t)) # [")"]
in
String.concat(helperFun Node)
end;
Change this:
| treeToString(NODE h::t) = ...
To this:
| treeToString (NODE (h::t)) = ...
The reason is that (NODE h::t) can be interpreted as either ((NODE h)::t) (where NODE h is the first item in a list of NODE's) or as (NODE (h::t)), which is what you want.

How to write iterative inorder traversal for BST in OCaml

It is easy enough to write recursive inorder traversal in OCaml, but how to write iterative one? with for loop or while?
Asking for someone to write something without recursive calls is stupid, but I'll still do it because it's an interesting exercise. Going from recursive to iterative is always the same process.
type tree = Leaf | Node of int * tree * tree
let rec in_order = function
| Leaf -> []
| Node(i,l,r) -> in_order l # (i :: in_order r);;
Alright, now we have our recursive function. The first step is to transform it to tail recursive. This is actually the hardest step since it requires a real logical and algorithmic change.
We are going to add a new parameter to the function that is going to contain the result of the computation :
let rec ino res = function
| Leaf -> ()
| Node(i,l,r) ->
begin
ino res r ;
res := i :: !res ;
ino res l
end
At the end, the result is !res.
Now that we have this, removing the recursive call is very easy, we just have to think about what does the compiler does when he has a recursive call. Well, it just does a while loop, after putting the parameters of the function and the next work to do in a stack. Let's just do it.
open Stack
type work = Value of int | NextNode of tree ref
let ino t : int list =
let res = ref [] in
let stack = Stack.create () in
push (NextNode (ref t)) stack;
try
while true do
let current = pop stack in
match current with
Value i -> res := i :: !res
| NextNode n ->
begin
match !n with
Leaf -> ()
| Node(i,l,r) ->
begin
push (NextNode (ref l)) stack;
push (Value i) stack;
push (NextNode (ref r)) stack
end
end
done;
assert false
with
| Empty -> !res
Here we just remember the next thing to do. We know that when we reach a node we have to treat its right child, then the value of the node, then its left child, so we just put all this in the stack (in reverse order of course), and we keep going to the next element of the stack. When the stack is empty, we have visited the whole tree, and we can return.
I hope that this post manages to convince some people of the power of recursion over iterative programming. 3 lines Vs 26 lines. QED.
Here's another take on iterative in-order traversals:
type 'a node = {mutable data: 'a;
mutable left : 'a node option;
mutable right: 'a node option; }
let new_node data = {data; left = None; right = None;}
let insert tree new_data =
let module Wrapper = struct exception Stop_loop end in
let iter = ref tree in
try
while true do
if new_data < !iter.data
then match !iter.left with
| None ->
!iter.left <- Some (new_node new_data);
raise Wrapper.Stop_loop
| Some left_tree -> iter := left_tree
else if new_data > !iter.data
then match !iter.right with
| None ->
!iter.right <- Some (new_node new_data);
raise Wrapper.Stop_loop
| Some right_tree -> iter := right_tree
done
with Wrapper.Stop_loop -> ()
let in_order_traversal tree =
let module W = struct exception Stop_loop end in
let visited_stack = Stack.create () in
let iter_node = ref (Some tree) in
try while true do
(* Inner loop, we keep trying to go left *)
(try while true do
match !iter_node with
| None -> raise W.Stop_loop
| Some left ->
Stack.push left visited_stack;
iter_node := left.left
done;
with W.Stop_loop -> ());
(* If we have no more to process in the stack, then we're
done *)
if Stack.length visited_stack = 0
then raise W.Stop_loop
else
(* Here we're forced to start moving rightward *)
let temp = Stack.pop visited_stack in
Printf.sprintf "%s " temp.data |> print_string;
iter_node := temp.right
done
with W.Stop_loop -> ()
let () =
let root = new_node "F" in
["B";"G";"A";"D";"I";"C";"E";"H"] |> List.iter (insert root);
in_order_traversal root;
print_newline ();