# Thread: Help with an Algorithm

1. ## Help with an Algorithm

HI people, am in need of an algorithm to sort a table. i have an idea but i really dont know where to start.
my table looks like this

Duration(Hrs) Power(%)
00:00 10
00:20 15
00:30 20
I want to sort the above table to show the duration column in minutes (after every 5 mins)
It should look this after the sorting:
Duration(Hrs) Power(%)
00:00 10
00:05 10
00:10 10
00:15 10
00:20 15
00:25 15
00:30 20  Reply With Quote

2. ## Date implements Comparable so it would be a good starting point.
You could use the TableRowSorter class (j2se 1.6+).
Java Code:
```import java.awt.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class DateSorting {
DateFormat df = new SimpleDateFormat("HH:mm");
JTable table;

private JScrollPane getContent() {
DefaultTableModel model = getModel();
table = new JTable(model);
TableRowSorter<DefaultTableModel> sorter =
new TableRowSorter<DefaultTableModel>(model);
table.setRowSorter(sorter);
((DefaultTableCellRenderer)table.getDefaultRenderer(Integer.class))
.setHorizontalAlignment(JLabel.CENTER);
table.setDefaultRenderer(Date.class, getDateRenderer());
Dimension d = table.getPreferredSize();
d.width = 225;
table.setPreferredScrollableViewportSize(d);
return new JScrollPane(table);
}

private DefaultTableModel getModel() {
String[] colNames = { "Duration(Hrs)", "Power(%)" };
Date[] dates = getDates();
Object[][] data = {
{ dates, Integer.valueOf(10) },
{ dates, Integer.valueOf(20) },
{ dates, Integer.valueOf(35) },
{ dates, Integer.valueOf(30) },
{ dates, Integer.valueOf(45) }
};
return new DefaultTableModel(data, colNames) {
// Recommended for performance at end
// of comments in TableRowSorter api.
public Class getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:  return Date.class;
case 1:  return Integer.class;
default: return Object.class;
}
}
};
}

private Date[] getDates() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);  // [0-23]
calendar.set(Calendar.SECOND, 0);
Date[] dates = new Date;
calendar.set(Calendar.MINUTE, 20);
dates = calendar.getTime();
calendar.set(Calendar.MINUTE, 5);
dates = calendar.getTime();
calendar.set(Calendar.MINUTE, 35);
dates = calendar.getTime();
calendar.set(Calendar.MINUTE, 15);
dates = calendar.getTime();
calendar.set(Calendar.MINUTE, 40);
dates = calendar.getTime();
//for(int i = 0; i < dates.length; i++) {
//    System.out.printf("dates[%d]  = %s%n", i,
//                       df.format(dates[i]));
//}
return dates;
}

private TableCellRenderer getDateRenderer() {
return new DefaultTableCellRenderer.UIResource() {
public void setValue(Object value) {
setText((value == null) ? "" : df.format(value));
}
};
}

public static void main(String[] args) {
DateSorting test = new DateSorting();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}```  Reply With Quote

3. ## Thank you for the reply, but i think the code you posted sorts the table in ascending or descending order.
I want when i click a button a new table to be created but then it should have the duration column broken down to 5minutes difference. for example,
00:00 10
00:10 20
00:30 40
when the button is clicked it should a produce a second table that looks like this,
00:00 10
00:05 10
00:10 20
00:15 20
00:20 20
00:25 20
00:30 40
The power colums should not change at all. I hope this is clear
Thank you  Reply With Quote

4. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
17

## In your example why does 00:15 have the value 20? What row in the first table needs to be consulted to figure this value out? In particular how does the time value of this row (and the next) relate to to 00:15?

Answer these questions in natural language, then with some Java code.  Reply With Quote

5. ## Time column in the first table determines everything, as in
from
00:00 - 00:09
the power level will be
10
and from
00:10 - 00:29
the power level should be
20
and
40
from
00:30---
I think this is the simplest way i can explain this. Is it clear now?  Reply With Quote

6. Senior Member Join Date
Sep 2008
Posts
564
Rep Power
12

## is it a sorting algorithm you really need? it looks like you're just creating a table with five minute intervals, taking the existing ones from the previous table, and filling in the blanks with the preceding value.  Reply With Quote

7. ## i think you are right. Thats ny problem!  Reply With Quote

8. Senior Member Join Date
Mar 2009
Posts
105
Rep Power
0

## will those values necessarily always be in order though?

Do they need to be sorted before you "fill in the blanks" between the values?  Reply With Quote

9. ## The first table keeps record of time and power levels during a certain reaction process. Time is recorded when there is a change in power level, for example.when a process is started at time 00:00 with a power level of lets say 10% then after 1 hour 30 mins power level changes to 25%. From the data that i have now, i want to create another table out of this such that time is recorded after every five mins.

So, there is no sorting done before filling the remaining values and the change is not always constant.

i hope am clear now

thank you  Reply With Quote

10. ## Java Code:
```    int[] times = { 10, 20, 30 };
int[] power = { 10, 20, 25 };

private void showSummary(int duration) {
determine the number of entries
for all the number of entries
print time and getPower(time)
}
}

private int getPower(int time) {
int retVal = 0;
for(int i = 0; i < times.length; i++) {
if(time >= times[i]) {
retVal = power[i];
}
}
return retVal;
}```  Reply With Quote

11. ## From my understanding, this is the part where the program is supposed to check for power level that corresponds to the time and display it.

i wrote some code using ur idea, and when i run it, the time column is displayed ok but the first value of the power column is repeated all through.
where am i messing up in my code??

Java Code:
```private void showSummary(){
double delta = 0.0;
int MAXH = (48*60)/5;
timeArray = new double[MAXH];//array size
for (int j = 0;j<timeArray.length;j++){

summaryTable.setValueAt(delta, j, 0);
retVal =  getPower(times);
summaryTable.setValueAt(retVal, j, 1);
delta +=5;
}
}
private double getPower(int times){
retVal = 0.0;
int k,rCount = table1.getRowCount();

//loop to set the array sizes
for (k= 0;k<rCount;k++){
String t = (String)table1.getValueAt(k,0);
if (t == null){
break;
}
}
timesA = new double[k];//timeArray size
powerArray = new double[k];//powerArray size

for ( int i = 0;i<rCount;i++){
String time =(String) table1.getValueAt(i, 0);
if (time == null){
break;
}
StringTokenizer st =   new StringTokenizer(time, ":");
String t1= st.nextToken();
String t2 = st.nextToken();

double time_hrs  = Double.parseDouble(t1);
double mins = Double.parseDouble(t2);
double HrsToMins = (time_hrs*60);
HrsToMins = (HrsToMins + mins);

timesA[i] = HrsToMins;//

String power =(String) table1.getValueAt(i, 1);
double pw =Double.parseDouble(power);

powerArray[i] = pw;// Add power values to the array
}

for ( int j = 0;j < timesA.length;j++){
if ( times >= timesA[j]){
retVal = powerArray[j];
}
}
return retVal;
}```  Reply With Quote

12. ## I tend to believe this is where the problem comes in
Java Code:
```for ( int j = 0;j < timesA.length;j++){
if ( times >= timesA[j]){
retVal = powerArray[j];
}
}
return retVal;```
any ideas?  Reply With Quote

13. ## Here's what I made up for you on the 23rd. Enter an int value on the command line to test it. I left out the table code to concentrate the focus on the algorithm.
Java Code:
```public class SummaryTest {
int[] times = { 10, 20, 30 };
int[] power = { 10, 20, 25 };
final int INTERVAL = 5;

private void showSummary(int duration) {
int numEntries = duration/INTERVAL + duration%INTERVAL;
int time = 0;
for(int i = 0; i <= numEntries; i++) {
String s1 = String.format("00:%02d", time);
String s2 = String.valueOf(getPower(time));
System.out.printf("  %s  %s%n", s1, s2);
time += INTERVAL;
}
}

private int getPower(int time) {
int retVal = 0;
for(int i = 0; i < times.length; i++) {
if(time >= times[i]) {
retVal = power[i];
}
}
return retVal;
}

public static void main(String[] args) {
int time = (args.length == 0) ? 5 :
Integer.parseInt(args);
new SummaryTest().showSummary(time);
}
}```
The general idea is to collect the data, walk thru it in timeincrements and use the time values when the power value changed to step up the power values from one time/power change to the next.
Your getPower method seems to collect all of the table data every time you call it.
Collect the data first and prepare it, like the two arrays that appear in SummaryTest, for use in the loop where you will call getPower. Then start your loop to determine the timepower values for your table. The only thing getPower should be concerned with is finding the current power value for any given time by using the previouslyprepared data arrays.  Reply With Quote

14. ## I tried to implement your idea in my program but still i get a problem. the power column displays 0.0 all through.
Check out my code and tell me where i made a mistake

Java Code:
```public void resultTable(){
int k;
double numEntries=0;
int rCount = Xenon.getRowCount();

//loop to get the array size
for (k= 0;k<rCount;k++){
String t = (String)Xenon.getValueAt(k,0);
if (t == null){
break;
}
}
timeArray = new double[k];//timeArray size
powerArray = new double[k];//powerArray size
for ( int i = 0;i<rCount;i++){
String time =(String) Xenon.getValueAt(i, 0);
if (time == null){
break;
}
StringTokenizer st =   new StringTokenizer(time, ":");
String t1= st.nextToken();
String t2 = st.nextToken();

double time_hrs  = Double.parseDouble(t1);
double mins = Double.parseDouble(t2);
double HrsToMins = (time_hrs*60);
HrsToMins = (HrsToMins + mins);
timeArray[i] = HrsToMins;

String pw =(String) Xenon.getValueAt(i, 1);
double power =Double.parseDouble(pw);

powerArray[i] = power;

}
int time_t= 0;
for (int j = 0;j<timeArray.length;j++){
numEntries = timeArray[j]++;
numEntries /=5;
}
for (int m = 0;m <= numEntries;m++){
Temp.setValueAt(time_t, m, 0);
String s2 = String.valueOf(getPower(times));
Temp.setValueAt(s2, m, 1);
time_t +=5;
}
}
public double getPower(int times){
retVal = 0;
for ( int k = 0;k < timeArray.length;k++){
if ( times >= timeArray[k]){
retVal = powerArray[k];
}
}
return retVal;
}```
Last edited by Manfizy; 07-02-2009 at 02:31 PM.  Reply With Quote

15. Member Join Date
Apr 2009
Location
Brisbane
Posts
86
Rep Power
0

## My 2c...

Sometimes Java can be juuuust soooo verrrrbose....

Java Code:
```Administrator@snadbox3 /tmp
\$ cat table
00:00 10
00:20 15
00:30 20

\$ gawk -F'[: ]' '
NR==1{
minutes=0;
power=\$3;
}

NR>0{
while(minutes<\$2){
printf("%s:%02s %s\n",\$1,minutes,power);
minutes+=5;
}
power=\$3;
}

END{
printf("%s:%02s %s\n", \$1, minutes, power);
}
' table
00:00 10
00:05 10
00:10 10
00:15 10
00:20 15
00:25 15
00:30 20```
Yeah, yeah... it's a java forum... and my variable names suck.... so shoot me ;-)

Cheers. Keith.
Last edited by corlettk; 07-02-2009 at 03:05 PM. Reason: legibility  Reply With Quote

16. ## Honestly i do not understand what you are trying to do here!!
I did run hardwired example code and i got the same results..yeah, its working.
I used the same idea in my program but i only get 0.0 when i display power array. Something like this is what i get:
0 0.0
5 0.0
10 0.0
15 0.0
20 0.0
25 0.0
30 0.0
35 0.0
40 0.0
45 0.0
50 0.0
55 0.0
60 0.0
65 0.0
70 0.0
75 0.0
I have spend alot of time in this and it sucks:(
can you checking my code and tell me where i am messing up???
Last edited by Manfizy; 07-02-2009 at 03:15 PM.  Reply With Quote

17. Member Join Date
Apr 2009
Location
Brisbane
Posts
86
Rep Power
0

##  Originally Posted by Manfizy [Please] can you check my code, and tell me where I am messing up???
Nope... for that you need to post an SSCCE... can't test something that doesn't compile now can we.

Cheers. Keith.
Last edited by corlettk; 07-02-2009 at 03:21 PM. Reason: Stuffed up! That'll teach my for being a smarty wishbone legs.  Reply With Quote

18. ## Mmmm.. thats abit tricky. my code is quite lengthy and ontop of that am using Netbeans IDE so definately if i post the code here u miss the parts where the tables are being created and populated.

Would you mind telling or rather explaining to me what happens with
int time
in getPower() method??

Btw, am refering to hardwired code.

I am tempted to think that is the source of my problem.

cheerz!
Last edited by Manfizy; 07-02-2009 at 03:46 PM. Reason: clarity!!  Reply With Quote

19. Member Join Date
Apr 2009
Location
Brisbane
Posts
86
Rep Power
0

## My last word on the problem... If you want more help then you're going to need to formulate a _short_ self contained example.

Java Code:
```package forums;

class Tabulator
{
public static void main(String[] args) {
try {
String[] fields = line.split("[: ]");
int minutes = 0;
int power = Integer.parseInt(fields);
fields = line.split("[: ]");
int lineMinutes = Integer.parseInt(fields);
while( minutes < lineMinutes ) {
System.out.printf("%s:%s %s\n", fields, OO(minutes), power);
minutes += 5;
}
power = Integer.parseInt(fields);
}
System.out.printf("%s:%s %s\n", fields, OO(minutes), power);
} catch (Exception e) {
e.printStackTrace();
}
}

private static String OO(int n) {
String On = "00"+n;
return (On).substring(On.length()-2);
}
}```  Reply With Quote

20. ## this is what i could come up with.. SSCCE

Java Code:
```public class resultTable {

double[] timeArray = {0, 2, 4, 7};
double[] powerArray = {70, 100, 100, 100};

public void resultTable(){

double numEntries=0;

for ( int i = 0;i<timeArray.length;i++){

double HrsToMins = (timeArray[i]*60);
timeArray[i] = HrsToMins;

}
int time_t= 0;
for (int j = 0;j<timeArray.length;j++){
numEntries = timeArray[j]++;
numEntries /=5;
}
for (int m = 0;m <= numEntries;m++){
String s1 = String.format("00:%02d", time_t);
String s2 = String.valueOf(getPower(times));
System.out.printf("  %s  %s%n", s1, s2);
time_t +=5;
}
}
public double getPower(int times){
double retVal = 0;
times =0;
for ( int k = 0;k < timeArray.length;k++){
if ( times >= timeArray[k]){
retVal = powerArray[k];
}
}
return retVal;
}
public static void main(String[] args) {
new resultTable();
}
}```
does it make any sense to you?  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•