split array into two equal subarray where index is selected - java

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.

Related

How to Insertion Sort?

What is missing?
less a little
It's almost done
Also is there a way to make it faster?
thanks
public class InsertionSort {
public static void main(String[] argv) {
int[] data = {4, 1, 7, 8, 9, 3, 2};
sort(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
public static void sort(int[] data) {
int j, pivot;
// insert data[i] to sorted array 0 ~ i - 1
// begins from i = 1, because if the array has only one element then it must be sorted.
for (int i = 1; i < data.length; i++) {
pivot = data[i];
for (j = i - 1; j >= 0 && data[j] > pivot; j--) // shift data[j] larger than pivot to right
{
data[j+1] = data[j];
}
}
}
}
Your code have a problem when you are interchanging the values between data[j+1] and data[j]. You overwriting the value from data[j+1], without to keep it in a temporal variable and put it in data[j].
public class InsertionSort {
public static void main(String[] argv) {
int[] data = {4, 1, 7, 8, 9, 3, 2};
sort(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
public static void sort(int[] data) {
int tmp, pivot;
// insert data[i] to sorted array 0 ~ i - 1
// begins from i = 1, because if the array has only one element then it must be sorted.
for (int i = 1; i < data.length; i++) {
pivot = data[i];
for (int j = i - 1; j >= 0 && data[j] > pivot; j--) // shift data[j] larger than pivot to right
{
tmp = data[j + 1];
data[j + 1] = data[j];
data[j] = tmp;
}
}
}
}
As #dan1st suggest, try to use quicksort if you want a better performance. A good explanation of the quicksort algorithm and it's Java implementation you could find here

How do I find the largest negative value in an array with both positive and negative values?

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

Given an array with odd length, look at the first, last, and middle values in the array and return an array with those three values

So for any given odd length array, I need to look at the first, middle and last value, and return an array with only hose 3 values but in ascending order.This is what I have, but it's only working with arrays of 3 elements, it's not working for other odd length arrays:
public int[] maxTriple(int[] nums) {
int toSwap, indexOfSmallest = 0;
int i, j, smallest;
for( i = 0; i < nums.length; i ++ )
{
smallest = Integer.MAX_VALUE;
for( j = i; j < nums.length; j ++ )
{
if( nums[ j ] < smallest )
{
smallest = nums[ j ];
indexOfSmallest = j;
}
}
toSwap = nums[ i ];
nums[ i ] = smallest;
nums[ indexOfSmallest ] = toSwap;
}
return nums;
}
You're getting the sorted array, so if you need just the first, middle and last values you can try it like this:
public int[] maxTriple(int[] nums) {
int toSwap, indexOfSmallest = 0;
int i, j, smallest;
for( i = 0; i < nums.length; i ++ )
{
smallest = Integer.MAX_VALUE;
for( j = i; j < nums.length; j ++ )
{
if( nums[ j ] < smallest )
{
smallest = nums[ j ];
indexOfSmallest = j;
}
}
toSwap = nums[ i ];
nums[ i ] = smallest;
nums[ indexOfSmallest ] = toSwap;
}
nums=new int[]{nums[0],nums[(nums.length/2)],nums[nums.length-1]};
return nums;
}
You're thinking about this too hard. If the length of your array is less than 3 or even, return null.
Otherwise, get the first element, the last element, and the middle element and store them in a new array. Sort the array with Arrays.sort() and return the new array.
public static void main(String[] args) throws Exception {
System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4})));
System.out.println(Arrays.toString(maxTriple(new int[] {1, 4, 2, 4, 5})));
System.out.println(Arrays.toString(maxTriple(new int[] {75, 99, 4, 999, 4, 65, 23})));
}
public static int[] maxTriple(int[] nums) {
if (nums.length < 3 || nums.length % 2 == 0) {
return null;
}
int[] result = new int[3];
result[0] = nums[0]; // First
result[1] = nums[nums.length - 1]; // Last
result[2] = nums[nums.length / 2]; // Middle
Arrays.sort(result);
return result;
}
Results:
null
[1, 2, 5]
[23, 75, 999]
I used another approach with ternary operators. I hope it can be useful...
public int maxTriple(int[] nums) {
return (nums[0] > nums[nums.length/2]) ? (nums[0] > nums[nums.length-1] ?
nums[0] : nums[nums.length-1]) : (nums[nums.length/2] > nums[nums.length-1]
? nums[nums.length/2] : nums[nums.length-1]);
}
This code works fine:
public int[] maxTriple(int[] nums) {
int[] myArray = new int[3];
int length = nums.length;
int middle = nums[(length + 1) / 2 - 1];
int last = nums[length - 1];
int first = nums[0];
myArray[0] = nums[0];
myArray[1] = nums[middle];
myArray[2] = nums[last];
return myArray;
}
What you are tyring to do is called selection sort. Here is the code for that:
int[] maxTriple(int[] nums, int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = i; j < size; j++) {
if (nums[j] < nums[i]) {
int toSwap = nums[i];
nums[i] = nums[j];
nums[j] = toSwap;
}
}
}
return nums;
}

Java > Array-2 > zeroMax

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;
}

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;
}

Categories