Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post 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
    Your opinions are highly appreciated
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Date implements Comparable so it would be a good starting point.
    You could use the TableRowSorter class (j2se 1.6+).
    Click column headers to sort.
    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[0], Integer.valueOf(10) },
                { dates[1], Integer.valueOf(20) },
                { dates[2], Integer.valueOf(35) },
                { dates[3], Integer.valueOf(30) },
                { dates[4], 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[5];
            calendar.set(Calendar.MINUTE, 20);
            dates[0] = calendar.getTime();
            calendar.set(Calendar.MINUTE, 5);
            dates[1] = calendar.getTime();
            calendar.set(Calendar.MINUTE, 35);
            dates[2] = calendar.getTime();
            calendar.set(Calendar.MINUTE, 15);
            dates[3] = calendar.getTime();
            calendar.set(Calendar.MINUTE, 40);
            dates[4] = 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.add(test.getContent());
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }

  3. #3
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    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.

  5. #5
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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?
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  6. #6
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    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.

  7. #7
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    i think you are right. Thats ny problem!
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  8. #8
    porchrat is offline Senior Member
    Join Date
    Mar 2009
    Posts
    105
    Rep Power
    0

    Default

    will those values necessarily always be in order though?

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

  9. #9
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  10. #10
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
        int[] times = { 10, 20, 30 };
        int[] power = { 10, 20, 25 };
    
        private void showSummary(int duration) {
            determine the number of entries
            start with time = 0
            for all the number of entries
                print time and getPower(time)
                time += your 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;
        }

  11. #11
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    Your post was helpful but i didn´t understand the getPower method.
    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;
    }
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  12. #12
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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?
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  13. #13
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    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[0]);
            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.

  14. #14
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Unhappy

    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 01:31 PM.
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  15. #15
    corlettk is offline Member
    Join Date
    Apr 2009
    Location
    Brisbane
    Posts
    86
    Rep Power
    0

    Default

    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
    
    Administrator@snadbox3 /tmp
    $ 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 02:05 PM. Reason: legibility

  16. #16
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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 02:15 PM.
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  17. #17
    corlettk is offline Member
    Join Date
    Apr 2009
    Location
    Brisbane
    Posts
    86
    Rep Power
    0

    Default

    Quote Originally Posted by Manfizy View Post
    [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 02:21 PM. Reason: Stuffed up! That'll teach my for being a smarty wishbone legs.

  18. #18
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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 02:46 PM. Reason: clarity!!
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

  19. #19
    corlettk is offline Member
    Join Date
    Apr 2009
    Location
    Brisbane
    Posts
    86
    Rep Power
    0

    Default

    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;
    
    import java.io.FileReader;
    import java.io.BufferedReader;
    
    class Tabulator
    {
      public static void main(String[] args) {
        try {
          BufferedReader reader = new BufferedReader(new FileReader("Tabulator.txt"));
          String line = reader.readLine();
          String[] fields = line.split("[: ]");
          int minutes = 0;
          int power = Integer.parseInt(fields[2]);
          while ( (line=reader.readLine()) != null ) {
            fields = line.split("[: ]");
            int lineMinutes = Integer.parseInt(fields[1]);
            while( minutes < lineMinutes ) {
              System.out.printf("%s:%s %s\n", fields[0], OO(minutes), power);
              minutes += 5;
            }
            power = Integer.parseInt(fields[2]);
          }
          System.out.printf("%s:%s %s\n", fields[0], OO(minutes), power);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      private static String OO(int n) {
        String On = "00"+n;
        return (On).substring(On.length()-2);
      }
    }

  20. #20
    Manfizy's Avatar
    Manfizy is offline Senior Member
    Join Date
    Nov 2008
    Location
    Germany
    Posts
    193
    Rep Power
    6

    Post

    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?
    We Learn Through Mistakes..,
    Manfizy:rolleyes:

Page 1 of 2 12 LastLast

Similar Threads

  1. Snapping algorithm
    By ankitmcgill in forum New To Java
    Replies: 3
    Last Post: 11-04-2008, 09:54 PM
  2. O(log n) algorithm help !!!!!!
    By itseeker87 in forum New To Java
    Replies: 8
    Last Post: 09-09-2008, 05:12 PM
  3. Help with algorithm
    By susan in forum New To Java
    Replies: 1
    Last Post: 07-13-2007, 10:26 PM
  4. Help me with this algorithm
    By Marcus in forum Advanced Java
    Replies: 3
    Last Post: 07-02-2007, 01:30 PM
  5. Help with Algorithm
    By Daniel in forum Advanced Java
    Replies: 2
    Last Post: 07-02-2007, 05:51 AM

Posting Permissions

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