I am trying to check whether the given array has equal number of maximum and minimum array element. If their number are equal should return 1 else return 0. But instead of which return always zero.
Could you please help me?
public class MaxMinEqual {
public static void main(String[] args) {
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 4, 9, 11, 8, 5, 4, 10}));
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 11, 4, 9, 11, 8, 5, 4, 10}));
}
public static int ismaxminequal(int[] a) {
int maxcount = 0;
int mincount = 0;
int largest = a[0];
for (int i = 0; i < a.length; i++) {
if (a[i] > largest) {
largest = a[i];
}
if (a[i] == largest) {
maxcount = maxcount + 1;
}
}
int smallest = a[0];
for (int j = 0; j < a.length; j++) {
if (a[j] < smallest) {
smallest = a[j];
}
if (a[j] == smallest) {
mincount = mincount + 1;
}
}
if (maxcount == mincount) {
return 1;
} else {
return 0;
}
}
}
You did not reset maxcount and mincount when you find a greater or smaller value.
public static boolean isMaxMinEqual(int[] a) {
int maxcount, mincount = 0;
int largest, smallest = a[0];
for (int i = 0: a) {
if (i > largest) {
largest = i;
maxcount = 0;
}
if (i == largest) {
maxcount++;
}
if (i < smallest) {
smallest = i;
mincount = 0;
}
if (i == smallest) {
mincount++;
}
}
return maxcount == mincount;
}
Not sure if you're supposed to learn this without Data Structures, but why not take advantage of an Algorithm Efficiency Technique called presorting.
We could do something like this:
public static int ismaxminequal(int[] a) {
Arrays.sort(a);
This puts the smallest elements at the 'head' of the array and the largest elements at the 'tail'.
So, now, we must iterate from both ends to see how many of each are available (max and min).
int num_min = 1;
int num_max = 1;
int cur_value = 0; //holds a reference for comparison
cur_value = a[0];
for (int i = 1; i < a.length; i++) {
if (a[I] == cur_value)
num_min++;
else
break;
}
cur_value = a[a.length - 1];
for (int i = a.length - 1; i > 0; I--) {
if (a[I] == cur_value)
num_min++;
else
break;
}
if (num_max == num_min) {
return 1;
} else {
return 0;
}
}
}
Java 8 way. Very readable and with big arrays can be quicker that O(N) single thread implementation.
public boolean isMaxMinEqual(int[] a) {
int max = Arrays.stream(a).parallel().max().getAsInt();
int min = Arrays.stream(a).parallel().min().getAsInt();
long maxCount = Arrays.stream(a).parallel().filter(s -> s == max).count();
long minCount = Arrays.stream(a).parallel().filter(s -> s == min).count();
return maxCount == minCount;
}
Related
I am trying to get an output of [4,6,6,7] with length 4 where arr[i] <= arr[i+1] where it is non-decreasing and it is contiguous. I know what i have to do but i dont know how to do it. my code prints out [3,4,6,6,7]. I am just having trouble on the contiguous part, any help? im not allowed to use extra arrays.
public static void ascentLength(int arr[], int size) {
int length = 0;
int index = 0;
int count = 1;
for (int i = 0; i < size-1; i++) {
index = i;
if (arr[0] <= arr[i+1] && count >0) {
System.out.println(arr[i]+ " index:" + index);
length++;
count++;
}
if (arr[0] >= arr[i+1]) {
}
}
System.out.println("length: " + length);
}
/* Driver program to test above function */
public static void main(String[] args) {
int arr[] = {5, 3, 6, 4, 6, 6, 7, 5};
int n = arr.length;
ascentLength(arr, n);
}
Here is my solution, it would be easier, if you could work with List, but this works for arrays:
public static void ascentLength(int arr[], int size) {
if(size == 1) System.out.println("length: 1");
// variables keeping longest values
int longestStartingIndex = 0;
int longestLength = 1;
// variables keeping current values
int currentStartingIndex = 0;
int currentCount = 1;
for (int i = 1; i < size; i++) {
if (arr[i-1] <= arr[i]) {
currentCount++;
} else {
// check if current count is the longest
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
currentStartingIndex = i;
currentCount = 1;
}
}
if(currentCount > longestLength) {
longestLength = currentCount;
longestStartingIndex = currentStartingIndex;
}
}
I'm trying to execute this so that it prints out the longest sequence of the same number. The error I get is that it's telling me that a class or enum is expected. Here's my code:
public class D4 {
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 6, 6, 45, 2, 2, 2};
System.out.println(getLongestRun(array));
}
}
This belongs as a comment, but I will give you full code so that it is clear. Just return max at the end of your getLongestRun() method:
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
// you forgot to return the length of the longest sequence to the caller
return max;
}
function getLongestRun() is missing return max; statement.
My task is to write a function that rearranges an array so that the odd numbers occur in the beginning of the array, from greatest to least, and the even numbers from least to greatest at the end. We are not allowed to use any other libraries except for the standard input and output streams.
The output works when the numbers are:
{-15, 450, 6, -9, 54}
But if I changed the elements to:
{-55, 45, 6, 11, 54}
There is an exception error. Here is my code:
public class ary1 {
public static void sort(int A[], int n) {
int tmp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (A[0] % 2 == 0) //even
{
if (A[i] < A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
} else {
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
}
}
public static void showAray(int A[], int n) {
for (int i = 0; i < n; i++) {
System.out.println(A[i]);
}
}
public static void main(String args[]) {
int array1[] = {-55, 45, 6, 11, 54};
int odd = 0;
int even = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int[] array2 = new int[even];
int[] array3 = new int[odd];
for (int i = 0, j = 0, k = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
array2[j++] = array1[i];
} else {
array3[k++] = array1[i];
}
}
System.out.println("Original array:\n");
showAray(array1, array1.length);
sort(array2, even);
sort(array3, odd);
for (int i = 1; i < array1.length; i++) {
if (i < odd) {
array1[i] = array3[i];
} else {
array1[i] = array2[(i + 1) - even];
}
}
System.out.println("\nAfter sorting:\n");
showAray(array1, array1.length);
}
}
I know there is a logical error here, but I can't figure out what exactly. Is there any way to change the logic to work with all integers? Thanks.
array1[i] = array2[(i + 1) - even];
EDIT - Here is the stacktrace.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at ary.main(arytest.java:67)
Java Result: 1
Change this
array1[i] = array2[(i + 1) - even];
to
array1[i] = array2[i - odd];
I guess this is what you want
I need to return the greatest negative value, and if there are no negative values, I need to return zero.
Here is what I have:
public int greatestNegative(int[] list) {
for (int i = 0; i < list.length; i++) {
if (list[i] < 0)
negativeNumbers ++;
}
int j = list.length - 1;
while (j >= 0) {
if (list[j - negativeNumbers] < 0) {
list[j] = 0;
list[j - 1] = list[j - negativeNumbers];
negativeNumbers--;
j--;
}
else{
list[j] = list[j - negativeNumbers];
j--;
}
}
}
You just need to think of this problem as 2 steps:
Only consider negative values in list[].
In the loop within negative values, update current result if (result == 0) or (value > result).
Code:
public int greatestNegative(int[] list) {
int result = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] < 0) {
if (result == 0 || list[i] > result) {
result = list[i];
}
}
}
return result;
}
Just go about finding the max number with an added condition.
public static int greatestNegative(int[] list) {
int max = Integer.MIN;
boolean set = false;
for (int i = 0; i < list.length; i++) {
if (list[i] < 0 && list[i] > max) {
max = arr[i];
set = true;
}
}
if (!set)
max = 0;
return max;
}
Here is the code which return the smallest negative number
public static int greatestNegative(int[] list) {
int negativeNumbers = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] < 0 && list[i] < negativeNumbers)
negativeNumbers = list[i];
}
return negativeNumbers;
}
Input : 1, 2, -3, 5, 0, -6
Output : -6
Input : 1, 2, 3, 5, 0, 6
Output : 0
If you need the greatest negative number then sort array thin search for first negative number
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int arr[] = { 2, 4, 1, 7,2,-3,5,-20,-4,5,-9};
System.out.println(greatestNegative(arr));
}
private static int greatestNegative(int[] arr) {
Arrays.sort(arr);
for (int i = arr.length - 1; i >= 0; i--) {
if (isNegative (arr[i])) {
return arr[i];
}
}
return 0;
}
private static boolean isNegative (int i) {
return i < 0;
}
}
Output : -3
Please check following code, which will
first calculate small number from array,
then check is it positive? if yes return 0 else return negative.
public static int greatestNegative(int[] list)
{
int negativeNumbers = Integer.MAX_VALUE;
for (int i = 0; i < list.length; i++) {
if (list[i] < negativeNumbers)
negativeNumbers = list[i];
}
if(negativeNumbers >=0)
return 0;
else
return negativeNumbers;
}
You have to try this....
public int greatestNegative(int[] list) {
int negNum = 0;
for(int i=0; i<list.length; i++) {
if(list[i] < negNum){
negNum = list[i];
}
}
return negNum;
}
public int largNegative(int[] list) {
int negNum = 0;
boolean foundNeg = false;
for(int i=0; i<list.length; i++) {
if(list[i] < negNum && !foundNeg){
foundNeg = true;
negNum = list[i];
} else if(foundNeg && list[i] < 0 && negNum < list[i]) {
negNum = list[i];
}
}
return negNum;
}
Start by setting your "maxNegative" value to 0. Then assign the first negative number you come across. After that, only assign negative numbers that are higher. If there are no negative numbers, then your "maxNegative" will still be zero.
public static void main(String[] args) {
int arr[] = {2, -1, 4, 1, 0, 7, 2, -3, 5, 9, -4, 5, -9};
int maxNegative = 0;
for (int i = 0; i < arr.length; i++) {
if (maxNegative == 0 && arr[i] < maxNegative) {
// Set the first negative number you come across
maxNegative = arr[i];
} else if (maxNegative < arr[i] && arr[i] < 0) {
// Set greater negative numbers
maxNegative = arr[i];
}
}
System.out.println(maxNegative);
}
Results:
-1
Java 8
Then there are streams, that allow you to do this with one line of code.
public static void main(String[] args) {
int arr[] = {2, 4, 1, 0, 7, 2, -3, 5, 9, -4, 5, -9};
int maxNegative = Arrays.stream(arr).filter(a -> a < 0).max().orElse(0);
System.out.println(maxNegative);
}
Results:
-3
my code only misses 5 cases and i dont know why, somebody help me.
problem
Return a version of the given array where each zero value in the array
is replaced by the largest odd value to the right of the zero in the
array. If there is no odd value to the right of the zero, leave the
zero as a zero.
zeroMax({0, 5, 0, 3}) → {5, 5, 3, 3}
zeroMax({0, 4, 0, 3}) → {3, 4, 3, 3}
zeroMax({0, 1, 0}) → {1, 1, 0}
my code
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for( i = 0; i < nums.length;i++){
if(nums[i]==0){
for(int j = i; j < nums.length;j++){
if (nums[j]%2!=0){
acum = nums[j];
break;
}
}
nums[i]=acum;
}
}
return nums;
}
This can be done much more efficiently by rearranging the problem a bit.
Instead of traversing left-to-right, then scanning the integers on the right for the replacement, you can instead just go right-to-left. Then, you can store the previous replacement until you encounter a larger odd number.
public int[] zeroMax(final int[] nums) {
int replace = 0; // Stores previous largest odd - default to 0 to avoid replacement
for (int i = nums.length - 1; i >= 0; i--) { // start from end
final int next = nums[i];
if (next == 0) { // If we should replace
nums[i] = replace;
} else if (next % 2 == 1 && next > replace) {
// If we have an odd number that is larger than the replacement
replace = next;
}
}
return nums;
}
Given your examples, this output:
[5, 5, 3, 3]
[3, 4, 3, 3]
[1, 1, 0]
What you are missing is, that there could be more than one odd number on the right side of your zero and you need to pick the largest one.
Edit: And you also need to reset 'acum'. I updated my suggestion :)
Here's a suggestion:
public int[] zeroMax(int[] nums) {
int acum = 0;
int i = 0;
for (i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
for (int j = i; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > acum) {
acum = nums[j];
}
}
nums[i] = acum;
acum = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
for (int i=0; i<nums.length; i++)
{
if (nums[i] == 0)
{
int maxindex = i;
for (int j=i+1; j<nums.length; j++)
{
if ((nums[j]%2 == 1) && (nums[j] > nums[maxindex]))
{
maxindex = j;
}
}
nums[i] = nums[maxindex];
}
}
return nums;
}
This alows you to find the index of the maximum odd number to the right, replacing the zero with the number at that index
The basic problem is that this algorithm doesn't search for the biggest odd value, but for the first odd value in the array, that is to the right of a given value. Apart from that, you might consider creating a table for the biggest odd value for all indices to simplify your code.
Here is one of the possible solutions to this :)
public int[] zeroMax(int[] nums) {
for(int i=0;i<nums.length;i++){
if(nums[i] == 0){
int val = largestOddValue(nums,i);//finding largest odd value
nums[i] = val; // assigning the odd value
}
}
return nums;
}
//finds largest odd value from the index provided to end
public int largestOddValue(int[] nums,int i){
int value = 0; // for storing value
for(int k=i;k<nums.length;k++){
if(nums[k]%2!=0 && value<nums[k]) // got the odd value
value = nums[k];
}
return value;
}
public int[] zeroMax(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 0) {
int max = 0;
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] % 2 != 0 && nums[j] > max) {
max = nums[j];
}
}
nums[i] = max;
max = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
int val = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
for(int j = i + 1; j < nums.length; j++) {
if(val <= nums[j]) {
if(nums[j] % 2 == 1) {
val = nums[j];
}
}
}
nums[i] = val;
val = 0;
}
}
return nums;
}
public int[] zeroMax(int[] nums) {
int[] result = nums.clone();
for (int i = nums.length - 1, max = 0; i >= 0; i--)
if (isOdd(nums[i])) max = Math.max(nums[i], max);
else if (nums[i] == 0) result[i] = max;
return result;
}
boolean isOdd(int num) { return (num & 1) == 1; }
We iterate backwards, always storing the biggest encountered odd number (or 0, if none was found) in max.
When we find a 0, we simply override it with max.
The input is untouched to avoid ruining somebody else's input.
Here is the code which works for every input. Try this on your IDE
public int[] m1(int a[]){
int j = 0;
for (int i = 0; i < a.length; i++) {
if(a[i]!=0){
continue;
}
else if(a[i]==0){
j=i;
while(j<a.length){
if(a[j] % 2 != 0){
if(a[i]<=a[j]){
a[i] = a[j];
j++;
}
else{
j++;
continue;
}
}
else{
j++;
continue;
}
}
}
}
return a;
}