int WordToInteger(Word w)
{
// convert w into an integer based on the values of letters
int intnumber = 0;
for (int i = 0; i < w.numletters; ++i)
{
intnumber += Math.pow(10, w.numletters-i-1) * elementAt(w.letters[i].id);
}
return intnumber;
}
Optimize this function
Do it in reverse and keep a digit factor:
No more pow(...) call. You probably want to make sure that the input passed in is valid too.
Cheers, dorix
int WordToInteger(Word w){ // convert w into an integer based on the values of letters int intnumber = 0; int digitfactor = 1; for (int i = w.numletters-1; i >= 0; i--) { intnumber += digitfactor * elementAt(w.letters[i].id); digitfactor *= 10; } return intnumber;}
No more pow(...) call. You probably want to make sure that the input passed in is valid too.
Cheers, dorix
Thanks! Simple and effective. I just tried it... in a program that called that function over 150,000 times it reduced the running time from 1600 milliseconds to 300
Yeah all non-primitive types are like pointers or references.. you don''t even have a choice. When you create a new instance of anything you have to call new.
Well that definitely helped... now i need to optimize other things and try to reduce the number of times i have to call that function.
Well that definitely helped... now i need to optimize other things and try to reduce the number of times i have to call that function.
Nothing is pass by reference in Java. Java has no references. Everything is pass by value; it just happens that object variables are pointers to objects on the garbage collected heap, so are passed by pointer value.
int WordToInteger(Word w){ int intnumber = 0; for (int i = 0; i < w.numletters; ++i) { intnumber = intnumber * 10 + elementAt (w.letters[i].id); } return intnumber;}
http 500 strike 1..
Stoffel: Your version will not give the same result, you push all digits left then add the new one at the end(right).
Bigshot and dorix add new digits left of all the others.
Bigshot and dorix add new digits left of all the others.
Ah, you are correct. When I''ve worked with hashing strings before, the first letter is the most significant so my method is the one I use. This will give the same output:
int WordToInteger(Word w){ int intnumber = 0; for (int i = w.numletters-1; i >= 0; i--) { intnumber = 10 * intnumber + elementAt(w.letters[i].id); }return intnumber;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement