Swap even odd indices in a java int array - java

I am trying to swap numbers in int array according to even and odd indices.
So far,
I was able to work out how to target even and odd indices but,
then because of nested for loops I am not able to print all the elements in one array.
Here is my code -
public class SwapIndexes {
public static void main(String []args) {
int temp;
int[] arr = {1, 2, 3, 4, 5, 6};
for (int j = 0; j < arr.length; j += 2) {
for (int k = 1; k < arr.length; k += 2) {
temp = arr[j];
arr[j] = arr[k];
arr[k] = temp;
System.out.print(arr[k]);
}
}
}
}
This code gives 124312531 as output for arr[k] and gives 246124312 as output for arr[j]. I want the output to be
2,1,4,3,6,5

I really don't understand why you have two loops. You only need one since you need to browse the array only once. Here is the code with one loop: j will have all the odd indexes and then you switch j-1 and j.
Since no specification is given about the behavior of an array with an odd number of elements, in that case it doesn't modify the last value. If needed, you can throw an exception.
public static void main(String []args) {
int temp;
int[] arr = {1, 2, 3, 4, 5, 6};
for (int j = 1; j < arr.length; j += 2) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
System.out.print(Arrays.toString(arr));
}

Well, I don't know why you have use two loop because the idea was there.
Remove the second loop, set k to j + 1 and the logic is here (commented the code that you don't need.
for (int j = 0; j < arr.length; j += 2) {
//for (int k = 1; k < arr.length; k += 2) {
int k = j + 1;
temp = arr[j];
arr[j] = arr[k];
arr[k] = temp;
//System.out.print(arr[k]);
//}
}
System.out.print(Arrays.toString(arr));
Now, you need to prevent exception to occurs for uneven length.
I like to simple use a slightly different loop :
for (int j = 1; j < arr.length; j += 2) {
int k = j - 1;
...
}
System.out.print(Arrays.toString(arr));
All you have to do is check if there is at least 2 cells, which make sense if you want to reverse an array like this
if(arr.length < 2)
return;
Test 1:
{1, 2, 3, 4, 5, 6}
[2, 1, 4, 3, 6, 5]
Test 2:
{1, 2, 3, 4, 5, 6, 7}
[2, 1, 4, 3, 6, 5, 7]

Related

How to implement a descending selection sort

The method I have to create should take as parameter an array of integers and return the integer array with its contents sorted in descending order — largest to smallest.
Note - no libraries should be used in your implementation for this method.
I've attempted to use a regular selection sort and using a swap at the end but syntax errors just occurred:
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
If you call the method on the array [3, 6, 8,
3, 5, 7, 1], then the method should return the array [8, 7, 6, 5, 3, 3, 1].
Once you add the implementation of swap to your code (and put it all inside a class), it produces exactly the output you wanted it to. Maybe you thought swap was a java uitl, which it is for Collections, but an array is not a Collection.
So very little has changed in the below:
public class soSelect{ //embed in class, added
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void swap(int[] a, int i, int j){ //had to implement it
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
}//added outer brace
I ran it in java doodle and it printed:
task: [8, 7, 6, 5, 3, 3, 1]
I did not test beyond that, but this should at least get you unstuck, or, at best, finished. For sure you could compare with the implementation to which the above comment points you.

My matrix multiplication function is returning blank or incorrect outputs

The function I've written to multiply matrices is not properly out putting or is giving me a blank one. It managed to give me one correct output though I can't get find that array anymore.
When I inputted
int[][] test = new int[][]{
{2, 4},
{5, 3},
{3, 5}
};
int[][] test2 = new int[][]{
{3, 4, 2},
{5, 1, 2}
};
It's return an array of zeros
int[][] toRet = new int[arr1.length][arr2[0].length];
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2[0].length; j++){
for(int k = 02; k < arr1[0].length; k++){
toRet[i][j] += arr1[i][k] * arr2[k][j];
}
}
}
return toRet;
}```
It worked for a minute and I didn't change anything but my test.
Your 3rd loop is wrong. You initialized k with 2, it should be k=0. Now taking your
example. Your matrix is
int[][] test = new int[][]{
{2, 4},
{5, 3},
{3, 5}
};
arr1[0].length will return 2 as there are 2 elements only and k < arr1[0].length will return false. So your 3rd loop will exit without any summation and multiplications. That is why you are getting all elements 0.
Change your 3rd loop to k=0, which looks like this:
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2[0].length; j++){
for(int k = 0; k < arr1[0].length; k++){
toRet[i][j] += arr1[i][k] * arr2[k][j];
}
}
}

Make new int array double the size of an array copy the first numbers and put others in reverse without using methods

Lets say I input array {1,2,3,4} and I want to make a new one {1,2,3,4,4,3,2,1}.
import java.util.Scanner;
public class Task2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
for(int i = 0; i < arr.length; i++){
System.out.println("Please enter number!");
arr[i]=sc.nextInt();
}
int[] actualArr = new int[arr.length*2];
for(int j = 0; j < arr.length; j++){
actualArr[j]=arr[j];
}
for (int k = arr.length - 1; k >= 0; k--) { //problem loop
actualArr[arr.length] = arr[k];
}
for (int g = 0; g < actualArr.length; g++) {
System.out.print(actualArr[g] + " ");
}
}
}
Why do I get 1 2 3 4 1 0 0 0 ? My int k starts from 3 but I get the [0] index from int[]arr which is 1 and not the last which is 4, also how can i copy the rest of the first array in reverse order?
Your problem is on this line insithe the for loop:
actualArr[arr.length] = arr[k];
arr.length will always be 4, so you will always update the 5th element (element at index 4 because arrays are zero-based in Java) in your actualArr array leaving the remaining slots of the array with the default int value 0. Look how actualArr changes on each iteration of that loop:
actualArr = {1, 2, 3, 4, 4, 0, 0, 0} // 1st iteration
actualArr = {1, 2, 3, 4, 3, 0, 0, 0} // 2nd iteration
actualArr = {1, 2, 3, 4, 2, 0, 0, 0} // 3rd iteration
actualArr = {1, 2, 3, 4, 1, 0, 0, 0} // 4th iteration and final output
You can do this to fill the array correctly:
for (int k = arr.length - 1; k >= 0; k--) {
actualArr[actualArr.length - k - 1] = arr[k];
}
The expression actualArr.length - k - 1 will result in a sequence from 4-7 filling the array as you want.
You may can define a new integer like z and z is initial for your new array (actualArr):
int[] actualArr = new int[arr.length*2];
int z=0;
for(int j = 0; j < arr.length; j++){
actualArr[z]=arr[j];
z++;
}
for (int k = arr.length-1 ; k >= 0; k--) { //problem loop
actualArr[z] = arr[k];
z++;
}

K-complementary pairs using given array of integers effectively

I am very new to programming. I need to find the K-complementary pairs using given array of integers effectively. I have written the below code. It includes the duplication. I need to eliminate that duplication. So please help me to remove that duplication and please suggest if there is a better efficient way to do it.
public class KComplexityOfArray {
public static StringBuffer oldFunction(int arr[], int k) {
int result = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (i != j && arr[i] + arr[j] == k) {
sb.append(arr[i] + "," + arr[j]);
result++;
}
}
}
System.out.println(result);
return sb;
}
public static void main(String[] args) {
int[] intArray1 = new int[]{4, 5, 6, 3, 1, 8, -7, -6, 7};
int[] intArray2 = new int[]{1, 2, 7, 5, 6, 3};
int[] intArray = new int[]{4, 5, 6, 3, 1, 8, -7, -6};
int k = 9;
System.out.println("No of k complementary pairs : " + oldFunction(intArray2, k));
}
}
Please anybody help me to sort this out. Thanks
This code is wrong, considering two different elements constitute a pair:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
Instead you should do j=i+1:
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
please suggest if there is a better efficient way to do it.
Your solution has TC of O(N^2). Instead you can reduce it in O(NlogN). See how:
Sort the array.
Use two index positions, i and j set to 0 and N-1 resp.
Now, if the sum of a[i] and a[j] equals k, print it. Else if sum < K, advance i by 1, else reduce j by 1.
Repeat Step 3 till (i < j)
Step 1 takes O(NlogN) and remaining steps take O(N); combining both incurs O(NLogN)
If I understand correctly your problem, you should replace
for (int j = 0; j < arr.length; j++) {
with
for (int j = i+1; j < arr.length; j++) {

Inserting an integer into a sorted array

I'm trying to write a method that takes a sorted array and an integer, creates a new array that is 1 size larger, and inserts the new integer and keeps it sorted.
I've tried a few different implementations and had them to work - but for this specific one, I can't grasp where it's going wrong.
int[] array1 = new int[]{1, 2, 3, 4, 6, 7, 8};
int[] printArray = insert(array1, 5);
are the arrays, and the method is
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
for(int i = 0; i < a.length; i++) {
if(k < s[i]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
This method prints out 1, 2, 3, 4, 6, 7, 8, 0, instead of 1, 2, 3, 4, 5, 6, 7, 8.
Change
if(k < s[i]) {
to
if(k < a[i]) {
in line 4.
Actually in the following line you are creating an array with all elements zero:
int[] s = new int[a.length + 1];
s[0] to s[7] will be 0.
Your loop counter i runs from 0 to a.length but the point to note is all the elements of array s will be zero. You are comparing k with s[i] which is zero and for that reason the shifting of arrays never happen (if block never executes).
You need to do two things to fix it.
Initialize element zero of s with the value of a[0].
Compare element with previous element to figure out position to insert.
The final code is:
public static int[] insert(int[] a, int k) {
int[] s = new int[a.length + 1];
s[0] = a[0];
for(int i = 1; i < a.length; i++) {
if(k < s[i-1]) {
s[i] = k;
for(int j = i + 1; j < s.length; j++) {
s[j] = a[i];
i++;
}
return s;
} else {
s[i] = a[i];
}
}
return s;
}
Now you will get:
[1, 2, 3, 4, 6, 5, 7, 8]
I would start by using Arrays.copyOf(int[], int) to create a new array that is one larger than the input. Then iterate that array until I reached the index that the new value belongs at. Then use System.arraycopy(Object,int,Object,int,int) to copy the values into the end of the array. That might look something like
public static int[] insert(int[] a, int k) {
int[] s = Arrays.copyOf(a, a.length + 1);
for (int i = 0; i < s.length; i++) {
if (a[i] < k) {
continue;
}
System.arraycopy(a, i, s, i + 1, s.length - i - 1);
s[i] = k;
break;
}
return s;
}
Which I tested with Arrays.toString(int[]) like
public static void main(String s[]) throws IOException {
int[] array1 = new int[] { 1, 2, 3, 4, 6, 7, 8 };
int[] printArray = insert(array1, 5);
System.out.println(Arrays.toString(printArray));
}
And I get the (expected)
[1, 2, 3, 4, 5, 6, 7, 8]

Categories

Resources