Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Another math question. 2

Status
Not open for further replies.

travs69

MIS
Dec 21, 2006
1,431
0
0
US
Right now I have a hash that looks like
%hash = (
1 => 1,
2 => 1,
3 => 2,
4 => 2,
5 => 3,
6 => 3,
7 => 4,
8 => 4,
);

Is there a way to do this other than hard coding them in? (In my best red neck voice) Maybe one of them their fangled dangled mathmatical formulas?

Thanks !


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
This should create the hash you are looking for:
Code:
my %h;

foreach (1..100) {
	$h{$_} = int(($_+1)/2);
}
Or another way:
Code:
my %h = map {$_, int(($_+1)/2)} 1..100;
 
Any performance reason to keep this as small as possible? I can't see us over going over 20 but who knows.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
Just as an aside, if all you're trying to do is create a lookup table for that maths function, you should check out the Memoize module.

This allows the return value of subroutines to be cached for efficiency.

So you would write your subroutine to do the int / 2 thing and Memoize would remember each value passed to the sub and simply return the previous answer.

Effectively it's doing the same as you are but more flexibly and transparently ... but perhaps a little slower.

Have a look anyway - I'm a convert these days :)
 
travs69 said:
Any performance reason to keep this as small as possible?
Since you asked, and I was curious, I ran the two different methods through benchmark ('map' vs. 'foreach'.) As I suspected, the 'foreach' method is definitely faster over a large number of iterations.

Since you're only making a list from 1 to 20 (or 100, or 1000 even.) the difference in speed will probably be insignificant. So use whichever method is easier for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top