Delete the highest and lowest value of an Array - java

I'm trying to delete the highest and lowest numbers of the array
int[] ary4 = {2,17,10,9,16,3,9,16,5,1,17,14};
it works on this specific one but when I'm changing the numbers it just doesn't do what my intentions are. I know how to do it a different way but I want to solve it with this method.
public static int[] elimAll(int[] a) {
int c = 1;
int g = 1;
int[] b = a.clone();
Arrays.sort(b);
for (int i = 0; i < b.length; i++){
if (i == 0) {
if (b[i] < b[c]) {
b[i] = 0;
c++;
}else{
if (b[i] < b[c] && b[i] < b[i-1]) {
b[i] = 0;
c++;
}
}
}
}
for (int i = 0; i < b.length; i++){
if (i == b.length-1 || i == b.length-2){
if (b[i] >= b[b.length-1] || b[i] >= b[b.length-2]){
b[i] = 0;
g++;
}
}else {
if (b[i] > b[i + 1]) {
b[i] = 0;
g++;
}
}
}
return b;
}

Here is one way. It does not require any sorting.
int[] ary4 = {2,17,10,9,16,3,9,16,5,1,17,14};
System.out.println("Before: " + Arrays.toString(ary4));
int[] result = elimAll(ary4);
System.out.println(" After: " + Arrays.toString(result));
prints (you can see the two 17's and the lone 1 were removed)
Before: [2, 17, 10, 9, 16, 3, 9, 16, 5, 1, 17, 14]
After: [2, 10, 9, 16, 3, 9, 16, 5, 14]
Explanation
iterate thru the array finding the highest and lowest values.
iterate again, testing if each value is the highest or lowest.
if, not, add value to new array and increment index.
when finished, return a copy of the array, with the remaining values removed.
public static int[] elimAll(int[] array) {
int highest = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;
for (int val : array) {
highest = Math.max(highest, val);
lowest = Math.min(lowest,val);
}
int k = 0;
int [] result = new int[array.length];
for(int val : array) {
if (val != highest && val != lowest) {
result[k++] = val;
}
}
return Arrays.copyOf(result, k);
}

Related

split array into two equal subarray where index is selected

I need to return an index of the element where the sum of the elements on the left is equal to the sum of the elements on the right. e.g for the array [-3, 8, 3, 1, 1, 3], the return value is index 2 since the sum of the elements to the left of the first 3 ([-3, 8]) is the same as the sum of elements to its right ([1, 1, 3]).
So I started by doing a liner-search function to find the intended index,
then after that i attempted to split the array left and right of the selected index but had no success doing so
I haven't had much success getting it to work
//linear-search portion,x is the index selected to be split point
public static int findindex(int arr[], int x) {
//if array is null
if (arr == null) {
return -1;
}
//find array length
int len = arr.length;
int i = 0;
//traverse the array
while (i < len) {
//if the i-th element is is x then return the index
if (arr[i] == x) {
return i;
} else {
i = i + 1;
}
}
//splint array portion,returns index if not possible
int leftsum = 0;
//treverse array elements
for (int i = 0; i < x; i++) {
//adds current elements to left
leftsum += arr[i];
//find sum of remader the array elements to rightsum
int rightsum = 0;
for (int j = i + 1; j < x; J++)
rightsum += arr[j];
//split pint index
if (leftsum == rightsum)
return i + 1;
}
//if not possible return
return -1;
}
// driver code
public static void main(String[] args) {
int[] array1 = { -3, 8, 3, 1, 1, 3 };
System.out.println(findindex(array1));
}
You can use the below code for solve the problem
static void Main(string[] args)
{
int[] array1 = {-3, 8, 3, 1, 1, 3}; // { -3, 8, 3, 1, 1, 3, 6, 1, 19 };
int indexPosition = GetIndex(array1);
if (indexPosition != -1)
{
Console.WriteLine(indexPosition);
}
}
static int GetIndex(int[] param)
{
if (param.Length < 0) return -1;
int leftSum = 0, rightSum = 0; int rightIndex = param.Length - 1;
for (int i = 0; i < param.Length; i++)
{
if (i < rightIndex)
{
if (leftSum > rightSum)
{
rightSum += param[rightIndex];
rightIndex -= 1;
}
else
{
if (i < rightIndex)
{
leftSum += param[i];
}
}
}
else
{
rightSum += param[rightIndex]; // if you are looking for only index position you can comment this line,
//variable rightSum and leftSum will give you the sum of left and right side of the array
rightIndex -= 1;
break;
}
}
return rightIndex;
}
Hope this helps .
Your code has two problems. One is that the variable i is defined two times in the same method. Another problem is that you only provide one input parameter and not two. I don't even know what parameter x should be and therefore also removed it from my improved version. I also removed the while loop as I don't understand what you tried to do there. Anyways here is my version of the code:
public static int findindex(int arr[]) {
if (arr == null) {
return -1;
}
int len = arr.length;
int leftsum = 0;
for(int i = 0; i < len; i++)
{
leftsum += arr[i];
int rightsum = 0;
for(int j = i+2; j < len; j++)
rightsum += arr[j];
if(leftsum == rightsum)
return i+1;
}
return -1;
}
public static void main(String[] args) {
int[] array1 = {-3, 8, 3, 1, 1, 3};
System.out.println(findindex(array1));
}
When I removed everything unneccessary from your code the only bug was that you should have initialized j with i+2, because you don't want to include the element at the index itself and only the right side, if I understood the requirements of your code correctly.

merging 3 sorted arrays

public class array12 {
static void merge_sort(int A[], int start, int end) {
if (end - start > 1) {
int middle1 = (2 * start + end + 1) / 3 - 1;
int middle2 = 2 * middle1 - start + 1;
merge_sort(A, start, middle1);
merge_sort(A, middle1 + 1, middle2);
merge_sort(A, middle2 + 1, end);
merge(A, start, middle1, middle2, end);
}
}
static void merge(int[] x, int start, int middle1, int middle2, int end) {
int n1 = middle1 - start + 1;
int n2 = middle2 - middle1;
int n3 = end - middle2;
int left[] = new int[n1]; // defining and initialising three arrays .
int mid[] = new int[n2];
int right[] = new int[n3];
for (int i = 0; i < left.length; i++) {
left[i] = x[i + start];
}
for (int i = 0; i < mid.length; i++) {
mid[i] = x[i + middle1 + 1];
}
for (int i = 0; i < right.length; i++) {
right[i] = x[i + middle2 + 1];
}
int i = 0;
int j = 0;
int k = 0;
int c = start;
// finding minimum element from the three arrays .
while (i < n1 && j < n2 && k < n3) {
if (left[i] <= mid[j] && left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else if (mid[j] <= left[i] && mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only two arrays are left to be compared
while (i < n1 && j < n2) {
if (left[i] <= mid[j]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = mid[j];
j++;
c++;
}
}
while (j < n2 && k < n3) {
if (mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
while (i < n1 && k < n3) {
if (left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only single array is left out of left[] , mid[] and right[].
while (i < n1) {
x[c] = left[i];
i++;
c++;
}
while (j < n2) {
x[c] = mid[j];
j++;
c++;
}
while (k < n3) {
x[c] = right[k];
k++;
c++;
}
System.out.println("");
// printing array elements after every merge operation .
for (int e = 0; e < x.length; e++) {
System.out.print(x[e] + " ");
}
}
public static void main(String[] args) {
int[] x = new int[9];
for (int i = 0; i < x.length; i++) {
x[i] = x.length - i;
}
System.out.println("initial array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
System.out.println("");
merge_sort(x, 0, x.length - 1);
System.out.println("");
System.out.println("");
System.out.println(" sorted array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
}
I am trying to merge 3 sorted arrays . I have been able to develop code for array size equal to power of 3 . I am unable to implement it with some other array size . I have tried to change values of middle1 and middle2 but am experiencing serious trouble . Setting their values is the main concern . Merging step is quite simple and is not causing problems .
What changes are required in my code so that it may work for any array size ? Can it be implemented using this approach ? I dont want size of any of the three arrays , left[] , mid[] and right[] to be zero at any time .
Please help .
Here's a similar answer to YCF_L's, but simplified (still uses Java 8):
public static int[] sortMultipleArrays(int[]... arrays) {
return Arrays.stream(arrays)
.flatMapToInt(Arrays::stream)
.sorted()
.toArray();
}
Output:
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
I don't follow your merge code. It seems overly complicated.
Here is a method for merging an unlimited number of sorted arrays, each a varying size.
private static int[] mergeSortedArrays(int[]... arrays) {
int totalLen = 0;
for (int[] arr : arrays)
totalLen += arr.length;
int[] idx = new int[arrays.length];
int[] merged = new int[totalLen];
for (int i = 0; i < totalLen; i++) {
int min = 0, minJ = -1;
for (int j = 0; j < arrays.length; j++)
if (idx[j] < arrays[j].length)
if (minJ == -1 || min > arrays[j][idx[j]]) {
min = arrays[j][idx[j]];
minJ = j;
}
merged[i] = min;
idx[minJ]++;
}
return merged;
}
Test
int[] a = { 3, 5, 9, 13, 17, 21 };
int[] b = { 2, 10, 20 };
int[] c = { 1, 7, 12, 24 };
int[] d = { 6 };
int[] merged = mergeSortedArrays(a, b, c, d);
System.out.println(Arrays.toString(merged));
Output
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
If using class "Integer" instead of primitive int is not a problem you can use this, basically first do the merge and after sort them: you can do the call Arrays.sort even in the same method and call it mergeAndSort, if you want...
import java.util.Arrays;
public class Main {
public static Integer[] merge(Integer[]... arrays) {
int count = 0;
for (Integer[] array : arrays) {
count += array.length;
}
Integer[] mergedArray = (Integer[]) java.lang.reflect.Array.newInstance(arrays[0][0].getClass(), count);
int start = 0;
for (Integer[] array : arrays) {
System.arraycopy(array, 0, mergedArray, start, array.length);
start += array.length;
}
return mergedArray;
}
public static void main(String[] args) {
Integer[] array1 = {3, 5, 6, 7, 78, 100};
Integer[] array2 = {5, 6, 7, 8, 9};
Integer[] array3 = {2, 6, 7};
Integer[] merged1 = merge(array1, array2);
Arrays.sort(merged1);
Integer[] merged2 = merge(array1, array2, array3);
Arrays.sort(merged2);
printArray(merged1);
printArray(merged2);
}
public static void printArray(Integer[] x) {
System.out.println("--ToString--");
for (Integer var : x) {
System.out.println(var);
}
System.out.println("----");
}
}

grouping algorithm java n choose k

I have 10 numbers in a vector container contains: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. And I want n numbers in a group, for example:
n = 3
[1,2,3], [4,5,6], [7,8,9], [10]
[2,3,4], [5,6,7], [8,9,10], [1]
Is there an algorithm to find all the combinations?
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int k = 3;
List<int[]> subsets = new ArrayList<>();
int[] s = new int[k]; // here we'll keep indices
// pointing to elements in input array
if (k <= input.length) {
// first index sequence: 0, 1, 2, ...
for (int i = 0; (s[i] = i) < k - 1; i++);
subsets.add(getSubset(input, s));
for(;;) {
int i;
// find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == input.length - k + i; i--);
if (i < 0) {
break;
}
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(input, s));
}
}
System.out.println();
for(int i = 0; i < subsets.size();i++) {
int[] result = subsets.get(i);
for(int j = 0; j < result.length; j++) {
System.out.print(result[j]+" ");
}
System.out.println();
}
}
int[] getSubset(int[] input, int[] subset) {
int[] result = new int[subset.length];
for (int i = 0; i < subset.length; i++)
result[i] = input[subset[i]];
return result;
}
Thank you.

Find out the odd value and meet criteria in java

I would like to write a function in java that receives a parameter and returns 1 or 0, in the following conditions:
If the length of the array is odd, return 1 if the sum of the odd numbers is greater than the sum of the even numbers, and 0 otherwise.
If the length of the array is even, check the largest number less or equal then 10. If it is odd, return 1. If it is even, return 0.
For example, using the following arrays:
array1 = {13, 4, 7, 2, 8}
array2 = {11, 7, 4, 2, 3, 10}
The first array returns 1, because there 13(odd) + 7(odd) = 20 is greater then 4 + 2 + 8 = 14.
The second array returns 0, because there 11, 7 are odd but, 10 is greater then 7.
What I already tried, please check below:
public static int isOddHeavy(int[] arr) {
int summationOd = 0;
int summationEv = 0;
for (int i = 0; i < arr.length; i++) {
if (i % 2 != 0) {
summationOd = sumOddEven(arr);
} else {
summationEv = sumOddEven(arr);
}
}
if(summationOd > summationEv) {
return 1;
} else {
return 0;
}
}
public static int sumOddEven(int[] arr) {
int total = 0;
for (int i = 1; i < arr.length; i++) {
total += arr[i];
}
return total;
}
Here is a Java function that does what you want. Just iterate through the array, updating the variables and check your conditions in the end.
public static int yourFunction(int[] arr) {
int sumOdd = 0;
int sumEven = 0;
int maxOdd = 0;
int maxEven = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
sumEven += arr[i];
if (maxEven < arr[i] && arr[i] <= 10)
maxEven = arr[i];
}
else {
sumOdd += arr[i];
if (maxOdd < arr[i] && arr[i] <= 10)
maxOdd = arr[i];
}
}
if (arr.length%2 != 0)
return (sumOdd > sumEven) ? 1 : 0;
return (maxOdd > maxEven) ? 1 : 0;
}

Insertion Sort not working properly

package sort;
public class InsertionSort {
public static void main(String[] args) {
int[] input ={5,3,5,3,2,1}; // the input to be sorted.
int key; // the value that will be put into its place in the pass
int j = 0; // indexes to be
int i = 0; // used for sorting
for(j = 1; j < input.length; j++){
key = input[j];
for(i = j-1; i >= 0; i--){ // Look for a proper place for the key
if(i-1 < 0){
if(input[i] > key){ // Have you found that place ?
for(int k = j;k > i; k--){ // Begin shifting
input[k] = input[k-1];
} // Done Shifting
input[i] = key; // Insert the key in proper place
break;
}
}else{
if(input[i] > key && input[i-1] < key){ // Have you found that place ?
for(int k = j;k > i; k--){ // Begin shifting
input[k] = input[k-1];
} // Done Shifting
input[i] = key; // Insert the key in proper place
break;
}
}
}
}
for(int each : input){
System.out.println(each);
}
}
}
The problem is that if my input has repeated numbers, sorting fails.
For int[] input ={5,3,5,3,2,1};, I get 1 2 3 5 5 3
For non-repeated numbers, sorting works fine.
What is wrong here ?
public static void main(String[] args) {
int[] input = {12, 21, 21, 1, 4, 5, 66, 74, 0, -2, 5, 3, 5, 3, 2, 1}; // the input to be sorted.
int key; // the value that will be put into its place in the pass
int j = 0; // indexes to be
int i = 0; // used for sorting
for (i = 1; i < input.length; i++) {
key = input[i];
j = i;
while (j > 0 && input[j - 1] > key) {
input[j] = input[j - 1];
j--;
}
input[j] = key;
}
for (int each : input) {
System.out.println(each);
}
}

Categories