Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Assignment - Write two Java programs!
The first one uses a recursive algorithm.
The second one uses a non-recursive algorithm.
They must determine if a list (of any length) has the following pattern:
Cell[0] = 2;
Cell[1] = 2squared = 4;
Cell[3] = 4squared = 16;
The pattern is where any value of a cell [n+1] is equal to the square of the value in cell[n].
e.g: 2, 4, 16, 256, 65536, 4294967296
Question:
Can anyone point me to a code example, please?
Thanks in advance!
Here is one way to do it using BigInteger. But even then, I limited the number of terms to 8 as they get quite large.
Iterative call.
BigInteger[] terms = iterative(8);
for (BigInteger b : terms) {
System.out.println(b);
}
System.out.println("Sequence array for iteration is " +
(validate(terms) ? "valid" : "invalid"));
Prints
2
4
16
256
65536
4294967296
18446744073709551616
340282366920938463463374607431768211456
Sequence array for iterative is valid
Recusive call
terms = recursive(8);
for (BigInteger b : terms) {
System.out.println(b);
}
System.out.println("Sequence array for recursion is " +
(validate(terms) ? "valid" : "invalid"));
Prints
2
4
16
256
65536
4294967296
18446744073709551616
340282366920938463463374607431768211456
Sequence array for recursion is valid
Validation method
public static boolean validate(BigInteger[] terms) {
for (int i = 1; i < terms.length; i++) {
if (!terms[i].equals(terms[i-1].pow(2))) {
return false;
}
}
return true;
}
The iterative approach.
simply initialize the first term to Biginteger.TWO.
then iterate over the list raising each previous term to the power of 2.
public static BigInteger[] iterative(int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be > 0");
}
BigInteger[] terms = new BigInteger[n];
terms[0] = BigInteger.TWO; // 2^2^0 = 2;
for (int i = 1; i < n; i++) {
terms[i] = terms[i-1].pow(2);
}
return terms;
}
The recursive approach.
Although it can be done without a helper method using one is more straightforward and efficient.
allocate the array based on n
initialize the 0th element to 2.
return immediately if n == 1
otherwise, invoke the helper method.
public static BigInteger[] recursive(int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be > 0");
}
BigInteger[] terms = new BigInteger[n];
terms[0] = BigInteger.TWO;
if (n == 1) {
return terms;
}
return recursiveHelper(terms, n);
}
recursively call the method until n == 2
then simply assign the n-1 element the value in n-2 raised to the power of 2
then return the terms.
private static BigInteger[] recursiveHelper(BigInteger[] terms, int n) {
if (n > 2) {
recursiveHelper(terms,n-1);
}
terms[n-1] = terms[n-2].pow(2);
return terms;
}
There is no specific algorithm for this problem that I know of, but here are code examples:
Recursive:
public boolean validSequenceFromIndex(int[] sequence, int index) {
if (index >= sequence.length - 1) return true; // If it is the last index or
// greater, then it works.
if (sequence[index + 1] != sequence[index] * sequence[index]) return false; // The
// pattern does not hold.
return validSequenceFromIndex(sequence, index + 1); // The sequence is valid at this
// index, check the rest of the sequence.
}
Notice here that the parameters here are an int[] sequence and an int index while the problem should only give you an int[] sequence. Simply write a function like the following:
public boolean validSequence(int[] sequence) {
return validSequenceFromIndex(sequence, 0); // Checks if the sequence is valid starting
// from the beginning (essentially the whole sequence.
}
which should transfer only having the sequence as a parameter to using a sequence and an index.
Non-recursive:
public boolean validSequence(int[] sequence) {
for (int i = 0; i < sequence.length - 1; i++) { // Loop through entirety of the
// except for the last index.
if (sequence[i + 1] != sequence[i] * sequence[i]) return false;
}
// All indices checked, the sequence works:
return true;
}
Hope this made sense to you!
Related
Write a function:
class Solution{
public int solution(int[] A);
}
that, given an array A of N integers, returns the smallest positive integer(greater than 0)
that does not occur in A.
For example, given A = [1,3,6,4,1,2], the function should return 5.
Given A = [1,2,3], the function should return 4.
Given A = [-1, -3], the function should return 1.
Write an efficient algorithm for the following assumptions.
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [-1,000,000..1,000,000].
I wrote the following algorithm in Java:
public class TestCodility {
public static void main(String args[]){
int a[] = {1,3,6,4,1,2};
//int a[] = {1,2,3};
//int b[] = {-1,-3};
int element = 0;
//checks if the array "a" was traversed until the last position
int countArrayLenght = 0;
loopExtern:
for(int i = 0; i < 1_000_000; i++){
element = i + 1;
countArrayLenght = 0;
loopIntern:
for(int j = 0; j < a.length; j++){
if(element == a[j]){
break loopIntern;
}
countArrayLenght++;
}
if(countArrayLenght == a.length && element > 0){
System.out.println("Smallest possible " + element);
break loopExtern;
}
}
}
}
It does the job but I am pretty sure that it is not efficient. So my question is, how to improve this algorithm so that it becomes efficient?
You should get a grasp on Big O, and runtime complexities.
Its a universal construct for better understanding the implementation of efficiency in code.
Check this website out, it shows the graph for runtime complexities in terms of Big O which can aid you in your search for more efficient programming.
http://bigocheatsheet.com/
However, long story short...
The least amount of operations and memory consumed by an arbitrary program is the most efficient way to achieve something you set out to do with your code.
You can make something more efficient by reducing redundancy in your algorithms and getting rid of any operation that does not need to occur to achieve what you are trying to do
Point is to sort your array and then iterate over it. With sorted array you can simply skip all negative numbers and then find minimal posible element that you need.
Here more general solution for your task:
import java.util.Arrays;
public class Main {
public static int solution(int[] A) {
int result = 1;
Arrays.sort(A);
for(int a: A) {
if(a > 0) {
if(result == a) {
result++;
} else if (result < a){
return result;
}
}
}
return result;
}
public static void main(String args[]){
int a[] = {1,3,6,4,1,2};
int b[] = {1,2,3};
int c[] = {-1,-3};
System.out.println("a) Smallest possible " + solution(a)); //prints 5
System.out.println("b) Smallest possible " + solution(b)); //prints 4
System.out.println("c) Smallest possible " + solution(c)); //prints 1
}
}
Complexity of that algorithm should be O(n*log(n))
The main idea is the same as Denis.
First sort, then process but using java8 feature.
There are few methods that may increase timings.(not very sure how efficient java 8 process them:filter,distinct and even take-while ... in the worst case you have here something similar with 3 full loops. One additional loop is for transforming array into stream). Overall you should get the same run-time complexity.
One advantage could be on verbosity, but also need some additional knowledge compared with Denis solution.
import java.util.function.Supplier;
import java.util.stream.IntStream;
public class AMin
{
public static void main(String args[])
{
int a[] = {-2,-3,1,2,3,-7,5,6};
int[] i = {1} ;
// get next integer starting from 1
Supplier<Integer> supplier = () -> i[0]++;
//1. transform array into specialized int-stream
//2. keep only positive numbers : filter
//3. keep no duplicates : distinct
//4. sort by natural order (ascending)
//5. get the maximum stream based on criteria(predicate) : longest consecutive numbers starting from 1
//6. get the number of elements from the longest "sub-stream" : count
long count = IntStream.of(a).filter(t->t>0).distinct().sorted().takeWhile(t->t== supplier.get()).count();
count = (count==0) ? 1 : ++count;
//print 4
System.out.println(count);
}
}
There are many solutions with O(n) space complexity and O(n) type complexity. You can convert array to;
set: array to set and for loop (1...N) check contains number or not. If not return number.
hashmap: array to map and for loop (1...N) check contains number or not. If not return number.
count array: convert given array to positive array count array like if arr[i] == 5, countArr[5]++, if arr[i] == 1, countArr[1]++ then check each item in countArr with for loop (1...N) whether greate than 1 or not. If not return it.
For now, looking more effective algoritm like #Ricola mentioned. Java solution with O(n) time complexity and O(1) space complexity:
static void swap(final int arr[], final int i,final int j){
final int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static boolean isIndexInSafeArea(final int arr[], final int i){
return arr[i] > 0 && arr[i] - 1 < arr.length && arr[i] != i + 1 ;
}
static int solution(final int arr[]){
for (int i = 0; i < arr.length; i++) {
while (isIndexInSafeArea(arr,i) && arr[i] != arr[arr[i] - 1]) {
swap(arr, i, arr[i] - 1);
}
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] != i + 1) {
return i+1;
}
}
return arr.length + 1;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to do something where I have two numbers (let's say 123 and 321). And I want to check if the first number has the same digits as the second in any order. I know how to do this if I check for the 1, the 2, and the 3 individually, but I want to check the entire integer. In other words, I need a code that says "if number x has the same digits as number y (in any order), then..."
Any help is greatly appreciated!
Not sure of the Java syntax but convert each number to an array. Sort the arrays ascending. Convert back to a number and compare.
If you don't want an exact match (i.e. 112233 and 123 both share the same digits), then walk through 1 array and see if each digit is contained in the other.
This code will turn both integers into strings and then check to see if the strings are the same length and the second string contains all of the characters of the first.
public class Sandbox { //opens class
public static void main(String[] args) {
int x = 125;
int y = 321;
boolean hasNumbers = true;
String a = Integer.toString(x);
String b = Integer.toString(y);
if(a.length() == b.length()) {
for(int i = 0; i < a.length(); i++) {
if(!b.contains(String.valueOf(a.charAt(i)))) {
hasNumbers = false;
}
}
if(hasNumbers) {
System.out.println(x + " contains the digits of " + y);
}
else {
System.out.println(x + " does not contain the digits of " + y);
}
}
else {
System.out.println("The length of " + x + " and " + y + " are different");
}
}
}
You could definitely tidy it up quite a bit but I believe it solves the problem you stated.
EDIT : The basic idea : The algorithm simply stores all the digits appearing in "a" in a set and checks if there is any that doesn't exist in "b".
Here is some code for implementing this logic. It basically makes use of the fact, that Set doesn't contain duplicate elements. HashSet can perform add, contains in a constant time, plus the maximum size of the digits set is 10, the function can be executed in O(n).
public boolean checkSameDigits(int x, int y){
String a = Integer.toString(x);
String b = Integer.toString(y);
Set digits = new HashSet();
for(int i = 0; i < a.length(); i++) {
digits.add(a.charAt(i));
}
for(int i = 0; i < b.length(); i++) {
if(!digits.contains(b.charAt(i)))
return false;
}
return true;
}
A rather short implementation is to get a char[] for each, sort, and check if they're the same:
import java.util.Arrays;
public class Whatever {
public static final boolean sameDigits(final int m, final int n) {
final char[] m2 = ("" + m).toCharArray();
final char[] n2 = ("" + n).toCharArray();
Arrays.sort(m2);
Arrays.sort(n2);
return Arrays.equals(m2, n2);
}
}
If you convert each number to a sorted list of digits then you can just compare the two lists:
private List<Integer> sortedDigits(int number, int base) {
assert number >= 0 && base > 0;
List<Integer> digits = new ArrayList<>();
for (int n = number; n > 0; n /= base)
digits.add(n % base);
digits.sort();
return digits;
}
So then sortedDigits(number1, 10).equals(sortedDigits(number2, 10)) will check if the digits are the same in base 10.
I need a task about finding Fibonacci Sequence for my independent project in Java. Here are methods for find.
private static long getFibonacci(int n) {
switch (n) {
case 0:
return 0;
case 1:
return 1;
default:
return (getFibonacci(n-1)+getFibonacci(n-2));
}
}
private static long getFibonacciSum(int n) {
long result = 0;
while(n >= 0) {
result += getFibonacci(n);
n--;
}
return result;
}
private static boolean isInFibonacci(long n) {
long a = 0, b = 1, c = 0;
while (c < n) {
c = a + b;
a = b;
b = c;
}
return c == n;
}
Here is main method:
long key = getFibonacciSum(n);
System.out.println("Sum of all Fibonacci Numbers until Fibonacci[n]: "+key);
System.out.println(getFibonacci(n)+" is Fibonacci[n]");
System.out.println("Is n2 in Fibonacci Sequence ?: "+isInFibonacci(n2));
Codes are completely done and working. But if the n or n2 will be more than normal (50th numbers in Fib. Seq.) ? Codes will be runout. Are there any suggestions ?
There is a way to calculate Fibonacci numbers instantaneously by using Binet's Formula
Algorithm:
function fib(n):
root5 = squareroot(5)
gr = (1 + root5) / 2
igr = 1 - gr
value = (power(gr, n) - power(igr, n)) / root5
// round it to the closest integer since floating
// point arithmetic cannot be trusted to give
// perfect integer answers.
return floor(value + 0.5)
Once you do this, you need to be aware of the programming language you're using and how it behaves. This will probably return a floating point decimal type, whereas integers are probably desired.
The complexity of this solution is O(1).
Yes, one improvement you can do is to getFibonacciSum(): instead of calling again and again to isInFibonacci which re-calculates everything from scratch, you can do the exact same thing that isInFibonacci is doing and get the sum in one pass, something like:
private static int getFibonacciSum(int n) {
int a = 0, b = 1, c = 0, sum = 0;
while (c < n) {
c = a + b;
a = b;
sum += b;
b = c;
}
sum += c;
return sum;
}
Well, here goes my solution using a Map and some math formulas. (source:https://www.nayuki.io/page/fast-fibonacci-algorithms)
F(2k) = F(k)[2F(k+1)−F(k)]
F(2k+1) = F(k+1)^2+F(k)^2
It is also possible implement it using lists instead of a map but it is just reinventing the wheel.
When using Iteration solution, we don't worry about running out of memory, but it takes a lot of time to get fib(1000000), for example. In this solution we may be running out of memory for very very very very big inputs (like 10000 billion, idk) but it is much much much faster.
public BigInteger fib(BigInteger n) {
if (n.equals(BigInteger.ZERO))
return BigInteger.ZERO;
if (n.equals(BigInteger.ONE) || n.equals(BigInteger.valueOf(2)))
return BigInteger.ONE;
BigInteger index = n;
//we could have 2 Lists instead of a map
Map<BigInteger,BigInteger> termsToCalculate = new TreeMap<BigInteger,BigInteger>();
//add every index needed to calculate index n
populateMapWhitTerms(termsToCalculate, index);
termsToCalculate.put(n,null); //finally add n to map
Iterator<Map.Entry<BigInteger, BigInteger>> it = termsToCalculate.entrySet().iterator();//it
it.next(); //it = key number 1, contains fib(1);
it.next(); //it = key number 2, contains fib(2);
//map is ordered
while (it.hasNext()) {
Map.Entry<BigInteger, BigInteger> pair = (Entry<BigInteger, BigInteger>)it.next();//first it = key number 3
index = (BigInteger) pair.getKey();
if(index.remainder(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
//index is divisible by 2
//F(2k) = F(k)[2F(k+1)−F(k)]
pair.setValue(termsToCalculate.get(index.divide(BigInteger.valueOf(2))).multiply(
(((BigInteger.valueOf(2)).multiply(
termsToCalculate.get(index.divide(BigInteger.valueOf(2)).add(BigInteger.ONE)))).subtract(
termsToCalculate.get(index.divide(BigInteger.valueOf(2)))))));
}
else {
//index is odd
//F(2k+1) = F(k+1)^2+F(k)^2
pair.setValue((termsToCalculate.get(index.divide(BigInteger.valueOf(2)).add(BigInteger.ONE)).multiply(
termsToCalculate.get(index.divide(BigInteger.valueOf(2)).add(BigInteger.ONE)))).add(
(termsToCalculate.get(index.divide(BigInteger.valueOf(2))).multiply(
termsToCalculate.get(index.divide(BigInteger.valueOf(2))))))
);
}
}
// fib(n) was calculated in the while loop
return termsToCalculate.get(n);
}
private void populateMapWhitTerms(Map<BigInteger, BigInteger> termsToCalculate, BigInteger index) {
if (index.equals(BigInteger.ONE)) { //stop
termsToCalculate.put(BigInteger.ONE, BigInteger.ONE);
return;
} else if(index.equals(BigInteger.valueOf(2))){
termsToCalculate.put(BigInteger.valueOf(2), BigInteger.ONE);
return;
} else if(index.remainder(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
// index is divisible by 2
// FORMUMA: F(2k) = F(k)[2F(k+1)−F(k)]
// add F(k) key to termsToCalculate (the key is replaced if it is already there, we are working with a map here)
termsToCalculate.put(index.divide(BigInteger.valueOf(2)), null);
populateMapWhitTerms(termsToCalculate, index.divide(BigInteger.valueOf(2)));
// add F(k+1) to termsToCalculate
termsToCalculate.put(index.divide(BigInteger.valueOf(2)).add(BigInteger.ONE), null);
populateMapWhitTerms(termsToCalculate, index.divide(BigInteger.valueOf(2)).add(BigInteger.ONE));
} else {
// index is odd
// FORMULA: F(2k+1) = F(k+1)^2+F(k)^2
// add F(k+1) to termsToCalculate
termsToCalculate.put(((index.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2)).add(BigInteger.ONE)),null);
populateMapWhitTerms(termsToCalculate,((index.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2)).add(BigInteger.ONE)));
// add F(k) to termsToCalculate
termsToCalculate.put((index.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2)), null);
populateMapWhitTerms(termsToCalculate, (index.subtract(BigInteger.ONE)).divide(BigInteger.valueOf(2)));
}
}
This method of solution is called dynamic programming
In this method we are remembering the previous results
so when recursion happens then the cpu doesn't have to do any work to recompute the same value again and again
class fibonacci
{
static int fib(int n)
{
/* Declare an array to store Fibonacci numbers. */
int f[] = new int[n+1];
int i;
/* 0th and 1st number of the series are 0 and 1*/
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++)
{
/* Add the previous 2 numbers in the series
and store it */
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
public static void main (String args[])
{
int n = 9;
System.out.println(fib(n));
}
}
public static long getFib(final int index) {
long a=0,b=0,total=0;
for(int i=0;i<= index;i++) {
if(i==0) {
a=0;
total=a+b;
}else if(i==1) {
b=1;
total=a+b;
}
else if(i%2==0) {
total = a+b;
a=total;
}else {
total = a+b;
b=total;
}
}
return total;
}
I have checked all solutions and for me, the quickest one is to use streams and this code could be easily modified to collect all Fibonacci numbers.
public static Long fibonaciN(long n){
return Stream.iterate(new long[]{0, 1}, a -> new long[]{a[1], a[0] + a[1]})
.limit(n)
.map(a->a[0])
.max(Long::compareTo)
.orElseThrow();
}
50 or just below 50 is as far as you can go with straight recursive implementation. You can switch to iterative or dynamic programming (DP) approaches if you want to go much higher than that. I suggest learning about those from this: https://www.javacodegeeks.com/2014/02/dynamic-programming-introduction.html. And don't forget to look the a solution in the comment by David therein, real efficient. The links shows how even n = 500000 can be computed instantaneously using the DP method. The link also explains the concept of "memoization" to speed up computation by storing intermediate (but later on re-callable) results.
Given a sorted integer array without duplicates, return the summary of
its ranges for consecutive numbers.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
I proposed the following solution:
public List<String> summaryRanges(int[] nums) {
if (nums == null){
return null;
}
if (nums.length == 0){
return new ArrayList<>();
}
if (nums.length == 1){
List<String> arr = new ArrayList<>();
arr.add(Integer.toString(nums[0]));
return arr;
}
List<String> summary = new ArrayList<>();
int n = nums.length;
int begin = nums[0];
int end;
for (int i = 1; i < n; i++) {
if (nums[i] - nums[i-1] > 1) {
end = nums[i-1];
if (begin == end){
summary.add(Integer.toString(begin));
}
else{
summary.add(Integer.toString(begin) + "->" + Integer.toString(end));
}
begin = nums[i];
}
}
if (nums[n-1] - nums[n-2] > 1){
summary.add(Integer.toString(nums[n-1]));
}
else{
summary.add(Integer.toString(begin) + "->" +Integer.toString(nums[n-1]));
}
return summary;
}
This program fails for the following example: [-2147483648, -2147483647, 2147483647] (returns the wrong answer: ["-2147483648->2147483647"])
I suspect this is due to an overflow issue, but I can't figure out why exactly. On the opposite, this example solution I found passes this test case:
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<String>();
if(nums == null || nums.length==0)
return result;
if(nums.length==1){
result.add(nums[0]+"");
}
int pre = nums[0]; // previous element
int first = pre; // first element of each range
for(int i=1; i<nums.length; i++){
if(nums[i]==pre+1){
if(i==nums.length-1){
result.add(first+"->"+nums[i]);
}
}else{
if(first == pre){
result.add(first+"");
}else{
result.add(first + "->"+pre);
}
if(i==nums.length-1){
result.add(nums[i]+"");
}
first = nums[i];
}
pre = nums[i];
}
return result;
}
Why does this solution pass this test and not the one I proposed?
Yes, indeed, the problem is overflow.
The difference between your programs is, basically, that you are using the test:
nums[i] - nums[i-1] > 1
whereas the other program uses
nums[i]==pre+1
In a purely mathematical world, there should be no difference between comparing y to x+1 and comparing y-x to 1, but in the world of 32-bit integer, there is a big difference.
When you get to the numbers -Integer.MAX_VALUE and Integer.MAX_VALUE, which is what the numbers in your example array are, then your comparison is:
Integer.MAX_VALUE - -Integer.MAX_VALUE > 1
As the minus signs cancel each other, this means 2 * Integer.MAX_VALUE, which is larger than an int can hold, and you get an overflow. The result is -2 and that's not greater than 1.
In the other program's way, you would be asking whether
Integer.MAX_VALUE == - Integer.MAX_VALUE + 1
The left hand part is, of course, a legal integer. The right hand value is also a legal integer, because you are just stepping away from the minimum. Thus, no overflow, and the comparison would return false, which is good.
Can you try using absolute values wherever checking the differences:
Math.abs(nums[i]) - Math.abs(nums[i-1])
I suppose this looks like an issue here in case of negative numbers.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My teacher challenged us to find the minimum value in an array using recursion, but you can only have one parameter which is the array.
public int minimum(int arry[])
The trick with these is to try to define the problem in a recursive manner, that is, in a way that uses the operation itself in its definition along with a "base case" that does not. For example, in this case, think about what the "minimum value in an array" is:
For an array of size 1, the minimum value is just that one element.
For a larger array, the minimum value is the smaller of the first element and the minimum value in the remainder of the array.
So you have your base case (array of size 1), and your recursion. That should be enough for you to go on.
Try below code:
Concept: Eliminate larger value from array and return min when you have only one element in array.
public int min(int[] n) {
if (n.length > 1) {
int a = n[0];
int b = n[1];
int[] newN = new int[n.length - 1];
for (int i = 0; i < newN.length; i++) {
if (i == 0)
newN[i] = a < b ? a : b;
else
newN[i] = n[i + 1];
}
return min(newN);
}
return n[0];
}
You have to pass successively smaller arrays to the next iteration:
public int minimum(int arr[]) {
if (arr == null || arr.length == 0)
throw new IllegalArgumentException();
if (arr.length == 1)
return arr[0];
int min = minimum(Arrays.copyOfRange(arr, 1, arr.length));
return arr[0] < min ? arr[0] : min;
}
But this is strictly an academic exercise - "do not try this at home".
public static int min(int[] n) {
if(n.length == 1)//base case
return(n[0]);
int a = n.length%2 == 0 ? 0:1; //Awesome sauce syntax http://www.cafeaulait.org/course/week2/43.html
int[] r =new int[n.length/2 + a]; // reduce by a factor of 2 each iteration
for(int k = 0 ; k < n.length/2 + a ; k++){ //While copying to a smaller array you might as well make comparisons.
r[k] = n[k]<=n[n.length-k-1] ? n[k] : n[n.length-k-1];//compare the beginning and end of your array, take the smaller of the two.
} //In the case that you have an odd number of elements the middle is always copied trough to the next iteration
return(min(r));//This is where the recursion happens.
} // There is always a better way but this should satisfy your teacher.
public static int[] removeElement(int element,int[] original){
int[] n = new int[original.length - 1];
System.arraycopy(original, 0, n, 0, element );
System.arraycopy(original, element+1, n, element, original.length - element-1);
return n;// http://stackoverflow.com/questions/4870188/delete-item-from-array-and-shrink-array
}
public static int [] shift(int[] original){
int[] a = new int[original.length];
for(int k = 1 ; k < original.length;k++){
a[k-1] = original[k];
}
a[original.length-1] = original[0];
return(a);
}
public static int minimum(int[] arr){ //Process of elimination
if(arr.length==1){ //Base Case
return(arr[0]);
}
if(arr[0]>=arr[1]){// reduction step
return(minimum(removeElement(0,arr)));
}else{ // tread water
return(minimum(shift(arr)));
}
}// There is always a better way but this sould satisfy your teacher.
Give Pratik Popat an up-vote for copying my mediocre logic.