Java - how to avoid this repetitive code - java

I am currently writing a Java program that displays values into an AreaChart and to do so I have an ArrayList with the name dataList from the generic type AreaChartPair.
Each AreaChartPair contains a X-Axis(String) value and a Y-Axis(Integer) value.
The X-Axis are dates and the Y-Axis is a counter and because all the data gets read from a file, the dates will be in a unsorted order. to sort them I use this function:
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
Which is not completely solving my issue, since it will only compare the first few alphanumeric characters (i.e 02.09.2030 would come after 01.01.2000, because 02 comes after 01)
To solve this problem I simply reversed the date from dd.mm.yyyy to yyyy.mm.dd, sorted the list with the function above and afterwards reversed the string back to dd.mm.yyyy
My Question now is how I can simplify this block of code, since it is repetitive:
//replaces the current data with the reversed string
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue()));
}
//sorts the data
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
//reverses the string back to normal, so it can be displayed
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue()));
}
Any suggestions?

A shorter way to perform the sorting is to do the reversing on the fly. The string could also be parsed to a real date object, to make it cleaner, but that requires catch blocks and dateformatter objects, so I won't write that code here.
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue,
(a, b) -> {
return model.reverseDate(a).compareTo(model.reverseDate(b));
}));

Perhaps make a method out of it:
AreaChartPair areaChartPair = new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue());
public DataListType dataListSorter(DataListType datalist, AreaChartPair areaChartPair) {
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, areaChartPair);
}
return dataList;
}
dataList = dataListSorter(dataList);
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
dataList = dataListSorter(dataList);
Still repetitive, though. Probably most useful to do it this way if you're going to do this over and over again throughout your application.

Related

Java Bucket Sort of Elements in another Array

I just recently started learning java and today I learned how I can do the so called selection sort. I have been trying for the last 3 hours to do a bucket sort, but there are some parts which I don't know how to code. Important : I am learning java completely by myself with a book. I am not a student and I am doing this as a hobby. I already googled everything I could think of and I didn't find a solution. I don't have a teacher or anybody who I can ask, so yea, any help would be appreciated!
Code:
private int[] bucketSort() {
int[]bucket=new int[maxSize+1];
int[]sortedElements = new int[elementaros.length];
for(int i=0; i<elementaros.length;i++) {
bucket[elementaros[i]]++; //it says that I can't convert from Car to int. How can I add the elements of array elemenators to bucket?
}
int outPos = 0;
for (int j = 0; j < bucket.length; j++){
for (int k = 0; k < bucket[i]; k++){
sortedElements[outPos++] = i;
}
}
return bucket;
}
The idea of the code :
I have an array elements of type Car(Car is another class of my program). It looks like this - Car[] elementaros. int maxSize shows the maximum number of administrable Car objects. What I want to do is the following - I want to sort the elements in the elementaros array alphabetically. I would really really appreciate it if somebody has the time to show me how this would function with an example code or would just give me some tips. As I said - I have nobody who I can ask.
A selection sort is a combination of searching and sorting.
The principle is quite simple but I always prefer a diagram than huge explanations.
Start a pointer at the beginning of your unsorted array. Then, for each value of the array, search for the minimum value (or search for the alphabeticaly ordered car) in your array and switch the position of the founded Car with the pointer (which is a Car too)
Then you can advance the pointer to the next element of the array.
Here is a basic implementation to do this
public static Car[] doSelectionSort(Car[] elementaros) {
for (int i = 0; i < elementaros.length - 1; i++) {
int index = i;
for (int j = i + 1; j < elementaros.length; j++) {
if (elementaros[j].getName().compareTo(elementaros[index].getName()) < 0) {
index = j;
}
}
Car nextOrderedCar = elementaros[index];
elementaros[index] = elementaros[i];
elementaros[i] = nextOrderedCar;
}
return elementaros;
}
Just for example sake, I imagine your object of type Car has a name that we could use for the comparison.
UPDATE 1:
I have read your initial question too quickly and it leds me to answer a total different sorting algorithm. My bad.
I found an implementation here that does the trick:
williamfiset bucket sort
explanation of bucket sort plus different implementation
Hope this helps.

2 dimensional array & method calls - beginner

I'm currently working on a homework assignment for a beginner-level class and I need help building a program that tests if a sodoku solution presented as an int[][] is valid. I do this by creating helper methods that check both rows, columns and grids.
To check the column I call a method called getColumn that returns a column[]. When I test it out it works fine. I then pass it out on a method called uniqueEntries that makes sure that there are no duplicates.
Problem is, when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333). I have no idea why it does that. Here is my code:
int[][] sodokuColumns = new int[length][length];
for(int k = 0 ; k < sodokuPuzzle.length ; k++) {
sodokuColumns[k] = getColumn(sodokuPuzzle, k);
}
for (int l = 0; l < sodokuPuzzle.length; l++) {
if(uniqueEntries(sodokuColumns[l]) == false) {
columnStatus = false;
}
}
my helper is as follows
public static int[] getColumn(int[][] intArray, int index) {
int[] column = new int[intArray.length];
for(int i = 0 ; i < intArray.length ; i++) {
column[i] = intArray[i][index];
}
return column;
}
Thanks !
You said:
when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333).
I don't see any issue with your getColumn method other than the fact it's not even needed because getColumn(sodokuPuzzle, k) is the same as sodokuPuzzle[k]. If you're going to conceptualize your 2D array in such a way that your first index is the column then for your purpose of checking uniqueness you only need to write a method to get rows.
The issue you're having would seem to be with another part of your code that you did not share. I suspect there's a bug in the logic that accepts user input and that it's populating the puzzle incorrectly.
Lastly a tip for checking uniqueness (if you're allowed to use it) would be to create a Set of some kind (e.g. HashSet) and add all of your items (in your case integers) to that set. If the set has the same size as your original array of items then the items are all unique, if the size differs there are duplicates.

ArrayList Retrieve First and Last Result without Sorting ArrayList

I have an ArrayList of String, and I would like to retrieve the first and last result of the names after calculating the order of alphabets. Below is my code snippet:
ArrayList<String> list = new ArrayList<String>(20);
list.add("Charles Darwin");
list.add("Albert Einstein");
list.add("Issac Newton");
list.add("Tony Hoare");
list.add("Grace Hopper");
list.add("Edgar Dijkstra");
list.add("Ada Lovelace");
list.add("Charles Babbage");
list.add("Stephen Hawking");
String biggest = "";
String smallest = "";
for (int i = 0; i < list.size(); i++) {
String first = list.get(i);
for (int j = 0; j < list.size(); j++) {
String second = list.get(j);
if (!first.equalsIgnoreCase(second)) {
if (first.compareToIgnoreCase(second)>0){
biggest=first;
}
if (first.compareToIgnoreCase(second)<0){
smallest=first;
}
}
}
}
System.out.println(biggest);
System.out.println(smallest);
I am able to retrieve every value for comparison, however, the results are always showing Stephen Hawking as the biggest and smallest.
My desired results are Ada Lovelace as biggest and Tony Hoare as smallest.
You can use Collections.min / max
Your conditional statements seem to wrong.
if (first.compareToIgnoreCase(second)>0){
biggest=first;
}
if (first.compareToIgnoreCase(second)<0){
smallest=first;
}
You're comparing the element in the outer loop to the element in the inner loop. You never make a comparison against the biggest and smallest.
This should help you find the biggest and smallest String in your list.
String biggest = list.get(0);
String smallest = list.get(0);
for (int i = 1; i < list.size(); i++) {
if(list.get(i).compareToIgnoreCase(biggest) > 0)
biggest = list.get(i);
if(list.get(i).compareToIgnoreCase(smallest) < 0)
smallest = list.get(i);
}
Alternatively, you can use Collections.min() and max() as stated in one of the other answers.
are your required to use List ? You might want to see http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html. then you can use first() and last() method
I'm new to Java, but I can still recognize multiple issues with this code:
Why are you hard coding initial capacity to 20?
Why are you using indexed loops instead of for each?
Why are you using a nested loop to find min/max?
Use else instead of running the same comparison twice
If first always equals second biggest and smallest will remain uninitiated
And last, and directly dressing your question, all your code does is finding if the last item is greater & smaller than any of the other items in the list, not all of them, since you keep ignoring previous findings and not using biggest/smallest as a condition in any of your comparisons.

how to sort a two dimensional char array (only column wise) by selection sort in java

im very new in java i need the whole sorting algorithm....i can find ways to sort a 1 D array but a 2 D array gets very confusing.PLEASE help
sorry i dont have a code yet, i dont know where to start from! (this is the code for a one D array:) but i need one of 2 D (only column wise selection sort)
public static void sort(Comparable[] table) {
int n = table.length;
for (int fill=0; fill < n-1; fill++) {
int posMin = fill;
for(int next=fill; next < n; next++) {
if(table[next].compareTo(table[posMin] < 0) {
posMin = next;
}
}
//Exchange table[fill] and table[posMin]
Comparable temp = table[fill];
table[fill] = table[posMin];
table[posMin] = temp;
}
From the comments, it sounds like you can treat each column as a 1D array, so you can apply your existing 1D solution to each column: wherever you refer to table[x], you can now refer to table[x][c], where c is the column being sorted (or table[c][x]; not certain which index you're using for column).
If you have each DNA sequence be a string, you have a List of Strings. Then just sort the strings.
List<String> dnaSequences = new ArrayList<String>();
dnaSequences.add("AGCAGAAGCGGAGCTTTAAGATGAATATAAATC");
...
dnaSequences.add("AGCAGAAGCGGAGCTTTAAGATGAATATAAATC");
Collections.sort(dnaSequences);

Use JTextField to List items

I'm not too familiar with Java GUI programming, and I wanted to do something where I have a loop that spits out a list of stuff and have the JTextField render it in the order it comes out.
I just do not know how the second parameter of the JTextField insert() function works. Right now when I do something like:
for(int i = 0; i < list.size(); i++){
textArea.insert(list.get(i), 0);
}
It does what I want, except it lists everything in backwards order that I put it in. I want it to display everything the other way around.
Thank you for any advice.
All you need to define a temporary string, result and for every item in the list add the string representation to that variable. When you have looped through everything, all you need to do is textArea.setText(result).
String result = "";
for(int i = 0; i < list.size(); i++)
{
result += list.get(i).toString();
}
textArea.setText(result);

Categories