Binary Search with Primitive Types - java

I am currently in a class for Java Programming and am completely new to Java. I am trying to create a program that will use binary search for the value 45.3
class findValue {
public static void main(String args[]) {
double a[] = new double[6]; //declaration
a[0] = -3; //initialization
a[1] = 10;
a[2] = 5;
a[3] = 24;
a[4] = 45.3;
a[5] = 10.5;
int n = a.length; //storing length of array
int temp = 0; //declaring temporary storage place
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = (int)a[j - 1];
a[j - 1] = a[j];
a[j] = temp; //bubble sorting
};
};
};
System.out.println("45.3 found" + binarySearch(a, 45.3));
};
public static void binarySearch(Integer[] a, int x) {
int low = 0;
int high = a.length - 1;
int mid; //values for binary search
while (low <= high) {
mid = (low + high) / 2; //setting value for searching
if (a[mid].compareTo(x) < 0) {
low = mid + 1;
}
else if (a[mid].compareTo(x) > 0) {
high = mid - 1;
};
};
};
This is the compiler error I got:
Line: 25
method binarySearch in class findValue cannot be applied to given types;
required: java.lang.Integer[],int
found: double[],double
reason: actual argument double[] cannot be converted to java.lang.Integer[] by method invocation conversion

(I know there is a lot of room for improvement, but I'm just suggesting the minimum number of changes for the program to work)
The method
public static void binarySearch(Integer[] a, int x) {...}
is expecting integers, but we want it to use doubles insted. This means that the arguments should be an array of doubles, and the double to find:
public static void binarySearch(double[] a, double x) {...}
This said, we know that this function will return an int, so we set the return type:
public static double binarySearch(double[] a, double x) {...}
Now, finally, we must return the number we were looking for by adding the following at the end of the method (after the while):
return mid;
The final result should be:
class findValue {
public static void main(String args[]) {
double a[] = new double[6]; //declaration
a[0] = -3; //initialization
a[1] = 10;
a[2] = 5;
a[3] = 24;
a[4] = 45.3;
a[5] = 10.5;
int n = a.length; //storing length of array
int temp = 0; //declaring temporary storage place
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = (int)a[j - 1];
a[j - 1] = a[j];
a[j] = temp; //bubble sorting
}
}
}
System.out.println("45.3 found: " + binarySearch(a, 45.3));
}
public static int binarySearch(double[] a, double x) {
int low = 0;
int high = a.length - 1;
int mid = (low + high) / 2; //values for binary search
while (low <= high) {
mid = (low + high) / 2; //setting value for searching
if (Double.compare(a[mid], (double)x) < 0) {
low = mid + 1;
}
else if (Double.compare(a[mid], (double)x) > 0) {
high = mid - 1;
}
}
return mid;
}
}
Output:
45.3 found: 5

From your declaration of the method public static void binarySearch(Integer[] a, int x) {
the binarySearch is expecting an array of Integer and an int as parameters,
While your call in line 25 is calling binary search with a double array and a double as parameter, hence the exception.
You can't convert a double to int because the double has more "information" than the int. double 43.5 converted to int would lose the .5

Related

Trouble outputting names in a backpack problem

I was trying to solve a problem based on value and weight. In the task i had to pick out the elements by their value and weight, and find the highest efficiency solution. I receive an answer, however i am having trouble outputting the elements that were used in order to get an answer.
I've tried creating a string in which i place the values, however it gives out an outofbounds error.
public static void main(String[] args) {
String z[] = new String[]{"a","b","c","d","e","f","g","h","l","m"};
int w[] = new int[]{10,2,4,6,8,1,7,11,4,5};
int c[] = new int[]{20,3,5,7,4,1,8,15,8,6};
int maxW = 50;
int n = c.length;
System.out.println("");
int a = Find(w,c,maxW,n,z);
System.out.println("max value is " + a);
}
static int max(int a, int b)
{
if(a>b)
{
return a;
}
return b;
}
public static int Find(int w[],int c[], int maxW,int n, String[]z)
{
int K[][] = new int[n + 1][maxW + 1];
String s = "";
// Build table K[][] in bottom up manner
for (int i = 0; i<= n; i++)
{
for(int j = 0; j<= maxW; j++)
{
if (i == 0 || j == 0)
{
K[i][j] = 0;
}
else if (w[i - 1]<= j)
{
K[i][j] = max(c[i - 1] + K[i - 1][j - w[i - 1]], K[i - 1][j]);
}
else
{
K[i][j] = K[i - 1][j];
}
}
}
return K[n][maxW];
}
}
i want to output the same index element in string z, as the index element that is used to find the efficiancy.
The ideal result would be something like this in a string:
a a a b c d e m
(Just an example)
Thank you in advance.

Java Fork/Join for large inputs not finishing

I am trying to complete the coding for a parallel version of my sequential code of a 1D median filter on an input of float values. I have been using some smaller lengths of test values to code the parallel version and finally seemed to get the code working, however now on a large dataset of +-36000 elements the code seems to just ramp up CPU resources and not complete whereas my sequential version completes on the same given input. Does anyone know where I am going wrong?
Test input that works: 2, 6, 80, 3, 1 and produces correctly: 2,6,6,3,1
// median filter code
public class MedianFilter extends RecursiveAction {
// filter class variables
float[] numbers;
int filter;
int window;
int length;
int lo;
int hi;
// sequential cutoff set to predetermined value
static final int SEQUENTIAL_CUTOFF = 500;
// array used for recursive calls in parallel code
float[] filtered;
float[] result;
public MedianFilter(float[] numbers, int filter, int lo, int hi) {
this.numbers = numbers;
this.filter = filter;
this.lo = lo;
this.hi = hi;
length = numbers.length;
// the section of floats to be filtered (median section)
window = (filter - 1) / 2;
}
protected void compute() {
filtered = new float[length];
result = new float[length];
if ((hi - lo) < SEQUENTIAL_CUTOFF) {
for (int a = lo; a < hi; a++) {
// iterate window through all elements of the array
for (int i = 0; i < length; i++) {
// fetch boundary elements
if (i < window || i >= length - window) {
result[i] = numbers[i];
}
// fetch elements within filter window
else {
for (int j = 0; j < filter; j++) {
filtered[j] = numbers[i - window + j];
}
// order elements
for (int j = 0; j < filtered.length / 2; j++) {
// get the position of the smallest float
int min = j;
for (int k = j + 1; k < filter; k++) {
if (filtered[k] < filtered[min]) {
min = k;
}
// reorder array for minimum element
float temp = filtered[j];
filtered[j] = filtered[min];
filtered[min] = temp;
}
// result
result[i] = filtered[window];
}
}
}
}
} else {
MedianFilter left = new MedianFilter(filtered, filter, lo, (hi + lo) / 2);
MedianFilter right = new MedianFilter(filtered, filter, (hi + lo) / 2, hi);
left.fork();
right.compute();
left.join();
}
}

two problems with mean med mode method

So here is my completed code that calculates Mean, Median, Mode, Standard deviation, min, max, q1, q2, and 5 number summary which is supposed to be returned as an array. The array is formatted properly to my knowledge, but for some odd reason the return array is spitting out this 5 number Summary:[D#689af4 and I don't for the life of my know why or how to fix it. Also the mode is outputting 22 when I need it to out put -1. Is there any one who can look at this and tell me what is wrong and what I can to do fix these issues?
import java.util.Arrays;
class Statistics {
public static void main(String[] args)
{
int[] a = new int[]{22,44,66,55,33};
bubbleSort(a);
double mean;
double median;
int mode;
int max;
int min;
double sd;
int q1;
int q3;
double[] vals;
mode = calcMoe (a);
median = calcMed (a);
mean = calcMean (a);
max =calcMax (a);
min =calcMin (a);
sd =calcSd (a);
q1=calcQuart1 (a);
q3=calcQuart3 (a);
vals=calcNumsum (a);
System.out.println("Median:"+median);
System.out.println("Mean:"+mean);
System.out.println("Mode:"+mode);
System.out.println("max number is : " + max);
System.out.println("min number is : " + min);
System.out.println("Standard Deviation:"+sd);
System.out.println("1st Quartile:"+q1);
System.out.println("3rd Quartile:"+q3);
System.out.println("5 number Summary:"+vals);
}
public static double calcMean(int[] a)
{
// int[]array = {22,44,66,55,33};
int i;//=0;
int sum=0;
double mean =0;
for ( i=0;i<a.length;i++)
{
//System.out.println(a[i]);
sum=sum+a[i];
}
{ mean = ((double) sum/ ((double) a.length));
//System.out.println(); } {
return mean;}
}
//Calulate median
public static double calcMed(int[] a)
{// Sort array
int[] sorta = bubbleSort(a);
double median = 0;
if (a.length % 2 == 0)
{
int indexA = (sorta.length - 1) / 2;
int indexB = sorta.length / 2;
median = ((double) (sorta[indexA] + sorta[indexB])) / 2;
}
// Else if our array's length is odd
else
{
int index = (sorta.length - 1) / 2;
median = a[ index ];
}
// Print the values of the sorted array
for (int v : sorta)
{
System.out.println(v);
}
return median;
}
public static int[] bubbleSort(int[] a)
{
//outer loop
for(int luck=0; luck<a.length -1; luck++){
for (int juck=1; juck<a.length - luck; juck++){
if (a[juck-1]>a[juck]){
int temp= a[juck];
a[juck]=a[juck-1];
a[juck-1]=temp;
//System.out.printf("unsorted array after %d pass %s: %n", luck+1, Arrays.toString(a));
}
}
}
return a;
}
public static int calcMoe(int[] a)
{
Arrays.sort(a);
int count2 = 0;
int count1 = 1;
int pupular1 =0;
int mode =0;
for (int i = 0; i < a.length; i++)
{
pupular1 = a[i];
count1 = 1;
for (int j = i + 1; j < a.length; j++)
{
if (pupular1 == a[j]) count1++;
}
if (count1 > count2)
{
mode = pupular1;
count2 = count1;
}
if (count1 == count2)
{
mode = Math.min(mode, pupular1);
}
}
return mode;
}
public static int calcMax(int[] a) {
//int min = a[0];
int max = a[0];
for (int i = 1; i <= a.length - 1; i++) {
if (max < a[i]) {
max = a[i];
}
}
return max;
}
public static int calcMin(int[] a) {
int min = a[0];
for (int i = 1; i <= a.length - 1; i++) {
if (min > a[i]) {
min = a[i];
}
}
return min;
}
public static double calcSd(int[] a) {
//int sum = 0;
//int max = 0;
//int min = a[0];
double sd = 0;
int i = 0;
double mean =0;
sd=0;
for ( i=0;i<a.length;i++)
{
sd += ((a[i] - mean)*(a[i] - mean)) / (a.length - 1);
}
double standarddeviation = Math.sqrt(sd);
{
}
return standarddeviation;
}
public static int calcQuart1(int[] a) {
int[] sorta = bubbleSort(a);
int q1 = 0;
{
int index = (sorta.length - 1) / 4;
q1 = a[ index ] ;
}
for (int v : sorta)
{
System.out.println(v);
}
return q1;
}
public static int calcQuart3(int[] a) {
int[] sorta = bubbleSort(a);
int q3 = 0;
{
int index = 3*(sorta.length - 1) / 4;
q3 = a[ index ] ;
}
for (int v : sorta)
{
System.out.println(v);
}
return q3;
}
public static double[] calcNumsum(int[] a) {
double median = calcMed (a);
double max =calcMax (a);
double min =calcMin (a);
double q1=calcQuart1 (a);
double q3=calcQuart3 (a);
double[] vals = new double[5];
vals[0] = min;
vals [1] = q1;
vals [2] = median;
vals [3] = q3;
vals [4] = max;
return vals;
}
}
This line:
System.out.println("5 number Summary:"+vals);
simply takes vals, converts it to a String, and prints it. The default toString implementation for array types in Java produces the output you noted: the overall type ([ for 'array'), the type stored in the array (D for double), an # symbol, and the location of the array in memory (689af4, in this case).
To get perhaps a more useful output for your purposes, you can use Arrays.toString:
System.out.println("5 number summary: " + Arrays.toString(vals));
In regard to that strange out put "5 number Summary:[D#689af4" this is just the reference of the array, and that is the general print of an array. If you want to print all elements in an array you need to implement a toString method and the basic way to do it is print one-by-one item from the array. In your case it will be something like that:
System.out.print( "5 number Summary: ");
for(int i = 0; i < vals.length; i++){
System.out.print(" " + vals[i]);
}
System.out.println();
Your code is printing the memory location of the Object vals not the content, to print the content you have to loop over it like this:
System.out.println("5 number Summary:");
for (double d : vals) {
System.out.print(d + ",");
}

java codility Max-Counters

I have been trying to solve the below task:
You are given N counters, initially set to 0, and you have two possible operations on them:
increase(X) − counter X is increased by 1,
max_counter − all counters are set to the maximum value of any counter.
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if A[K] = N + 1 then operation K is max_counter.
For example, given integer N = 5 and array A such that:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the values of the counters after each consecutive operation will be:
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)
The goal is to calculate the value of every counter after all operations.
struct Results {
int * C;
int L;
};
Write a function:
struct Results solution(int N, int A[], int M);
that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.
The sequence should be returned as:
a structure Results (in C), or
a vector of integers (in C++), or
a record Results (in Pascal), or
an array of integers (in any other programming language).
For example, given:
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4
the function should return [3, 2, 2, 4, 2], as explained above.
Assume that:
N and M are integers within the range [1..100,000];
each element of array A is an integer within the range [1..N + 1].
Complexity:
expected worst-case time complexity is O(N+M);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
Here is my solution:
import java.util.Arrays;
class Solution {
public int[] solution(int N, int[] A) {
final int condition = N + 1;
int currentMax = 0;
int countersArray[] = new int[N];
for (int iii = 0; iii < A.length; iii++) {
int currentValue = A[iii];
if (currentValue == condition) {
Arrays.fill(countersArray, currentMax);
} else {
int position = currentValue - 1;
int localValue = countersArray[position] + 1;
countersArray[position] = localValue;
if (localValue > currentMax) {
currentMax = localValue;
}
}
}
return countersArray;
}
}
Here is the code valuation:
https://codility.com/demo/results/demo6AKE5C-EJQ/
Can you give me a hint what is wrong with this solution?
The problem comes with this piece of code:
for (int iii = 0; iii < A.length; iii++) {
...
if (currentValue == condition) {
Arrays.fill(countersArray, currentMax);
}
...
}
Imagine that every element of the array A was initialized with the value N+1. Since the function call Arrays.fill(countersArray, currentMax) has a time complexity of O(N) then overall your algorithm will have a time complexity O(M * N). A way to fix this, I think, instead of explicitly updating the whole array A when the max_counter operation is called you may keep the value of last update as a variable. When first operation (incrementation) is called you just see if the value you try to increment is larger than the last_update. If it is you just update the value with 1 otherwise you initialize it to last_update + 1. When the second operation is called you just update last_update to current_max. And finally, when you are finished and try to return the final values you again compare each value to last_update. If it is greater you just keep the value otherwise you return last_update
class Solution {
public int[] solution(int N, int[] A) {
final int condition = N + 1;
int currentMax = 0;
int lastUpdate = 0;
int countersArray[] = new int[N];
for (int iii = 0; iii < A.length; iii++) {
int currentValue = A[iii];
if (currentValue == condition) {
lastUpdate = currentMax
} else {
int position = currentValue - 1;
if (countersArray[position] < lastUpdate)
countersArray[position] = lastUpdate + 1;
else
countersArray[position]++;
if (countersArray[position] > currentMax) {
currentMax = countersArray[position];
}
}
}
for (int iii = 0; iii < N; iii++) {
if (countersArray[iii] < lastUpdate)
countersArray[iii] = lastUpdate;
}
return countersArray;
}
}
The problem is that when you get lots of max_counter operations you get lots of calls to Arrays.fill which makes your solution slow.
You should keep a currentMax and a currentMin:
When you get a max_counter you just set currentMin = currentMax.
If you get another value, let's call it i:
If the value at position i - 1 is smaller or equal to currentMin you set it to currentMin + 1.
Otherwise you increment it.
At the end just go through the counters array again and set everything less than currentMin to currentMin.
Another solution that I have developed and might be worth considering: http://codility.com/demo/results/demoM658NU-DYR/
This is the 100% solution of this question.
// you can also use imports, for example:
// import java.math.*;
class Solution {
public int[] solution(int N, int[] A) {
int counter[] = new int[N];
int n = A.length;
int max=-1,current_min=0;
for(int i=0;i<n;i++){
if(A[i]>=1 && A[i]<= N){
if(counter[A[i] - 1] < current_min) counter[A[i] - 1] = current_min;
counter[A[i] - 1] = counter[A[i] - 1] + 1;
if(counter[A[i] - 1] > max) max = counter[A[i] - 1];
}
else if(A[i] == N+1){
current_min = max;
}
}
for(int i=0;i<N;i++){
if(counter[i] < current_min) counter[i] = current_min;
}
return counter;
}
}
I'm adding another Java 100 solution with some test cases it they're helpful.
// https://codility.com/demo/results/demoD8J6M5-K3T/ 77
// https://codility.com/demo/results/demoSEJHZS-ZPR/ 100
public class MaxCounters {
// Some testcases
// (1,[1,2,3]) = [1]
// (1,[1]) = [1]
// (1,[5]) = [0]
// (1,[1,1,1,2,3]) = 3
// (2,[1,1,1,2,3,1]) = [4,3]
// (5, [3, 4, 4, 5, 1, 4, 4]) = (1, 0, 1, 4, 1)
public int[] solution(int N, int[] A) {
int length = A.length, maxOfCounter = 0, lastUpdate = 0;
int applyMax = N + 1;
int result[] = new int[N];
for (int i = 0; i < length; ++i ) {
if(A[i] == applyMax){
lastUpdate = maxOfCounter;
} else if (A[i] <= N) {
int position = A[i]-1;
result[position] = result[position] > lastUpdate
? result[position] + 1 : lastUpdate + 1;
// updating the max for future use
if(maxOfCounter <= result[position]) {
maxOfCounter = result[position];
}
}
}
// updating all the values that are less than the lastUpdate to the max value
for (int i = 0; i < N; ++i) {
if(result[i] < lastUpdate) {
result[i] = lastUpdate;
}
}
return result;
}
}
My java solution with a detailed explanation 100% Correctness, 100% Performance :
Time Complexity O(N+M)
public static int[] solution(int N, int[] A) {
int[] counters = new int[N];
//The Max value between all counters at a given time
int max = 0;
//The base Max that all counter should have after the "max counter" operation happens
int baseMax = 0;
for (int i = 0; i < A.length; i++) {
//max counter Operation ==> updating the baseMax
if (A[i] > N) {
// Set The Base Max that all counters should have
baseMax = max;
}
//Verify if the value is bigger than the last baseMax because at any time a "max counter" operation can happen and the counter should have the max value
if (A[i] <= N && counters[A[i] - 1] < baseMax) {
counters[A[i] - 1] = baseMax;
}
//increase(X) Operation => increase the counter value
if (A[i] <= N) {
counters[A[i] - 1] = counters[A[i] - 1] + 1;
//Update the max
max = Math.max(counters[A[i] - 1], max);
}
}
//Set The remaining values to the baseMax as not all counters are guaranteed to be affected by an increase(X) operation in "counters[A[i] - 1] = baseMax;"
for (int j = 0; j < N; j++) {
if (counters[j] < baseMax)
counters[j] = baseMax;
}
return counters;
}
Here is my C++ solution which got 100 on codility. The concept is same as explained above.
int maxx=0;
int lastvalue=0;
void set(vector<int>& A, int N,int X)
{
for ( int i=0;i<N;i++)
if(A[i]<lastvalue)
A[i]=lastvalue;
}
vector<int> solution(int N, vector<int> &A) {
// write your code in C++11
vector<int> B(N,0);
for(unsigned int i=0;i<A.size();i++)
{
if(A[i]==N+1)
lastvalue=maxx;
else
{ if(B[A[i]-1]<lastvalue)
B[A[i]-1]=lastvalue+1;
else
B[A[i]-1]++;
if(B[A[i]-1]>maxx)
maxx=B[A[i]-1];
}
}
set(B,N,maxx);
return B;
}
vector<int> solution(int N, vector<int> &A)
{
std::vector<int> counters(N);
auto max = 0;
auto current = 0;
for (auto& counter : A)
{
if (counter >= 1 && counter <= N)
{
if (counters[counter-1] < max)
counters[counter - 1] = max;
counters[counter - 1] += 1;
if (counters[counter - 1] > current)
current = counters[counter - 1];
}
else if (counter > N)
max = current;
}
for (auto&& counter : counters)
if (counter < max)
counter = max;
return counters;
}
Arrays.fill() invocation inside array interation makes the program O(N^2)
Here is a possible solution which has O(M+N) runtime.
The idea is -
For the second operation, keep track of max value that is achieved through increment, this is our base value till the current iteration, no values can't be less than this.
For the first operation, resetting the value to base value if needed before the increment.
public static int[] solution(int N, int[] A) {
int counters[] = new int[N];
int base = 0;
int cMax = 0;
for (int a : A) {
if (a > counters.length) {
base = cMax;
} else {
if (counters[a - 1] < base) {
counters[a - 1] = base;
}
counters[a - 1]++;
cMax = Math.max(cMax, counters[a - 1]);
}
}
for (int i = 0; i < counters.length; i++) {
if (counters[i] < base) {
counters[i] = base;
}
}
return counters;
}
vector<int> solution(int N, vector<int> &A)
{
std::vector<int> counter(N, 0);
int max = 0;
int floor = 0;
for(std::vector<int>::iterator i = A.begin();i != A.end(); i++)
{
int index = *i-1;
if(*i<=N && *i >= 1)
{
if(counter[index] < floor)
counter[index] = floor;
counter[index] += 1;
max = std::max(counter[index], max);
}
else
{
floor = std::max(max, floor);
}
}
for(std::vector<int>::iterator i = counter.begin();i != counter.end(); i++)
{
if(*i < floor)
*i = floor;
}
return counter;
}
Hera is my AC Java solution. The idea is the same as #Inwvr explained:
public int[] solution(int N, int[] A) {
int[] count = new int[N];
int max = 0;
int lastUpdate = 0;
for(int i = 0; i < A.length; i++){
if(A[i] <= N){
if(count[A[i]-1] < lastUpdate){
count[A[i]-1] = lastUpdate+1;
}
else{
count[A[i]-1]++;
}
max = Math.max(max, count[A[i]-1]);
}
else{
lastUpdate = max;
}
}
for(int i = 0; i < N; i++){
if(count[i] < lastUpdate)
count[i] = lastUpdate;
}
return count;
}
I just got 100 in PHP with some help from the above
function solution($N, $A) {
$B = array(0);
$max = 0;
foreach($A as $key => $a) {
$a -= 1;
if($a == $N) {
$max = max($B);
} else {
if(!isset($B[$a])) {
$B[$a] = 0;
}
if($B[$a] < $max) {
$B[$a] = $max + 1;
} else {
$B[$a] ++;
}
}
}
for($i=0; $i<$N; $i++) {
if(!isset($B[$i]) || $B[$i] < $max) {
$B[$i] = $max;
}
}
return $B;
}
This is another C++ solution to the problem.
The rationale is always the same.
Avoid to set to max counter all the counter upon instruction two, as this would bring the complexity to O(N*M).
Wait until we get another operation code on a single counter.
At this point the algorithm remembers whether it had met a max_counter and set the counter value consequently.
Here the code:
vector<int> MaxCounters(int N, vector<int> &A)
{
vector<int> n(N, 0);
int globalMax = 0;
int localMax = 0;
for( vector<int>::const_iterator it = A.begin(); it != A.end(); ++it)
{
if ( *it >= 1 && *it <= N)
{
// this is an increase op.
int value = *it - 1;
n[value] = std::max(n[value], localMax ) + 1;
globalMax = std::max(n[value], globalMax);
}
else
{
// set max counter op.
localMax = globalMax;
}
}
for( vector<int>::iterator it = n.begin(); it != n.end(); ++it)
*it = std::max( *it, localMax );
return n;
}
100%, O(m+n)
public int[] solution(int N, int[] A) {
int[] counters = new int[N];
int maxAIs = 0;
int minAShouldBe = 0;
for(int x : A) {
if(x >= 1 && x <= N) {
if(counters[x-1] < minAShouldBe) {
counters[x-1] = minAShouldBe;
}
counters[x-1]++;
if(counters[x-1] > maxAIs) {
maxAIs = counters[x-1];
}
} else if(x == N+1) {
minAShouldBe = maxAIs;
}
}
for(int i = 0; i < N; i++) {
if(counters[i] < minAShouldBe) {
counters[i] = minAShouldBe;
}
}
return counters;
}
here is my code, but its 88% cause it takes 3.80 sec for 10000 elements instead of 2.20
class Solution {
boolean maxCalled;
public int[] solution(int N, int[] A) {
int max =0;
int [] counters = new int [N];
int temp=0;
int currentVal = 0;
for(int i=0;i<A.length;i++){
currentVal = A[i];
if(currentVal <=N){
temp = increas(counters,currentVal);
if(temp > max){
max = temp;
}
}else{
if(!maxCalled)
maxCounter(counters,max);
}
}
return counters;
}
int increas (int [] A, int x){
maxCalled = false;
return ++A[x-1];
//return t;
}
void maxCounter (int [] A, int x){
maxCalled = true;
for (int i = 0; i < A.length; i++) {
A[i] = x;
}
}
}
Following my solution in JAVA (100/100).
public boolean isToSum(int value, int N) {
return value >= 1 && value <= N;
}
public int[] solution(int N, int[] A) {
int[] res = new int[N];
int max =0;
int minValue = 0;
for (int i=0; i < A.length; i++){
int value = A[i];
int pos = value -1;
if ( isToSum(value, N)) {
if( res[pos] < minValue) {
res[pos] = minValue;
}
res[pos] += 1;
if (max < res[pos]) {
max = res[pos];
}
} else {
minValue = max;
}
}
for (int i=0; i < res.length; i++){
if ( res[i] < minValue ){
res[i] = minValue;
}
}
return res;
}
my solution is :
public class Solution {
public int[] solution(int N, int[] A) {
int[] counters = new int[N];
int[] countersLastMaxIndexes = new int[N];
int maxValue = 0;
int fixedMaxValue = 0;
int maxIndex = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] <= N) {
if (countersLastMaxIndexes[A[i] - 1] != maxIndex) {
counters[A[i] - 1] = fixedMaxValue;
countersLastMaxIndexes[A[i] - 1] = maxIndex;
}
counters[A[i] - 1]++;
if (counters[A[i] - 1] > maxValue) {
maxValue = counters[A[i] - 1];
}
} else {
maxIndex = i;
fixedMaxValue = maxValue;
}
}
for (int i = 0; i < countersLastMaxIndexes.length; i++) {
if (countersLastMaxIndexes[i] != maxIndex) {
counters[i] = fixedMaxValue;
countersLastMaxIndexes[i] = maxIndex;
}
}
return counters;
}
}
In my Java solution I updated values in solution[] only when needed. And finally updated solution[] with a right values.
public int[] solution(int N, int[] A) {
int[] solution = new int[N];
int maxCounter = 0;
int maxCountersSum = 0;
for(int a: A) {
if(a >= 1 && a <= N) {
if(solution[a - 1] < maxCountersSum)
solution[a - 1] = maxCountersSum;
solution[a - 1]++;
if(solution[a - 1] > maxCounter)
maxCounter = solution[a - 1];
}
if(a == N + 1) {
maxCountersSum = maxCounter;
}
}
for(int i = 0; i < N; i++) {
if(solution[i] < maxCountersSum)
solution[i] = maxCountersSum;
}
return solution;
}
Here's my python solution:
def solution(N, A):
# write your code in Python 3.6
RESP = [0] * N
MAX_OPERATION = N + 1
current_max = 0
current_min = 0
for operation in A:
if operation != MAX_OPERATION:
if RESP[operation-1] <= current_min:
RESP[operation-1] = current_min + 1
else:
RESP[operation-1] += 1
if RESP[operation-1] > current_max:
current_max = RESP[operation-1]
else:
if current_min == current_max:
current_min += 1
else:
current_min = current_max
for i, val in enumerate(RESP):
if val < current_min:
RESP[i] = current_min
return RESP
def sample_method(A,N=5):
initial_array = [0,0,0,0,0]
for i in A:
if(i>=1):
if(i<=N):
initial_array[i-1]+=1
else:
for a in range(len(initial_array)):
initial_array[a]+=1
print i
print initial_array
Here's my solution using python 3.6. The result is 100% correctness but 40% performance (most of them were because of timeout). Still cannot figure out how to optimize this code but hopefully someone can find it useful.
def solution(N, A):
count = [0]*(N+1)
for i in range(0,len(A)):
if A[i] >=1 and A[i] <= N:
count[A[i]] += 1
elif A[i] == (N+1):
count = [max(count)] * len(count)
count.pop(0)
return count
Typescript:
function counters(numCounters: number, operations: number[]) {
const counters = Array(numCounters)
let max = 0
let currentMin = 0
for (const operation of operations) {
if (operation === numCounters + 1) {
currentMin = max
} else {
if (!counters[operation - 1] || counters[operation - 1] < currentMin) {
counters[operation - 1] = currentMin
}
counters[operation - 1] = counters[operation - 1] + 1
if (counters[operation - 1] > max) {
max += 1
}
}
}
for (let i = 0; i < numCounters; i++) {
if (!counters[i] || counters[i] < currentMin) {
counters[i] = currentMin
}
}
return counters
}
console.log(solution=${counters(5, [3, 4, 4, 6, 1, 4, 4])})
100 points JavaScript solution, includes performance improvement to ignore repeated max_counter iterations:
function solution(N, A) {
let max = 0;
let counters = Array(N).fill(max);
let maxCounter = 0;
for (let op of A) {
if (op <= N && op >= 1) {
maxCounter = 0;
if (++counters[op - 1] > max) {
max = counters[op - 1];
}
} else if(op === N + 1 && maxCounter === 0) {
maxCounter = 1;
for (let i = 0; i < counters.length; i++) {
counters[i] = max;
}
}
}
return counters;
}
solution in JAVA (100/100)
class Solution {
public int[] solution(int N, int[] A) {
// write your code in Java SE 8
int[] result = new int[N];
int base = 0;
int max = 0;
int needToChange=A.length;;
for (int k = 0; k < A.length; k++) {
int X = A[k];
if (X >= 1 && X <= N) {
if (result[X - 1] < base) {
result[X - 1] = base;
}
result[X - 1]++;
if (max < result[X - 1]) {
max = result[X - 1];
}
}
if (X == N + 1) {
base = max;
needToChange= X-1;
}
}
for (int i = 0; i < needToChange; i++) {
if (result[i] < base) {
result[i] = base;
}
}
return result;
}
}
My Java solution. It gives 100% but is very long (in comparison). I have used HashMap for storing counters.
Detected time complexity: O(N + M)
import java.util.*;
class Solution {
final private Map<Integer, Integer> counters = new HashMap<>();
private int maxCounterValue = 0;
private int maxCounterValueRealized = 0;
public int[] solution(int N, int[] A) {
if (N < 1) return new int[0];
for (int a : A) {
if (a <= N) {
Integer current = counters.putIfAbsent(a, maxCounterValueRealized + 1);
if (current == null) {
updateMaxCounterValue(maxCounterValueRealized + 1);
} else {
++current;
counters.replace(a, current);
updateMaxCounterValue(current);
}
} else {
maxCounterValueRealized = maxCounterValue;
counters.clear();
}
}
return getCountersArray(N);
}
private void updateMaxCounterValue(int currentCounterValue) {
if (currentCounterValue > maxCounterValue)
maxCounterValue = currentCounterValue;
}
private int[] getCountersArray(int N) {
int[] countersArray = new int[N];
for (int j = 0; j < N; j++) {
Integer current = counters.get(j + 1);
if (current == null) {
countersArray[j] = maxCounterValueRealized;
} else {
countersArray[j] = current;
}
}
return countersArray;
}
}
Here is solution in python with 100 %
Codility Max counter 100%
def solution(N, A):
"""
Solution at 100% - https://app.codility.com/demo/results/trainingUQ95SB-4GA/
Idea is first take the counter array of given size N
take item from main A one by one + 1 and put in counter array , use item as index
keep track of last max operation
at the end replace counter items with max of local or counter item it self
:param N:
:param A:
:return:
"""
global_max = 0
local_max = 0
# counter array
counter = [0] * N
for i, item in enumerate(A):
# take item from original array one by one - 1 - minus due to using item as index
item_as_counter_index = item - 1
# print(item_as_counter_index)
# print(counter)
# print(local_max)
# current element less or equal value in array and greater than 1
# if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
if N >= item >= 1:
# max of local_max counter at item_as_counter_index
# increase counter array value and put in counter array
counter[item_as_counter_index] = max(local_max, counter[item_as_counter_index]) + 1
# track the status of global_max counter so far
# this is operation K
global_max = max(global_max, counter[item_as_counter_index])
# if A[K] = N + 1 then operation K is max counter.
elif item == N + 1:
# now operation k is as local max
# here we need to replace all items in array with this global max
# we can do using for loop for array length but that will cost bigo n2 complexity
# example - for i, item in A: counter[i] = global_max
local_max = global_max
# print("global_max each step")
# print(global_max)
# print("local max so far....")
# print(local_max)
# print("counter - ")
# print(counter)
# now counter array - replace all elements which are less than the local max found so far
# all counters are set to the maximum value of any counter
for i, item in enumerate(counter):
counter[i] = max(item, local_max)
return counter
result = solution(1, [3, 4, 4, 6, 1, 4, 4])
print("Sol " + str(result))
enter link description here
Got 100% result with O ( N + M )
class Solution {
public int[] solution(int N, int[] A) {
// write your code in Java SE 8
int max = 0;
int[] counter = new int[N];
int upgrade = 0;
for ( int i = 0; i < A.length; i++ )
{
if ( A[i] <= N )
{
if ( upgrade > 0 && upgrade > counter[A[i] - 1 ] )
{
counter[A[i] - 1] = upgrade;
}
counter[A[i] - 1 ]++;
if ( counter[A[i] - 1 ] > max )
{
max = counter[A[i] - 1 ];
}
}
else
{
upgrade = max;
}
}
for ( int i = 0; i < N; i++ )
{
if ( counter[i] < upgrade)
{
counter[i] = upgrade;
}
}
return counter;
}
}
Java 100%/100%, no imports
public int[] solution(int N, int[] A) {
int[] counters = new int[N];
int currentMax = 0;
int sumOfMaxCounters = 0;
boolean justDoneMaxCounter = false;
for (int i = 0; i < A.length ; i++) {
if (A[i] <= N) {
justDoneMaxCounter = false;
counters[A[i]-1]++;
currentMax = currentMax < counters[A[i]-1] ? counters[A[i]-1] : currentMax;
}else if (!justDoneMaxCounter){
sumOfMaxCounters += currentMax;
currentMax = 0;
counters = new int[N];
justDoneMaxCounter = true;
}
}
for (int j = 0; j < counters.length; j++) {
counters[j] = counters[j] + sumOfMaxCounters;
}
return counters;
}
python solution: 100% 100%
def solution(N, A):
c = [0] * N
max_element = 0
base = 0
for item in A:
if item >= 1 and N >= item:
c[item-1] = max(c[item-1], base) + 1
max_element = max(c[item - 1], max_element)
elif item == N + 1:
base = max_element
for i in range(N):
c[i] = max (c[i], base)
return c
pass
Using applyMax to record max operations
Time complexity:
O(N + M)
class Solution {
public int[] solution(int N, int[] A) {
// write your code in Java SE 8
int max = 0, applyMax = 0;;
int[] result = new int[N];
for (int i = 0; i < A.length; ++i) {
int a = A[i];
if (a == N + 1) {
applyMax = max;
}
if (1 <= a && a <= N) {
result[A[i] - 1] = Math.max(applyMax, result[A[i] - 1]);
max = Math.max(max, ++result[A[i] - 1]);
}
}
for (int i = 0; i < N; ++i) {
if (result[i] < applyMax) {
result[i] = applyMax;
}
}
return result;
}
}

Void merge sort method java

So, my computer science teacher has told me to make every method here void, except for copyPartArray. I have no idea how to do this, when I try, the sort simply fails.
public static ArrayList<String> mergeSortHelper(ArrayList<String> a) {
int mid = a.size() / 2 - 1;
if (a.size() <= 1)
return a;
return merge(mergeSortHelper(copyPartArray(a, 0, mid)),
mergeSortHelper(copyPartArray(a, mid + 1, a.size() - 1)));
}
public static void mergeSort(ArrayList<String> a) {
ArrayList<String> x = mergeSortHelper(a);
for (int i = 0; i < a.size(); i++) {
a.set(i, x.get(i));
}
}
public static ArrayList<String> merge(ArrayList<String> a,
ArrayList<String> b) {
ArrayList<String> x = new ArrayList<String>(a.size() + b.size());
int aCount = 0;
int bCount = 0;
for (int i = 0; i < a.size() + b.size(); i++) {
if (aCount > a.size() - 1) {
for (int j = bCount; j < b.size(); j++) {
x.add(b.get(j));
}
break;
}
if (bCount > b.size() - 1) {
for (int j = aCount; j < a.size(); j++) {
x.add(a.get(j));
}
break;
}
if ((a.get(aCount)).compareTo(b.get(bCount)) < 0) {
x.add(a.get(aCount));
aCount++;
} else {
x.add(b.get(bCount));
bCount++;
}
}
return x;
}
public static ArrayList<String> copyPartArray(ArrayList<String> a, int s,
int e) {
ArrayList<String> x = new ArrayList<String>();
for (int i = s; i <= e; i++) {
x.add(a.get(i));
}
return x;
I have tried to change my mergeSort to:
public static void mergeSort(ArrayList<String> a) {
int mid = a.size() / 2 - 1;
if (a.size() <= 1)
return;
mergeSort(copyPartArray(a, 0, mid));
mergeSort(copyPartArray(a, mid + 1, a.size() - 1));
merge(a, copyPartArray(a, 0, mid),
copyPartArray(a, mid + 1, a.size() - 1));
}
and get rid of the mergeSortHelper all together.
Now I have:
public static void mergeSort(ArrayList<String> a, int start, int end) {
int mid = (start + end) / 2;
if (a.size() <= 1)
return;
mergeSort(a, start, mid);
mergeSort(a, mid + 1, end);
how would I incorporate my merge method into this?
copyPartArray is going to make a copy of the array so that's no good, your lecturer wants you to pass the array by reference and then also pass in the start/end (or start/length) integers. Try doing something like this:
public static void mergeSort(ArrayList<String> a, int start, int length) {
// refer to 'the array' as a[start] to a[start + length]
}
a will be passed by reference which means you don't need a return value.
So I would change your methods to take a start and length and get rid of copyPartArray all together, you can do your merging in-place on the one array.
I use this method in my blog post on Quicksort.

Categories