JAVA:How to output Array in 2 directions - java

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]

Related

Save integer into vector after foor loop with conditionals

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.

I dont understand why this code works (Codingbat Array2 tenRun)

For each multiple of 10 in the given array, change all the values following it to be that multiple of 10, until encountering another multiple of 10. So {2, 10, 3, 4, 20, 5} yields {2, 10, 10, 10, 20, 20}.
I don't understand why this works. In my mind the output for {1, 10, 2, 2} should be {1, 10, 10, 2}, because the for loop should only detect %10 == 0 once, and then loop back and not detect it the next time. Why does it do this more then once?
public int[] tenRun(int[] nums) {
for (int i = 0; i < nums.length-1; i++) {
if (nums[i] % 10 == 0) {
if (nums[i+1] % 10 != 0) {
nums[i+1] = nums[i];
}
}
}
return nums;
}
Try this:-
public int[] tenRun(int[] nums) {
for(int i=0;i<nums.length;i++){
if(nums[i]%10==0){
for(int j=i+1;j<nums.length && nums[j]%10!=0;j++){
nums[j]=nums[i];
}
}
}
return nums;
}
In each iteration, whenever the condition, nums[i] % 10 == 0 evaluates to true (i.e. nums[i] is a multiple of 10), it checks if the next element is not a multiple of 10 i.e. nums[i + 1] % 10 != 0 and if it is the case, it sets the next element to nums[i] which is a multiple of 10. I hope, it helps you understand how it works. Feel free to comment in case of any further doubt.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(tenRun(new int[] { 2, 10, 3, 4, 20, 5 })));
}
public static int[] tenRun(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] % 10 == 0) {
if (nums[i + 1] % 10 != 0) {
nums[i + 1] = nums[i];
}
}
}
return nums;
}
}
Output:
[2, 10, 10, 10, 20, 20]
The for loop only loops nums.length-1 times, and it looks at all the overlapping pairs of elements in the array: nums[i] (which I will call a) and nums[i+1] (which I will call b).
The for loop will only ever change b, and never a. It only checks if a is a multiple of 10. If it is, set b to a. Look at the last pair in the array, b here is the last element. Therefore, the last element will potentially be changed by the loop.
The loop will at some point look at nums[1] and nums[2], and after setting nums[2] to 10, it now looks at the last pair, which is nums[2] (a) and nums[3] (b). Notice how nums[2] has just been set a value of 10, so that, nums[3] can be set to 10 as well.
On the other hand, the loop will never sets the first element, which is the a of the first pair. This is correct as it will not be after any multiples of 10.
When you detect a multiple of 10, followed by a non-multiple of 10, your algorithm updates the following value. On the next iteration of the loop you encounter this updated value. Given that this has to be a multiple of 10 now, the subsequent value is then updated.
If we consider the state of i and nums at the start of each iteration, we find:
0: 1, 10, 2, 2
1: 1, 10, 2, 2
2: 1, 10, 10, 2
So on that final iteration (the loop terminates when i == 3), nums[2] == 10, hence nums[3] is also set to 10.

Square Value at Index without using a temp array

At 0th index value is 4, so I have to check the value at index 4 and square it and place the value at 0th index without using a temp array:
Index 0 1 2 3 4
Values 4 3 1 2 0
================
Result 0 4 9 1 16
Now I am getting the first two values right, but the last three are not right. My code is as below:
static void Index(int arr[], int n) {
for(int i=0;i<n;i++) {
int index = arr[i];
int value = arr[index];
arr[i]=value*value;
}
}
Below is the output that I am getting:
Original Array
4 3 1 2 0
Array after Squaring
0 4 16 256 0
Can anyone help me out here as to what am I doing wrong?
Assuming the numbers are within range [0, 46341), we can store both the old and the new values in the array during the process (as 32 bits are enough). Then after the first loop we do another one to discard the old values and square the new ones.
// assume array[i] is within range [0, 46341) for any i
static void f(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i] & 0xffff; // get old value
array[i] = array[j] << 16 | j; // put new and old values
}
for (int i = 0; i < array.length; i++) {
int j = array[i] >>> 16; // get new value
array[i] = j * j; // put new value squared
}
}
NOTE: This approach is valid only if length of array is less than 10.
I have completed this code using only one loop without using any extra space.
Although, I have set a flag to run the complete loop twice.
If you do not have any constraint of using one loop, you can avoid using the flag and simply use two loops.
Approach:
Index 0 1 2 3 4
Values 4 3 1 2 0
Updated value 04 23 31 12 40
You must have got the idea what I did here.
I put the values at tens place whose square is to be displayed.
Now you have to just have to iterate once more and put the square of tens place at that index
Here's the code:
void sq(int arr[], int n){
bool flag = false;
for(int i=0; i<n; i++){
if(!flag){
if(arr[arr[i]] < 10){
arr[i] += (arr[arr[i]] * 10);
}
else{
arr[i] += ((arr[arr[i]]%10) * 10);
}
}
if(i==n-1 && !flag){
i=0;
flag = true;
}
if(flag)
arr[i] = (arr[i]/10) * (arr[i]/10);
}
}
It is in C++.
The problem is you are changing the values in your original array. In you current implementation this is how your array changes on each iteration:
{4, 3, 1, 2, 0}
{0, 3, 1, 2, 0}
{0, 4, 1, 2, 0}
{0, 4, 16, 2, 0}
{0, 4, 16, 256, 0}
The problem is you still need the values stored in the original array for each iteration. So the solution is to leave the original array untouched and put your values into a new array.
public static void index(int arr[]) {
int[] arr2 = new int[arr.length];
for(int i=0;i<arr.length;i++) {
int index = arr[i];
int value = arr[index];
arr2[i]=value*value;
}
}
Values of arr2 in revised process:
{0, 0, 0, 0, 0}
{0, 0, 0, 0, 0}
{0, 4, 0, 0, 0}
{0, 4, 9, 0, 0}
{0, 4, 9, 1, 0}
{0, 4, 9, 1, 16}

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

how to order Arrays value as circular format in java?

i have array values as like
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
suppose if i pass value "5" to tat array, it should be ordered as like
{"5","6","7","8","9","10",1","2","3","4"};...
how to do?plz anyone help?
thank u
What you need is called rotation. You can use Collections.rotate() method. Convert the array to a list and pass it to the method. This will rotate the array in place since the list is backed by the array:
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
Collections.rotate(Arrays.asList(value), 5);
The above code will rotate the array by a distance of 5. The resulting value array:
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
Your question has two interpretations:
Rotate 5 steps, or
rotate the array so that 5 is the first element (regardless of where it is in the array).
Here is a solution for both alternatives:
import java.util.Arrays;
public class Test {
public static String[] rotateArray(String[] arr, int n) {
String[] rotated = new String[arr.length];
System.arraycopy(arr, n-1, rotated, 0, arr.length-n+1);
System.arraycopy(arr, 0, rotated, arr.length-n+1, n-1);
return rotated;
}
public static String[] rotateArrayTo(String[] arr, String head) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(head))
return rotateArray(arr, i + 1);
throw new IllegalArgumentException("Could not find " + head);
}
public static void main(String[] args) {
String[] value = {"1","2","3","4","5","6","7","8","9","10"};
// Rotate so that it starts at 5:th element
value = rotateArray(value, 5);
System.out.println(Arrays.toString(value));
// Rotate so that it starts with element "7"
value = rotateArrayTo(value, "7");
System.out.println(Arrays.toString(value));
}
}
Output:
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4]
[7, 8, 9, 10, 1, 2, 3, 4, 5, 6]
(ideone.com link)
first find the index of the entered value from the array..
and then in a loop move from the index to the final position.. and store these values in a new array.
after that, in the same result array, store the values from index 0 to the index of the entered value - 1.
You really don't need to store the values in a different array. Just find the index [say idx] of the value passed. And then start a loop from the start of the array and swap the values starting from idx.
For example -
idx = [some-value]
while [idx < arr.length]
temp = arr[i]
arr[i] = arr[idx]
arr[idx] = t
idx += 1
i += 1
Update:
I stand corrected by #aioobe. I simply worked out something for the 5th index - my bad. Here's something that works, if in case, you want to stay away from library functions -
private void slideLeft(String[] arr)
{
String t = arr[arr.length - 1];
String temp = null;
int next = -1;
for (int i = arr.length - 1; i >= 0; i--)
{
next = ( i == 0 ) ? arr.length - 1 : i - 1;
temp = arr[next];
arr[next] = t;
t = temp;
}
}
you'll need to call this method the number of times you need to shift the array members.
note: O(n^2) alert. not suitable for large shifts/arrays.

Categories