Question

Please Help me! Recursive approximate median Consider an array of integers. You wish to find an...

Please Help me!

Recursive approximate median

Consider an array of integers. You wish to find an approximate median. You have an idea: split the array (or a range of the array) into three pieces, find the approximate median of each piece, and then return the actual median of the three approximate medians (if you put the three approximate medians in sorted order, the one in the middle). There are a few details to consider. If we are trying to find the approximate median of a range consisting of one element, that element itself is its own median. If the range contains two elements, take the mean (average) which may be a fractional value. Otherwise, the range contains at least three elements and we can split it into three pieces. The length of the range may be divisible by 3, have a remainder of 1 when divided by 3, or a remainder of 2 when divided by 3. If the range length has a remainder of 0 when divided by 3: each piece should be ?/3 elements. If a remainder of 1: the first piece should consist of the first ⌊?/3⌋ elements, the last piece should consist of the last ⌊?/3⌋ elements, and the middle piece is the remaining ⌈?/3⌉ elements. ⌈?/3⌉ rounds up. (For example, if there were 4 elements, the first piece is the first element, the last piece is the last element, and the middle two elements constitute the middle piece.) If a remainder of 2: the first piece should consist of the first ⌈?/3⌉ elements, the last piece should consist of the last ⌈?/3⌉ elements, and the middle piece is the remaining ⌊?/3⌋ elements. (For example, if there were 8 elements, the first piece is the first 3 elements, the last piece is the last 3, and the middle two elements constitute the middle piece.)
Implement the method public static double median3(int[] a) that follows the above strategy. Do not create any new arrays; you will need one or more helper methods that look at portions/ranges/pieces of the existing array. Do not modify the array you are given.

Examples, where the square braces show the elements in each recursive call’s range:

int[] a = {1};

median3(a); // returns 1.0

int[] b = {1, 2};

median3(b); // return 1.5

int[] c = {3, -10, 100};

median3(c); // returns 3.0

int[] d = {1, 2, -5, 10, 100, 6};

median3(d); // median of [1, 2], [-5, 10], [100, 6]: returns 2.5

int[] e = {1, 2, -10, 7, 20, -3, 100, 6};

median3(e); // [[1], [2], [-10]], [7, 20], [[-3], [100], [6]]: returns 6.0

int[] f = {1, 2, -20, -10, 7, 20, -3, 100, 6, 92};

median3(f); //[[1],[2],[-20]], [[-10],[7,20],[-3]],[[10],[6],[92]]: 1.0

Here is my code:

https://drive.google.com/file/d/1hswar8us7nAgwUQVcguB0nOUpCb9XFtd/view?usp=sharing

here is the tester:

https://drive.google.com/file/d/12nzpyZeZf-TzMEF6kOLve5kkxZQtsqgb/view?usp=sharing

0 0
Add a comment Improve this question Transcribed image text
Answer #1

-------------------------------------------------------------------------------------------------------------------

//RecursionIntro.java


public class RecursionIntro {
  
   public static long eduodd(long n)
   {
       if(n<0)return displayhelper(-n,-1);
       else return displayhelper(n,1);
   }
  
   public static long displayhelper(long n1, long sign1) {
       if(n1<10){
           if(n1%2==1)n1--;
           else n1++;
           return sign1*n1;
       }
       long tempval=n1%10;
       if(n1%2==1)tempval--;
       else tempval++;
       return displayhelper(n1/10,sign1)*10+sign1*tempval;
   }
  
   public static int fibby(int n1) {
       if(n1<0)
           return -1;
       if(n1==0)
           return 1;
       return fibby((int)(n1/4))+fibby((int)(3*n1/4));
   }
  
   public static void table_Gen(int a, int b) {
       long answer = fibby(a);
       System.out.println(a+"\t"+answer);
       if(a!=b) {
           table_Gen(a+1,b);
       }
   }
  
   public static double getMedian(int a[], int start, int end) {
       if(end-start == 0) {
           return (double)a[start];
       }else if(end-start == 1) {
           double mean = ((double)a[start] + (double)a[end])/2.0 ;
           return mean;
       }else{
           int n = end-start+1;
           double m1,m2,m3;
           if(n%3 == 0) {
               m1 = getMedian(a,start, start+ (n/3) - 1);
               m2 = getMedian(a,start + (n/3), start +2*(n/3) - 1);
               m3 = getMedian(a,start + 2*(n/3), end);
           }else if(n%3 == 1) {
               m1 = getMedian(a,start, start+ (n/3) - 1);
               m2 = getMedian(a,start + (n/3), start +2*(n/3) );
               m3 = getMedian(a,start + 2*(n/3) + 1, end);
           }else {
               m1 = getMedian(a,start, start+ (n/3) );
               m2 = getMedian(a,start + (n/3) + 1, start +2*(n/3) );
               m3 = getMedian(a,start + 2*(n/3) + 1, end);
           }
          
           //return the median of m1 ,m2 and m3
           double temp;
           if(m1 > m2) {
               temp = m1;
               m1 = m2;
               m2 = temp;
           }
          
           if(m1 > m3) {
               temp = m1;
               m1 = m3;
               m3 = temp;
           }
          
           if(m2 > m3) {
               return m3;
           }else {
               return m2;
           }
              
       }
   }
  
   public static double median3(int a[]) {
       int n = a.length;
       return getMedian(a,0,n-1);
      
   }
   public static void main(String[] args) {
       System.out.println("Table Generatio:n");
       table_Gen(0,10);
       System.out.println("20 "+fibby(20));
       System.out.println("100 "+fibby(100));
   }

}

-------------------------------------------------------------------------------------------------------------------

// I have commented the sparsetable test part in RecursionIntroTest.java

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;


public class RecursionIntroTest {
   public static void rowColumn(String source, int offset) {
       int row = 1;
       int col = 1;
       String tabby = "";
       for (int i = 0; i < offset; i++) {
           if (source.charAt(i) == '\n') {
               row++;
               col = 1;
               tabby = "";
           } else if (source.charAt(i) == '\t') {
               col += (4 - (col - 1) % 4);
               tabby += '\t';
           } else {
               col++;
               tabby += ' ';
           }
       }
       System.out.println(tabby+"^--- Problem!!!");
       System.out.println("Above problem is on line " + row + " column " + col + " (Assuming tab width of 4)");
   }

   public static void main(String[] args) throws NoSuchAlgorithmException {
       String source = null;
       try {
           source = new String(Files.readAllBytes(Paths.get("src" + File.separator + "RecursionIntro.java")));
       } catch (Exception e) {
           System.out.println(
                   "Couldn't find RecursionIntro.java! Run this from the same Eclipse project as RecursionIntro.");
           return;
       }
       if (source.matches("(?s).*\\sfor[\\s\\(].*")) {
           System.out.println(
                   "Detected 'for' statement in your program! Please remove anything that resembles a 'for'.");
           System.exit(-1);
       }
       if (source.matches("(?s).*\\swhile[\\s\\(].*")) {
           System.out.println(
                   "Detected 'while' statement in your program! Please remove anything that resembles a 'while'.");
           System.exit(-1);
       }
       if (source.matches("(?s).*\\simport\\s.*") || source.indexOf("import") == 0) {
           System.out.println("Detected 'import' statement in your program! Please remove any word 'import'.");
           System.exit(-1);
       }
       if (source.matches("(?s).*\\spublic\\s+static\\s+\\w+[^(]*=.*")
               || source.matches("(?s).*\\spublic\\s+static\\s+\\w+[^(]*;.*")) {
           System.out.println("Detected static variable in your program! Please remove static variables.");
           System.exit(-1);
       }
       for (int dotIndex = source.indexOf('.'); dotIndex != -1; dotIndex = source.indexOf('.', dotIndex + 1)) {
           if ("System.out.println".equals(source.substring(dotIndex - 6, dotIndex + 12))
                   || "System.out.println".equals(source.substring(dotIndex - 10, dotIndex + 8))
                   || "length".equals(source.substring(dotIndex + 1, dotIndex + 7))
               || Character.isDigit(source.charAt(dotIndex+1))) {
               continue;
           }
           int lastLine = source.lastIndexOf('\n', dotIndex);
           String dotLine = source.substring(Math.max(0, lastLine), dotIndex);
           if (dotLine.contains("//") && !dotLine.contains("\"")) continue; // Dot in line comment
           System.out.println("Bad dot! Context: "
                   + source.substring(Math.max(0, lastLine), Math.min(source.indexOf('\n', dotIndex)-1, source.length())));
           rowColumn(source, dotIndex);
           System.exit(-1);
       }

       System.out.println("Passed syntax checks!");
       System.out.println("If you don't see a score, your program didn't get to the end (possibly taking an extremely long or infinite amount of time)!");
       PrintStream out = System.out;
       MessageDigest md5 = MessageDigest.getInstance("MD5");
       int score = 0;
       int eduoddScore = 0;
       int fibbyScore = 0;
       int stGenScore = 0;
       int median3Score = 0;
       try {
           try { // Part 1: eduodd
               long[] ns = {0, 27, 987654321, -8443, 11121113, -11, 99999999999L, -987654321, -1016548095, -458096230};
               long[] eos = {1, 36, 896745230, -9552, 30002, 0, 88888888888L, -896745230, -107459184, -549187321};
               System.out.println("Testing eduodd...");
               for (int i = 0; i < ns.length; i++) {
                   long eo = RecursionIntro.eduodd(ns[i]);
                   if (eo != eos[i]) {
                       System.out.println("Expected eduodd("+ns[i]+") = "+eos[i]+" but got "+eo);
                   } else {
                       eduoddScore++;
                   }
               }
               Random r = new Random(123456789);
               long[] rando = new long[1000];
               for (int i = 0; i < rando.length; i++) {
                   rando[i] = RecursionIntro.eduodd(r.nextInt());
               }
               byte[] b = md5.digest(Arrays.toString(rando).getBytes());
               byte[] good = {-106, 111, -96, -46, -125, 4, 30, 41, 69, -39, 87, -114, -123, -119, -12, 22};
               if (!Arrays.equals(b, good)) {
                   System.out.println("Your eduodd method doesn't always work. Please consult the assignment carefully.");
                   if (eduoddScore == 10) {
                       System.out.println("It looks like you passed the above test cases! You may want to ask your instructor for help!");
                   }
               } else {
                   eduoddScore += 20;
               }
           } catch (Throwable t) {
               t.printStackTrace();
           }
           try { // Part 2a: fibby
               int[] fibbys = { 1, 2, 3, 4, 6, 6, 8, 8, 11, 11};
               System.out.println("Testing fibby...");
               for (int i = 0; i < fibbys.length; i++) {
                   int fib = RecursionIntro.fibby(i);
                   if (fib != fibbys[i]) {
                       System.out.println("Expected fibby(" + i + ") = " + fibbys[i] + " but got " + fib);
                   } else
                       fibbyScore++;
               }
               int[] fibbys2 = new int[10000];
               for (int i = 0; i < 10000; i++) {
                   fibbys2[i] = RecursionIntro.fibby(i);
               }
               byte[] b = md5.digest(Arrays.toString(fibbys2).getBytes());
               byte[] good = {-54, -34, -99, -113, -3, -71, -109, 113, 63, 127, 114, 95, 109, -82, 114, -108};
               if (!Arrays.equals(b, good)) {
                   System.out.println("Your fibby method doesn't work for some value between 0 and 9999. Please consult the definition carefully.");
               } else {
                   fibbyScore += 10;
               }
           } catch (Throwable t) {
               t.printStackTrace();
           }
           /**
           try { // Part 2b: printsparsetable
               System.out.println("Testing printsparsetable...");
               int[] starts = { 1, 1000, 101 };
               int[] ends = { 100, 1020, 999 };
               byte[][] md5s = { { 58, 46, 104, 125, -11, -80, -18, 110, -37, -96, 106, 87, -22, 122, 72, 64 },
                       { 19, 45, 112, -113, -33, 77, 114, 123, -71, -95, -38, 101, 59, 57, 45, -54 },
                       { -87, 94, 100, 67, -96, 45, -42, -83, -84, 111, -39, 102, -87, -70, -112, -84 } };
               for (int i = -2; i < starts.length; i++) {
                   ByteArrayOutputStream ba = new ByteArrayOutputStream();
                   System.setOut(new PrintStream(ba));
                   if (i == -2) {
                       RecursionIntro.printsparsetable(5, 10);
                       System.setOut(out);
                       String expected = "5 6\n6 8\n8 11\n";
                       if (!Arrays.equals(expected.split("\\r?\\n"), ba.toString().split("\\r?\\n"))) {
                           System.out.println("For printsparsetable(5, 10), expected:\n" + expected + "\n, got: \n" + ba);
                       } else {
                           stGenScore ++;
                       }
                   } else if (i == -1) {
                       RecursionIntro.printsparsetable(13, 20);
                       System.setOut(out);
                       String expected = "13 15\n15 18\n16 21\n20 24\n";
                       if (!Arrays.equals(expected.split("\\r?\\n"), ba.toString().split("\\r?\\n"))) {
                           System.out.println("For printsparsetable(13, 20), expected:\n" + expected + "\n, got: \n" + ba);
                       } else {
                           stGenScore ++;
                       }
                   } else {
                       RecursionIntro.printsparsetable(starts[i], ends[i]);
                       System.setOut(out);
                       byte[] digest = md5.digest(Arrays.toString(ba.toString().split("\\r?\\n")).getBytes());
                       if (!Arrays.equals(md5s[i], digest)) {
                           System.out.println(
                                   "Didn't get expected output for printsparsetable(" + starts[i] + ", " + ends[i] + ")");
                           System.out.println("Saw this:");
                           System.out.println(ba);
                           System.out.println("MD5 sum of output seen: " + Arrays.toString(digest));
                       } else
                           stGenScore ++;
                   }
               }
               ByteArrayOutputStream ba = new ByteArrayOutputStream();
               System.setOut(new PrintStream(ba));
               Random r = new Random(918273645);
               for (int i = 0; i < 1000; i++) {
                   int start = r.nextInt(1000);
                   RecursionIntro.printsparsetable(start, start+r.nextInt(1000)+1);
               }
               System.setOut(out);
               byte[] digest = md5.digest(Arrays.toString(ba.toString().split("\\r?\\n")).getBytes());
               byte[] good = {62, -87, -60, -83, -81, 99, -84, -73, -40, -24, -89, 115, 77, -82, 109, -53};
               if (!Arrays.equals(digest, good)) {
                   System.out.println("Your printsparsetable method doesn't always work (for starting values up to 1000 and ending values up to 1000 positions away). Please consult the definition carefully.");
                   if (stGenScore == 5) {
                       System.out.println("It looks like you passed the above test cases! You may want to ask your instructor for help!");
                   }
               } else {
                   stGenScore += 15;
               }
           } catch (Throwable t) {
               t.printStackTrace();
           } finally {
               System.setOut(out);
           }
           **/
           try { // Part 3: median3
               System.out.println("Testing median3...");
               int[][] a = {{1}, {1, 2}, {3, -10, 100}, {-1, 1, 1}, {123,234,345}, {100, 50, -1000}, {3, 100, -10}, {1, 200, 30}, {2000, -1, 300}, {1, 2, -5, 10, 100, 6}, {1, 2, -10, 7, 20, -3, 100, 6}, {1, 2, -20, -10, 7, 20, -3, 100, 6, 92}, {-60, -14, 52, -57, -25, 4, 1, -52, 0, -23, 46, 9, 23}};
               double[] rets = {1.0, 1.5, 3, 1, 234, 50, 3, 30, 300, 2.5, 6, 1.0, -10.5};
               for (int i = 0; i < a.length; i++) {
                   int[] ai = a[i].clone();
                   double ra = RecursionIntro.median3(a[i]);
                   if (!Arrays.equals(ai, a[i])) {
                       System.out.println("Please do not modify the input array! It started as "+Arrays.toString(ai)+" but after you modified it, it became "+Arrays.toString(a[i]));
                   } else if (ra != rets[i]) {
                       System.out.println("Expected median3("+Arrays.toString(a[i])+") = "+rets[i]+" but got "+ra);
                   } else {
                       median3Score++;
                   }
               }
               Random r = new Random(54321);
               double[] rando = new double[2000];
               for (int i = 0; i < 2000; i++) {
                   int[] b = new int[r.nextInt(100000)+1];
                   for (int j = 0; j < b.length; j++) {
                       b[j] = r.nextInt()/1024;
                   }
                   rando[i] = RecursionIntro.median3(b);
               }
               byte[] b = md5.digest(Arrays.toString(rando).getBytes());
               byte[] good = {29, 25, 56, -24, -17, -68, 24, 78, -9, 25, -22, -28, -8, 123, 0, 46};
               if (!Arrays.equals(b, good)) {
                   System.out.println("Your median3 method doesn't always work (for arrays up to 100,000 elements). Please consult the definition carefully.");
                   if (median3Score == 11) {
                       System.out.println("It looks like you passed the above test cases! You may want to ask your instructor for help!");
                   }
               } else {
                   median3Score += 17;
               }
           } catch (Throwable t) {
               t.printStackTrace();
           }
       } finally {
           System.out.println("eduodd: " + eduoddScore + " / 30");
           System.out.println("fibby: " + fibbyScore + " / 20");
           System.out.println("printsparsetable: " + stGenScore + " / 20");
           System.out.println("median3: "+median3Score+" / 30");
           score = eduoddScore + fibbyScore + stGenScore + median3Score;
           System.out.println("Tentative score: " + score + " / 100");
           System.out.println("*** Please note that grading is subject to the academic dishonesty policy! ***");
       }
   }

}

-------------------------------------------------------------------------------------------------------------------

// ScreenShot of Output

Add a comment
Know the answer?
Add Answer to:
Please Help me! Recursive approximate median Consider an array of integers. You wish to find an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Recursion Intro Assignment. You may not use for or while. Any looping must be accomplished using...

    Recursion Intro Assignment. You may not use for or while. Any looping must be accomplished using recursion. You may not declare static or non-static member fields – only local or parameter variables allowed. Consider an array of integers. You wish to find an approximate median. You have an idea: split the array into three pieces, find the approximate median of each piece, and then calculate the median of the three approximate medians (if you put the three approximate medians in...

  • Write a function called median that returns the median entry in a 1-dimensional array of integers....

    Write a function called median that returns the median entry in a 1-dimensional array of integers. For example, if we have an array a={3,4,5,1,6}; then the median entry of this array a is 4. You need to sort the array a first, to get {1,3,4,5,6}, then find the entry in the middle position. If the array size is even, it means that array has even number of elements. For example, a={3,2,4,1}, then first sort it, a becomes {1,2,3,4}, then the...

  • Suppose v is an array with 100 int elements. If 100 is assigned to v[100], what happens? Show the code. An array of 1000 integers is declared. What is the largest integer that can be used as an index...

    Suppose v is an array with 100 int elements. If 100 is assigned to v[100], what happens? Show the code. An array of 1000 integers is declared. What is the largest integer that can be used as an index to the array? Shows the code. Consider the declaration: int v[1]; What is the index of the last element of this array? Declare an array named a of 10 int elements and initialize the elements (starting with the first) to the...

  • you will analyse two algorithms for finding the median of an array of integers. You will...

    you will analyse two algorithms for finding the median of an array of integers. You will compare both algorithms in terms of timing, and hopefully design a hybrid algorithm that uses both, depending on input size. You will write a report describing your experiments and results. the following Java program implements two algorithms for finding the median of an array of integers. The first uses merge sort, and the other implements the recursive linear time selection algorithm, the task is...

  • c++, need help thank you Given an array of ints, return the sum of all elements...

    c++, need help thank you Given an array of ints, return the sum of all elements from the array that come before the first element that equals number 4 in the array. The array will contain at least one 4. Function prototype: int pre4int array ( ], int size); Hint: to find the array size, use: int size = sizeof(array) / sizeof( array[0]); Sample runs: int array1[ ] = {1, 2, 4, 1); pre4(array1, 4); // returns 3 int array2...

  • I need help In the lecture you got acquainted with the median algorithm, which calculates the median of an unsorted array with n∈N elements in O (n). But the algorithm can actually do much more: it is...

    I need help In the lecture you got acquainted with the median algorithm, which calculates the median of an unsorted array with n∈N elements in O (n). But the algorithm can actually do much more: it is not limited to finding only the median, but can generally find the ith element with 0≤i <n. Implement this generic version of the median algorithm by creating a class selector in the ads.set2.select package and implementing the following method: /** * Returns the...

  • Exercise 2: Write array methods that carry out the following tasks for an array of integers...

    Exercise 2: Write array methods that carry out the following tasks for an array of integers by creating and completing the “ArrayMethods” class below. Add documentation comments for each method. Provide a test program called 'Lab5_yourID.java” that test methods of ArrayMethods class. In your test program, use random class to generate array values. public class ArrayMethods { private int[ ] values; //declare instant variables public ArrayMethods (int[] initialValues) {values = initialValues;} //constructor public void shiftRight() { } public Boolean adjacentDuplicate()...

  • The code below is already completed using C++. Could you please explain why the input is...

    The code below is already completed using C++. Could you please explain why the input is 3 : 2 : 3 : 6 : 4 : -1 : 3 : 1 : 0 :? Please let me know really short explanation. #include <iostream> using namespace std ; int binarySearch(const int array[], int numElems, int value) { int first = 0, // First array element last = numElems - 1, // Last array element middle, // Midpoint of search position =...

  • Write a program that initializes an array with ten random integers and then prints out the...

    Write a program that initializes an array with ten random integers and then prints out the following: Every element at an even index; Every even element All elements in reverse order; Only the first and last elements; The minimum and maximum element The sum of all elements The alternating sum of all elements, where the alternating sum contains all elements at even index added, and the elements at odd index subtracted. Please write comments above the piece of code that...

  • 1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array...

    1. Please write a Divide-and-Conquer Java algorithm solving the following problem: Given an "almost sorted" array of distinct integers, and an integer x, return the index of x in the array. If the element x is not present in the array, return -1. "Almost sorted" means the following. Assume you had a sorted array A[0…N], and then split it into two pieces A[0…M] and A[M+1…N], and move the second piece upfront to get the following: A[M+1]…A[N]A[0]…A[M]. Thus, the "almost sorted"...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT