## 4 replies

Last post Nov 09, 2010 09:20 AM by cookie_powered

• stevex33

Member

154 Points

350 Posts

### Simple "While" question

Hi,

I'm using a while loop and I think it can be done more efficiently but I'm not sure how.

Can anyone make any suggestions:

```Dim maxInfraPurchase As Integer = 1

While infrastructureChunkCost(currentInfra, maxInfraPurchase) < currentCash

If infrastructureChunkCost(currentInfra, maxInfraPurchase + 1) < currentCash Then
maxInfraPurchase = maxInfraPurchase + 1
Else : Exit While
End If

End While```

I should probably use a "do while" loop, but I'm not as confident with those.

Basically I want to see if an existing value results in a cost that is greater than a persons current cash, if it's not, then I'll increase the cost by 1 and test again, until it DOES cost more than the person can afford.

Member

132 Points

126 Posts

### Re: Simple "While" question

from what i can gather,  you are getting the persons currentCash  therefore why not just:<:o:p>

infrastructureChunkCost = currentcash + 1 and do away with the loop, unless i'm misunderstanding what you are trying to achieve?<:o:p>

• stevex33

Member

154 Points

350 Posts

### Re: Simple "While" question

the function "infrastructureChunkCost" returns the total cost of the requested infrastructure based on the currentinfrastructure level and the extra requested amount, it splits the infrastructure request into chunks of 10, and must loop through it as after the first loop, it may cross a threshold that makes the next purchase more expensive than the last, even if it's for the same number of units.

In other words the cost can be dynamic, while the currentcash is fixed.

If they can afford 1 unit of infrastructure, then see if they can afford another unit of infrastructure, if they can't end the loop and return the amount they can purchase, otherwise keep testing to see if they can afford 1 more unit.

• David Anton

Contributor

2132 Points

675 Posts

### Re: Simple "While" question

Nov 09, 2010 09:02 AM|David Anton|LINK

```Do While infrastructureChunkCost(currentInfra, maxInfraPurchase) < currentCash
maxInfraPurchase += 1
Loop```

You might have to decrement 'maxInfraPurchase' after the loop if you're using it again since the my version leaves this variable with a value greater by one than your version after the loop.

David Anton
http://www.tangiblesoftwaresolutions.com
Instant C# - VB to C# Converter
Instant VB - C# to VB Converter

Member

132 Points

126 Posts