Trying to swap the maximum and the minimum numbers in an array - java

I'm trying to swap the maximum and minimum values in an array in my program.
Here is the code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int myArray[] = new int[25];
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter a number: ");
myArray[i] = in.nextInt();
}
int maximum = maxNumber(myArray);
int minimum = minNumber(myArray);
System.out.println(Arrays.toString(myArray));
}
public static int maxNumber(int[] arr) {
int maximumValue = arr[0];
//finds the maximum value in an array
for (int a = 1; a < arr.length; a++) {
if (arr[a] > maximumValue) {
maximumValue = arr[a];
}
}
return maximumValue;
}
public static int minNumber(int[] arr) {
int minimumValue = arr[0];
//finds the minimum value in an array
for (int a = 1; a < arr.length; a++) {
if (arr[a] < minimumValue) {
minimumValue = arr[a];
}
}
return minimumValue;
}
I have two separate functions to find the Maximum and Minimum values, but I'm stuck on the actual swapping of the values. The two functions work as I've used them for another program, but I'm not sure if they would work for this program.
At first I was thinking of finding them by setting them equal to each other in some way, but that led to nothing.
Any help would be appreciated.

public static void main(String... args) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[25];
System.out.format("Enter array int numbers (%d in total): ", arr.length);
for (int i = 0; i < arr.length; i++)
arr[i] = scan.nextInt();
System.out.println(Arrays.toString(arr));
swamMinMax(arr);
System.out.println(Arrays.toString(arr));
}
private static void swamMinMax(int[] arr) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
min = Math.min(min, arr[i]);
max = Math.max(max, arr[i]);
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == min)
arr[i] = max;
else if (arr[i] == max)
arr[i] = min;
}
}
Output:
Enter array int numbers (25 in total): 1 2 3 4 5 6 7 8 9 10 -1 -1 -1 14 15 16 17 18 19 20 21 22 23 66 66
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, -1, -1, 1, 1, 1, 17, 18, 19, 20, 21, 22, 23, 66, 66]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 66, 66, 66, 1, 1, 1, 17, 18, 19, 20, 21, 22, 23, -1, -1]

You were real close. I copied some of the code and commented where the changes need to be made. You can still use your existing code to populate the array from the console.
Also, kudos for assigning the first element in the array to min or max and starting your loop at 1. A lot of folks don't think about doing that.
int myArray[] = {1,10,-5,99,48,-22,43, 44,100,2};
System.out.println(Arrays.toString(myArray)); // print original array
int maxIdx = maxNumber(myArray); // get index of max
int minIdx = minNumber(myArray); // get index of min
// now swap max and min using the returned indices.
int save = myArray[maxIdx];
myArray[maxIdx] = myArray[minIdx];
myArray[minIdx] = save;
System.out.println(Arrays.toString(myArray)); // print the altered array
public static int maxNumber(int[] arr) {
int maximumValue = arr[0];
// finds the maximum value in an array
int idx = 0; //idx = 0 to start
for (int a = 1; a < arr.length; a++) {
if (arr[a] > maximumValue) {
idx = a; //save index of current max
maximumValue = arr[a];
}
}
return idx; // return index of max
}
public static int minNumber(int[] arr) {
int minimumValue = arr[0];
// finds the minimum value in an array
int idx = 0; // idx = 0 to start
for (int a = 1; a < arr.length; a++) {
if (arr[a] < minimumValue) {
idx = a; // save index of current min
minimumValue = arr[a];
}
}
return idx; // return index of min
}
This would print
[1, 10, -5, 99, 48, -22, 43, 44, 100, 2]
[1, 10, -5, 99, 48, 100, 43, 44, -22, 2]

You can use IntStream to find indexes of the maximum and minimum elements and then swap their values:
int[] arr = {1, 3, 5, 6, 4, 2, 8, 7, 9, -1, -3};
// indexes of the maximum and minimum elements
int max = IntStream.range(0, arr.length)
.boxed().max(Comparator.comparing(i -> arr[i])).orElse(-1);
int min = IntStream.range(0, arr.length)
.boxed().min(Comparator.comparing(i -> arr[i])).orElse(-1);
// swap the values
int temp = arr[max];
arr[max] = arr[min];
arr[min] = temp;
System.out.println(Arrays.toString(arr));
// [1, 3, 5, 6, 4, 2, 8, 7, -3, -1, 9]

Related

Rearrange an array such that arr[i] = i

Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19]
Approach
1. Nav­i­gate the array.
Check if a[i] = -1, if yes then ignore it.
If a[i] != -1, Check if element a[i] is at its cor­rect posi­tion (i=A[i]). If yes then ignore it.
If a[i] != -1 and ele­ment a[i] is not at its cor­rect posi­tion (i!=A[i]) then place it to its correct posi­tion, but there are two conditions:
(i).Either A[i] is vacant, means A[i] = -1, then just put A[i] = i .
(ii).OR A[i] is not vacant, means A[i] = x, then int y=x put A[i] = i. Now, we need to place y to its cor­rect place, so repeat from step 3.
What would be the time complexity of below solution?
public static int[] fix(int[] A) {
for (int i = 0, x = A[i]; i < A.length; i++) {
if (x == -1 || x == i)
continue;
// check if desired place is not vacant
while (A[x] != -1 && A[x] != x) {
int y = A[x]; // store the value from desired place
A[x] = x; // place the x to its correct position
x = y; // now y will become x, now search the place for x
}
A[x] = x; // place the x to its correct position
// check if while loop hasn't set the correct value at A[i]
if (A[i] != i)
A[i] = -1; // if not then put -1 at the vacated place
}
return A;
}
I can offer you two algorithms.
First one: using extra array, time complexity is O(n), with O(n) additional memory
public static int[] fix(int[] arr) {
int[] res = new int[arr.length];
Arrays.fill(res, -1);
for (int i = 0; i < arr.length; i++)
if (arr[i] != -1)
res[arr[i]] = arr[i];
return res;
}
Second one: in place, time complexity is O(n^2) in worst case and O(n) in average case, without additional memory
public static int[] fix(int[] arr) {
int i;
while ((i = findIncorrectPosition(arr)) >= 0) {
while (arr[i] != -1 && arr[i] != i) {
swap(arr, i, arr[i]);
}
}
return arr;
}
...plus two private support methods:
private static int findIncorrectPosition(int[] arr) {
for (int i = 0; i < arr.length; i++)
if (arr[i] != -1 && arr[i] != i)
return i;
return -1;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
f(n) = O(n) using swapping methodology #Swift
for i in stride(from: 0, to: array.count, by: 1){
if(array[i] >= 0 && array[i] != i){
let ele = array[array[i]]
array[array[i]] = array[i]
array[i] = ele
}
}
for k in stride(from: 0, to: array.count, by:1 ){
print(" ",array[k])
}

Switch Maximum and Minimum values in Two Dimensional Array

I'm trying to switch the minimum and maximum values of the array.
My code:
public static void swap(int[][] a, int i0, int j0, int i1, int j1) {
int temp = a[i0][j0];
a[i0][j0] = a[i1][j1];
a[i1][j1] = temp;
}
public static void main(String args[]){
int max = 0, min = 0, tmpI = 0, tmpJ = 0, tmpI1 = 0, tmpJ1 = 0;
int[][] a = {{10,9,20} , {2,10,10}};
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (min > a[i][j]) {
min = a[i][j];
tmpI1 = i; tmpJ1 = j;
}
if (max < a[i][j]) {
max = a[i][j];
tmpI = i; tmpJ = j;
}
}
}
System.out.println(Arrays.deepToString(a));
swap(a,tmpI1,tmpJ1,tmpI,tmpJ);
System.out.println(Arrays.deepToString(a));
}
Output:
[[10, 9, 20], [2, 10, 10]]
[[20, 9, 10], [2, 10, 10]]
It is switching only to the first number for some reason. Any help? I'm new to java.
The issue is with your initial value of min (0). When you say,
if (min > a[i][j]) {
it will never be true (because 0 is less than your numbers). Change the declaration of min to something like
min = Integer.MAX_VALUE
because every int value will be less than that.

How to transform an array to the table in Java?

Suppose, I have an array like
[1,2,3,4,5,6,7,8,9,10,11,12]
Are there any standard methods to transform it to the table with N columns?
For example, if N=3:
[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
or if N=4:
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
etc.
With Java 8, you can use an IntStream to generate the corresponding indexes that you'll give to Arrays.copyOfRange.
I answered a sort of a similar question and you can find the logic there but here's it's slightly modified to take the array as parameter:
static List<int[]> partitionIntoList(int[] arr, int pageSize) {
return IntStream.range(0, (arr.length + pageSize - 1) / pageSize)
.mapToObj(i -> Arrays.copyOfRange(arr, i * pageSize, min(pageSize * (i + 1), arr.length)))
.collect(toList());
}
static int[][] partitionIntoArray(int[] arr, int pageSize) {
return IntStream.range(0, (arr.length + pageSize - 1) / pageSize)
.mapToObj(i -> Arrays.copyOfRange(arr, i * pageSize, min(pageSize * (i + 1), arr.length)))
.toArray(int[][]::new);
}
Note that if pageSize does not partition perfectly the input's size, the remaining elements are added in the last int array.
For example,
partitionIntoArray(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, 4);
outputs:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
and if you take a page size of 5, the two last elements will be added to a third array:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12]]
Hope it helps! :)
Just using for loops:
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12};
int n = 3;
int m = (int) Math.ceil( ( (double) array.length ) / n );
int[][] table = new int[m][n];
int k = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (k < array.length) {
table[i][j] = array[k];
k++;
}
}
}
The output should be what you are asking for.
Not really but you can create one easily using some math and a loop:
public int[][] getTable(int[] arr, int n) {
int[][] table = new int[(int)Math.ceil(arr.length / (float)n)][n];
for (int i = 0, row = 0, column = 0; i < arr.length; i++) {
if (i % n == 0 && i != 0) {
row++;
column = 0;
}
table[row][column++] = arr[i];
}
return table;
}
We could do it this way :
int n = 5; // what ever size you want to break it with
int[] bytes = {1,2,3,4,5,6,7,8,9,10,11,12};
int length = bytes.length;
int counter = 0;
int newSize = length % n == 0 ? length/n : (length/n)+1;
int[][] newArray = new int[newSize][n];
for (int i = 0; i < length - n + 1; i += n)
newArray[counter++] = Arrays.copyOfRange(bytes, i, i + n);
if (length % n != 0)
newArray[counter] = Arrays.copyOfRange(bytes, length - length % n, length);

Maximum Contiguous Subsequence Sum and sequence

I am trying to find to the max sum of an array and print the corresponding sequence that produces that max sum. I have been able to get the correct sum but when I try to print the sequence for some of the test arrays my program leaves off one of the indices. For example, for the array [1, -1, 2, 3, -2] my program finds the max sum of 5 but it only prints 1, -1, 2 instead of 1, -1, 2, 3. I know the problem is inside my for loop and my count variable not incrementing correctly but I do not know how to fix it.
import java.util.*;
public class practice
{
public static void main(String args[])
{
int arr[] = {1, -1, 2, 3, -2};
int arr2[] = {1, 12, -2, -15, 10};
int arr3[] = {0, -1, -3, -5, -6};
int arr4[] = {1, 2, 3, 4, 5};
int arr5[] = {1, 12, -2, 15, 10};
subsequence(arr);
subsequence(arr2);
subsequence(arr3);
subsequence(arr4);
subsequence(arr5);
}
public static void subsequence(int[] arr)
{
int max = 0;
int tempMax = 0;
int count = 0;
// My problem is in here:
for (int i = 0; i < arr.length; i++)
{
tempMax += arr[i];
if (max < tempMax)
{
max = tempMax;
count++;
}
}
System.out.println("count = " + count);
System.out.println("Max sum is " + max);
System.out.print("Sequence is: ");
for (int j = 0; j < count; j++)
System.out.print(arr[j] + " ");
System.out.println("\n");
}
}
here is my output
count = 3
Max sum is 5
Sequence is: 1 -1 2
count = 2
Max sum is 13
Sequence is: 1 12
count = 0
Max sum is 0
Sequence is:
count = 5
Max sum is 15
Sequence is: 1 2 3 4 5
count = 4
Max sum is 36
Sequence is: 1 12 -2 15
here is my edited code:
public class practice
{
public static void main(String args[])
{
int arr[] = {1, -1, 2, 3, -2};
int arr2[] = {1, 12, -2, -15, 10};
int arr3[] = {0, -1, -3, -5, -6};
int arr4[] = {-1, 2, 3, -4, -5};
int arr5[] = {1, 12, -2, 15, 10};
subsequence(arr);
subsequence(arr2);
subsequence(arr3);
subsequence(arr4);
subsequence(arr5);
}
public static void subsequence(int[] arr)
{
int max = 0;
int tempMax = 0;
int count = 0;
int start = 0;
int end = 0;
if (arr[0] < 0)
start++;
for (int i = start; i < arr.length; i++)
{
tempMax += arr[i];
if (max < tempMax)
{
max = tempMax;
count = i;
}
if (Math.abs(arr[i]) < tempMax)
end = i;
}
System.out.println("count = " + count);
System.out.println("Max sum is " + max);
System.out.print("Sequence is: ");
if (arr[end] < 0)
end--;
for (int j = start; j <= end; j++)
System.out.print(arr[j] + " ");
System.out.println("\n");
}
}
and here is my new output:
count = 3
Max sum is 5
Sequence is: 1 -1 2 3
count = 1
Max sum is 13
Sequence is: 1 12
count = 0
Max sum is 0
Sequence is: 0
count = 2
Max sum is 5
Sequence is: 2 3
count = 4
Max sum is 36
Sequence is: 1 12 -2 15 10
Your count variable doesn't make sense, since you only increment it if you find a new candidate for the maximum. When you find a new maximum candidate, set count to the current index :
count = i;
Then when you print the sequence, change the condition to j <= count.
BTW, I'm not sure your implementation is correct. You always return a sub-sequence that starts in the beginning of the array. What if the sub-sequence with the max sum doesn't start at the beginning? (for example, in [-1,2,3,4,5], the max sequence is [2,3,4,5]).

how to get more than one minumum value from an int array?

I am trying to get at least 5 minimum values from an array of int's. My code attached works but it skips few values!
public static void main(String[] args) {
int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
int min = 0;
int index = 0;
String output = "";
for (int x = 0; x < 5; x++){
min = array[x];
index++;
for(int i = index, limit = array.length; i < limit; ++i){
if(array[i] <= min){
min = array[i];
index = i + 1;
break;
}
}
output += index + "\t";
}
System.out.println(output);
}
Arrays.sort(array);
return Arrays.copyOfRange(array, 0, 5);
If you don't want to mutate the array passed in (ie you want to leave it unsorted), add this line first:
int[] array = Arrays.copyOf(array);
Perhaps you could sort the array using Arrays.sort() and then take the first five values:
Arrays.sort(array);
Now array[0] to array[4] contain the lowest 5 values.
If you only want to get 5 minimum values, I agree with Bohemian's Answer.
If you want to show the position of the array,such as 1,2,4,7,10, your demo is skips 2,
try my test...
public static void main(String[] args) {
int getNum = 5;
int step = 0;
String output = "";
int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
int arrayClone[] = array.clone();
Arrays.sort(array);
int arrayResult[] = Arrays.copyOfRange(array, 0, getNum); //the arrayResult is what you want minimum values
ploop:for (int i:arrayResult) {
int index = 1;
for (int j :arrayClone) {
if(j==i){
step++;
output += index + "\t";
if (step>=getNum) {
break ploop;
}
}
index++;
}
}
System.out.println(output);
}

Categories