Sunday, December 23, 2012

How to lap with an expanding amount of ints

Blog Post 12: How to "lap" with an expanding amount of ints

Well, you should be happy to know that once again I am back with an actual programming post. I was on Stack Overflow and somebody asked a question on how to make laps with an int. Here's the set up:

There is an UIButton, it launches an action on press that increments a value (tapCount), the OP wanted to know how he increases a lapCount every hundred place. So, when tapCount = 100, lapCount should =1, etc. Now, since this value could go on forever, he needed some math to accomplish this.

If we used a float value, or any unit of infinite precision, or even fairly accurate precision, this would be a little more complicated. Luckily, at least in Objective-C, we can just use int. Int will NOT use decimals, and will only increment if it actually equals that value, it also tends to round down everytime. Therefore, with this simple code, you can lap things.

In the .h

#import <UIKit/UIKit.h>

@interface TapCounterViewController : UIViewController
- (IBAction)buttonTouched:(id)sender;

In the .m

#import "TapCounterViewController.h"

@interface TapCounterViewController ()


@implementation TapCounterViewController

int lapNumber = 0;
int buttonTaps = 0;
- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

- (void)didReceiveMemoryWarning
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

- (IBAction)buttonTouched:(id)sender {
    buttonTaps = buttonTaps + 1;
    NSLog(@"Current Button Taps = %i", buttonTaps);

    //Check for Lap
    [self checkForLap];

-(void)checkForLap {
    //We must divide by 100 to check for the number if laps.
    int laps = buttonTaps/100;
    NSLog(@"Number of laps = %i", laps);
    lapNumber = laps;
As you can see, by using two simple global variables, we are able to every time the button is tapped, increment tapCount by 1, then check for lap. In check for lap, we simply take the buttonTaps, divide by whatever number we want per lap, in this case 100, and that will always round to the correct value.

So, I tested this out and here are some examples of the return.

tapCount = 5, lapCount = 0

tapCount = 55, lapCount = 0

tapCount = 177, lapCount = 1

tapCount = 200, lapCount = 2

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.