package unit4; import java.util.ArrayList; import java.util.Arrays; public class ExamplesRecursion { public static void main(String args[]) { System.out.println("sumN(5):"+sumN(5)); System.out.println("power(5,0):"+power(5,0)); int a[]={3,4,5,2}; System.out.println("sumArray({3,4,5,2}):"+sumArray(a)); System.out.println("checkSort({3,4,5,2}):"+checkSort(a)); a[3]=8; System.out.println("checkSort({3,4,5,8}):"+checkSort(a)); a[3]=-1; try { System.out.println("findMin({3,4,5,-1}):"+findMin(a)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("find({3,4,5,-1},5):"+find(a,5)); System.out.println("russianmultiply({5,-4}):"+russianmultiply(5,-4)); System.out.println("sum2toN(5):"+sum2toN(5)); System.out.println("binomial(5,2):"+binomial(5,2)); sort(a); System.out.println("sort({3,4,5,-1}):"+ Arrays.toString(a)); a=new int[1]; a[0]=3; sort(a); System.out.println("sort({3}):"+ Arrays.toString(a)); int[] b= {-2,1,0,-1}; sort(b); System.out.println("sort({-2,1,0,-1}):"+ Arrays.toString(b)); reverse(b); System.out.println("reverse({-2,1,0,-1}):"+ Arrays.toString(b)); System.out.println("tobinary(100):"+ toBinary(53)); System.out.println("minIndex({-1,0,1,-2}):"+minIndex(b,0,b.length-1)); fun2(b,0,b.length-1); System.out.println("fun2({-1,0,1,-2},0,3):"+Arrays.toString(b)); System.out.println("f(1):"+ f(91)); System.out.println("checkPalindrome('doctor'):"+ checkPalindrome("doctor")); System.out.println("checkPalindrome('acbca'):"+ checkPalindrome("acbca")); System.out.println("checkPalindrome('acbbca'):"+ checkPalindrome("acbbca")); System.out.println("checkPalindrome('a'):"+ checkPalindrome("a")); System.out.println("mystery(4):"+ mystery(3)); System.out.println("ackerman(3,5):"+ ackerman(3,5)); System.out.println("f2(0):"+ f2(0)); System.out.println("isPrimer(11):"+isPrime(11)); System.out.println("reversePhrase('this is my cat'):"+reversePhrase("cat")); System.out.println("elfish('telefono'):"+elfish("teleono")); } /*Problema 1 - Escribir un método recursivo que devuelve la suma de los N primeros enteros.*/ public static int sumN(int n) { if (n<0) { System.out.println("Error: n cannot be negative!!!"); return -1; } if (n==0) return 0; else return n+ sumN(n-1); } /*Problema 2 – Escribir un método recursivo que tome dos enteros, x y n (podemos suponer que n> = 0) y devuelve x power n. */ public static int power(int x, int n) { if (n<0) { System.out.println("Error: n cannot be negative!!!"); return -1; } if (n==0) return 1; //case base else return x*power(x,n-1); } /* * Problema 3 – Escribir un método recursivo que tome un número entero y devuelva el número de sus dígitos (por ejemplo, 2356 tiene 4 dígitos). Pista: 2356/10 = 235 , 235/10=23 y 23/10= 2 y no puedo seguir dividiendo entre 10 */ public static int digits(int n) { if (n<0) n=Math.abs(n); if (0<=n && n<10) return 1;//case base else return 1 + digits(n/10); } /* * Problema 4 – Escribir un método recursivo que toma un array de enteros y devuelve la suma de sus elementos. */ public static int sumArray(int a[]) { if (a==null || a.length==0) return 0; return sumArray(a,0); } private static int sumArray(int a[], int pos) { if (pos==a.length-1) return a[pos]; //case base else return a[pos]+sumArray(a,pos+1); } /* * Problema 5 – Escribir un método recursivo que tome un array de enteros y compruebe si el array está ordenado (orden ascendente). */ public static boolean checkSort(int a[]) { if (a==null || a.length<0) return true; return checkSort(a,0); } private static boolean checkSort(int a[], int pos) { if (pos==a.length-1) return true; if (a[pos+1]100) return x- 10; else return(f(f(x+11))); } /* * Problema 15 – Escribir un método recursivo que tome una cadena y verifica si es una palabra capicúa (por ejemplo, level, did, rotator). */ public static boolean checkPalindrome(String s) { if (s==null) return true; else return checkPalindrome(s,0,s.length()-1); } private static boolean checkPalindrome(String s, int left, int right) { if (left==right) return true; else if (lefta[m]) return binarySearchRec(a,x,m+1,end); else return m; //x=a[m] } else return -1; } /* Problema 17 – Escribir un método recursivo que toma una cadena y devuelve su longitud (sin utilizar la propiedad de la longitud). Se puede usar la subcadena del método. */ public static int lengthof(String s) { if (s==null||s.equals("")) return 0; return 1+lengthof(s.substring(1)); } /* * Problema 18 – Escribir un método recursivo que toma una cadena y la imprime. Pista: debes imprimir cada carácter. */ public static void printRec(String s) { if (s==null||s.equals("")) System.out.println(""); System.out.print(s.charAt(0)); printRec(s.substring(1)); } //Problema 19- ¿Qué significa este método? public static int mystery(int n) { if (n == 0) return 0; else return n + mystery(n-1); } /* * Problem 20. Una permutación de un conjunto de objetos es un orden particular de esos objetos. Cuando hablamos de "todas las permutaciones" de un conjunto, nos referimos a todas las formas posibles de ordenar esos objetos. Ejemplos: • Dado el conjunto vacío {}, la única permutación posible es {} • Dado el conjunto {A}, la única permutación posible es {A} • Dado el conjunto {A, B}, las posibles permutaciones son {AB, BA} • Dado el conjunto {A, B, C}, las posibles permutaciones son • {ABC, ACB, BAC, BCA, CAB, CBA} Escribir un método que tome un array de caracteres y encuentre todas sus permutaciones. */ public static ArrayList permutationsOf(String s) { ArrayList result=new ArrayList(); if (s.length()==0) result.add(""); else if (s.length()==1) result.add(s); else { char letter=s.charAt(0); ArrayList lstPerm=permutationsOf(s.substring(1)); for (String perm: lstPerm) { for (int i=0; i<=perm.length();i++) { result.add(perm.substring(0, i)+letter+perm.substring(i)); } } } return result; } /* Problema 21 – Escribir un método que implemente la función de Ackerman. La función de Ackermann se puede definir de la siguiente manera: • • • A(0, y) = y + 1 A(x, 0) = A(x - 1, 1) A(x, y) = A(x - 1, A(x, y - 1)) Esta función tarda mucho tiempo en computarse (¿por qué?). Implica llamadas recursivas repetidas */ public static int ackerman(int x, int y) { if (x == 0) return y + 1; else if (y == 0) return ackerman(x - 1, 1); else return ackerman(x - 1, ackerman(x, y - 1)); } /* * Problema 22. Escribir un método recursivo que toma una cadena y devuelve una nueva cadena donde todos los caracteres x en minúscula han sido reemplazados por caracteres y. No puede usar los métodos replaceAll o replace. */ public static String replaceXbyY(String s) { if (s==null || s.equals("")) return s; char first=s.charAt(0); if (first=='x') first='y'; return first + replaceXbyY(s.substring(1)); } /* * Problema 23. Escribe un método recursivo que toma un número entero y devuelve la suma de sus dígitos. Si usa x% 10, puede obtener su dígito más a la derecha (126% 10 es 6). x / 10 elimina este dígito (126/10 es 12). */ public static int sumDigits(int n) { n=Math.abs(n); if (n<10) return n; else return n%10 + sumDigits(n/10); } //Problema 24 – Escribir un método recursivo que toma una cadena y devuelve su inversa. public static String reverse(String s) { if (s==null ||s.equals("")) return s; char letter=s.charAt(0); return reverse(s.substring(1))+letter; } /* * Problema 25 – Escribir un método recursivo que toma una cadena y elimina sus duplicados consecutivos. Por ejemplo, "aabccba" se transforma en "abcba". */ public static String removeConDupli(String s) { if (s==null ||s.length()<=1) return s; char first=s.charAt(0); char second=s.charAt(1); if (first==second) return removeConDupli(s.substring(1)); else return first + removeConDupli(s.substring(1)); } /* * Problema 26 – Escribir un método recursivo que tome dos enteros, x e y, y calcule x mod * sin usar el operador %. */ public static int modulus(int val, int divisor) { if(val < divisor) return val; else return modulus(val - divisor, divisor); } //Problema 27. Qué es f(0)? f(0) = 997 public static int f2(int x) { if (x >1000) return x-4; else return f(f(x+5)); } /* * Problema 28 – Escribir un método recursivo que toma dos cadenas ordenadas alfabéticamente y las concatena en una nueva cadena. El resultado también debe estar ordenado alfabéticamente. */ public static boolean isSorted(String str) { if (str==null || str.length()<=1) return true; char first=str.charAt(0); char second=str.charAt(1); if (first>second) return false; return isSorted(str.substring(1)); } public String merge(String first, String second) { if (!isSorted(first) || !isSorted(first) ) { System.out.println("strings have to be sorted"); return null; } if(first ==null || first.equals("")) return second==null? first:second; else if (second == null || second.equals("")) return first; else if(first.charAt(0) < second.charAt(0)) return first.charAt(0) + merge( first.substring(1, first.length()), second); else return second.charAt(0) + merge(first, second.substring(1, second.length())); } //Problema 29. Explicar la funcionalidad de las siguientes funciones: //a) Obtiene la suma de y más el sumatorio de los números de 1 a x: fun1(x,y)=1+2+3+...+x+y public static int fun1(int x, int y) { if(x == 0) return y; else return fun1(x - 1,x + y); } //b) Devuvelve el índice del elemento más pequeño del array public static int minIndex(int a[], int start, int end) { if (start==end) return start; else { int m=(start+end)/2; int x=minIndex(a,start,m); int y=minIndex(a,m+1,end); //return the lower number if (a[x]= end_index) return; int min_index; int temp; min_index = minIndex(arr, start_index, end_index); temp = arr[start_index]; arr[start_index] = arr[min_index]; arr[min_index] = temp; } /* * Problema 30. Escribir un método recursivo que compruebe si un número n es primo (hay que comprobar si n es divisible por cualquier número por debajo n). */ public static boolean isPrime(int n) { if (n<0) { System.out.println("n cannot be negative"); return false; } if (n<=2) return true; else return isPrime(n,2); } public static boolean isPrime(int x,int y) { if (x==y) return true; if (x%y==0) return false; else return isPrime(x,y+1); } /* * Problema 31. Escribir un método recursivo que imprima un número entero con comas en los lugares correctos. Por ejemplo, 12345 se imprimirá como 12,345. */ public static String addCommas(int n) { if (n<1000) return String.valueOf(n); else { String tmp=addCommas(n/1000)+","; if (n % 1000 < 100) tmp=tmp+"0"; if (n % 1000 < 10) tmp=tmp+"0"; tmp=tmp+n%1000; return tmp; } } /* * Problema 32. Escribir un método recursivo para invertir las palabras en una cadena, es decir, "cat is running" se convierte en "running is cat". */ public static String reversePhrase(String str) { if (str==null||str.length()==0) return str; int pos=str.indexOf(' '); if (pos>-1) { String firstWord=str.substring(0, pos); return reversePhrase(str.substring(pos+1))+" " +firstWord; } else return str; } /* * Problema 33. Una palabra se considera elfish si contiene las letras: e, l, y f en ella, en cualquier orden. Por ejemplo, diríamos que las siguientes palabras son elfish: whiteleaf, tasteful y waffles, porque cada uno contiene esas letras. Escribir un método recursivo llamado elfish? que, dada una palabra, se indique si esa palabra es elfish o no. Escribir una función de predicado más generalizada llamada x-ish? que, dadas dos palabras, devuelva verdadero si todas las letras de la primera palabra están contenidas en el segundo. */ public static boolean elfish(String str) { if (str==null||str.length()==0) return false; String aux="elf"; return elfish(str,aux,0); } public static boolean elfish(String str, String aux, int i) { if (i>=aux.length()) return true; char letter=aux.charAt(i); if (str.contains(String.valueOf(letter))) return elfish(str,aux,i+1); else return false; } //Write a more generalized predicate function called x-ish? that, given two words, returns //true if all the letters of the first word are contained in the second. public static boolean xish(String word1, String word2) { if (word1==null||word1.length()==0) return true; if (word2==null||word2.length()==0) return false; String first=String.valueOf(word1.charAt(0)); if (word2.contains(first)) return xish(word1.substring(1),word2); else return false; } /* * Problema 34. Escribir un método recursivo de Java que cuente el número de ocurrencias del carácter 'a' en una cadena. Sugerencia: una método signature que funciona es public static int countA (String s). Considerar usar los métodos charAt o startsWith en String. */ public static int countA(String s) { if (s==null||s.length()==0) return 0; if (s.charAt(0)=='a') return 1+countA(s.substring(1)); else return countA(s.substring(1)); } }