Segmented Controllers - ios5

Trying to set an int value using a Segmented Controller. I've seen several tuts on how to change labels, but I need to set an int value.
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize caseCost;
#synthesize dilution;
#synthesize returnMsg;
#synthesize opcValue;
//synthesize opc; < -- Tried
//int opc; <--- tried
- (IBAction)opcView:(id)sender {
if (opcValue.selectedSegmentIndex == 0) {
int opc = 320;
}
if (opcValue.selectedSegmentIndex == 1) {
int opc = 128;
}
if (opcValue.selectedSegmentIndex == 2) {
int opc = 135;
}
if (opcValue.selectedSegmentIndex == 3) {
int opc = 88;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//int opc; <--- tried
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)finishBtn:(id)sender {
//int opc = 320;
float case_cost = ([caseCost.text floatValue]);
float dilutionValue = ([dilution.text floatValue]);
float gpc = (opc / dilutionValue);
float gCost = (case_cost / gpc);
float bCost = (gCost / 4);
float bpc = (gpc * 4);
NSNumberFormatter *formatterCur = [[NSNumberFormatter alloc] init];
NSNumberFormatter *formatterInt = [[NSNumberFormatter alloc] init];
[formatterCur setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatterInt setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *bottlesCost = [formatterCur stringFromNumber:[NSNumber numberWithFloat:bCost]];
NSString *gallons = [formatterInt stringFromNumber:[NSNumber numberWithInt:gpc]];
NSString *gallonsCost = [formatterCur stringFromNumber:[NSNumber numberWithFloat:gCost]];
NSString *bottles = [formatterInt stringFromNumber:[NSNumber numberWithInt:bpc]];
returnMsg.text = [NSString stringWithFormat:#"%# gallons per case at %# per gallon and %# - 32 oz bottles at %# per bottle.", gallons, gallonsCost, bottles, bottlesCost];
}
- (IBAction)opcView:(id)sender {
}
#end
in the line "float gpc = (opc / dilutionValue);" is shows as an unknown value of opc, even though I think it should from the segmented controller. I'm using the segmented controller instead of Radio Buttons i've used in Java. I used the "//int opc=320" to make sure the rest of the code worked.

In each of the if blocks in your method - (IBAction)opcView:(id)sender you are creating a local int variable named opc. So when execution leaves the if block, the local variable disappears. Thus, in - (IBAction)finishBtn:(id)sender there is no variable named opc in scope.
You should declare opc to be a property as well. You will set this property when the segment control changes selection. Later, you can read the property's value in your finish button's handler.
#import "SecondViewController.h"
#interface SecondViewController()
#property (nonatomic) int opc;
#end
#implementation SecondViewController
// this method is wired to the segment control's UIControlEventValueChanged event
- (IBAction)opcView:(id)sender
{
if (opcValue.selectedSegmentIndex == 0) {
self.opc = 320;
}
if (opcValue.selectedSegmentIndex == 1) {
self.opc = 128;
}
if (opcValue.selectedSegmentIndex == 2) {
self.opc = 135;
}
if (opcValue.selectedSegmentIndex == 3) {
self.opc = 88;
}
}
- (IBAction)finishBtn:(id)sender
{
float case_cost = ([caseCost.text floatValue]);
float dilutionValue = ([dilution.text floatValue]);
float gpc = (self.opc / dilutionValue);
// lots more code
}

Related

How to extend my method that checking if 2 cards are matched to 3 cards that are matched?

I'm following the Stanford course, and we had to build a method for the app that checks for 2 cards matching, this is how the model that have the logic looks like (the method to look there is flipCardAtIndex):
#import "CardMatchingGame.h"
#import "PlayingCardsDeck.h"
#interface CardMatchingGame()
#property (readwrite, nonatomic) int score;
#property (strong, nonatomic) NSMutableArray *cards;
#property (strong, nonatomic) NSString *notification;
#end
#implementation CardMatchingGame
-(NSMutableArray *) cards {
if (!_cards) _cards = [[NSMutableArray alloc] init];
return _cards;
}
-(id)initWithCardCount:(NSUInteger)count usingDeck:(Deck *)deck {
self = [super init];
if (self) {
for (int i = 0; i < count; i++) {
Card *card = [deck drawRandonCard];
if (!card) {
self = nil;
} else {
self.cards[i] = card;
}
}
}
return self;
}
-(Card *) cardAtIndex:(NSUInteger)index {
return (index < self.cards.count) ? self.cards[index] : nil;
}
#define FLIP_COST 1
#define MISMATCH_PENALTY 2
#define BONUS 4
-(void) flipCardAtIndex:(NSUInteger)index {
Card *card = [self cardAtIndex:index];
if (!card.isUnplayable) {
if (!card.isFaceUp) {
for (Card *otherCard in self.cards) {
if (otherCard.isFaceUp && !otherCard.isUnplayable) {
int matchScore = [card match:#[otherCard]];
if (matchScore) {
otherCard.unplayble = YES;
card.unplayble = YES;
self.notification = [NSString stringWithFormat:#"%# & %# match!", card.contents, otherCard.contents];
self.score += matchScore * BONUS;
} else {
otherCard.faceUp = NO;
self.score -= MISMATCH_PENALTY;
self.notification = [NSString stringWithFormat:#"%# did not matched to %#", card.contents, otherCard.contents];
}
break;
}
}
self.score -= FLIP_COST;
}
card.faceUp = !card.isFaceUp;
}
}
#end
And this is the class model of the whole game, that got the actual matching method:
#import "PlayingCards.h"
#implementation PlayingCards
#synthesize suit = _suit;
//overriding the :match method of cards to give different acore if its only a suit match or a number match
-(int)match:(NSArray *)cardToMatch {
int score = 0;
if (cardToMatch.count == 1) {
PlayingCards *aCard = [cardToMatch lastObject];
if ([aCard.suit isEqualToString: self.suit]) {
score = 1;
} else if (aCard.rank == self.rank) {
score = 4;
}
}
return score;
}
//more stuff...
W already created it with an array so we will be able to extend it for more objects, but now i'm trying to figure out how do I extend it :/
This is my github for the project https://github.com/NirOhayon/Matchismo
i'm new to objective C and would appreciate it munch if you could help me to figure it out.
Thanks a bunch
You can chain these with a loop to check them all. Very basic way of doing it. Just loop through each card and check it against the "self" card that you have and increment the score instead of setting it.
-(int)match:(NSArray *)cardToMatch {
int score = 0;
for(int i = 0; i < cardToMatch.count; i++) {
PlayingCards *aCard = cardToMatch[i];
if ([aCard.suit isEqualToString: self.suit]) {
score += 1;
} else if (aCard.rank == self.rank) {
score += 4;
}
}
return score;
}
For flipCardAtIndex: , I would change it to flipCardsAtIndexes:(NSArray*)indexes, where indexes is an NSArray of NSNumbers. Then I would run a for loop checking and removing any cards that are unplayable or faceup, and pass through the remaining cards at those indexes to check match, and retrieve the match score.
To tell your view controller to add another card depends on how you have your view controller set up. You could do a protocol in a method that your view controller becomes the delegate of, and through a protocol method, tell it to switch. It could also be simpler than that, depending on how it checks your model of cards to decide what to show, if it sees three cards available instead of two, it could switch.
As the point of this exercise is to learn iOS programming, I want to give you a good head start and you should tweak and figure some stuff out on your own. I have a feeling you're a novice at programming, and if you are, you'll be surprised how much programming at your stage is trial and error. Eventually it will become second nature.

How to put a decimal point according to the will of the user in a calculator in iphone?

I have a calculator in which i would like to put the decimal point according to the button press for the decimal point. I get the decimal point but if I enter another digit the decimal pint vanishes and is overwritten .
The code is mentioned below for the decimal press:-
-(IBAction)decimalPressed:(id)sender{
calculatorScreen.text = [calculatorScreen.text stringByAppendingString:#"."];
}
For the digit press it is :-
-(IBAction)buttonDigitPressed:(id)sender{
currentNumber = currentNumber*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%g",currentNumber];
}
How can i do something like 23 then "." then 45. The result would be 23.45
I've recently done a calculator app and could understand your problem. Another thing you want to take note about the point is that you do not want to have multiple point in your calculation, e.g. 10.345.1123.5. Simply put, you want it to be a legal float number as well.
With that said, you can use a IBAction (remember to link it to your storyboard or xib file)
-(IBAction)decimalPressed:(UIButton *)sender
{
NSRange range = [self.display.text rangeOfString:#"."];
if (range.location ==NSNotFound){
self.display.text = [ self.display.text stringByAppendingString:#"."];
}
self.userIsInTheMiddleOfEnteringANumber = YES;
}
While it might be possible we are doing on the same project, it could also be entirely different (you starting from scratch by yourself) so i will go through some of the codes
you could replace UIButton with the default id, but it is better to static replace it to make clear clarification for yourself, or anyone else who view your code.
NSRange as the name implies, mark the range, and the range will be ur display text of calculation (e.g. 1235.3568), and the range of string it is targeting in this case is "."
therefore, if NSNotfound (rangeOfString "." is not found in the text range) you will append the current display text with "." with the function stringByAppendingString:#".", there is no else, so no function will take place if "." is already found, which solve the problem of multiple point on the display.
userIsInTheMiddleOfEnteringANumber is a BOOL to solve the problem of having 0 in ur display (e.g. 06357), if you have a method to change it, then replace my method name with your own.
Try with below code:
-(IBAction)buttonDigitPressed:(id)sender
{
UIButton *pressedButton = (UIButton *)sender;
calculatorScreen.text = [calculatorScreen.text stringByAppendingFormat:#"%d",pressedButton.tag];
currentNumber = [calculatorScreen.text floatValue];
}
-(IBAction)ButtonDot
{
decimalChecker = 10;
calculatorScreen.text = [NSString stringWithFormat:#"$ %g.", currentSavings];
decimalChecker=1;
}
-(IBAction)buttonDigitPressed:(id)sender
{
if (decimalChecker ==1)
{
currentDecimal = currentDecimal*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"$ %g.%g", currentSavings,currentDecimal];
}
else
{
currentSavings = currentSavings*10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"$ %g",currentSavings];
}
}
This is my solution:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
float result;
IBOutlet UILabel *TextInput;
int currentOperation;
float currentNumber;
BOOL userInTheMiddleOfEnteringDecimal;
}
- (IBAction)buttonDigitPressed:(id)sender;
- (IBAction)buttonOperationPressed:(id)sender;
- (IBAction)cancelInput;
- (IBAction)cancelOperation;
- (IBAction)dotPressed;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)buttonDigitPressed:(id)sender {
if(!userInTheMiddleOfEnteringDecimal)
{
currentNumber = currentNumber*10 + (float)[sender tag];
TextInput.text = [NSString stringWithFormat:#"%d",(int)currentNumber];
}
else{
TextInput.text= [TextInput.text stringByAppendingString:[NSString stringWithFormat:#"%d",[sender tag]]];
currentNumber = [TextInput.text floatValue];
}
}
- (IBAction)buttonOperationPressed:(id)sender {
if (currentOperation == 0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
default:
break;
}
}
currentNumber = 0;
TextInput.text = [NSString stringWithFormat:#"%.2f",result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
}
-(IBAction)cancelInput{
currentNumber = (int)(currentNumber/10);
TextInput.text = [NSString stringWithFormat:#"%.2f",currentNumber];;
}
-(IBAction)cancelOperation{
currentNumber = 0;
TextInput.text = #"0";
userInTheMiddleOfEnteringDecimal = NO;
}
- (IBAction)dotPressed{
if(!userInTheMiddleOfEnteringDecimal){
userInTheMiddleOfEnteringDecimal = YES;
TextInput.text= [TextInput.text stringByAppendingString:#"."];
}
}
#end
Hope this helps.. Another way of solution...
after pressing the "." all values after will be divided as following
the first number ur press after pressing "." will be divided by 10 the second by 100 and so on
so editing ur function it would be like this
-(IBAction)buttonDigitPressed:(id)sender{
currentNumber = currentNumber + (float)[sender tag] / 10.0;
calculatorScreen.text = [NSString stringWithFormat:#"%g",currentNumber];
}
i think in that solve your problem
http://www.datasprings.com/resources/articles-information/iphone-sdk-getting-started-example-code
There is sample code of calculator.

How to change number of decimal places and add decimal button iPhone Calculator?

So, look at the following code below- my first question is, how can I make it so there is only 0, 1, or 2 decimal places or make it automatically have however many decimal places are there? the second question is, how would I add a decimal button to the calculator? it has +-/*, how would I add a decimal button? Tutorial I used is here http://www.youtube.com/watch?v=Ihw0cfNOrr4 and here is my code-
viewcontroller.h
#import <UIKit/UIKit.h>
#interface calcViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
#end
in the .m
#import "calcViewController.h"
#implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:#"%2f", currentNumber];
}
-(IBAction)buttonOperationPressed:(id)sender {
if (currentOperation ==0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:#"%2f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = #"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = #"0";
currentOperation = 0;
}
you can use this on the output.
Float *number = 2.2f;
NSLog(#"%.2f",number);
Another thing you want to take note about the point is that you do not want to have multiple point in your calculation, e.g. 10.345.1123.5. Simply put, you want it to be a legal float number as well.
With that said, you can use a IBAction (remember to link it to your storyboard or xib file)
-(IBAction)decimalPressed:(UIButton *)sender
{
NSRange range = [self.display.text rangeOfString:#"."];
if (range.location ==NSNotFound){
self.display.text = [ self.display.text stringByAppendingString:#"."];
}
self.userIsInTheMiddleOfEnteringANumber = YES;
}
While it might be possible we are doing on the same project, it could also be entirely different (you starting from scratch by yourself) so i will go through some of the codes
you could replace UIButton with the default id, but it is better to static replace it to make clear clarification for yourself, or anyone else who view your code.
NSRange as the name implies, mark the range, and the range will be ur display text of calculation (e.g. 1235.3568), and the range of string it is targeting in this case is "." therefore, if NSNotfound (rangeOfString "." is not found in the text range) you will append the current display text with "." with the function stringByAppendingString:#".", there is no else, so no function will take place if "." is already found, which solve the problem of multiple point on the display.
userIsInTheMiddleOfEnteringANumber is a BOOL to solve the problem of having 0 in ur display (e.g. 06357), if you have a method to change it, then replace my method name with your own.
Regarding the display, as I'm using a different approach compared to yours, I'm unable to give any help or guide in that aspect.
This is my solution:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
float result;
IBOutlet UILabel *TextInput;
int currentOperation;
float currentNumber;
BOOL userInTheMiddleOfEnteringDecimal;
}
- (IBAction)buttonDigitPressed:(id)sender;
- (IBAction)buttonOperationPressed:(id)sender;
- (IBAction)cancelInput;
- (IBAction)cancelOperation;
- (IBAction)dotPressed;
#end
Viewcontroller.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)buttonDigitPressed:(id)sender {
if(!userInTheMiddleOfEnteringDecimal)
{
currentNumber = currentNumber*10 + (float)[sender tag];
TextInput.text = [NSString stringWithFormat:#"%d",(int)currentNumber];
}
else{
TextInput.text= [TextInput.text stringByAppendingString:[NSString stringWithFormat:#"%d",[sender tag]]];
currentNumber = [TextInput.text floatValue];
}
}
- (IBAction)buttonOperationPressed:(id)sender {
if (currentOperation == 0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
default:
break;
}
}
currentNumber = 0;
TextInput.text = [NSString stringWithFormat:#"%.2f",result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
}
-(IBAction)cancelInput{
currentNumber = (int)(currentNumber/10);
TextInput.text = [NSString stringWithFormat:#"%.2f",currentNumber];;
}
-(IBAction)cancelOperation{
currentNumber = 0;
TextInput.text = #"0";
userInTheMiddleOfEnteringDecimal = NO;
}
- (IBAction)dotPressed{
if(!userInTheMiddleOfEnteringDecimal){
userInTheMiddleOfEnteringDecimal = YES;
TextInput.text= [TextInput.text stringByAppendingString:#"."];
}
}
#end
Hope this helps.. This includes the decimal point in the button...

iphone slider with constum steps

i am not really familiar with objC and looking for a solution to build a slider that slides with "steps". on moving the slider the value increases like value+=10 or maybe value+=100. how do i do that?
I modified the code above for a custom Cocos2D slider http://yannickloriot.com/library/ios/cccontrolextension/Classes/CCControlSlider.html
It has properties:
#property (nonatomic, readwrite) float value;
#property (nonatomic, readwrite) minimumValue;
#property (nonatomic, readwrite) maximumValue;
#property (nonatomic, readwrite) int steps;
the recalculation:
- (void)recalcuateValue
{
float stepValues[self.steps];
stepValues[0] = self.minimumValue;
stepValues[self.steps - 1] = self.maximumValue;
for(int i = 1; i < self.steps; i++){
stepValues[i] = i * (self.maximumValue - self.minimumValue) / (self.steps - 1);
if (self.value < stepValues[i] && self.value > stepValues[i-1]){
self.value = (self.value > (stepValues[i] - stepValues[i-1]) / 2 + stepValues[i-1])?stepValues[i]:stepValues[i-1];
}
}
}
And the ccTouchesEnded: I added if(self.steps != 0), for the case steps is set to 0, the slider could work in usual mode
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
if ([self isSelected]){
self.value = [self valueForLocation:_thumbSprite.position];
if(self.steps != 0) {
[self recalcuateValue];
[_thumbSprite setPosition:[self locationFromValue:self.value]];
}
}
self.thumbSprite.color = ccWHITE;
self.selected = NO;
}
It calls valueForLocation and locationFromValue methods:
- (float)valueForLocation:(CGPoint)location
{
float percent = location.x / _backgroundSprite.contentSize.width;
return _minimumValue + percent * (_maximumValue - _minimumValue);
}
- (CGPoint)locationFromValue:(float)value{
float percent = self.value / self.maximumValue;
return ccp(percent * _backgroundSprite.contentSize.width, _backgroundSprite.position.y);
}
So an example of usage. I needed a slider with 3 steps and values 0, 1 and 2 on each step:
self.Slider = [CCControlSlider sliderWithBackgroundFile:#"sliderTrack.png"
progressFile:#"sliderProgress.png"
thumbFile:#"sliderThumb-hd.png"]; progressFile:#"sliderProgress.png" thumbFile:#"sliderThumb-hd.png"];
self.Slider.minimumValue = 0.0f;
self.Slider.maximumValue = 2.0f;
self.Slider.steps = 3;
self.Slider.value = [[GameSettings sharedSettings] defaultAILevel];
[self.Slider addTarget:self action:#selector(onSliderValueChanged:) forControlEvents:CCControlEventValueChanged];
Hope it may be useful
I created my discrete slider this way:
#import <UIKit/UIKit.h>
#interface DiscreteSlider : UISlider {
int step;
}
#property (nonatomic) int step;
#end
which that implementation:
#import "DiscreteSlider.h"
#implementation DiscreteSlider
#synthesize step;
- (void) recalcuateStep
{
float lValue = self.value;
int lLowerValue = (int) ( lValue / self.step );
float lDifference = lValue - ( lLowerValue * step );
float lHalfStep = ((float) step) / 2;
if( lDifference < lHalfStep ) {
} else {
self.value = (float) ( lLowerValue + step );
[self sendActionsForControlEvents:UIControlEventValueChanged];
}
}
- (void) touchesMoved:(NSSet *) touches
withEvent:(UIEvent *) event
{
[super touchesMoved:touches withEvent:event];
NSLog( #"DS.touchesMoved(), event: %#", event );
[self recalcuateStep];
}
- (void) endTrackingWithTouch:(UITouch *) touch
withEvent:(UIEvent *) event
{
[super endTrackingWithTouch:touch withEvent:event];
NSLog( #"DS.endTrackingWithTouch(), event: %#", event );
[self recalcuateStep];
}
- (int) step {
return ( step ? step : 1 );
}
#end

Rewrite C++ code into Objective C

I got some C++ Sourcecode that I would like to rewrite into Objective C.
It would help me alot if someone could write me a header file for this Code. When I get the Headerfile I would be able to rewrite the rest of the Sourcecode.
It would be very nice if someone could help me please.
Thanks
I will poste the sourcecode here:
#include <stdlib.h>
#include <iostream.h>
#define STATES 5
int transitionTable[STATES][STATES];
// function declarations:
double randfloat (void);
int chooseNextEventFromTable (int current, int table[STATES][STATES]);
int chooseNextEventFromTransitionTablee (int currentState);
void setTable (int value, int table[STATES][STATES]);
//////////////////////////////////////////////////////////////////////////
int main(void) {
int i;
// for demo purposes:
transitionTable[0][0] = 0;
transitionTable[0][1] = 20;
transitionTable[0][2] = 30;
transitionTable[0][3] = 50;
transitionTable[0][4] = 0;
transitionTable[1][0] = 35;
transitionTable[1][1] = 25;
transitionTable[1][2] = 20;
transitionTable[1][3] = 30;
transitionTable[1][4] = 0;
transitionTable[2][0] = 70;
transitionTable[2][1] = 0;
transitionTable[2][2] = 15;
transitionTable[2][3] = 0;
transitionTable[2][4] = 15;
transitionTable[3][0] = 0;
transitionTable[3][1] = 25;
transitionTable[3][2] = 25;
transitionTable[3][3] = 0;
transitionTable[3][4] = 50;
transitionTable[4][0] = 13;
transitionTable[4][1] = 17;
transitionTable[4][2] = 22;
transitionTable[4][3] = 48;
transitionTable[4][4] = 0;
int currentState = 0;
for (i=0; i<10; i++) {
std::cout << currentState << " ";
currentState = chooseNextEventFromTransitionTablee(currentState);
}
return 0;
};
//////////////////////////////////////////////////////////////////////////
//////////////////////////////
//
// chooseNextEventFromTransitionTable -- choose the next note.
//
int chooseNextEventFromTransitionTablee(int currentState) {
int targetSum = 0;
int sum = 0;
int targetNote = 0;
int totalevents = 0;
int i;
currentState = currentState % STATES; // remove any octave value
for (i=0; i<STATES; i++) {
totalevents += transitionTable[currentState][i];
}
targetSum = (int)(randfloat() * totalevents + 0.5);
while (targetNote < STATES &&
sum+transitionTable[currentState][targetNote] < targetSum) {
sum += transitionTable[currentState][targetNote];
targetNote++;
}
return targetNote;
}
//////////////////////////////
//
// randfloat -- returns a random number between 0.0 and 1.0.
//
double randfloat(void) {
return (double)rand()/RAND_MAX;
}
//////////////////////////////
//
// setTable -- set all values in the transition table to the given value.
//
void setTable(int value, int table[STATES][STATES]) {
int i, j;
for (i=0; i<STATES; i++) {
for (j=0; j<STATES; j++) {
table[i][j] = value;
}
}
}
Update
I'm not only compiling the header file there is another file i'm compiling too
SourceCode:
//
// markovThreadsChainsViewController.m
// markovThreadsChains
//
// Created by Philippe Mokrzycki on 15.01.11.
// Copyright 2011 TGM. All rights reserved.
//
#import "markovThreadsChainsViewController.h"
#import "markov.h"
//#import "markovChainOC.h"
#implementation markovThreadsChainsViewController
#synthesize mcValueLabel, threadStartGenerateButton, threadStopGenerateButton;
- (IBAction) startThreadGen:(UIButton *)sender{
threadStopGenerateButton.hidden=NO;
threadStartGenerateButton.hidden=YES;
mcValueLabel.text = #"0";
currentState=0;
// markovChainOC *mCobc = [[markovChainOC alloc]init];
// [mCobc setCurrentState:0];
[NSThread detachNewThreadSelector:#selector(startThreading) toTarget:self withObject:nil];
}
- (IBAction) stopThreadGen:(UIButton *)sender{
threadStopGenerateButton.hidden=YES;
threadStartGenerateButton.hidden=NO;
[NSThread detachNewThreadSelector:#selector(stopThreading) toTarget:self withObject:nil];
}
- (void) startThreading {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
[NSThread sleepForTimeInterval:3];
[self performSelectorOnMainThread:#selector(markovGen) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void) stopThreading {
[NSThread cancelPreviousPerformRequestsWithTarget:self];
}
- (void)markovGen{
transitionTable[0][0] = 25;
transitionTable[0][1] = 25;
transitionTable[1][0] = 25;
transitionTable[1][1] = 25;
// int actualValue = [mCobc getCurrentState];
int actualValue = currentState;
mcValueLabel.text = [NSString stringWithFormat:#"%", actualValue];
currentState = chooseNextEventFromTransitionTablee(currentState);
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(markovGen) userInfo:nil repeats:NO];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[mcValueLabel release];
[threadStartGenerateButton release];
[threadStopGenerateButton release];
// [mCobc release];
[super dealloc];
}
#end
This code has nothing object-oriented in it at all. Just change iostream.h to stdio.h, and cout to printf. Then it's a regular C program.
Just put these lines into a header file, and you should be able to include the header and call the functions from any other Objective-C or C source file.
(To support C++ also, you may need to put extern "C" { ... } around them, unless you are compiling everything as C++ or Objective-C++.)
#pragma once
#define STATES 5
int transitionTable[STATES][STATES];
// function declarations:
double randfloat (void);
int chooseNextEventFromTable (int current, int table[STATES][STATES]);
int chooseNextEventFromTransitionTablee (int currentState);
void setTable (int value, int table[STATES][STATES]);
More detail:
To use these functions from another class, you'll need the following files in your project:
markov.h (or whatever you decide to call it), containing the lines above.
markov.c (or whatever you decide to call it), containing the other stuff from your original source file, except for the main function, which you should remove
Then, your other files that use the functions should have an #include "markov.h" line, and then you should be able to call them.
If you are getting linker errors about missing functions, it means that you are not compiling markov.c as part of the project, or there are some options that are causing the function names to not match properly.