Show me your best recursive functions.private static int pow(int x, int n) {
if (n == 0) {
return 1;
} else if (n % 2 == 0) {
return pow(x*x, n/2);
}
return pow(x*x, n/2)*x;
}
private static int fib(int n) {
if (n <= 2) return 1;
return fib (n-1) + fib(n-2);
}
int ack(int m, int n)
{
if (!m) return n + 1;
if (!n) return ack(m - 1, 1);
return ack(m - 1, ack(m, n - 1));
}
cmon guysprivate static HashSet<String> combinations(String s, int c) {
HashSet<String> combs = new HashSet<String>();
if(s.equals("")) {
return null;
} else if(s.length() == c) {
combs.add(s);
return combs;
}
for(int i = 0; i < s.length(); i++) {
combs.addAll(combinations(s.substring(0, i) + s.substring(i+1), c));
}
return combs;
}
private static HashSet<String> permutations(String s, String prefix) {
HashSet<String> perms = new HashSet<String>();
if(s.length() == 0) {
perms.add(prefix);
return perms;
}
for(int i = 0; i < s.length(); i++) {
perms.addAll(permutations(s.substring(0,i) + s.substring(i+1), prefix + s.charAt(i)));
}
return perms;
}
>>57494502
implying half of gee could even write a recursive function
here's a nice way to reverse a LL.public ListNode reverseList(ListNode head) {
return reverseListUtil(head, null);
}
private ListNode reverseListUtil(ListNode root, ListNode prev) {
if (root == null) return prev;
ListNode temp = root.next;
root.next = prev;
return reverseListUtil(temp, root);
}
>>57494394
>>57494430
>>57494502
>not tail recursive
>>57494430
Not using this
>>57494626
Here you arelet pow a b =
let rec loop accu a = function
| 0 -> accu
| b ->
let accu =
if b mod 2 = 0 then
accu
else
a * accu in
loop accu (a * a) (b / 2) in
loop 1 a b
;;
>>57494394public static bool rec() {
if(Math.random() < 0.0005) {
return true;
}
return rec();
}
Will this code halt?
If it halts what will it return?
I can never think recursively.
>>57497755
I think it will go to a loop for ever because I am pretty sure that Math.random() generates integers which you are comparing it to a different data type
>>57494394
int willy()
{
return willy() + 1;
}
>>57499009
>Math.random() generates integers
>public static double random()
>Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.