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]).
Related
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]
I wrote a method for finding and deriving the largest number of increasing (decreasing) elements of the matrix, going in a row. But it seems that the code is not quite good.
private void findLargestIncreasingAndDecreasingElements() {
int[][] matrix = getMatrix();
int[] oneArray = new int[matrix.length * matrix.length];
int r = 0;
int min = 0;
int max = 0;
int h = 0;
int m = 0;
int h1 = 0;
for (int[] x : matrix) {
int c = 0;
for (int z : x) {
oneArray[c++] = z;
}
}
for (int i = 0; i < oneArray.length - 1; i++) {
if (oneArray[i] < oneArray[i + 1]) {
r += 1;
if (r > max) {
max = r;
h = i + 1;
}
} else {
r = 0;
}
if (oneArray[i] > oneArray[i + 1]) {
m += 1;
if (m > min) {
min = m;
h1 = i + 1;
}
} else {
m = 0;
}
}
System.out.println("Maximum sequence of increasing numbers:");
int[] l = new int[max + 1];
System.arraycopy(oneArray, (h - max), l, 0, (max + 1));
System.out.println(java.util.Arrays.toString(l) + " " + (max + 1));
System.out.println("Maximum sequence of decreasing numbers:");
int[] t = new int[min + 1];
System.arraycopy(oneArray, (h1 - min), t, 0, (min + 1));
System.out.println(java.util.Arrays.toString(t) + " " + (min + 1));
}
Maybe someone knows how to make the algorithm better?
Sometimes incorrect output. For example:
{{-3, -3, 3, -5, 2}, {1, -2, 5, -2, -1}, {5, -3, -4, 2, 5}, {4, 4, -2, 3, 5}, {-2, 5, 4, 0, 0}}
outputs incremental:[-2, 5]
although there is [-2, 3, 5]
In the code that flattens the matrix, c gets reset on each pass through the outer loop, so only the final row of the matrix actually makes it into oneArray. Moving the int c = 0; line out of the loop will allow the whole matrix to get copied into oneArray so your code can find sequences outside the final row.
I'm working on an assignment for a beginning Java course and I am completely stuck on this problem.
Write a program that computes the sum of the differences of pairs of numbers in an array. For example if the array is [2, 3, 7, 8, 9, 12] the sum of the differences of pairs is
(2-3) + (7-8) + (9-12)
** we are not allowed to use built in Java functions.
Here is what I have so far.. (I know it is terrible)
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i++)
{
for(int j = i+1; j < A.length; j++)
sum = (A[i] - A[j]);
}
System.out.println(sum);
}
}
When you use that nested cycle you're doing this:
i = 0,
j = 1,
sum = 3 - 4;
// next cycle,
i = 0,
j = 2,
sum = 3 - 5;
// etc...,
i = 1,
j = 2,
sum = 4 - 5,
// etc..;
Which means for each value of A[i] you're making the difference of A[i] and all the values in the array for A[j + 1]. Also you're not updating the sum variable. When you do sum = A[i] - A[i + 1] because this operation only gives the variable sum a new value. What you want is sum+= value, which means sum = sum + newValue (newValue = A[i] - A[i +1]). This operation adds the new value to the old value stored in sum.
So what you need to do is add the two values and jump 2 indexes (i+=2) so you don't do (for example) 3-4, 4-5, 5-6 etc. what you want is 3-4, 5-6, etc.
Try this:
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i+=2)
{
sum +=(A[i] - A[i + 1]);
}
System.out.println(sum);
}
}
I am not sure what are you stuck on exactly but looks like you are not adding the sum.
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0,i=0;
while(i<A.length){
sum+= (A[i] - A[i++]);
}
System.out.println(sum);
}
I have to segregate the even and odd numbers in a 2D array in java in two different rows (even in row 1 and odd in row two). I have included the output of my code bellow here is what I have:
class TwoDimensionArrays {
public static void main(String[] args) {
int sum = 0;
int row = 2;
int column = 10;
int[][] iArrays = new int[row][column];
for(int rowCount = 0; rowCount < iArrays.length /*&& rowCount % 2 == 0*/; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length /*&& columnCount % 2 != 0*/; columnCount++) {
if(columnCount % 2 != 0 /*&& rowCount % 2 == 0*/) {
iArrays[rowCount][columnCount] = columnCount + 1;
}
}
}
System.out.println("The array has " + iArrays.length + " rows");
System.out.println("The array has " + iArrays[0].length + " columns");
for(int rowCount = 0; rowCount < iArrays.length; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length; columnCount++) {
System.out.print(iArrays[rowCount][columnCount] + " ");
sum += iArrays[rowCount][columnCount];
}
System.out.println();
}
System.out.println("The sum is: " +sum);
}
}
//OUTPUT//
/*The array has 2 rows
The array has 10 columns
0 2 0 4 0 6 0 8 0 10
0 2 0 4 0 6 0 8 0 10
The sum is: 60*/
Can anyone lend a hand?
Thank you in advance.
Instead of passing over the list twice try this:
for(int v = 0; v < 20; v++) {
iArrays[v % 2][(int)v/2] = v;
}
This will set iArrays to:
[[0,2,4,6,8,10,12,14,16,18],
[1,3,5,7,9,11,13,15,17,19]]
What is happening is the row is being set to the remainder of v % 2 (0 if v is even, 1 if v is odd) and the col is being set to the corresponding index (with the cast to int to drop any fraction). You can even generalize it like this:
public static int[][] group(int groups, int size){
int[][] output = new int[groups][size];
for(int value = 0; value < (groups*size); value++) {
output[value % groups][(int)value/groups] = value;
}
return output;
}
Then a call to group(2, 10) will return:
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]
If I understand your question, one solution is to iterate the array from 0 to COLUMN and set each successive slot to two plus the previous slots value (starting with 0 for even and 1 for odd). Like,
public static void main(String arg[]) {
final int ROW = 2;
final int COLUMN = 10;
int[][] iArrays = new int[ROW][COLUMN];
for (int i = 0; i < COLUMN; i++) {
iArrays[0][i] = (i > 0) ? iArrays[0][i - 1] + 2 : 0; // 0,2,4,6...
iArrays[1][i] = (i > 0) ? iArrays[1][i - 1] + 2 : 1; // 1,3,5,7...
}
System.out.println(Arrays.deepToString(iArrays));
}
Output is
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]
I have an array, say
int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};
I need to append each of the 5 neighboring elements and assign them to a new array b with length=(a.length/5); and i want to append the 5 neighboring elements so that I have:
int b[]={20101,10211,10101}; I need to do this for various length arrays, in most cases with length of a being greater than 15.
Any help would be greatly appreciated, I'm programming in Java.
Thanks in advance.
It's pretty straighforward:
// Assuming a.length % 5 == 0.
int[] b = new int[a.length / 5];
for (int i = 0; i < a.length; i += 5) {
b[i/5] = a[i]*10000 + a[i+1]*1000 + a[i+2]*100 + a[i+3]*10 + a[i+4];
}
This sounds like a homework question, so I won't give you the complete solution, but the basic rundown is:
Compute the length of b: len = a.length / 5
Construct b with that many elements.
Initialize an index variable to point to the first element in a
For each element in b:
Construct the value for that element from a[idx]...a[idx+4]
Advance the index into a by 5.
Also note that you may need to verify that the input a is actually a multiple of 5 in length.
This works with (a.length % 5) != 0, and keeps leading zeroes (by storing digits into String).
int a[]={2,0,1,0,1,1,0,2,1,1,1,0,1,0,1,0,0,7};
final int N = 5;
String b[] = new String[(a.length + N - 1)/ N];
StringBuilder sb = new StringBuilder(N);
int x = 0;
for (int i = 0; i < b.length; i++) {
sb.setLength(0);
for (int k = 0; k < N && x < a.length; k++) {
sb.append(a[x++]);
}
b[i] = sb.toString();
}
System.out.println(java.util.Arrays.toString(b));
// prints "[20101, 10211, 10101, 007]"
Alternately, you can also use regex:
String[] arr =
java.util.Arrays.toString(a)
.replaceAll("\\D", "")
.split("(?<=\\G.{5})");
System.out.println(java.util.Arrays.toString(arr));
// prints "[20101, 10211, 10101, 007]"
Basically this uses Arrays.toString(int[]) to append all digits into one long String, then removes all non-digits \D, then uses \G-anchored lookbehind to split every .{5}
Naive approach.
import java.util.ArrayList;
/* Naive approach */
public class j2728476 {
public static void main(String[] args) {
int a[] = {2,0,1,0,1,1,0,2,1,1,1,0,1,0,1};
ArrayList<String> al = new ArrayList<String>();
String s = "";
for (int i = 0; i < a.length; i++) {
if (i % 5 == 0 && i != 0) {
al.add(s);
s = "" + a[i];
} else {
s += a[i];
}
}
al.add(s);
for (String t : al) {
// convert values to ints ...
System.out.println(t);
}
}
}
Will print:
20101
10211
10101
import java.util.Arrays;
public class MainClass {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 1);
System.out.println("Didn't find 1 # "
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
}
It will print
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 # -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8