Reduction - PowerPoint PPT Presentation

1 / 21
About This Presentation
Title:

Reduction

Description:

1. Reduction. Reduction is a technique for solving problems by rephrasing the ... catch(IOException e) System.out.print('Error while writing: ' e); System.exit(1) ... – PowerPoint PPT presentation

Number of Views:58
Avg rating:3.0/5.0
Slides: 22
Provided by: Udi8
Category:

less

Transcript and Presenter's Notes

Title: Reduction


1
Reduction
  • Reduction is a technique for solving problems by
    rephrasing the problem in terms of another
    problem whose solution is known.
  • We say that we reduce the problem into another
    known problem.Reduction ExamplesP(x) ? Q1(x),
    Q2(x), Qk(x)
  • Where Qi(x) is simpler than P(x)
  • Sorting ? Finding minimum (selection sort)
  • Polynomial multiplication? Integer multiplication
    and addition

2
Recursion As Reduction
  • P(x) ? P(x1), P(x2), P(xk)
  • When xi ltlt x (xi is smaller than x)
  • Recursion is a fundamental programming technique
    that can provide an elegant solution to certain
    kinds of problems.
  • In recursion we solve a problem by reducing it to
    a similar, smaller problem whose input might be
    different.

3
Recursion In Programs
  • public static void f()
  • f()
  • public static void f(int n)
  • f(n-1)//reduction!
  • public static void f(int n)
  • if (n 0)//base case!
  • return
  • f(n-1)//reduction!
  • Effective Recursion Rules
  • Self call

4
Factorial Example
  • If n is a positive integer, we define n! - the
    factorial of n - as follows
  • n!123n
  • A simple implementation for a method that
    computes the factorial of a number would be with
    a loop that goes over the expression and keep
    track of the partial multiplication.

5
Factorial Example
  • public static long factorial(long n)
  • long fact 1
  • for (int i1 iltn i)
  • fact i
  • return fact
  • Factorial Reduction
  • The previous solution is simple, but we can
    find a simpler and more elegant solution with
    the following observation
  • For every integer n, such that n gt 1
  • n! 12...n (12...n-1)n (n-1)! n
  • So we have
  • 1! 1
  • n! (n-1)! n , for ngt1

6
From (n-1)! to n!
  • We can use these observations to derive a new
    implementation for computing n!
  • If n is 1, there is no problem, we know that
    1!1.
  • If ngt1 we cant say immediately the result, but
    if we only knew how to compute (n-1)! we could
    compute n! using the fact that n!(n-1)!
    n.How to find (n-1)! ?
  • Note, that we can make the reduction for any
    arbitrary n, such that n gt 1. So we can reduce
    the problem from n! to (n-1)! to (n-2)! etc.
    until we will face the problem of computing 1!
    which is known.

7
Factorial Recursive Computation
5! 5 4! 4 3!
3 2! 2 1!
1!
24
6
2
1
8
Factorial Recursive Code
  • public static long factorial(long n)
  • if (n1)
  • return 1
  • return nfactorial(n-1)
  • More elegant
  • public static long factorial(long n)
  • return ((n1) ? 1 nfactorial(n-1))

9
Recursive Methods
  • A method in Java that invokes itself is called a
    recursive method.
  • A recursive method has a base case which solve
    the task without a recursive call and the
    recursive part which solve the task by reducing
    it and using a recursive call.
  • If there is no base case the sequence of
    reductions will not come to an end. We call this
    case an infinite recursion.

10
isNumeric() Code
/ Checks if a given string consists only
from digit symbols. / public static boolean
isNumeric(String s) for (int i0
ilts.length() i) char c
s.charAt(i) if (clt0 cgt9)
return false return true
11
Recursive isNumeric()
  • Observe the following facts
  • An empty string doesnt contain non-digit
    characters, therefore the method should return
    true for the empty string.
  • If the first character of s is non-digit then the
    method should return false.
  • If the first character of s is a digit symbol,
    then the s is numeric if and only if the rest of
    s (without the first character) is numeric.

12
isNumeric() Recursive
/ Checks if a given string consists only
from digit symbols. / public static boolean
isNumeric(String s) if (s.length()0)
return true char c s.charAt(0)
return (cgt0 clt9
isNumeric(s.substring(1))
13
Fibonacci Code
1 1 2 3 5 8 13 21 34 55 89 144...
  • /
  • Returns the n number in fibonacci
  • series
  • /
  • public static int fibonacci(int n)
  • if (nlt1)
  • return 1
  • return fibonacci(n-1) fibonacci(n-2)

14
String Reversal
  • public static String reverse (String string)
  • if (string.length() 0)
  • return new String()
  • int last string.length() - 1
  • return string.charAt(last) reverse(string.subs
    tring(0, last))
  • hello world
  • dlrow olleh

15
Binary Search
  • Searching for 32
  • from 0, middle 4, to 9
  • from 5, middle 7, to 9
  • from 5, middle 5, to 6
  • 6

1 3 7 18 20 27 32
50 70 87
0 1 2 3 4 5 6
7 8 9
16
Binary Search
  • public class Searcher
  • public static int binarySearch (int values ,
    int target)
  • return binarySearch(values , 0 ,
    values.length-1,target)
  • public static int binarySearch (int values, int
    from, int to, int target)
  • if (from gt to) return -1
  • int middle (from to) / 2
  • if (valuesmiddle target) return middle
  • if (valuesmiddle gt target)
  • return binarySearch(values, from, middle -1,
    target)
  • else
  • return binarySearch(values,middle 1, to,
    target)

17
I/O - Text Files
  • System
  • The System class contains several
  • useful class fields and methods.
  • It cannot be instantiated.
  • err - The "standard" error output stream
  • in - The "standard" input stream
  • out - The "standard" output stream.
  •  

18
Text Files
  • import java.io.
  • public class Copy
  • public static void main(String args)
  • try
  • File inputFile new File("c\\read.txt"
    )
  • File outputFile new
    File("c\\write.txt")
  • FileReader in new FileReader(inputFile
    )
  • FileWriter out new FileWriter(outputFi
    le)
  • int c
  • while ((c in.read()) ! -1)
  • out.write(c)
  • in.close()
  • out.close()
  • catch(IOException e)
  • System.out.print("Error " e)
  • System.exit(1)

19
Text Files
  • import java.io.
  • import java.util.
  • public class TextFile
  • public static void main(String args)
  • // write to file
  • try
  • FileWriter fi new FileWriter("c\\out.txt")
  • PrintWriter os new PrintWriter(fi)
  • os.println("First line to write!")
  • os.println("Second line!")
  • os.close()
  • catch(IOException e)
  • System.out.print("Error while writing "
    e)
  • System.exit(1)

20
Text Files
  • // read from file
  • try
  • FileReader fr new FileReader("c\\out.txt")
  • BufferedReader is new BufferedReader(fr)
  • String s1 is.readLine()
  • while (s1 ! null)
  • StringTokenizer st new StringTokenizer(s1)
  • for(int i0 st.hasMoreTokens() i)
  • System.out.print(" " i ") "
    st.nextToken())
  • System.out.println()
  • s1 is.readLine()
  • is.close()
  • catch(IOException e)
  • System.out.print("Error while reading"
    e)
  • System.exit(2)

21
Directory / Folders
  • import java.io.
  • public class DirectoryFiles
  • public static void main(String args)
  • File fd new File("c\\NewFolder")
  • if(fd.exists())
  • if(fd.isDirectory())
  • File fileList fd.listFiles()
  • for(int i0 i lt fileList.length i)
  • System.out.println(fileListi.getName
    ())
  • else
  • System.out.println("This is not a
    Directory !")
  • else
  • System.out.println("Folder dose not exist
    !")
Write a Comment
User Comments (0)
About PowerShow.com