Testing array issue - java

I am stuck on an issue that I cannot seem to resolve. I cannot seem to to test my code correctly. My code is as follows
public static int sum13( int[] nums) {
int sum = 0;
for(int i = 0; i <= nums.length - 1; i++){
if( nums[i] != 13){
sum += nums[i];
if(i > 0 && nums[i-1] == 13)
sum -= nums[i];
}
}
return sum;
}
public static void main(String[] args) {
}
If I try to put System.out.println(sum13([1,2,2,1]) I am met with several errors relating to the [] as well as the ,. I cannot figure out, what it is that I've done wrong.
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13, also do not count. sum13([1, 2, 2, 1]) →6
sum13([1, 1]) →2

I decided to add flag to know when the previous value was 13. In that way, you don't have to deal with edge cases.
public static int sum13(int[] nums) {
int sum = 0;
boolean was13 = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 13) {
was13 = true;
} else {
if(!was13)
sum += nums[i];
was13 = false;
}
}
return sum;
}

A possible solution with some test cases:
public static int sum13(int[] numbers)
{
int sum = 0;
int prev = 0;
for (var number : numbers)
{
if (number != 13 && prev != 13)
{
sum += number;
}
prev = number;
}
return sum;
}
public static void main(String[] args)
{
System.out.println(sum13(new int[]{}));
System.out.println(sum13(new int[]{1, 2, 3, 4, 5}));
System.out.println(sum13(new int[]{13, 1, 13, 13, 2, 3, 4, 5}));
}

Related

Arrays: Find Numbers with Even Number of Digits

public class Nodigeven {
static int even=0;
static int count=0;
static int findnodigeven(int[] arr) {
for(int i=0;i<arr.length;i++) {
while(arr[i]!=0) {
arr[i]= arr[i]/10;
count++;
}
if(count%2==0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = {122,255,133,14,15,16};
System.out.println(findnodigeven(arr));
}
}
am getting wrong output i.e : 1 .. can you tell me where i am going wrong here in the code
As far as I can tell you have two errors. The first is that you did not reset count to 0 for each iteration of the loop. The second is that you did not check the special case of 0 in the array. 0 is a single digit and thus odd. But since you never enter the while loop, count will remain 0 and even will be incremented.
public class Nodigeven {
static int findnodigeven(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int count = 0;
// check for 0 value and skip.
if (arr[i] == 0) {
continue;
}
while (arr[i] != 0) {
arr[i] = arr[i] / 10;
count++;
}
if (count % 2 == 0) {
even++;
}
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}
If you're interested you and do this without explicitly counting the digits. Use Math.log10() to get the count, again skipping 0 since the log of 0 is undefined. The number of digits in a decimal number N is Math.log10(N)+1. You can use the conditional operator to add 1 or 0 as appropriate to the parity count.
public class Nodigeven {
static int even = 0;
static int findnodigeven(int[] arr) {
int even = 0;
for (int i = 0; i < arr.length; i++) {
even += arr[i] != 0 &&
(int) (Math.log10(arr[i])+1) % 2 == 0
? 1 : 0;
}
return even;
}
public static void main(String[] args) {
int[] arr = { 122, 255,0, 133, 14, 15, 16 };
System.out.println(findnodigeven(arr));
}
}

26. Remove Duplicates from Sorted Array - Java

Question : Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
What exactly does the return statement do here. What does return i + 1 mean here ?
The return i + 1 is returning how many unique integers are there. I believe this is a Leetcode problem, and since its in place, the int[] is passed in by reference, Leetcode wants to know how many numbers to check (you're supposed to put the unique numbers in the first i + 1 spots).
If you look at the question, it says:
Which means that you return the length of the array.
So, if you have the array [1,1,2,3,4,4], you would turn that into [1,2,3,4,...], where the ... is the rest of the array. However, you return 4 because the length of the new array should be 4.
Hope this clears things up for you!
Your question has been already answered here; in addition to that, we can also start from zero and remove the first if statement:
Test with a b.java file:
import java.util.*;
class Solution {
public static final int removeDuplicates(
final int[] nums
) {
int i = 0;
for (int num : nums)
if (i == 0 || num > nums[i - 1]) {
nums[i++] = num;
}
return i;
}
}
class b {
public static void main(String[] args) {
System.out.println(new Solution().removeDuplicates(new int[] { 1, 1, 2}));
System.out.println(new Solution().removeDuplicates(new int[] { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4}));
}
}
prints
2
5
I tried in this easy way. Here Time complexity is O(n) and space
complexity: O(1).
static int removeDuplicates(int[] nums){
if(nums.length == 0) {
return 0;
}
int value = nums[0];
int lastIndex = 0;
int count = 1;
for (int i = 1; i < nums.length; i++) {
if(nums[i] > value) {
value = nums[i];
lastIndex = lastIndex+1;
nums[lastIndex] = value;
count++;
}
}
return count;
}
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0 || n == 1)
return n;
int j = 0;
for (int i=0; i<n-1; i++)
if (nums[i]!= nums[i+1])
nums[j++] = nums[i];
nums[j++]=nums[n-1];
return j;
}
}
public class RemoveDuplicateSortedArray {
//Remove Duplicates from Sorted Array
public static void main(String[] args) {
int[] intArray = new int[]{0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
int count = extracted(intArray);
for (int i = 0; i < count; i++) {
System.out.println(intArray[i]);
}
}
private static int extracted(int[] intArray) {
int size = intArray.length;
int count = 1;
if (size == 1) {
return 1;
} else if (size == 2) {
if (intArray[0] == intArray[1]) {
return 1;
} else {
return 2;
}
} else {
for (int i = 0, j = i + 1; j < size; j++) {
if (intArray[i] < intArray[j]) {
i++;
intArray[i] = intArray[j];
count++;
}
}
return count;
}
}
}

How to iterate over array of integers to find a sequence based on an O(N) solution?

I saw following question and tried to find an answer for that.
Question: Given a sequence of positive integers A and an integer T, return whether there is a *continuous sequence* of A that sums up to exactly T
Example
[23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20
[1, 3, 5, 23, 2], 8. Return True because 3 + 5 = 8
[1, 3, 5, 23, 2], 7 Return False because no sequence in this array adds up to 7
Note: We are looking for an O(N) solution. There is an obvious O(N^2) solution which is a good starting point but is not the final solution we are looking for.
My answer to above question is:
public class Tester {
public static void main(String[] args) {
int[] myArray = {23, 5, 4, 7, 2, 11};
System.out.println(isValid(myArray, 20));
}
public static boolean isValid(int[] array, int sum) {
int pointer = 0;
int temp = 0;
while (pointer < array.length)
{
for (int i = pointer; i < array.length; i++)
{
if (array[i] > sum)
break;
temp += array[i];
if (temp == sum)
return true;
else if (temp > sum)
break;
// otherwise continue
}
temp = 0;
pointer++;
}
return false;
}
}
I think my answer is O(N^2) which is not acceptable based on Question. Is there a solution based on O(N)?
You only need to loop once actually which is O(N).
Start adding from index 0 and once you exceed the sum start removing from the beginning of the array. if temp falls below sum continue looping.
public static boolean isValid(int[] array, int sum) {
int init = 0,temp = 0;
for (int i = 0; i < array.length; i++) {
temp += array[i];
while (temp > sum) {
temp -= array[init];
init++;
}
if (temp == sum)
return true;
}
return false;
}
What you should do is to have two indices (start and stop) then you increase stop until the sum is the required (and return true) or above. Then you increase start until the sum is the required (and return true or below. Then you repeat this until you reach the end of the array. You can update the sum incrementally (add the element when you increase stop and subtract when you increase start). This ought to be O(N).
Here's an example:
public class t {
public static void main(String[] args) {
int[] myArray = {23, 5, 4, 7, 2, 11};
System.out.println(isValid(myArray, 20));
}
public static boolean isValid(int[] array, int sum) {
int start = 0;
int stop = 0;
int tsum = 0;
while( true )
{
if( tsum < sum )
{
if( stop >= array.length )
break;
tsum += array[stop];
stop++;
}
else if( tsum > sum )
{
tsum -= array[start];
start++;
}
else if( tsum == sum )
return true;
// System.out.println(start + " -- " + stop + " => " + tsum);
}
return false;
}
}

remove and print prime numbers in an array

I have an assignment due for class and the objective is to take an Array and run it through a method that will print the array out in reverse order, then run it through a second method to test if the number is prime then print the still reversed order array out without the prime numbers. I can get the reverse the order part fine, I am running into trouble with the prime numbers part:
public class Driver {
public static void main(String[] args) {
// CTORs
int[] MyArray = { 10, 8, 7, 14, 22, 11 };
int[] myArray2 = new int[7];
// METHOD CALLING
MyArray = reverseOrder(6, MyArray);
MyArray = primeCheck(MyArray, 6);
for (int i = 0; i < myArray2.length; i++)
System.out.println(myArray2[i] + " ");
}// MAIN
/*--------------------ARRAY PRIME TEST---------------------*/
private static int[] primeCheck(int[] myArray, int num) {
//prime
boolean prime = true;
int[] myArray2 = new int[10];
//test all components of an array
for (int i = num + 1 ; i >= 0; i++) {
if (num % i > 0) {
prime = false;
System.arraycopy(myArray, 0, myArray2, 0, 4);
return myArray2;
}
}
return myArray2;
}// ISPRIME REMOVE
}// CLOSE CLASS
my output is as follows:
11 22 14 7 8 10 0
0
0
0
0
0
I feel really rusty because this is the first assignment back after a long break, so any guidance or help would be greatly appreciated.
myArray2 is defined and never filled with values. So every element is 0.
I think
for (int i = 0; i < myArray2.length; i++)
must be
for (int i = 0; i < myArray.length; i++)
There's definitely something wrong about for (int i = num + 1 ; i >= 0; i++). Below is one way to achieve the objective.
public static void main(String[] args) {
int[] arr = { 10, 8, 7, 14, 22, 11 };
for(int i = 0; i < arr.length; i++) {
if(!isPrime(arr[i])) {
System.out.print(arr[i] + " ");
}
}
}
public static boolean isPrime(int num) {
if(num < 2) return false;
if(num == 2) return true;
int remainder, divisor;
divisor = num - 1;
do {
try {
remainder = num % divisor;
} catch (ArithmeticException e) {
return false;
}
if(remainder == 0) return false;
divisor--;
} while (divisor > 1);
return true;
}

Solving codingBat 'evenOdd' with one loop in Java

The question is about Solving this problem from codingBat in Java.
Problem Statement:
Return an array that contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. Other than that, the numbers can be in any order. You may modify and return the given array, or make a new array.
evenOdd({1, 0, 1, 0, 0, 1, 1}) → {0, 0, 0, 1, 1, 1, 1}
evenOdd({3, 3, 2}) → {2, 3, 3}
evenOdd({2, 2, 2}) → {2, 2, 2}
The Problem is simple with 2 loops I attempted at solving it with 1 it got too lengthy I believe, is there any other efficient way to solve the above problem using 1 loop?
do not use collections!
My solution:
public int[] evenOdd(int[] nums) {
boolean oddFound=false;
int count=-1;
int oddGap=0;
for(int i=0;i<nums.length;i++)
{
if(!(oddFound)&(nums[i]%2==0))
continue;
if((!oddFound)&(nums[i]%2==1))
{
oddFound=true;
count=i;
continue;
}
if((oddFound)&(nums[i]%2==1))
{
oddGap++;
continue;
}
if((oddFound)&(nums[i]%2==0))
{
int temp=nums[count];
nums[count]=nums[i];
nums[i]=temp;
if(i>0)
i--;
if(oddGap>0)
{
oddGap--;
count+=1;
oddFound=true;
continue;
}
oddFound=false;
}
}
return nums;
}
Since creating a new array is allowed, and the order of the numbers is irrelevant, I would use the following approach:
public int[] evenOdd(int[] nums) {
int[] output = new int[nums.length];
int evenPos = 0;
int oddPos = nums.length-1;
for (int i : nums) {
if (i%2==0) {
output[evenPos++]=i;
} else {
output[oddPos--]=i;
}
}
return output;
}
Update: A somewhat less readable version that doesn't require an extra array (along the lines of what #Seelenvirtuose suggests, just without the extra loops)
public int[] evenOdd(int[] nums) {
int evenPos = 0;
int oddPos = nums.length-1;
while (true) {
if (evenPos>=oddPos || evenPos>=nums.length || oddPos<0) {
break;
}
if (nums[evenPos]%2==0) {
evenPos++;
}
if (nums[oddPos]%2!=0) {
oddPos--;
}
if (evenPos<oddPos && nums[evenPos]%2 != 0 && nums[oddPos]%2 == 0) {
int tmp = nums[evenPos];
nums[evenPos] = nums[oddPos];
nums[oddPos] = tmp;
oddPos--;
evenPos++;
}
}
return nums;
}
You do not need any temporary lists or array because you can reorder the elements in-situ.
This is a simple algorithm:
Define two pointers, left and right (initially set to the bounds of the array).
As long as left does not exceed right and nums[left] is even, increment left.
As long as right does not exceed left and nums[right] is odd, decrement right.
If left is still less than right, swap the elements at positions left and right.
Repeat 2,3,4 as long as left is still less than right.
Got it? Here some code:
public int[] evenOdd(int[] nums) {
// (1)
int left = 0;
int right = nums.length -1;
do {
// (2)
while (left < right && nums[left] % 2 == 0)
left += 1;
// (3)
while (right > left && nums[right] % 2 != 0)
right -= 1;
// (4)
if (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
} while (left < right); // (5)
return nums;
}
Okay! I finally jumped across this question which is actually closed but the solution by asker was almost there apart from failing in 2 cases which I fixed:
I commented out he code by asker which was making it fail in a couple of cases as seen in the question.
I think below is the simplest and most optimized solution:
public int[] evenOdd(int[] nums) {
int y=nums.length,x,a=0;
int temp=0;
for(x=0;x<y;x++)
{
if(nums[x]%2==0) {
if(a>(y-2))
return nums;
else{
//nums[a]=nums[a]+nums[x];
//nums[x]=nums[a]-nums[x];
//nums[a]=nums[a]-nums[x];
temp=nums[a];
nums[a]=nums[x];
nums[x]=temp;
a+=1;
}
}
return nums;
}
Traverse evenOdd from 0 to N.
for every even number encountered, copy it to the required position on the evenOdd array.
for every odd num encountered, store it in a separate array called oddnum.
After traversing the whole array, just copy the elements from oddnum to the Back of evenOdd.
Ex: evenOdd = {5,2,1,4}
Step 1. copy 5 to oddnum[0]
2. copy 2 to evenodd[0]
3. copy 1 to oddnum[1]
4. copy 1 to evenodd[1]
5. cpy oddnum[0] to evenOdd[2] and oddnum[1] to evenOdd[3]
Keeping to your restrictions, here's a one-loop answer:
public int[] evenOdd(int[] nums) {
int[] result = new int[nums.length];
int nextEven = 0;
int nextOdd = nums.length - 1;
for ( int num : nums )
{
if ( num % 2 == 0 )
result[ nextEven++ ] = num;
else
result[ nextOdd-- ] = num;
}
return result;
}
public int[] evenOdd(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
int temp = nums[i];
nums[i] = nums[count];
nums[count] = temp;
count++;
}
}
return nums;
}
public int[] evenOdd(int[] nums) {
Stack stack = new Stack();
int[] nums2 = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
if(nums[i] % 2 != 0) {
stack.push(nums[i]);
}
}
for(int i = 0; i < nums.length; i++) {
if(nums[i] % 2 == 0) {
stack.push(nums[i]);
}
}
for(int i = 0; i < nums.length; i++) {
nums2[i] = (Integer) stack.pop();
}
return nums2;
}
In-place version (stable):
We continually search for te first and last invalid values (first odd, before last even) and keep swapping them until they cross:
public int[] evenOdd(int[] nums) {
int first = 0, last = nums.length - 1;
while (first < last) {
while ((first < last) && isOdd(nums[last])) last--;
while ((first < last) && !isOdd(nums[first])) first++;
swap(nums, first, last);
}
return nums;
}
boolean isOdd(int num) { return (num & 1) == 1; }
void swap(int[] nums, int i, int j) {
int copy = nums[i];
nums[i] = nums[j];
nums[j] = copy;
}
With auxiliaries (stable):
We partition the even and odd values in separate lists and concatenate them back:
public int[] evenOdd(int[] nums) {
List<Integer> evens = new ArrayList<Integer>(nums.length);
List<Integer> odds = new ArrayList<Integer>(nums.length);
for (int num : nums)
if (isOdd(num)) odds.add(num);
else evens.add(num);
int[] results = new int[nums.length];
int i = 0;
for (int num : evens) results[i++] = num;
for (int num : odds) results[i++] = num;
return results;
}
boolean isOdd(int num) { return (num & 1) == 1; }
Simplified solution which uses Srteam API:
public int[] evenOdd(int[] nums) {
int[] evenOddArr = new int[nums.length];;
int[] evenArr = Arrays.stream(nums).filter(x -> x % 2 == 0).toArray();;
int[] oddArr = Arrays.stream(nums).filter(x -> x % 2 != 0).toArray();
evenOddArr = java.util.stream.IntStream.concat(Arrays.stream(evenArr), Arrays.stream(oddArr))
.toArray();
return evenOddArr;
}
It passes all the tests on CodingBat:

Categories

Resources