Codility - Counting Elements Lessons : fastest algorithm swap - java

i am studying Codility chapter 2 : Counting elements.
I tried to make the exercise, and i think I have a good solution O(n). is It a valid solution ?
Is it a better solution that the BEST solution proposed in te lesson ?
Problem: You are given an integer m (1 􏰀 m 􏰀 1 000 000) and two non-empty, zero-indexed arrays A and B of n integers, a0,a1,...,an−1 and b0,b1,...,bn−1 respectively (0 􏰀 ai,bi 􏰀 m). The goal is to check whether there is a swap operation which can be performed on these arrays in such a way that the sum of elements in array A equals the sum of elements in array B after the swap. By swap operation we mean picking one element from array A and
one element from array B and exchanging them.
I tested my solution with these values :
int a[] = {2, 7, 12, 16};
int b[] = {4, 8, 9};
m = 16;
note: I commented the return to see the swapped values.
public int resultat(int[] A, int B[], int max) {
int sumA = Arrays.stream(A).sum();
int sumB = Arrays.stream(B).sum();
int[] countA = count(A, max);
int[] countB = count(B, max);
int diff = sumA - sumB;
int diffMin = 0;
if (diff % 2 != 0) {
return -1;
}
diffMin = diff / 2;
if (sumA > sumB) {
if (diff < countA.length && diffMin < countB.length && countA[diff] != 0 && countB[diffMin] != 0) {
System.out.println("A:" + diff + "- B:" + diffMin);
//return 1;
}
} else {
if (diffMin < countA.length && diff < countB.length && countB[diff] != 0 && countA[diffMin] != 0) {
System.out.println("A:" + diffMin + "- B:" + diff);
//return 1;
}
}
return -1;
}
public int[] count(int[] X, int max) {
int[] p = new int[max + 1];
Arrays.fill(p, 0);
for (int i = 0; i < X.length; i++) {
p[X[i]] += 1;
}
return p;
}

Your solution is O(n + m), because of count(A, max) and count(B, max) invocations. count() is linear.
It's not valid solution. Counter-example: A = [1, 2, 4], B = [3, 5, 1], m = 5. Answer is true, because we can swap 2 with 3. Your code throws ArrayIndexOutOfBoundsException: -2 on countB[diff], because diff is -2. Even if you secure it with, for example diff = Math.abs(sumA - sumB), the algorithm is still not correct and it will return false.
You don't need to do Arrays.fill(p, 0), int default value is 0.
Instead of p[X[i]] += 1 you could write p[X[i]]++.

Here's (i hope) a correct solution.
Please note, that counting can still be put after checking dif is not an odd number to make performance higher.
Note, too, that listA and listB arrays are used as the value at zero place is never used. This is for better understanding, too. We don't need the occurrence of the value 0 but we need the occurrence of max value.
public boolean solution(int[] A, int[] B, int max) {
int[] listA = new int[max+1];
int[] listB = new int[max+1];
int listAsum =0;
int listBsum=0;
for(int i = 0; i<A.length; i++){
listA[A[i]]++;
listAsum +=A[i];
listBsum +=B[i];
}
int diff = listAsum - listBsum;
if(diff%2 == 1) return false;
diff /=2;
for(int i=0; i<A.length; i++){
if((B[i] - diff) >= 0 && (B[i]-diff) <= max && listA[(B[i]-diff)] > 0) return true;
}
return false;
}

public boolean solution(int[] A, int[] B, int max) {
int[] count = new int[max + 1];//count(A, max);
int sum_a = 0; //Arrays.stream(A).sum();
int sum_b = 0;//Arrays.stream(B).sum();
for (int i = 0; i < A.length; i++) {
count[A[i]]++;
sum_a += A[i];
sum_b += B[i];
}
int d = sum_b - sum_a;
if (d % 2 == 1) return false;
d /= 2;
for (int i = 0; i < A.length; i++) {
if ((B[i] - d) >= 0 && (B[i] - d) <= max && count[(B[i] - d)] > 0)
return true;
}
return false;
}
public int[] count(int[] X, int max) {
int[] p = new int[max + 1];
Arrays.fill(p, 0);
for (int i = 0; i < X.length; i++) {
p[X[i]]++;
}
return p;
}

Related

Find the Least Common Multiple (LCM) of exactly N-1 numbers chosen among N numbers

Find the smallest number M, which is divided by exactly n-1 numbers from the input array. If there is no such M then return -1.
Example:
array = [2,3,5]
Answer :
6
Explanation :
6 can be divided by 2 and 3
Example:
array = [2,3,6]
Answer:
-1
Explanation :
It's not possible in this case so return -1.
My code:
As we need to find the smallest M, I am selecting only the elements from 0 to n-2
public int process(int[] arr) {
int answer = 1;
for(int i=0; i<arr.length-1; i++) {
answer *= arr[i];
}
return answer;
}
This program works for these 2 sample test cases but it was failing for multiple hidden test cases. I trying to understand what I am missing here.
Calculation of the Least Common Multiple (LCM)
A problem inside the task is the calculation of the Least Common Multiple of 2 numbers. The method public int lowerCommonMultiple(int x1, int x2) solves this problem and I think it can be used in other context.
List of the class methods
All the code is included in the methods of the BestMultiple class. These methods (excluding the main) are:
public int[] removeElem(int[] tensArray, int rm_index): used to remove an element from an array
public int leastCommonMultiple(int x1, int x2): calculates the Least Common Multiple of 2 numbers
private int getLeastCommonMultipleNnumber(int[] arr): Calculates the least common multiple of N-1 integer contain in an array
public int process(int[] arr): calculates the least multiple of exactly N-1 number of an array of N integer; it manages many test strange cases (array empty, elem<=0, etc.)
May be the code is not optimized, but I hope it is correct (the output added, shows that it works correctly, at least with the test cases chosen).
public class BestMultiple {
/*++++++++++++++++++++++++++++++++++++++++++++
Method: removeElem() remove an element from
an array.
+++++++++++++++++++++++++++++++++++++++++++*/
public int[] removeElem(int[] tensArray, int rm_index) {
// Create a proxy array of size one less than original array
int[] proxyArray = new int[tensArray.length - 1];
// copy all the elements in the original to proxy array
// except the one at index
for (int i = 0, k = 0; i < tensArray.length; i++) {
// check if index is crossed, continue without copying
if (i == rm_index) {
continue;
}
// else copy the element
proxyArray[k++] = tensArray[i];
}
return proxyArray;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Method: leastCommonMultiple() Calculates the Least Common
multiple for 2 numbers
++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public int leastCommonMultiple(int x1, int x2) {
int lcm = 1;
int max = x1;
if ((x1 == 0) || (x2 == 0)) {
lcm = 0;
} else {
if (x2 > x1) {
max = x2;
}
for (int i = 2; i <= max; i++) {
int exp_x1 = 0;
int exp_x2 = 0;
int exp = 0;
if (x1 > 1) {
while ((x1 % i) == 0) {
exp_x1++;
x1 /= i;
}
}
if (x2 > 1) {
while ((x2 % i) == 0) {
exp_x2++;
x2 /= i;
}
}
if ((exp_x1 > 0) || (exp_x2 > 0)) {
exp = exp_x1;
if (exp_x2 > exp) {
exp = exp_x2;
}
while (exp > 0) {
lcm *= i;
exp--;
}
}
}
}
return lcm;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Method: getLeastCommonMultipleNnumber()
Calculates the least common multiple of N-1
integer contain in an array
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public int getLeastCommonMultipleNnumber(int[] arr) {
int multiple = 1;
if (arr.length >= 2) {
multiple = leastCommonMultiple(arr[0], arr[1]);
for (int j = 2; j < arr.length; j++) {
multiple = leastCommonMultiple(multiple, arr[j]);
}
} else {
// array with only 2 elements
multiple = arr[0];
}
return multiple;
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Method: process()
Calculates the least multiple of EXACTLY N-1
number of an array of N integer
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
public int process(int[] arr) {
int answer;
if (arr.length <= 1) {
// array contains only one element or is empty => return -1
answer = -1;
} else {
int pos_elem_zero = -1;
int prod = 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
prod *= arr[i];
} else {
if (arr[i] < 0) {
// integer < 0 are not allowed
return -1;
}
if (pos_elem_zero == -1) {
pos_elem_zero = i;
} else {
// there are more element == 0
return -1;
}
}
}
if (pos_elem_zero >= 0) {
// there is one element == 0
arr = this.removeElem(arr, pos_elem_zero);
return getLeastCommonMultipleNnumber(arr);
}
// managing of normal test case
answer = prod;
for (int i = 0; i < arr.length; i++) {
int elem = arr[i];
int[] arr2 = this.removeElem(arr, i);
int multiple = getLeastCommonMultipleNnumber(arr2);
if (multiple > elem) {
if ((multiple % elem) != 0) {
if (multiple < answer) {
answer = multiple;
}
}
} else {
if (multiple < elem) {
answer = multiple;
}
}
}
if (answer == prod) {
answer = -1;
}
}
return answer;
}
/*++++++++++++++++++++++++++++++++++++++++++
Method: main() Executes test of process()
method
+++++++++++++++++++++++++++++++++++++++++*/
public static void main(String[] args) {
BestMultiple bm = new BestMultiple();
int[] arr1 = {6,30,5,3};
int[] arr2 = {1,2,3};
int[] arr3 = {1,2,3,3};
int[] arr4 = {6,7,5,3};
int[] arr5 = {9,14, 21};
int[] arr6 = {2,4};
int[] arr7 = {2,3,5};
int[] arr8 = {2,3,6};
int[] arr9 = {2};
int[] arr10 = {};
int[] arr11 = {2,3,0};
int[] arr12 = {0,2,3,0};
int[] arr13 = {20,3};
int[] arr14 = {0,6,15};
int[] arr15 = {1,6,15,-1};
int[] arr16 = {1,6,15};
int[] arr17 = {2,3,0,6,15};
System.out.println("{6,30,5,3} --> " + bm.process(arr1));
System.out.println("{1,2,3} --> " + bm.process(arr2));
System.out.println("{1,2,3,3} --> " + bm.process(arr3));
System.out.println("{6,7,5,3} --> " + bm.process(arr4));
System.out.println("{9,14,21} --> " + bm.process(arr5));
System.out.println("{2,4} --> " + bm.process(arr6));
System.out.println("{2,3,5} --> " + bm.process(arr7));
System.out.println("{2,3,6} --> " + bm.process(arr8));
System.out.println("{2} --> " + bm.process(arr9));
System.out.println("{} --> " + bm.process(arr10));
System.out.println("{2,3,0} --> " + bm.process(arr11));
System.out.println("{0,2,3,0} --> " + bm.process(arr12));
System.out.println("{20,3} --> " + bm.process(arr13));
System.out.println("{0,6,15} --> " + bm.process(arr14));
System.out.println("{1,6,15,-1} --> " + bm.process(arr15));
System.out.println("{1,6,15} --> " + bm.process(arr16));
System.out.println("{2,3,0,6,15} --> " + bm.process(arr17));
}
}
Output of the program
The output of the program with the test cases chosen is:
{6,30,5,3} --> -1
{1,2,3} --> 2
{1,2,3,3} --> 3
{6,7,5,3} --> 30
{9,14,21} --> 42
{2,4} --> 2
{2,3,5} --> 6
{2,3,6} --> -1
{2} --> -1
{} --> -1
{2,3,0} --> 6
{0,2,3,0} --> -1
{20,3} --> 3
{0,6,15} --> 30
{1,6,15,-1} --> -1
{1,6,15} --> 6
{2,3,0,6,15} --> 30
You start by writing a method process that computes the minimum number for each subarray with one element excluded:
public static int process(int... arr) {
int min = -1;
for (int i = 0; i < arr.length; ++i) {
int r = process(arr, i);
if (r != -1) {
if (min == -1) {
min = r;
} else {
min = Math.min(min, r);
}
}
}
return min;
}
Where the second process method looks like this:
private static int process(int[] arr, int exclude) {
int result = 0;
for (int i = 0; i < arr.length; ++i) {
if (i != exclude) {
if (result == 0) {
result = arr[i];
} else {
result = lcm(result, arr[i]);
}
}
}
if (result%arr[exclude] == 0) {
return -1;
}
return result;
}
You need a method that computes the LCM of two numbers. Here, I'll use a second method that computes the GCD:
private static int lcm(int a, int b) {
return a*b/gcd(a,b);
}
private static int gcd(int a, int b) {
if (a == 0) {
return b;
} else if (b == 0) {
return a;
} else {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
}
Examples:
System.out.println(process(2, 3, 5)); // prints 6
System.out.println(process(2, 3, 6)); // prints -1
System.out.println(process(9, 14, 21)); // prints 42 (divisible by 14 and 21, but not by 9
System.out.println(process(6, 7, 5, 3)); // prints 30 (divisible by 6, 5, 3, but not by 7
The way you implemented process() assumes the input array is sorted. But anyway, I don't think sorting will help here. Note that the number satisfying the given conditions can be divided by the biggest number. For [2, 3, 5, 6] it is 6. Dividing the product of all the elements by consecutive elements from the biggest to the lowest and stopping at the first that is not a divisor is also not correct. In the example [2, 4, 5, 6] this would give 2 * 4 * 5 = 40 when the correct answer is 20.
My idea is to use an algorithm inspired by Sieve of Eratosthenes. Note that the number that satisfies the conditions can't be bigger than the product of all the elements. So create a table divisors[] with indices from 0 through the product of the elements of array where divisors[i] indicates how many elements from array divide i. Iterate over elements of array and increment all elements in divisors[i] where i is divided by the element. Then find the first i for which divisors[i] == n - 1.
The limitation is that divisors can be quite big depending on what is the product of array, so applicability will be limited to relatively small values in array.

perfect squares leetcode - recursive solution with memoization

Trying to solve this problem with recursion and memoization but for input 7168 I'm getting wrong answer.
public int numSquares(int n) {
Map<Integer, Integer> memo = new HashMap();
List<Integer> list = fillSquares(n, memo);
if (list == null)
return 1;
return helper(list.size()-1, list, n, memo);
}
private int helper(int index, List<Integer> list, int left, Map<Integer, Integer> memo) {
if (left == 0)
return 0;
if (left < 0 || index < 0)
return Integer.MAX_VALUE-1;
if (memo.containsKey(left)) {
return memo.get(left);
}
int d1 = 1+helper(index, list, left-list.get(index), memo);
int d2 = 1+helper(index-1, list, left-list.get(index), memo);
int d3 = helper(index-1, list, left, memo);
int d = Math.min(Math.min(d1,d2), d3);
memo.put(left, d);
return d;
}
private List<Integer> fillSquares(int n, Map<Integer, Integer> memo) {
int curr = 1;
List<Integer> list = new ArrayList();
int d = (int)Math.pow(curr, 2);
while (d < n) {
list.add(d);
memo.put(d, 1);
curr++;
d = (int)Math.pow(curr, 2);
}
if (d == n)
return null;
return list;
}
I'm calling like this:
numSquares(7168)
All test cases pass (even complex cases), but this one fails. I suspect something is wrong with my memoization but cannot pinpoint what exactly. Any help will be appreciated.
You have the memoization keyed by the value to be attained, but this does not take into account the value of index, which actually puts restrictions on which powers you can use to attain that value. That means that if (in the extreme case) index is 0, you can only reduce what is left with one square (1²), which rarely is the optimal way to form that number. So in a first instance memo.set() will register a non-optimal number of squares, which later will get updated by other recursive calls which are pending in the recursion tree.
If you add some conditional debugging code, you'll see that map.set is called for the same value of left multiple times, and with differing values. This is not good, because that means the if (memo.has(left)) block will execute for cases where that value is not guaranteed to be optimal (yet).
You could solve this by incorporating the index in your memoization key. This increases the space used for memoization, but it will work. I assume you can work this out.
But according to Lagrange's four square theorem every natural number can be written as the sum of at most four squares, so the returned value should never be 5 or more. You can shortcut the recursion when you get passed that number of terms. This reduces the benefit of using memoization.
Finally, there is a mistake in fillSquares: it should add n itself also when it is a perfect square, otherwise you'll not find solutions that should return 1.
Not sure about your bug, here is a short dynamic programming Solution:
Java
public class Solution {
public static final int numSquares(
final int n
) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
int j = 1;
int min = Integer.MAX_VALUE;
while (i - j * j >= 0) {
min = Math.min(min, dp[i - j * j] + 1);
++j;
}
dp[i] = min;
}
return dp[n];
}
}
C++
// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <vector>
#include <algorithm>
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
#define MAX INT_MAX
using ValueType = std::uint_fast32_t;
struct Solution {
static const int numSquares(
const int n
) {
if (n < 1) {
return 0;
}
static std::vector<ValueType> count_perfect_squares{0};
while (std::size(count_perfect_squares) <= n) {
const ValueType len = std::size(count_perfect_squares);
ValueType count_squares = MAX;
for (ValueType index = 1; index * index <= len; ++index) {
count_squares = std::min(count_squares, 1 + count_perfect_squares[len - index * index]);
}
count_perfect_squares.emplace_back(count_squares);
}
return count_perfect_squares[n];
}
};
int main() {
std::cout << std::to_string(Solution().numSquares(12) == 3) << "\n";
return 0;
}
Python
Here we can simply use lru_cache:
class Solution:
dp = [0]
#functools.lru_cache
def numSquares(self, n):
dp = self.dp
while len(dp) <= n:
dp += min(dp[-i * i] for i in range(1, int(len(dp) ** 0.5 + 1))) + 1,
return dp[n]
Here are LeetCode's official solutions with comments:
Java: DP
class Solution {
public int numSquares(int n) {
int dp[] = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
// bottom case
dp[0] = 0;
// pre-calculate the square numbers.
int max_square_index = (int) Math.sqrt(n) + 1;
int square_nums[] = new int[max_square_index];
for (int i = 1; i < max_square_index; ++i) {
square_nums[i] = i * i;
}
for (int i = 1; i <= n; ++i) {
for (int s = 1; s < max_square_index; ++s) {
if (i < square_nums[s])
break;
dp[i] = Math.min(dp[i], dp[i - square_nums[s]] + 1);
}
}
return dp[n];
}
}
Java: Greedy
class Solution {
Set<Integer> square_nums = new HashSet<Integer>();
protected boolean is_divided_by(int n, int count) {
if (count == 1) {
return square_nums.contains(n);
}
for (Integer square : square_nums) {
if (is_divided_by(n - square, count - 1)) {
return true;
}
}
return false;
}
public int numSquares(int n) {
this.square_nums.clear();
for (int i = 1; i * i <= n; ++i) {
this.square_nums.add(i * i);
}
int count = 1;
for (; count <= n; ++count) {
if (is_divided_by(n, count))
return count;
}
return count;
}
}
Java: Breadth First Search
class Solution {
public int numSquares(int n) {
ArrayList<Integer> square_nums = new ArrayList<Integer>();
for (int i = 1; i * i <= n; ++i) {
square_nums.add(i * i);
}
Set<Integer> queue = new HashSet<Integer>();
queue.add(n);
int level = 0;
while (queue.size() > 0) {
level += 1;
Set<Integer> next_queue = new HashSet<Integer>();
for (Integer remainder : queue) {
for (Integer square : square_nums) {
if (remainder.equals(square)) {
return level;
} else if (remainder < square) {
break;
} else {
next_queue.add(remainder - square);
}
}
}
queue = next_queue;
}
return level;
}
}
Java: Most efficient solution using math
Runtime: O(N ^ 0.5)
Memory: O(1)
class Solution {
protected boolean isSquare(int n) {
int sq = (int) Math.sqrt(n);
return n == sq * sq;
}
public int numSquares(int n) {
// four-square and three-square theorems.
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)
return 4;
if (this.isSquare(n))
return 1;
// enumeration to check if the number can be decomposed into sum of two squares.
for (int i = 1; i * i <= n; ++i) {
if (this.isSquare(n - i * i))
return 2;
}
// bottom case of three-square theorem.
return 3;
}
}

How to properly subtract 2 numbers taken from String after converting them to int array

I'm currently stuck in algorithm which takes two Strings (which are made from numbers) as an argument. Steps are:
Convert String to int array
Reverse this array so from String(123456) array would look like: int[654321].
Subtract values from two made arrays and save it to third(result) array using given algorithm.
Reading values from third(result) table, read them backwards and save result to String.
Basically, I'm currently on algorithms and data structure course on Uni and we wrote this algorithm in our class, but it's only working when I'm subtracting A-B, where A > B. What is my current problem is that I need to refactor this to the point where I can subtract B from A, even though B > A.
I've tried to add some 'if' statements which would depend on A > B || A < B but I don't think that it would lead my anywhere.
Conversion function which cannot be changed anyway:
public static int[] convert(String number, int size)
{
int[] tab = new int[size];
int position = number.length() - 1;
for (int i = 0; i < size; i++)
{
if (position < 0) tab[i] = 0;
else tab[i] = number.charAt(position--) - 48;
}
return tab;
}
public static String substract(String number1, String number2)
{
String result = "";
int size = Math.max(number1.length(), number2.length()) + 1;
int[] tA = new int[size];
int[] tB = new int[size];
int[] tW = new int[size];
tA = convert(number1, size);
tB = convert(number2, size);
for(int i = 0; i < size; i++) tW[i] = 0;
for(int i = 0; i < size-1; i++)
{
tW[i+1] += (tW[i] + tA[i] - tB[i] + 10) / 10 - 1;
tW[i] = (tW[i] + tA[i] - tB[i] + 10) % 10;
}
while(size > 1 && tW[size-1] == 0) size--;
for(int i = size; i > 0; i--) result += (char)(tW[i-1] + 48);
return result;
}
I expect that output of subtract("12", "20") would be -8 but actual output is /92.
Here are some example solutions using Java 8. If you are allowed to use them, I'd recommend using streams as they really fit your problem:
convert: return the numeric value of each char in string, into an int array.
int[] convert(String s) {
return s.chars().map(Character::getNumericValue).toArray();
}
reverse: reverse an int array.
int[] reverse(int[] toReverse) {
return IntStream.range(0, toReverse.length)
.map(i -> toReverse[toReverse.length - 1 - i])
.toArray();
}
substract: for a range between 0 and the biggest length, return the value of the int in a minus the int in b at position i, if both exist, in form of an array of results.
int[] substract(int[] a, int[] b) {
return IntStream.range(0, Math.max(a.length, b.length))
.map(i -> {
if(i < a.length && i < b.length)
return a[i] - b[i];
if(i < a.length)
return a[i];
return b[i];
})
.toArray();
}
What you can do is that if number1 < number2, calculate number2 - number1, and add a minus sign to the result. Of course, if there are equal, result is 0.
You need to compare number1 and number2 as follows:
if (number1.length() == number2.length()) {
if (number1 > number2) {
// number1 is greater then number2.
} else {
// number2 is greater than number1.
}
} else if (number1.length() > number2.length()) {
// number1 is greater than number2.
} else
// number2 is greater than number1.
}

How do I solve this StackOverflowError?

In this section of my MergeSort program, I am recursively dividing a unsorted array called "arr". To do this I create two subarrays, "leftArr" and "rightArr", then I fill "leftArr" and "rightArr" with the first half of "arr" and the second half of "arr" respectively. Afterwards I will use recursion to divde / sort leftArr and rightArr.
Just wanted clarify: mid = arr.length;
To initialise the rightArr I do the following:
double halfLength = arr.length * 0.5;
if((!(halfLength < 0)) && (!(0 < halfLength))){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}
When I do this I get no errors:
if(arr.length % 2 == 0){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}
But my project doesn't allow me to use the modulus operator "%" and the "==" operator.
Im not getting any syntax error. All i see in the console window is:
" Exception in thread "main" java.lang.StackOverflowError ".
The Complete recursive method looks like this:
public int[] mergeSort(int[] arr) {
if (arr.length < 2){
return arr; // if array has only one element, its already sorted
}
int mid = arr.length / 2; // find midpoint of array
int leftArr[] = new int [mid]; // create left subarray of length mid
int rightArr[]; // create right subarray
/* if(arr.length % 2 == 0){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}*/
double halfLength = arr.length * 0.5;
if((!(halfLength < 0)) && (!(0 < halfLength))){
// if right array is an even num, length of right array is mid
rightArr = new int [mid];
} else
{
// else right arrays length is mid + 1
rightArr = new int[mid + 1];
}
// create a resultArr of size arr, to store the sorted array
int resultArr[] = new int [arr.length];
int i = 0;
// Copy first half of arr[] into leftArr[]
while(i < mid){
leftArr[i] = arr[i];
i = i + 1;
}
int j = mid;
int indexOfRight = 0;
// Copy second half of arr into rightArr
while(j < arr.length){
rightArr[indexOfRight] = arr[j];
indexOfRight = indexOfRight + 1;
j = j + 1;
}
// Recursively call mergeSort to sort leftArr and rightArr
leftArr = mergeSort(leftArr);
rightArr = mergeSort(rightArr);
// merge leftArr and rightArr into a resultant Array, and then return the resultArr
return resultArr = merge(leftArr, rightArr);
}
This is how I merge:
public int[] merge(int[] a1, int[] a2) {
// TO BE COMPLETED
int lengthOfRes = a1.length + a2.length;
int resArr[] = new int [lengthOfRes]; // create resultant array of size a1 + a2
int a1Index = 0;
int a2Index = 0;
int resIndex = 0;
while((a1Index < a1.length) || (a2Index < a2.length))
{
if((a1Index < a1.length) && (a2Index < a2.length)){
// if a1's element is <= a2's element, then insert a1's elem in resArr
if(a1[a1Index] < a2[a2Index]){
resArr[resIndex] = a1[a1Index];
a1Index = a1Index + 1;
resIndex = resIndex + 1;
} else
// else, insert a2's elem in resArr
{
resArr[resIndex] = a2[a2Index];
a2Index = a2Index + 1;
resIndex = resIndex + 1;
}
}
// Here, if there are any of a1's elements left over, then insert them into resArr
else if(a1Index < a1.length){
resArr[resIndex] = a1[a1Index];
a1Index = a1Index + 1;
resIndex = resIndex + 1;
}
// Here, if there are any of a2's elements left over, then insert them into resArr
else
{
resArr[resIndex] = a2[a2Index];
a2Index = a2Index + 1;
resIndex = resIndex + 1;
}
}
return resArr; // return the resulting array
}
How can I fix this problem?
Thanks in advance!
This algorithm is not sorting anything. You are only breaking the array recursively, but there isn't any comparison.
This site have a good explanation about merge sorting algorithm: http://algs4.cs.princeton.edu/22mergesort/
http://algs4.cs.princeton.edu/22mergesort/Merge.java.html
It's worth studying it.
The problem is that this code
double halfLength = arr.length * 0.5;
if((!(halfLength < 0)) && (!(0 < halfLength)))
do not determine if the arr.length is even. Try this:
public boolean isEven(int number) {
// return (number - (number / 2) * 2) == 0;
return (!((number - (number / 2) * 2) > 0)) && (!((number - (number / 2) * 2) < 0));
}
Here is another method without division, mod or equals operations
public boolean isEven(int number) {
number = number < 0 ? number * -1 : number;
if (number < 1) {
return true;
}
if (number > 0 && number < 2) {
return false;
}
return isEven(number - 2);
}

How can i fin the index using exponential, binary or interpolatin search recursively? [duplicate]

This question already has an answer here:
How can I locate an index given the following constraints? [closed]
(1 answer)
Closed 9 years ago.
Given an array of n integers A[0…n−1], such that ∀i,0≤i≤n, we have that |A[i]−A[i+1]|≤1, and if A[0]=x, A[n−1]=y, we have that x<y. Locate the index j such that A[j]=z, for a given value of z, x≤ z ≤y
I dont understand the problem. I've been stuck on it for 4 days. Any idea of how to approach it with binary search, exponential search or interpolation search recursively? We are given an element z find the index j such that a [j] = z (a j) am i right?.
static int binarySearch(int[] searchArray, int x) {
int start, end, midPt;
start = 0;
end = searchArray.length - 1;
while (start <= end) {
midPt = (start + end) / 2;
if (searchArray[midPt] == x) {
return midPt;
} else if (searchArray[midPt] < x) {
start = midPt + 1;
} else {
end = midPt - 1;
}
}
return -1;
}
You can use the basic binary search algorithm. The fact that A[i] and A[i+1] differ by at most 1 guarantees you will find a match.
Pseudocode:
search(A, z):
start := 0
end := A.length - 1
while start < end:
x = A[start]
y = A[end]
mid := (start+end)/2
if x <= z <= A[mid]:
end := mid
else if A[mid] < z <= y
start := mid + 1
return start
Note that this doesn't necessarily return the first match, but that wasn't required.
to apply your algorithms your need a sorted array.
the condition of you problem says that you have an array which has elements that differ with max 1, not necessarily sorted!!!
so, here are the steps to write the code :
check if problem data respects given conditions
sort input array + saving old indexes values, so later can can initial positions of elements
implement you search methods in recursive way
Binary search source
Interpolation search source
Here's full example source :
public class Test {
// given start ======================================================
public int[] A = new int[] { 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6,
7, 8 };
public int z = 4;
// given end =======================================================
public int[] indexes = new int[A.length];
public static void main(String[] args) throws Exception {
Test test = new Test();
if (test.z < test.A[0] || test.z > test.A[test.A.length - 1]){
System.out.println("Value z="+test.z+" can't be within given array");
return;
}
sort(test.A, test.indexes);
int index = binSearch(test.A, 0, test.A.length, test.z);
if (index > -1) {
System.out.println("Binary search result index =\t"
+ test.indexes[index]);
}
index = interpolationSearch(test.A, test.z, 0, test.A.length-1);
if (index > -1) {
System.out.println("Binary search result index =\t"
+ test.indexes[index]);
}
}
public static void sort(int[] a, int[] b) {
for (int i = 0; i < a.length; i++)
b[i] = i;
boolean notSorted = true;
while (notSorted) {
notSorted = false;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
int aux = a[i];
a[i] = a[i + 1];
a[i + 1] = aux;
aux = b[i];
b[i] = b[i + 1];
b[i + 1] = aux;
notSorted = true;
}
}
}
}
public static int binSearch(int[] a, int imin, int imax, int key) {
// test if array is empty
if (imax < imin)
// set is empty, so return value showing not found
return -1;
else {
// calculate midpoint to cut set in half
int imid = (imin + imax) / 2;
// three-way comparison
if (a[imid] > key)
// key is in lower subset
return binSearch(a, imin, imid - 1, key);
else if (a[imid] < key)
// key is in upper subset
return binSearch(a, imid + 1, imax, key);
else
// key has been found
return imid;
}
}
public static int interpolationSearch(int[] sortedArray, int toFind, int low,
int high) {
if (sortedArray[low] == toFind)
return low;
// Returns index of toFind in sortedArray, or -1 if not found
int mid;
if (sortedArray[low] <= toFind && sortedArray[high] >= toFind) {
mid = low + ((toFind - sortedArray[low]) * (high - low))
/ (sortedArray[high] - sortedArray[low]); // out of range is
// possible here
if (sortedArray[mid] < toFind)
low = mid + 1;
else if (sortedArray[mid] > toFind)
// Repetition of the comparison code is forced by syntax
// limitations.
high = mid - 1;
else
return mid;
return interpolationSearch(sortedArray, toFind, low, high);
} else {
return -1;
}
}
}

Categories