lab7soln - String asterisks = getAsterisks(n-1); return...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1. public static int factorial(int n) { assert n >=0; if (n == 0) return 1; else return n * factorial(n-1); } When using an int, factorial is correct for n = 1, 2, 3, . .., 12 When using long, factorial is correct for n = 1, 2, 3, . .., 20 factorial(n) is incorrect when factorial(n)/n != factorial(n-1) 2. public static int count(String s, char c) { if (s.equals("")) return 0; int countRest = count(s.substring(1), c); if (s.charAt(0) == c) return 1 + countRest; else return countRest; } 3. public static String getAsterisks(int n) { assert(n >= 0); if (n == 0) return "*"; else { // save results so linear time instead of exponential time
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: String asterisks = getAsterisks(n-1); return asterisks + asterisks; } } 4. public static ArrayList<String> makePermutations(String s) { ArrayList<String> permutations = new ArrayList<String>(); if (s.length() == 0) { permutations.add(""); return permutations; } for (int i = 0; i < s.length(); i++) { String letter = s.substring(i, i+1); String shorter = s.substring(0,i) + s.substring(i+1); ArrayList<String> rest = makePermutations(shorter); for (String perm: rest) { permutations.add(letter + perm); } } return permutations; } Complexity: O(n!)...
View Full Document

This note was uploaded on 12/19/2009 for the course CS 121 taught by Professor Reid-miller during the Spring '09 term at Carnegie Mellon.

Page1 / 2

lab7soln - String asterisks = getAsterisks(n-1); return...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online