Java Array sort by means of a comparator - java

The complete code can be found at: https://skydrive.live.com/redir?resid=7B7D2F11B13EF9C9!54468&authkey=!AD4fD8sGgc7oJIE
This is part of the code:
g_sorted = 0;
for (int l_loop = 0; l_loop < l_length; l_loop++)
{
if (!l_IntegerArray[l_loop].equals(g_exclude))
{
g_tag[g_sorted] = l_loop;
g_tosort_Integer[g_sorted] = l_IntegerArray[l_loop];
g_sorted++;
}
} // for (int l_loop = 0; l_loop < p_toSort; l_loop++)
Arrays.sort
(g_tag, 0, g_sorted, new Comparator<Integer>()
{
public int compare(Integer i1, Integer i2)
{
return Integer.compare(g_tosort_Integer[i1], g_tosort_Integer[i2]);
}
}
);
g_tosort_Integer, g_tag, g_tosort_Integer are 'Integer'.
g_exclude is used to exclude items which must not be part of the sort.
When no items are excluded (no item has the value equal to g_exclude or the if-statement is commented), everything works fine.
When 1 or more items are excluded I get a NullPointerException:
Exception in thread "main" java.lang.NullPointerException
at TestSort$1.compare(TestSort.java:53)
at TestSort$1.compare(TestSort.java:50)
at java.util.TimSort.binarySort(TimSort.java:265)
at java.util.TimSort.sort(TimSort.java:190)
at java.util.Arrays.sort(Arrays.java:727)
at TestSort.<init>(TestSort.java:48)
at TestSort.main(TestSort.java:71)
Can someone explain this to me ? Thanks.

This is how to solve. I kept your class "structure", but I took the liberty of changing variable names to get clearer what I was doing. You asked how to order an array not changing the order of elements, but changing a index upon it.
Here's the code.
public class TestSort {
int c_maxSort = 10000;
Integer[] unsortedAndFiltered = new Integer[c_maxSort];
Integer[] index = new Integer[c_maxSort];
public TestSort() {
Integer exclude = 0;
int newPosition;
int lengthOfOriginalArray;
Integer[] originalArray = { 5, 3, 0, 2, 7, 1, 5, 6, 8, 4 };
lengthOfOriginalArray = originalArray.length;
System.out.print("Original: ");
for (int i = 0; i < lengthOfOriginalArray; i++)
System.out.print(originalArray[i] + " ");
System.out.println(" - Length: " + lengthOfOriginalArray);
newPosition = 0;
for (int i = 0; i < lengthOfOriginalArray; i++) {
if (!originalArray[i].equals(exclude)) {
index[newPosition] = newPosition;
unsortedAndFiltered[newPosition] = originalArray[i];
newPosition++;
}
}
System.out.println("Tags: ");
for (int i = 0; i < newPosition; i++)
System.out.print(index[i] + " ");
System.out.println("");
System.out.println("Unsorted numbers: ");
for (int l_loop = 0; l_loop < newPosition; l_loop++)
System.out.print(unsortedAndFiltered[l_loop] + " ");
System.out.println("");
int deleted = lengthOfOriginalArray - newPosition;
Arrays.sort(index, 0, newPosition, new IndirectedComparator(unsortedAndFiltered, index));
System.out.println("Sorted Tags: ");
for (int i = 0; i < newPosition; i++)
System.out.print(index[i] + " ");
System.out.println("");
System.out.println("Sorted Numbers: ");
for (int i = 0; i < newPosition; i++)
System.out.print(unsortedAndFiltered[index[i]] + " ");
System.out.println("");
}
public static void main(String[] args) {
new TestSort();
}
}
where the comparator is coded like this:
public class IndirectedComparator implements Comparator<Integer> {
private Integer[] array;
private Integer[] index;
public IndirectedComparator(Integer [] array, Integer[] index){
this.array = array;
this.index = new Integer[index.length];
System.arraycopy(index, 0, this.index, 0, index.length);
}
#Override
public int compare(Integer i1, Integer i2) {
return Integer.compare(array[index[i1]], array[index[i2]]);
}
}
This is my execution:
Original: 5 3 0 2 7 1 5 6 8 4 - Length: 10
Tags:
0 1 2 3 4 5 6 7 8
Unsorted numbers:
5 3 2 7 1 5 6 8 4
Sorted Tags:
4 2 1 8 0 5 6 3 7
Sorted Numbers:
1 2 3 4 5 5 6 7 8

Related

How to locate an inputted integer value in a list of an Array in Java?

this is my first "problem": Make a program to allow the user to input an integer value to be searched in list3. Your program should display whether the inputted integer value is found in list3, how many of it is in list3, and what are their locations in list3?"
It's almost done, the only problem is that I couldn't follow what is written output given in the example:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List3.
Located at: list3[4], list3[5], list3[6], list3[8]
and this is my output:
list1 : 1 3 2 5 7 8 5 6 9 4
list2 : 2 1 4 3 2 1 4 2 0 2
list3 : 3 4 6 8 9 9 9 8 9 6
Input value to search in List3: 9
The value 9 is in List3!
There are 4 of it in List 3.
Located at: 4
how do i display the "located at: " like in the example?
EDITED
Sorry, I'm kinda new here and in Programming. This is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class List2Sample
{
public static void main(String[] args)
{
int list1[] = new int[10];
int list2[] = new int[10];
int list3[] = new int[10];
String input = "";
int i, x, num = 0, count = 0;
boolean found = false;
ArrayList<Integer> arr = new ArrayList<Integer>(10);
Scanner in = new Scanner(System.in);
for(i = 0; i < 10; i++)
{
list1[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 1 [" + i + "] : ");
try
{
list1[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
for(i = 0; i < 10; i++)
{
list2[i] = 0;
}
for(i = 0; i < 10; i++)
{
System.out.print("List 2 [" + i + "] : ");
try
{
list2[i] = in.nextInt();
}
catch(Exception e)
{
System.out.println("Error!");
}
}
System.out.print("list1 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list1[i] + "\t");
}
System.out.println();
System.out.print("list2 : ");
for(i = 0; i < 10; i++)
{
System.out.print(list2[i] + "\t");
}
System.out.println();
System.out.print("list3 : ");
for(i = 0; i < 10; i++)
{
list3[0] = list1[0] + list2[0]; list3[1] = list1[1] + list2[1]; list3[2] = list1[2] + list2[2];
list3[3] = list1[3] + list2[3]; list3[4] = list1[4] + list2[4]; list3[5] = list1[5] + list2[5];
list3[6] = list1[6] + list2[6]; list3[7] = list1[7] + list2[7]; list3[8] = list1[8] + list2[8];
list3[9] = list1[9] + list2[9];
System.out.print(list3[i] + "\t");
}
System.out.println();
System.out.print("Input value to search in List3: ");
x = in.nextInt();
arr.add(list3[0]);
arr.add(list3[1]);
arr.add(list3[2]);
arr.add(list3[3]);
arr.add(list3[4]);
arr.add(list3[5]);
arr.add(list3[6]);
arr.add(list3[7]);
arr.add(list3[8]);
arr.add(list3[9]);
for (int n : list3)
{
if (n == x)
{
found = true;
break;
}
}
for (i = 0; i < 10; i++)
{
if (list3[i] == x)
{
count++;
}
}
for (Integer value : arr)
{}
int pos = arr.indexOf(x);
if(found)
System.out.println("The value " + x + " is in List3!");
else
System.out.println("The value " + x + " is in List3!");
System.out.println("There are " + count + " of it in List 3.");
System.out.println("Located at: " + pos);
}
}
Assuming list3 is an list of integers then using java8 streams
String locations=IntStream.range(0,list3.size())
.filter(i->list3.get(i)==userInput)
.map(index->"list3["+index+"]")
.collect(Collectors.joining(","));
Int occurences=locations.split(","). length;
if(occurences>0){System.out.println(userInput +"occurred" + occurences +" Times +" at locations "+locations);}
else{System.out.println(userInput +"Was not found");}
indexOf(ch) will only return the first appearance of the value in the array, if you want, you could supplement a second parameter to tell Java where to start looking for the character, like this: indexOf(ch, fromIndex).
However, in your case, it's much easier to just use an index based loop to loop through all elements in the array, then record the positions if you found matching characters, like this:
for(int i = 0; i < arr.length; i++){ // loop through all indices of the array, starting from 0, end at arr.length - 1
if(arr[i] == ch){ // arr[i] is each character in the array at index i, ch is the target character you're matching against
System.out.println("Character found at position " + i);
}
}

Get the maximum summation of 2D array

There is a 2D array. int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}} . I want to get summation of each columns and get the maximum number. Finally it should be returned {5,7,8,9} . Because it has the maximum summation. I have mentioned i tried code below and it not return correct value. Help me to solve this
Your k is supposed to track the index with the greatest sum. So when you are resetting max you need to say k=i. You said i=k by mistake. Changing it makes your program run as desired.
EDIT: There was once code in the original question, to which this solution referred.
If the max column is expected, then I might have a solution:
import java.util.Arrays;
public class ArrayTest {
public static void main(String args[]) {
/*
* 1 3 4 1
* 5 7 8 9
* 6 1 2 1
*
*/
int[][] arr = {{1, 3, 4, 1}, {5, 7, 8, 9}, {6, 1, 2, 1}};
int m = arr.length;
int n = arr[0].length;
int[] arr2 = new int[n];
int p = 0;
int[][] colArray = new int[n][m];
for (int i = 0; i < n; i++) {
int[] arr_i = new int[m];
//System.out.println("i = " + i);
//System.out.println("p = " + p);
int sum = 0;
for (int j = 0; j < m; j++) {
arr_i[j] = arr[j][p];
sum += arr_i[j];
}
//System.out.println("Col: " + p + " : " + Arrays.toString(arr_i));
colArray[i] = arr_i;
arr2[p] = sum;
p++;
}
System.out.println("Sum: " + Arrays.toString(arr2));
int k = 0;
int max = arr2[0];
for (int i = 0; i < 3; i++) {
if (arr2[i] > max) {
max = arr2[i];
k = i;
}
}
System.out.println("Column index for max: " + k);
System.out.println("Column: " + Arrays.toString(colArray[k]));
}
}
Output:
Sum: [12, 11, 14, 11]
Column index for max: 2
Column: [4, 8, 2]
I recommend you find a way to break down your problem into smaller parts, solve each part with a function, then combine everything into a solution.
Example solution below:
public class Main {
public static long sum(int[] a){
long sum = 0;
for (int i : a) {
sum = sum + i;
}
return sum;
}
public static int[] withMaxSumOf(int[][] as){
// keep one sum for each array
long[] sums = new long[as.length];
// calculate sums
for (int i = 0; i < as.length; i++) {
int[] a = as[i];
sums[i] = sum(a);
}
// find the biggest one
int maxIndex = 0;
long maxSum = sums[0];
for (int i=1;i<sums.length;i++){
if (sums[i] > maxSum){
maxSum = sums[i];
maxIndex = i;
}
}
// return array that had biggest sum
return as[maxIndex];
}
public static void main(String[] args){
int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}};
// find the one with max sum
int[] max = withMaxSumOf(arr);
// print it
for (int i = 0; i < max.length; i++) {
int x = max[i];
if (i > 0) System.out.print(", ");
System.out.print(x);
}
System.out.println();
}
}
I think this might be your problem:
for(int i=0;i<3;i++) {
if(arr2[i]>max) {
max=arr2[i];
i=k;
}
}
I think that i=k really needs to be k=i.
Note also that it's worthwhile using better variable names. index instead of i, for instance. What is k? Call it "indexForHighestSum" or something like that. It doesn't have to be that long, but k is a meaningless name.
Also, you can combine the summation loop with the find-highest loop.
In the end, I might write it like this:
public class twoDMax {
public static void main(String args[]) {
int[][] arr= { {1,3,4,1}, {5,7,8,9}, {6,1,2,1} };
int indexForMaxRow = 0;
int previousMax = 0;
for(int index = 0; index < 4; ++index) {
int sum = 0;
for(int innerIndex = 0; innerIndex < 4; ++innerIndex) {
sum += arr[index][innerIndex];
}
if (sum > previousMax) {
previousMax = sum;
indexForMaxRow = index;
}
System.out.println(indexForMaxRow);
for(int index = 0; index < 4; ++index) {
System.out.println(arr[indexForMaxRow][index]);
}
}
}
I did a few other stylish things. I made use of more obvious variable names. And I am a little nicer about whitespace, which makes the code easier to read.
public static void main( String args[] ) {
int[][] arr = { { 1, 3, 4, 1 }, { 5, 7, 8, 9 }, { 6, 1, 2, 1 } };
int indexOfMaxSum = 0;
int maxSum = 0;
for ( int i = 0; i < arr.length; i++ ) {
int[] innerArr = arr[ i ]; // grab inner array
int sum = 0; // start sum at 0
for ( int j : innerArr ) {
// iterate over each int in array
sum += j; // add each int to sum
}
if ( sum > maxSum ) {
// if this sum is greater than the old max, store it
maxSum = sum;
indexOfMaxSum = i;
}
}
System.out.println( String.format( "Index %d has the highest sum with a sum of %d", indexOfMaxSum, maxSum ) );
int [] arrayWithLargestSum = arr[indexOfMaxSum]; // return me
}

Code has incorrect last value in array

I can not find why the code has the last incorrect value for test 3 and 5. I can not change the array to array list. The methods are the only thing that I can change.
package Semester;
import java.util.ArrayList;
public class MemberArrayList {
private ArrayList<Integer> friendsScore = new ArrayList<Integer>();
private ArrayList<String> friendsID = new ArrayList<String>();
// Add a friend with ID with the score into friends.
public void addFriend(String friendID, int score) {
// TODO
friendsScore.add(score);
friendsID.add(friendID);
}
// Removes a friend with friendID, but you cannot use indexOf. Only methods you can use: size, equals, get, remove
public void removeFriend(String friendID) {
// TODO
for (int i = 0; i < friendsID.size(); i++)
{
if ( friendID.equals(friendsID.get(i)))
{
friendsScore.remove(i);
friendsID.remove(i);
}
}
}
// Get the scores of first 10 friends added
public int [] getScores10() {
// TODO
int size = 10;
int[] score = new int[size];
for (int i = 0; i < 10; i++)
{
score[i] = friendsScore.get(i);
}
return score;
}
public int [] getScoresLast10() {
// TODO
int[] score = new int[10];
int j = 0;
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
{
score[j] = friendsScore.get(i);
j++;
}
return score;
}
// Get the scores of the friends in the array, but you cannot use indexOf function. You can only use size, get, equals, intValue
public int [] getScores(String [] friendIDs) {
// TODO
int value = friendIDs.length;
int[] score = new int[value];
for (int i = 0; i < value; i++)
{
String person = friendIDs[i];
for (int j = 0; j < friendsID.size(); j++)
{
if (person.equals(friendsID.get(j)))
{
score[i] = friendsScore.get(j);
}
}
}
return score;
}
public static void main(String[] args) {
MemberArrayList member = new MemberArrayList();
member.addFriend("Paul", 3);
member.addFriend("Peter", 1);
member.addFriend("Mary", 2);
member.addFriend("John", 4);
member.addFriend("Karen", 7);
member.addFriend("Kevin", 3);
member.addFriend("Walter", 1);
member.removeFriend("Mary");
member.removeFriend("Walter");
member.addFriend("Steven", 21);
member.addFriend("Kelly", 9);
member.addFriend("Kaitlin", -5);
member.addFriend("Bea", 77);
member.addFriend("Max", 32);
System.out.println("Test 1");
String [] friendIDs = {"Paul","Kevin","Steven","Max"};
int [] scores = member.getScores(friendIDs);
for (int i = 0; i < scores.length; i++)
System.out.println(friendIDs[i]+" "+scores[i]);
System.out.println("Test 2");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 3");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
member.removeFriend("Bea");
member.addFriend("Eric", -1);
member.addFriend("Abby", -2);
member.addFriend("Jacob", 3);
member.addFriend("Blake", 8);
System.out.println("Test 4");
scores = member.getScores10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
System.out.println("Test 5");
scores = member.getScoresLast10();
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
}
}
The output should be
Test 1
Paul 3
Kevin 3
Steven 21
Max 32
Test 2
3
1
4
7
3
21
9
-5
77
32
Test 3
32
77
-5
9
21
3
7
4
1
3
Test 4
3
1
4
7
3
21
9
-5
32
-1
Test 5
8
3
-2
-1
32
-5
9
21
3
7
Your loop for counting down is missing one value to copy:
Wrong:
for (int i = friendsScore.size()-1; i > (friendsScore.size()-10); i--)
This runs for 9 times.
Right:
for (int i = friendsScore.size()-1; i >= (friendsScore.size()-10); i--)
This runs 10 times and copies all 10 values to the array. Note the >= instead of >.
With the first loop the last value of your array will never be set and so defaults to 0 or whatever your compiler might set (I think it is always 0 in java but I'm not sure).

Swap rows in 2d array by row sum in Java

I implemented this thing but I am not sure this is correct
Example : int [][]={{2,1,0},{2,8,9},{1,1,0}}
In the above sum of elements in row 1 (2+1+0=3) is lesser than sum of elements in row 2(2+8+9=19) and greater than row 3 sum(2).
The final array should be like {{2,8,9},{2,1,0},{1,1,0}}
int arr[5][5];
int rowSum[5];
int sum = 0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
sum = sum + arr[i][j];
}
rowSum[i] = sum;
sum=0;
}
int swap;
//now sorting
for (int c = 0 ; c < ( n - 1 ); c++)
{
for (int d = 0 ; d < n - c - 1; d++)
{
if (rowSum[d] > rowSum[d+1]) /* For decreasing order use < */
{
swap = rowSum[d];
rowSum[d] = rowSum[d+1];
rowSum[d+1] = swap;
//swapping original array
for(int i=0;i<5;i++){
swap = arr[d][i];
arr[d][i] = arr[d+1][i];
arr[d+1][i] = swap;
}
}
}
}
Using Java 8 features:
int[][] arr = { { 2, 1, 0 }, { 2, 8, 9 }, { 1, 1, 0 } };
Arrays.sort(arr, Comparator.comparingInt((int[] row) -> Arrays.stream(row).sum()).reversed());
System.out.println(Arrays.deepToString(arr));
Integer[][] numbers = new Integer[][]{{2,1,0},{2,8,9},{1,1,0}};
System.out.println("Before:");
for(Integer[] row : numbers) {
for(Integer num : row) {
System.out.print(num+",");
}
System.out.println("");
}
Arrays.sort(numbers, new Comparator<Integer[]>(){
#Override
public int compare(Integer[] o1, Integer[] o2) {
Integer sumArray_1 = 0;
Integer sumArray_2 = 0;
for(int i = 0; i < o1.length; ++i) {
sumArray_1 += o1[i];
}
for(int i = 0; i < o2.length; ++i) {
sumArray_2 += o2[i];
}
return sumArray_2.compareTo(sumArray_1); //Decending order
}
});
System.out.println("After:");
for(Integer[] row : numbers) {
for(Integer num : row) {
System.out.print(num+",");
}
System.out.println("");
}
Output:
Before:
2,1,0,
2,8,9,
1,1,0,
After:
2,8,9,
2,1,0,
1,1,0,
Use the below Code Snippet,
int[][] temp = {{2,1,0},{2,8,9},{1,1,0}};
Arrays.sort(temp, new Comparator<int[]>() {
#Override
public int compare(int[] a, int[] b) {
return Integer.compare(b[1], a[1]);
}
});
System.out.println("After applying comparator");
for(int[] arr:temp){
for(int val:arr){
System.out.print(val+" ");
}
System.out.println("");
}
It will display the output like this,
After applying comparator
2 8 9
2 1 0
1 1 0

Find numbers of monotonically increasing Sub-array

Given the array, i need to find how many monotonically increasing Sub-arrays there are in that array?
For example, with [0, 1, 3, 1 , 2] - has 2 monotonical sub-arrays : [0, 1,3] and [1,2].
public class SUB_ARRAY {
public static void main(String a[]){
int[] x = new int[6];
x[0]=1;
x[1]=2;
x[2]=3;
x[3]=6;
x[4]=9;
x[5]=10;
ArrayList<Object> arraylist = new ArrayList<Object>();
HashSet list = new HashSet();
for ( int i=0; i< (x.length -1); i++){
if (x[i+1]> x[i] ){
list.add(x[i]);
list.add(x[i+1]);
} else if (x[i+1] < x[i] || x[i+1]==x[i]) {
arraylist.add(list.clone());
list.clear();
}
}
System.out.println(arraylist.size());
}
}
The output is : 0 (instead of 1).
So, where I'm wrong?
Check out this solution. It now only displays the counter but print you the subarrays. If you need only the continues subarrays you can easily modify it.
As you see I use neither HashSet nor ArrayList for storing temporary data just a counter.
import java.util.ArrayList;
public class SUB_ARRAY{
public static int SUBARRAY_MINIMUM_LENGTH = 2;
public static void main(String a[]){
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(5);
x.add(0);
x.add(1);
x.add(3);
x.add(4);
x.add(2);
x.add(3);
x.add(6);
x.add(1);
x.add(0);
x.add(4);
int monoton = 0;
int changed = -1;
System.out.println("Initial array: " + x.toString());
for ( int i=0; i< x.size() -1; ++i){
if (x.get(i+1) > x.get(i)){
if (changed > -1){
for (int j = changed; j <i+2; ++j){
monoton += checkSubArray(x, j, i+2);;
}
}
else{
System.out.println("New monoton subarray start index: " + i + " value: " + x.get(i));
changed = i;
monoton += checkSubArray(x, changed, i+2);
}
}
else if (changed > -1){
changed = -1;
}
}
System.out.println("Monoton count: " + monoton);
}
private static int checkSubArray(ArrayList<Integer> x, int start, int end)
{
if (end-start < SUBARRAY_MINIMUM_LENGTH){
return 0;
}
for (int subi = start; subi < end; ++subi){
System.out.print(" " + x.get(subi));
}
System.out.println();
return 1;
}
}
The output will be the following
Initial array: [5, 0, 1, 3, 4, 2, 3, 6, 1, 0, 4]
New monoton subarray start index: 1 value: 0
0 1
0 1 3
1 3
0 1 3 4
1 3 4
3 4
New monoton subarray start index: 5 value: 2
2 3
2 3 6
3 6
New monoton subarray start index: 9 value: 0
0 4
Monoton count: 10

Categories

Resources