Reputation: 197
My guess is. However all the example I see create an instance of item_type say item_type_instance. However my case is more simpler...I want something descriptive for my array not just using 0 and 1.
enum item_type {weight, cost};
and then substitute weight and cost for 0 and 1.
void algo(int cost_low,int cost_high,int throw_weight, int item_id)
{
int quantity,remainder;
quantity=throw_weight/item_matrix[item_id][0];
remainder=throw_weight%item_matrix[item_id][0];
if(remainder==0)
{
cost_low=(quantity-1)*item_matrix[item_id][1];
cost_high=quantity*item_matrix[item_id][1];
throw_weight-=(quantity-1)*item_matrix[item_id][0];
}
else
{
cost_low=quantity*item_matrix[item_id][1];
cost_high=(quantity+1)*item_matrix[item_id][1];
throw_weight-=quantity*item_matrix[item_id][0];
}
}
Upvotes: 0
Views: 71
Reputation: 41519
Of course you could do that; but wouldn't you rather represent the item
s in the item_matrix
by something more meaningful than an array?
struct Item {
int weight;
int cost;
};
This may render your algorithm more readable:
void algo(int cost_low,int cost_high,int throw_weight, int item_id)
{
int quantity,remainder;
Item& item = item_matrix[item_id];
quantity=throw_weight/item.weight;
remainder=throw_weight%item.weight;
if(remainder==0)
{
cost_low=(quantity-1)*item.cost;
cost_high=quantity*item.cost;
throw_weight-=(quantity-1)*item.weight;
}
else
{
cost_low=quantity*item.cost;
cost_high=(quantity+1)*item.cost;
throw_weight-=quantity*item.cost;
}
}
It may be possible to refactor even further, and delegating the calculation to the Item
, too.
-- EDIT
I couldn't resist... It is possible to delegate to the Item
itself, getting rid of all the item.xxx
notations.
struct Item {
int weight;
int cost;
void algo( int& cost_low, int& cost_high, int& throw_weight ) {
int quantity = throw_weight / weight;
int remainder = throw_weight % weight;
cost_low=(quantity-1)*cost;
cost_high=quantity*cost;
throw_weight -= (quantity-1)*weight;
if( remainder != 0 ) {
cost_low += cost;
cost_high += cost;
throw_weight += weight;
}
}
};
Usage:
item_matrix[item_id].algo( cost_low, cost_high, throw_weight );
Upvotes: 3
Reputation: 361702
If I understand your question correctly then I think you want to use enum
as index to the array. If so, then you can do that:
quantity=throw_weight/item_matrix[item_id][weight]; //weight <=> 0
cost_low=(quantity-1)*item_matrix[item_id][cost]; //cost <=> 1
The value of weight
and cost
are 0
and 1
respectively, so the above code is perfectly fine. If the value for enumeration is not provided, then it starts with 0
and increments 1
with each subsequent enum label.
Upvotes: 0
Reputation: 81389
Simply define the enumerators to be 0 and 1:
enum item_type
{
weight = 0
, cost = 1
};
The standard conversion from enum
to int
will allow you to use enumerations to index an array.
Upvotes: 1