Related
Basically, I am trying to make an entirely new array of a new length that contains only the even ints in an array of integers.
However, I am getting an index out of bounds error. Can you help me find what I did wrong?
import java.util.Arrays;
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[i] += arr[i];
}
}
return result;
}
}
You should use a new variable to keep track of the current result index (let's say, j):
public static int[] evens(int[] arr) {
int length = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// Access result with `j` and update its value
result[j++] = arr[i];
}
}
return result;
}
Also, you can you streams:
int[] array = {1, 3, 4, 5, 6};
int[] even = IntStream.of(array).filter(item -> item%2 == 0).toArray();
System.out.println(Arrays.toString(even));
You need a new index variable for the result array and your assignment is also wrong as instead of assigning you are adding the even number to the result array element.
int j = 0;
int[] result = new int[length];
// add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
result[j++] = arr[i];
}
}
Problem is you are using i for the result array AND the original array. You should only increment the result array inside of the IF (when you find an even number) otherwise, you go out of bounds due to i (the original arr) being a larger size than the result array.
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
int resultCount = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[resultCount] += arr[i];
resultCount++;
}
}
return result;
}
Simply when you want to assign a value to result[] you do it with the index in the array arr, 0, 1 and 5. You just have to declare an auxiliary int aux = 0; variable before second loop and increment according to arr[i] % 2 == 0 so true
result[i] += arr[i];
a
int aux = 0;
result[aux++] += arr[i];
Complete code
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int aux = 0;
//add even ints to new array
for (int i = 0; i < arr.length; i++){
if (arr[i] % 2 == 0) {
result[aux++] += arr[i];
}
}
return result;
}
}
Since you don't really know how long the resultant array will be you can copy them to the front of the current array. Then use the final location as the count of values.
int[] input = {1,2,3,4,5,6,7,8,9};
int k = 0;
for(int i = 0; i < input.length; i++) {
if (input[i] % 2 == 0) {
input[k++] = input[i];
}
}
int[] evens = Arrays.copyOf(input, k);
System.out.println(Arrays.toString(evens));
Prints
[2, 4, 6, 8]
A simple way is to filter even numbers using the Stream API and return the result as an array.
Arrays.stream(arr)
.filter(n -> n % 2 == 0)
.toArray();
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[] { 4, 8, 19, 3, 5, 6 })));
}
static int[] evens(int[] arr) {
return Arrays.stream(arr).filter(n -> n % 2 == 0).toArray();
}
}
Output:
[4, 8, 6]
What went wrong with your code:
result.length is 3 and therefore in result[], the maximum index you can access is 2 (i.e. result.length -1) whereas your second loop counter goes up to 5 (i.e. arr.length - 1) and you are using the same counter to access elements in result[] resulting in ArrayIndexOutOfBoundsException.
If you want to do it in your own way, you need to use a separate counter for result[] e.g.
int[] result = new int[length];
//add even ints to new array
for (int i = 0, j = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[j++] = arr[i];
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e.
A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].
Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1.
For example, consider the following array A consisting of N = 8 elements:
A[0] = -1
A[1] = 3
A[2] = -4
A[3] = 5
A[4] = 1
A[5] = -6
A[6] = 2
A[7] = 1
P = 1 is an equilibrium index of this array, because:
A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]
P = 3 is an equilibrium index of this array, because:
A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]
P = 7 is also an equilibrium index, because:
A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0
and there are no elements with indices greater than 7.
P = 8 is not an equilibrium index, because it does not fulfill the condition 0 ≤ P < N.
Now i have to write a function:
int solution(int A[], int N);
that, given a zero-indexed array A consisting of N integers, returns any of its equilibrium indices. The function should return −1 if no equilibrium index exists.
For example, given array A shown above, the function may return 1, 3 or 7, as explained above.
Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
here have some Complexity:
Elements of input arrays can be modified.
100% - Java
int solution(int A[], int N) {
long sum = 0;
for (int i = 0; i < A.length; i++) {
sum += (long) A[i];
}
long leftSum = 0;
long rightSum = 0;
for (int i = 0; i < A.length; i++) {
rightSum = sum - (leftSum + A[i]);
if (leftSum == rightSum) {
return i;
}
leftSum += A[i];
}
return -1;
}
}
100% scored with c#
using System;
class Solution {
public int solution(int[] A) {
// First calculate sum of complete array as `sum_right`
long sum_right = 0;
for (int i = 0; i < A.Length; i++)
{
sum_right += A[i];
}
// start calculating sum from left side (lower index) as `sum_left`
// in each iteration subtract A[i] from complete array sum - `sum_right`
long sum_left = 0;
for (int p = 0; p < A.Length; p++)
{
sum_left += p - 1 < 0 ? 0: A[p-1];
sum_right -= A[p];
if (sum_left == sum_right)
{
return p;
}
}
return -1;
}
}
100 Score in Javascript
function solution(V) {
var sum = 0;
for (i=0; i < V.length; i++) {
sum += V[i];
}
var leftSum= 0;
var rightSum = 0;
for (j=0; j < V.length; j++) {
rightSum = sum - (leftSum + V[j]);
if(leftSum == rightSum) {
return j;
}
leftSum += V[j];
}
return -1;
}
In C++ (because that was one of the original tags, though it looks like it has been removed...)
int solution(int a[], int N){
int left;
int right;
for(int i = 0; i < N; i++){
left = 0;
right = 0;
for(int t = 0; t < N; t++){
if(t < i) left += a[t];
else if(t > i) right += a[t];
else continue;
}
if(left == right) return i;
}
return -1;
}
...
int demo[] = {-1, 3, -4, 5, 1, -6, 2, 1};
cout << solution(demo,sizeof(demo)/sizeof(*demo));
if you want to see all the indices...
if(left == right) cout << "Equilibrium Index: " << i << endl;
I find it odd it doesn't need to return an array of indices; that said, should you need it that's not too hard to implement with some slight modification
The answer is posted in this blog: http://blog.codility.com/2011/03/solutions-for-task-equi.html. In order to avoid O(N^2) and achieve O(N) performance:
The key observation for better running time is to update the left/right sums in constant time instead of recomputing them from the scratch.
int equi(int arr[], int n)
{
if (n==0) return -1;
long long sum = 0;
int i;
for(i=0;i<n;i++) sum+=(long long) arr[i];
long long sum_left = 0;
for(i=0;i<n;i++) {
long long sum_right = sum - sum_left - (long long) arr[i];
if (sum_left == sum_right) return i;
sum_left += (long long) arr[i];
}
return -1;
}
Here is the java equivalent
public static int equilibriumIndex(int[] array) {
int INDEX_NOT_FOUND = -1;
int rSum = 0, lSum = 0;
for (int index = 0; index < array.length; index++) {
rSum += array[index];
}
for (int index = 0; index < array.length; index++) {
lSum += (index==0) ? 0 : array[index -1];// cumulative sum before (left sum) the current index
rSum -= array[index]; // sum after (right sum) the current index onwards
if (lSum == rSum) { // if both sums, cumulative sum before the current index and cumulative sum after the current index is equal, we got the equilibrium index
return index;
}
}
return INDEX_NOT_FOUND;
}
Here is how you would test it
#Test
public void equilibriumTest() {
int result = ArrayUtils.equilibriumIndex(new int[]{1,2,3,1,6});
assertThat(result, equalTo(3));
}
Dynamic programming approach. O(N) time. O(2N) space.
Keep two tables (arrays), tableBefore and tableAfter.
tableBefore has sum up to index i for every i; i -> 1 to N.
tableAfter has sum up to index i for every i; i -> N to 1.
Afterwards loops and compare every index in tableBefore and tableAfter. If it's equal, that's your equilibrium index.
public static int EquilibriumIndex2(int[] a) {
int len = a.length;
int[] tableBefore = new int[len];
int[] tableAfter = new int[len];
tableBefore[0] = 0;
for (int i = 1; i < len; i++) {
tableBefore[i] = tableBefore[i - 1] + a[i - 1];
}
//System.out.println("tableBefore: " + Arrays.toString(tableBefore));
tableAfter[len - 1] = 0;
for (int i = len - 2; i >= 0; i--) {
tableAfter[i] = tableAfter[i + 1] + a[i + 1];
}
//System.out.println("tableAfter: " + java.util.Arrays.toString(tableAfter));
for (int j = 0; j < len; j++) {
if (tableAfter[j] == tableBefore[j]) {
return j;
}
}
return -1;
}
You can use the sums approach to solve this. Whenever sum from left = sum from right, you have an equilibrium point.
public int solution(int[] A) {
int[] sumLeft = new int[A.length];
int[] sumRight = new int[A.length];
sumLeft[0] = A[0];
sumRight[A.length-1] = A[A.length-1];
for (int i=1; i<A.length; i++){
sumLeft[i] = A[i] + sumLeft[i-1];
}
for (int i=A.length-2; i>=0; i--) {
sumRight[i] = sumRight[i+1] + A[i];
}
for (int i=0; i<A.length; i++) {
if (sumLeft[i]==sumRight[i]) {
return i;
}
}
return -1;
}
The straightforward approach looks the following way.
First of all you need to calculate the sum of all elements of the array
For example if you have the array in C++
int a[] = { -1, 3, -4, 5, 1, -6, 2, 1 };
then you can use an ordinary loop to calculate the sum or standard algorithm std::accumulate declared in header <numeric>
For example
long long int right_sum =
std::accumulate( std::begin( a ), std::end( a ), 0ll );
The sum of the elements of the left subsequence initially is equal to zero
long long int left_sum = 0;
Then you can apply standard algorithm std::find_if with an appropriate lambda-expression or again write an ordinary loop as for example
for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
{
right_sum -= a[i];
if ( left_sum == right_sum ) std::cout << i << ' ';
left_sum += a[i];
}
The result will be
1 3 7
My answer in Swift 3.0
public func solution(_ A : inout [Int]) -> Int {
var nElements = A.count
var equilibriumIndexArray = [Int]() /* to store all possible indices */
var equilibriumIndex = -1
for fixedIndex in 0..<nElements{
var sumLeft = 0
var sumRight = 0
//Sum the left part
for index in 0..<fixedIndex
{
sumLeft += A[index]
}
//Sum the right part
for index in fixedIndex+1..<nElements
{
sumRight += A[index]
}
//Check for equilibrium
if sumLeft == sumRight
{
equilibriumIndexArray.append(fixedIndex)
}
}
//pick a random element from the list of possible answers
if equilibriumIndexArray.count > 0
{
let randomIndex = Int(arc4random_uniform(UInt32(equilibriumIndexArray.count)))
equilibriumIndex = equilibriumIndexArray[randomIndex]
}
return equilibriumIndex
}
in python :)
def solution(A):
INDEX_NOT_FOUND = -1
right_sum = 0
left_sum = 0
for item in range(0, len(A)):
right_sum += A[item]
for item in range(0, len(A)):
if item == 0:
left_sum += 0
else:
left_sum += A[item -1]
right_sum -= A[item]
if left_sum == right_sum:
return item
return INDEX_NOT_FOUND;
100% - PHP
function solution(array $a)
{
$result = [];
for($i = 0; $count = count($a), $i < $count; $i++) {
if(sumLeft($a, $i-1) === sumRight($a, $i+1)) {
$result[] = $i;
}
}
return count($result) ? $result : -1;
}
function sumRight(array $a, int $position): int
{
return array_sum(array_slice($a, $position));;
}
function sumLeft(array $a, int $position): int
{
return array_sum(array_slice($a, 0, $position + 1));
}
echo "<pre>";
print_r(solution([-1, 3, -4, 5, 1, -6, 2, 1]));
output:
Array
(
[0] => 1
[1] => 3
[2] => 7
)
Simple Solution :
steps :
1) Check (Array = null)
Then Print “No Equilibrium point present as the array is NULL”
2) Check (length of Array = 1)
Then Print "Equilibrium_Index = 0" => Only single element present in array which is the equilibrium point
3) Check (Length of Array > 1)
Loop (Array Index 1 to Length-1)
Consider each index as equilibrium point
Check (sum of elements below equilibrium point = sum of elements above equilibrium poin)
Yes => equilibrium_index = i (break the loop)
No => continue step 3 with next value of loop counter
4) if control is not returned from step 3 means the equilibrium point is not present in loop
Then Print "No equilibrium point present in array."
Please find below code for same :
public int findSum(int equillibrium,int a[],int flag)
{
/*Flag - It represents whether sum is required for left side of equilibrium
point or right side of equilibrium point
*Flag = 0 => Sum is required for left side of equilibrium point
*Flag = 1 => Sum is required for right side of equilibrium point
*/
int lowlimit = 0, uplimit = a.length-1, i ,sum = 0;
if(flag==0)
uplimit = equillibrium - 1;
else
lowlimit = equillibrium + 1;
for(i=lowlimit ; i<=uplimit; i++)
sum = sum + a[i];
return sum;
}
public int findEquillibriumPoint(int a[])
{
int i = 0; //Loop Counter
//Since only one element is present it is at equilibrium only and index of equillibrium point is index of single element i.e 0
if(a.length==1)
return 0;
else
{
for(i=1;i<a.length;i++)
{
if(findSum(i,a,0)==findSum(i,a,1)) //checking if some of lower half from equilibrium point is equal to sum of upper half
return i; //if equilibrium point is found return the index of equilibrium point
}
}
return -1;//if equilibrium point is not present in array then return -1
}
For the lazy ones and PHP developers:
$A = [];
$A[0] = -1;
$A[1] = 3;
$A[2] = -4;
$A[3] = 5;
$A[4] = 1;
$A[5] = -6;
$A[6] = 2;
$A[7] = 1;
echo solution($A) . "\n";
function solution($A)
{
$sum = 0;
for ($i=0; $i < count($A); $i++) {
$sum += $A[$i];
}
$sumRight = 0;
$sumLeft = 0;
for ($j=0; $j < count($A); $j++) {
$sumRight = $sum - ($sumLeft + $A[$j]);
if ($sumLeft == $sumRight) {
return $j;
}
$sumLeft += $A[$j];
}
return -1;
}
Complexity O(N)
100 Score in Ruby
def equilibrium(a)
sum = 0
n = a.length
left_sum = 0
right_sum = 0
n.times do |i|
sum += a[i]
end
n.times do |i|
right_sum = sum - left_sum - a[i]
if right_sum == left_sum
return i
end
left_sum += a[i]
end
return -1
end
Fully tested C#
using System;
class Program
{
static int Function1(int[] arr, int n)
{
int i, j;
int leftsum;
int rightsum;
for (i = 0; i < n; ++i)
{
leftsum = 0;
rightsum = 0;
if(i == 0)
{
leftsum = 0;
for (j = 0; j < n; j++)
{
rightsum += arr[j];
}
if (leftsum == rightsum)
return i;
}
for (j = 0; j < i; j++)
{
leftsum += arr[j];
}
if (n-1 != j)
{
for (j = i + 1; j < n; j++)
{
rightsum += arr[j];
}
}
else
{
rightsum = arr[n-1];
}
if (leftsum == rightsum)
return i;
}
return -1;
}
public static void Main(string[] args)
{
int[] arr = { 1, 5, -8, 0, -2 };
int arr_size = arr.Length;
Console.Write(Function1(arr, arr_size));
}
}
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;
}
I am a beginner. I am unable to figure out how to write a function which will return 1, if have this property:
arr[0] = arr[1] + arr[2] = arr[3] + arr[4] + arr[5] = arr[6] + arr[7] + arr[8] + arr[9] = ...
else returns 0. The length of an array must be n*(n+1)/2 for some n.
For example, if input array is {2, 1, 1, 4, -1, -1}, it returns 1 because 2 = 1 + 1, 2 = 4 + -1 + -1
I have tried this:
public static int myArray(int[] a) {
int len = a.length;
if (checkLenght(len)) {
int firstElem = a[0];
int value = 1;
int sum = 0;
for (int i = 1; i <= a.length; i++) {
for (int j = value; j < value + 1; j++) {
sum += a[j];
value++;
}
}
}
return 0;
}
public static boolean checkLenght(int len) {
for (int i = 0; i <= 100; i++) {
if ((i * (i + 1) / 2) == len) {
return true;
}
}
return false;
}
Thanks in advance.
I try to partition input in sets of two , three , .... elements. for that I use a pointer to show how many elements are in this partition. firs it is 2. then it is three , ... . and I use a temp number to count if in this partition I have enough element or not. after I have enough element in each partition I just check sum of the element of that partition.
This should do the work:
public static int myArray(int[] a) {
int len = a.length;
if (checkLenght(len)) {
int firstElem = a[0];
int pointer = 2; // pointer that will be 2, 3, 4 , ...
int sum = 0; // sum of element in each partition
int temp = 0; // a temp value to check if I reach desirable number of element in this partition or not.
for (int i = 1; i < a.length; i++) { // i<=a.length give you exception.
temp++;
sum += a[i];
if (temp == pointer) { // check if I have enough element.
pointer++; // plus pointer by one
temp = 0; // reset temp
if (sum != firstElem) // if in any of those partitions my needs doesnt meet I return zero.
return 0;
sum = 0; // reset sum
}
}
return 1;
}
return 0;
}