سؤال

I have a algorithm which does bin packing based on certain conditions. I find that the flow of the algorithm is little bit complex for the readers to understand.

Below you can find the developed Java code. Is there a much simplified alternative flow for this code?

void binpack() {
boolean set=false, cmap=false;
        while(set==false) {
            set=true;
            cmap=false;
            pack[k.cnt]=new bins(k.lim, k.ptim);
            for(int i=0;i<tot;i++) {           
                int s1,s2;
                if(jm[i][1]==0) {
                    s1=jm[i][0]; 
                    set=false;

                    else if(pack[k.cnt].pushk<k.lim) {
                        for(int j=0;j<pack[k.cnt].pushk;j++) {
                            s2=pack[k.cnt].binjm[j][0];
                            for (Iterator<Integer> g= list[s1].iterator(); g.hasNext();) {

    }
}

Notes:

ptim-->present time

etim-->end time

lim-->limit

هل كانت مفيدة؟

المحلول

A couple of things off the top of my head:

  1. Variable names should be more expressive. Don't abbreviate, especially not to save one or two characters (e.g. ptim, chk())
  2. Put spaces after opening and before closing parentheses, after and before operators and so on. It sounds daft but you'll be amazed how easier your code will be to read.
  3. Avoid unnecessary boolean comparisons (e.g. if ( bool == false ) should be if ( !bool )
  4. Avoid one-liner ifs or whiles, use proper {} blocks.
  5. Don't pre-declare variables if you don't have to.
  6. Instead of the double break structure you have in your nested loop, break to a label.
  7. And most of all: factor some of those loops out into methods.

نصائح أخرى

Firstly: Do not abbreviate variables just to save some typing. This leads to obfuscate incrompreensible codes like that one.

Second, have you already heard about java.util.Map?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top