Save integer into vector after foor loop with conditionals - java

I have to set up a for loop that differences between odd and even numbers. I'm thinking to use an if/else statement into the for loop that evaluates de residue to know if is even or odd. Once done it, i'd like to save the number in a vector: one vector for the if condition, and another for the else.
This is my code!
import java.io.*;
import java.util.Arrays;
import java.util.*;
class Even_odd_array {
static void CountingEvenOdd(int arr[],
int arr_size)
{
int even_count = 0;
int odd_count = 0;
//int [] subvector_odd = {};
Vector<Integer> vector_odd = new Vector<Integer>();
Vector<Integer> vector_even = new Vector<Integer>();
// loop to read all the values in
// the array
for(int i = 0 ; i < arr_size ; i++)
{
// checking if a number is
// completely divisible by 2
if ((arr[i] & 1) == 1)
odd_count ++ ;
vector_odd.addElement(arr[i]);
else
even_count ++ ;
vector_even.addElement(arr[i]);
}
System.out.println( "Number of even"
+ " elements = " + even_count
+ " Number of odd elements = "
+ odd_count) ;
System.out.println(vector_odd); //This vector should look like [1, 3, 5, 7]
}
// Driver Code
public static void main (String[] args)
{
int arr[] = {2, 4, 6, 8, 10, 1, 3, 5, 7};
int n = arr.length;
CountingEvenOdd(arr, n);
}
}
The output should be:
Number of even elements = 5 Number of odd elements = 4
even_vector = [2, 4, 6, 8, 10]
odd_vector = [1, 3, 5, 7]
I'm getting an error in the else statement line when I include the vector.add() method inside the if statement, and I don't understand why...
Thanks!!

Modulo operator is %, not & which is bitwise and (see https://www.tutorialspoint.com/java/java_basic_operators.htm ). In addition, array length does not need to be given as parameter and a for loop is not needed. You have everything you need by using the two lines below.
Integer[] array = {2, 4, 6, 8, 1, 3, 7};
Vector<Integer> vectorEven = Arrays.stream(array).filter(i -> i % 2 == 0).collect(Collectors.toCollection(Vector::new));
Vector<Integer> vectorOdd =Arrays.stream(array).filter(i -> i % 2 == 1).collect(Collectors.toCollection(Vector::new));
System.out.println(vectorEven);
System.out.println(vectorOdd.size());

Currently your else block is not related to any if condition (you can omit curly braces if the block contains a single statement, though) .
To fix this, use curly braces to delimit the if and else blocks :
if ((arr[i] & 1) == 1) {
odd_count ++ ;
vector_odd.addElement(arr[i]);
}
else {
even_count ++ ;
vector_even.addElement(arr[i]);
}
Your current code is equivalent to :
if ((arr[i] & 1) == 1) {
odd_count ++ ;
}
vector_odd.addElement(arr[i]);
else {
even_count ++ ;
}
vector_even.addElement(arr[i]);
As you see, the else part can't be related to the if part here.

Related

To remove 3 consecutive numbers in an array

I need to remove 3 consecutive integers, done with the code but i am not able to print the last index number. can you please help me out..
here is the code..
public class MyClass {
public static void main(String args[]) {
int[] list={ 1, 1, 1, 2, 3, 4, 5, 5, 6, 5, 7, 8, 9};
for(int i=0; i<list.length;i++)
{
if((list[i]==list[i+1]) )
{
if(list[i]==list[i+2])
{
i=i+2;
continue;
}
System.out.print(list[i]) ;
}
else
{
System.out.print(list[i]);
}
}
}
}
As stated by #Dr.Will in his/her answer, one of the problems in your code is the check i < list.length.
Anyway, it's not the only one: you are accessing [i+1] and [i+2] elements without checking if those two values are acceptable indexes.
I just want to add some hint:
Use a debugger while writing such algorithms (it may save you A LOT of time)
cache the value of intermediate results, to avoid multiple access to the same element of the array
cache the size of the array, for the same reason, or use a reverse loop (which has some advantages)
The result would look something like this:
public class MyClass {
public static void main(String... args) {
int[] list = { 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 5, 7, 8, 9}; // sample list
int len = list.length;
if(len < 3)
return; // avoid ArrayIndexOutOfBoundsException
// forward loop
System.out.println("Forward loop:");
int elem1;
for(int i = 0; i < len; i++){
elem1 = list[i];
if(i+1 < len && elem1 != list[i+1])
System.out.println(elem1);
else if (i+2 < len && elem1 == list[i+2] && ++i < len){
// note that "&&" in java is a shot-circuit "AND", so the last "++i" will not be executed if not necessary
// also note that i'm not incrementing "+2", because the for loop will add another "+1" just after this "continue" statement
continue;
} else
System.out.println(elem1);
}
// reverse loop
System.out.println("\nReverse loop (if the order is not that relevant):");
for(int i = len; --i >= 0;){
elem1 = list[i];
if(i-1 >= 0 && elem1 != list[i-1])
System.out.println(elem1);
else if(i-2 >= 0 && elem1 == list[i-2] && --i >= 0)
continue;
else
System.out.println(elem1);
}
}
}
thank you for your logic (–Marco Carlo Moriggi), your logic is helpful and also slightly look complicated, but i changed or edited one line after referring your logic, this seems not much complicated as your logic but gives same result.
public class MyClass {
public static void main(String args[]) {
int[] list={ 1, 1, 1, 2, 3, 4, 5, 5, 6, 5, 7, 8, 9};
int elem = list.length;
for(int i=0; i<list.length;i++)
{
if((i+2<elem) && (list[i]==list[i+1]) )
{
System.out.print(list[i] + " ") ;
if(list[i]==list[i+2])
{
i=i+2;
continue;
}
}
else
{
System.out.print(list[i] + " ");
}
}
}
}
I think that is the i<list.length-1 clause. Your lis.length will return a value of 13, if i remember how to count, adding the -1, you are giving a value of 12, and if you add the <, you´re telling the i to only reach the 11 position.
So i think the solution could be either one of these:
for(int i=0; i<=list.length-1;i++)
or
for(int i=0; i<list.length;i++)

How do I correct this For Each loop in java (incorrect output on final test)?

I'm struggling to run this java correctly with a for each loop. It is fine for every test but the last. Could anyone kindly assist in letting me know where I'm going wrong? I feel confident I could do it with a for loop but would like to do it with a for each loop (if suitable).
Drill Question:
Given an array of ints, return true if the sequence of numbers 1, 2, 3 appears in the array somewhere.
arrayOneTwoThree([1, 1, 2, 3, 1]) -> true.
arrayOneTwoThree([1, 1, 2, 4, 1]) -> false.
arrayOneTwoThree([1, 1, 2, 1, 2, 3]) -> true.
For example:
int[] array = {2, 1, 2, 3, 2, 3, 2, 4, 1};
System.out.println(arrayOneTwoThree(array));
Result: true
public static void main(String[] args) {
//int[] array = {2, 1, 2, 3, 2, 3, 2, 4, 1};
//int[] array = {1, 1, 2, 3, 1};
//int[] array = {1, 1, 2, 4, 1};
int[] array = {1, 1, 2, 1, 2, 3};
System.out.println(arrayOneTwoThree(array));
}
public static boolean arrayOneTwoThree(int[] nums) {
for (int num : nums) {
//System.out.print(num);
if (nums[num] == 3 && nums[num-1] == 2 && nums[num-2] == 1)
return true;
}
return false;
}
In the loop, num is NOT the index within the array, it is the value.
I think you are expecting num to be the index, which would be the case if you did a for loop of the form for (int num =0; num < nums.length; num++)
If you want to compare n adiacent elements of array you have to use a loop ending to length - n - 1 : in your case n = 3 so your method can be written like below:
private static boolean arrayOneTwoThree(int[] array) {
final int n = array.length;
if (n < 3) { return false; } //<-- for arrays with less than 3 elements
for (int i = 0; i < n - 2; ++i) {
if (array[i] == 1 && array[i + 1] == 2 && array[i + 2] == 3) {
return true;
}
}
return false;
}
First tree test cases accidentally shoved correct result!
Your code works ONLY for cases, when index of 1 is 1, index of 2 is 2, and index of 3 is 3:
[*, 1, 2, 3, ......... ]
You are probably confused with another programming language. (Maybe for in construction of JavaScript?).
In Java for each over array (or anything else) iterates over values and never over indexes. (As was already specified)
I can see commented out System.out.print(num); why you've ignored it prints values not indexes?
Another issue is ignoring array bounds... Try to examine your code with next array:
int[] array = {2, 3, 2, 1, 2, 3};
It'll end up with ArrayIndexOutOfBoundsException
And answer for your question, how to solve with for each.
Yes, you can introduce external counter, but what would be the sense then?
public static boolean arrayOneTwoThree(int[] nums) {
int i = 0;
for (int num : nums) {
//System.out.print(num);
if (i < 2) continue; // we do not want ArrayIndexOutOfBoundsException happened, right?
if (nums[i] == 3 && nums[num-1] == 2 && nums[num-2] == 1)
return true;
}
return false;
}
If you wish to use for each you should avoid of using indexes to be consistent.
There could be tons of different solutions. You can use some flags or save previous and beforePrevious:
public static boolean arrayOneTwoThree(int[] nums) {
int beforePrevious;
int previous = 0;
int current = 0;
for (int num : nums) {
//System.out.print(num);
beforePrevious = previous;
previous = current;
current = num;
if (current == 3 && previous == 2 && beforePrevious == 1)
return true;
}
return false;
}
Beware: It's just first thought, so this solution may be not optimal and far from perfect, probably you can do better.

Reverse plus Even and Odd of an array

I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}

JAVA:How to output Array in 2 directions

My Title may sound a bit silly, so here is the explanation:
I have an Array
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
And the output in the End should be like
123321
I already managed to output 123456 and 654321 but I can´t figure out how to output 123321 :(
I am only allowed to use one outer loop and in this loop it is allowed to have a new loop.
I tried different things but I didn´t manage to get it running, can you guys give me a hint please?
What I was thinking about in the beginning:
while(x <=2){
System.out.print(a[x]);
x++;
if(x==2){
while(x>0){
System.out.print(a[x]);
x--;
}
}
}
You should specify what conditions must the output meet.
For iterating to half of the array and then back to the beginning you don't need any inner loop. Try this:
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < a.length; ++i){
if (i<a.length/2) System.out.print(a[i]);
else System.out.print(a[a.length-i-1]);
}
The problem with your code is that you go to an infinite loop :
while(x <=2){
System.out.print(a[x]);
x++; // <-- you increment x until it reaches 2
if(x==2){ // <-- x equals to 2
while(x>0){
System.out.print(a[x]);
x--; // <-- you decrement x until it reaches 0
}
} // <-- Wow, 0 <= 2 so re-execute the while loop
You can implement it like this. When you'll go until the middle of the array, the inner loop will get executed until it prints the elements from the current index to 0.
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
int x = 0;
while(x != a.length/2){ // <-- loop until the middle of the array
System.out.print(a[x]);
x++;
if(x == a.length/2){ // <-- when we reach the middle execute the inner loop
for(int i = x -1; i >= 0; i--) // <-- print the elements of the array from current index to 0
System.out.print(a[i]);
}
}
Just other way with Collections:
List<Integer> first = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6 ));
int half = first.size()/2;
List<Integer> out = new ArrayList<Integer>( first.subList(0, half) );
Collections.reverse( first.subList( 0, half ) );
out.addAll( first.subList( 0, half ) );
System.out.println(out); // [1, 2, 3, 3, 2, 1]

Sum of 4 elements in java array equaling to k, duplicated array elements

I've a homework of a code which searches for four numbers in an array whose sum equals to k (in this example, k = 10). The same array elements can be used more than once. In other words, it sums four elements of the array, compares the sums to value k, and returns true if they are equal, or moves on to other elements if not. So far the code sums four distinct elements of the array but I would need to alter it so that it works also when any single element is used in the sum of four elements more than once, for example if array[2] * 4 == k or array[0] * 2 + array[1] * 2 == k, it returns true.
"static int[][] esim" in the code are example inputs. For instance, {1, 2, 3, 4} returns true, because 1 + 2 + 3 + 4 == k when k = 10. {4, 3, 1, 5, 5, 6, 6} returns false when true is expected, because the code does not take into account duplicated elements and therefore ignores that 2 * 4 + 2 * 1 == k. Similarly {2, 3} returns false when true is expected, although 2 * 2 + 2 * 3 == k.
Anyone could give me a hint how to achieve what I want?
import java.util.Arrays;
public class Etsinta2 {
public static boolean etsi(int[] tl, int k) {
Arrays.sort(tl);
for (int i = 0; i < tl.length; i++) {
int b = i + 1;
int c = i + 2;
int d = tl.length - 1;
while (b < d) {
if (tl[i] + tl[b] + tl[c] + tl[d] == k) {
return true;
} else if (tl[i] + tl[b] + tl[c] + tl[d] < k) {
b++;
c++;
} else {
d--;
}
}
}
return false;
}
static int[][] esim = new int[][]{{5},
{2, 3},
{1, 1, 1, 1},
{1, 2, 3, 4},
{4, 2, 3, 1},
{4, 6, 5, 5},
{6, 4, 5, 5},
{6, 6, 6, 4},
{4, 4, 1, 1, 1, 6, 6},
{9, 1, 1, 1, 1, 5, 6},
{4, 3, 1, 5, 5, 6, 6}};
public static void main(String[] args) {
for (int[] taulu : esim) {
System.out.println(Arrays.toString(taulu) + " 10 : " + etsi(taulu, 10));
}
}
}
Are you checking if the total sum of elements is a multiple of k? If so, you could just sum all elements and check if % (mod) k is zero (i.e. no remainder after dividing by k).
Edit: Okay I read the question again and I think the question is to find 4 numbers from the array (and duplicating the numbers are okay) to sum to k.
(Sorry I tried to delete this answer but couldn't easily)
So here's a swing at the solution: Have four nested loops, one for each "number slot". Let each loop pick one number at a time from the array (therefore allowing duplicate selections). Check the sum in the inner-most loop. If it's k, break w/ true. If not true at the end, false.
Ok, I found a different solution which should bring the time complexity to O(n^2 log n). This uses an auxiliary list which stores all possible sums of pairs of array elements and then compares the sums of pairs of these sums to k. Here's the edited method where I've used an ArrayList. It works fine, except that it's still too slow: the homework is submitted via a robo tester, and a hidden test apparently testing with large numbers, clocks 27.0 ms whereas the required max is 25.0 ms. Is there any way I could speed up the code a little with some minor changes?
public static boolean etsi(int[] tl, int k) {
ArrayList<Integer> summat = new ArrayList<Integer>()
Arrays.sort(tl);
for (int i = 0; i < tl.length; i++) {
for (int j = 0; j < tl.length; j++) {
summat.add(tl[i] + tl[j]);
}
}
int a = 0;
int b = summat.size() - 1;
for (int i = 0; i < summat.size(); i++) {
if (summat.get(a) + summat.get(b) == k) {
return true;
} else if (summat.get(a) + summat.get(b) < k) {
a++;
} else {
b--;
}
}
return false;
}

Categories