Accelerometer calculations resulting in inf - ios

I have been trying to get to move an UIImageView with the accelerometer, however I have run into an issue. When I try to smooth out the data and work out the acceleration of the data from the original position, the values return infinity. I'm not really sure what I'm doing wrong!
Here's my code:
- (void)viewDidLoad {
gameObjects = [NSMutableArray arrayWithObjects: nil];
UIImageView* mainChar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[mainChar setCenter:CGPointMake(screenHeight/2, screenWidth/2)];
mainChar.image = [UIImage imageNamed:#"dot.png"];
[self.view insertSubview:mainChar atIndex:2];
[gameObjects addObject:mainChar];
mainChar = nil;
AvData = [NSMutableArray arrayWithObjects: nil];
motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 20;
[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData* accelerationData, NSError* error) {
if (defaultData == nil) {defaultData = accelerationData;}
[self accelerometerUpdate:accelerationData];
}];
}
-(void) accelerometerUpdate:(CMAccelerometerData*)aData {
//Accelerometer Smoothing
[AvData addObject:aData];
if ([AvData count] >= 20) {[AvData removeObjectAtIndex:0];}
float avX = 0;
float avY = 0;
float avZ = 0;
for (int i = 0; i < [AvData count]; i++) {
avX = avX + [[AvData objectAtIndex:i] acceleration].x;
avY = avY + [[AvData objectAtIndex:i] acceleration].y;
avZ = avZ + [[AvData objectAtIndex:i] acceleration].z;
}
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
//Calculate the delta from original device acceleration value
float accX = defaultData.acceleration.x - avX;
float accY = defaultData.acceleration.y - avY;
//float accZ = defaultData.acceleration.z - avZ;
NSLog([NSString stringWithFormat:#"%f", accY]);
UIImageView* mainChar = [gameObjects objectAtIndex:0];
[mainChar setCenter:CGPointMake(mainChar.center.x + accX, mainChar.center.y + accY)];
//accX and accY are infinity for some reason, and so the image disappears!
mainChar = nil;
}
The weird thing is when I NSLog accY, it returns a proper value. What am I doing wrong?

Off the top of my head:
When you get to these lines:
avX = avX/([AvData count] - 1);
avY = avY/([AvData count] - 1);
avZ = avZ/([AvData count] - 1);
If count == 1 at that point, your code will divide by zero. I would expect that to crash, but if not, the result would be infinity or NAN. (I'd expect NAN, but it might return INF if it doesn't throw an exception. I'd need to test it or look it up to be sure.)

Related

How to draw PolyLine in MapView ios9

I have create a PolyLine in MapView. I tried to many times but did not draw. Ones a draw polyLine but that case run only simulator, I run in device and crash my app. and I already post my question here
I tried to many times and using lots of tutorials, please suggest any other tutorial.
I want to create a PolyLine in MapView using google direction URL. Starting point is my device location and end point is any lat long. so both points in centre draw a polyLine. That means create a root map starting point to end point draw a PolyLine.
Please help, Thank you
you can use google api for this
http://maps.googleapis.com/maps/api/directions/json?origin
in this api you have to pass lat log of your locations like this methode
-(NSArray*) calculateRoutes
{
NSString *baseUrl = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true",currentlatitude,currentlongitude,destination lat,destination log];
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:baseUrl]];
if (data) {
NSDictionary *direction_dictionary=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (direction_dictionary) {
if ([[direction_dictionary valueForKey:#"status"] isEqualToString:#"OK"]) {
NSArray *routes_array=[direction_dictionary valueForKey:#"routes"];
if (routes_array) {
NSString *poinstEncoded_String=[[[routes_array firstObject] valueForKey:#"overview_polyline"] valueForKey:#"points"];
routes = [self decodePolyLine:[poinstEncoded_String mutableCopy]];
NSInteger numberOfSteps = routes.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++)
{
CLLocation *location = [routes objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
dispatch_async(dispatch_get_main_queue(), ^{
[self.MapVw addOverlay:polyLine];
// add polyline here to your mapview
});
}
}
}
}
}
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded
{
[encoded replaceOccurrencesOfString:#"\\\\" withString:#"\\" options:NSLiteralSearch range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init];
NSInteger lat=0;
NSInteger lng=0;
while (index < len)
{
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do
{
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
[array addObject:loc];
}
return array;
}
After getting response (Full example http://way2ios.com/development/ios-development-2/iphone-2/draw-polygon-mkmapview-stylus/):
– (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id )overlay
{
MKPolygonView *polygonView = [[MKPolygonView alloc] initWithPolygon:overlay];
polygonView.lineWidth = 5;
polygonView.strokeColor = [UIColor redColor];
polygonView.fillColor = [UIColor colorWithRed:0 green:191 blue:255 alpha:0.5];
mapView.userInteractionEnabled = YES;
return polygonView;
}
Check these also :
https://github.com/kadirpekel/MapWithRoutes and https://github.com/versluis/MapViewLines

Move Buttons to image targets

I am new in objective c and now i try to build game like What's the word and i have some problems with targets coordinates and button passing into targets. I create a -(void)dealRandomWord here I am take randome a word from plist and output all my subview on screen. I call it from viewDidLoad: [self dealRandomWord].
And here is my problem:
#pragma mark Targets
_targets = [NSMutableArray arrayWithCapacity:word1len];
for (NSInteger i = 0; i < word1len; i++) {
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
TargetView *target = [[TargetView alloc] initWithLetter:letter andSideLength: letterSide];
target.center = CGPointMake(xCenterTarget + i * (letterSide + kLetterMargin), placesView.frame.size.height / 2);
[placesView addSubview:target];
NSLog(#"biiitch %#", NSStringFromCGPoint(target.center));
}
In target.center i have the coordinates of targets where i want to move my buttons by click. When i click one of the button it moved but not in the target, it happens because in
-(void)placeForButton:(InputButtonsView*)inputButtonsView atTarget:(TargetView*)targetView {
targetView.center coordinate equal {0,0}
How can i pass coordinates for each of target to my button that it's move to target. Every next button should move to next target.
Here is image: Screenshot
Thanks for any help!!!
Here is my code:
-(void)dealRandomWord {
#pragma mark Level and words init
NSAssert(self.level.words, #"Level not loaded");
// random word from plist
NSInteger randomIndex = arc4random()%[self.level.words count];
NSArray* anaPair = self.level.words[ randomIndex ];
NSString* question = anaPair[0]; // question
NSString* word1 = anaPair[1]; // answer
NSString* word2 = anaPair[2]; // some letters
NSString* helpstr = anaPair[3]; // helper
NSLog(#"qweqweq %# %# %#" , word1 , word2 , helpstr);
NSInteger word1len = [word1 length];
NSInteger word2len = [word2 length];
NSLog(#"phrase1[%li]: %#", (long)word1len, word1);
NSLog(#"phrase2[%li]: %#", (long)word2len, word2);
NSLog(#"question %#", question);
float letterSide = ceilf (kScreenWidth * 0.9 / (float)MAX(word1len, word2len) - kLetterMargin);
float xOffset = (kScreenWidth - (float)MAX(word1len, word2len) * (letterSide + kLetterMargin))/3;
xOffset += letterSide/2;
float yOffset = 1.5* letterSide;
#pragma mark QuestionView init
QuestionView *quv = [[QuestionView alloc] init];
quv.questionLabel.text = question;
[self.view addSubview:quv];
quv.center = CGPointMake(185, 210);
#pragma mark PlacesView init
PlacesView *placesView = [[PlacesView alloc] init];
[self.view addSubview:placesView];
placesView.center = CGPointMake(185, 400);
//Center x position for targets
float xCenterTarget = ((placesView.frame.size.width / 2) - ((word1len / 2) * letterSide ));
#pragma mark LetterView init
LettersView *lettersView = [[LettersView alloc] init];
[self.view addSubview:lettersView];
lettersView.center = CGPointMake(185, 500);
#pragma mark Targets
_targets = [NSMutableArray arrayWithCapacity:word1len];
for (NSInteger i = 0; i < word1len; i++) {
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
TargetView *target = [[TargetView alloc] initWithLetter:letter andSideLength: letterSide];
target.center = CGPointMake(xCenterTarget + i * (letterSide + kLetterMargin), placesView.frame.size.height / 2);
[placesView addSubview:target];
NSLog(#"coord target init %#", NSStringFromCGPoint(target.center));
}
#pragma mark LettersView init
//init letters list
_letters = [NSMutableArray arrayWithCapacity: word2len];
//create letter
for (NSInteger i=0;i<word2len;i++) {
NSString* letter = [word2 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
InputButtonsView *buttons = [[InputButtonsView alloc] initWithLetter:letter andSideLength:letterSide];
buttons.center = CGPointMake(xOffset + i * (letterSide + kLetterMargin), lettersView.frame.size.height /2); // "/3*4" kScreenHeight/4*3
if (i > 6) {
buttons.center = CGPointMake(- 7 * xOffset + i * (letterSide + kLetterMargin), lettersView.frame.size.height/2 + (letterSide + kLetterMargin)); // "/3*4"
}
buttons.clickDelegate = self;
[lettersView addSubview:buttons];
//[buttons addSubview:buttons];
[_letters addObject: letter];
}
}
}
-(void)inputButtonView:(InputButtonsView *)inputButtonView didPress:(CGPoint)didPress {
TargetView *targetView = nil;
NSLog(#"did press x = %f, y = %f", didPress.x , didPress.y);
for(TargetView *tv in _targets) {
if(CGRectContainsPoint(tv.frame, didPress)){
targetView = tv;
break;
}
}
[self placeForButton:inputButtonView atTarget:targetView];
if (targetView != nil) {
NSLog(#"Kek");
if ([targetView.letter isEqualToString: inputButtonView.letter]) {
[self placeForButton:inputButtonView atTarget:targetView];
}
}
}
-(void)placeForButton:(InputButtonsView*)inputButtonsView atTarget:(TargetView*)targetView {
targetView.isMatched = YES;
inputButtonsView.isMatched = YES;
inputButtonsView.userInteractionEnabled = NO;
CGPoint originButtons = [self.view.superview convertPoint:CGPointZero fromView:inputButtonsView];
CGPoint originTargets = [self.view.superview convertPoint:CGPointZero fromView:targetView];
inputButtonsView.center = originButtons;
targetView.center = originTargets;
NSLog(#"OriginButtons = %# , OriginTargets = %#", NSStringFromCGPoint(originButtons) , NSStringFromCGPoint(originTargets));
inputButtonsView.center = targetView.center;
NSLog(#"TARGETVIEW.center %#", NSStringFromCGPoint(targetView.center));
}

ios-charts radar chart turn auto scaling OFF

These two radar charts have the same data points for the orange bit, but different for the gray. However, as you can see it is autoscaling, and the orange bit ends up bigger on the second chart, even though they are the same exact data points. Is there a way to turn autoscaling off? I would like 100% to go right to the edge of the chart also.
-(void)setupRadarChart
{
self.radarChart.descriptionText = #"";
self.radarChart.webLineWidth = .75;
self.radarChart.innerWebLineWidth = 0.375;
self.radarChart.webAlpha = 1.0;
self.radarChart.userInteractionEnabled = NO;
self.radarChart.xAxis.enabled = YES;
ChartYAxis *yAxis = self.radarChart.yAxis;
yAxis.enabled = NO;
ChartLegend *l = self.radarChart.legend;
l.position = ChartLegendPositionBelowChartLeft;
l.font = [UIFont systemFontOfSize:UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? 12 : (headerWidth/40)];
[self setRadarData];
}
- (void)setRadarData
{
NSMutableArray *parties = [[NSMutableArray alloc] init];
for (PillarModel *m in [DataManager sharedData].pillars)
{
[parties addObject:m.abbreviation];
}
NSMutableArray *yVals2 = [[NSMutableArray alloc] init];
NSMutableArray *benchMark = [[NSMutableArray alloc] init];
BOOL shouldAdd = YES;
for (PillarModel *pillar in [DataManager sharedData].pillars)
{ int totalPillarScore = (int)[[DataManager sharedData] getTotalScorePossible:[[DataManager sharedData] getIndividualQuestionResultsForPillar:pillar.pillarId]];
if ((isCompany ? [[DataManager sharedData] getCompanyScoresForCategory:pillar] : [[DataManager sharedData] getIndividualScoreForCategory:pillar.pillarId]) != 0)
{
shouldAdd = NO;
}
if (pillar.pillarId == numberOfPillars -1 && shouldAdd) {
[yVals2 addObject:[[ChartDataEntry alloc] initWithValue:0.01 xIndex:pillar.pillarId]];
}
else{
double val = (isCompany ? (double)[[DataManager sharedData] getCompanyScoresForCategory:pillar]/totalPillarScore : (double)[[DataManager sharedData] getIndividualScoreForCategory:pillar.pillarId] / totalPillarScore);
[yVals2 addObject:[[ChartDataEntry alloc] initWithValue:val xIndex:pillar.pillarId]];
}
float pillarBenchMark = [[[[[DataManager sharedData].benchmarkJSONDict objectForKey:hightlightedView.lowercaseString] objectForKey:pillar.title] objectForKey:#"pillar"] intValue];
float ifNoBenchMarkThanCompanyScore = (pillarBenchMark ? pillarBenchMark : (isCompany ? [[DataManager sharedData] getIndividualScoreForCategory:pillar.pillarId]: [[DataManager sharedData] getCompanyScoresForCategory:pillar]));
[benchMark addObject:[[ChartDataEntry alloc] initWithValue:ifNoBenchMarkThanCompanyScore/totalPillarScore xIndex:pillar.pillarId]];
}
NSMutableArray *xVals = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfPillars; i++)
{
[xVals addObject:parties[i % parties.count]];
}
NSString *label = (isCompany ? #"Company score" : #"Your score");
RadarChartDataSet *set2 = [[RadarChartDataSet alloc] initWithYVals:yVals2 label:label];
[set2 setColor:[DataManager sharedData].mainColor];
set2.drawFilledEnabled = YES;
set2.fillAlpha = 1.0f;
set2.lineWidth = 2.0;
RadarChartDataSet *benchMarkSet = [[RadarChartDataSet alloc] initWithYVals:benchMark label:#"Benchmark"];
[benchMarkSet setColor:[UIColor colorWithRed:125/255.0f green:125/255.0f blue:125/255.0f alpha:0.6f]];
benchMarkSet.drawFilledEnabled = YES;
benchMarkSet.fillAlpha = 0.0f;
benchMarkSet.lineWidth = 2.0;
benchMarkSet.highlightLineDashLengths = #[[NSNumber numberWithInt:2]];
benchMarkSet.highlightLineDashPhase = 2;
RadarChartData *data = [[RadarChartData alloc] initWithXVals:xVals dataSets:#[set2, benchMarkSet]];
[data setValueFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:8.f]];
[data setDrawValues:NO];
self.radarChart.data = data;
}
The answer that was posted by 孙博弘 wasn't correct, but it led me to realise how easy this was to solve. This solves both the autoscaling problem and also now reaches the edge.
self.radarChart.yAxis.customAxisMin = 0;
self.radarChart.yAxis.customAxisMax = 1;
i'm afraid that you shouln't use customAxisMax directly as it use a Internal Access Levels.https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html
/// Flag indicating that the axis-max value has been customized
internal var _customAxisMax: Bool = false
Instead, you can use axisMaxValue to control it.
/// The maximum value for this axis.
/// If set, this value will not be calculated automatically depending on the provided data.
/// Use `resetCustomAxisMin()` to undo this.
public var axisMaxValue: Double
{
get
{
return _axisMaximum
}
set
{
_customAxisMax = true
_axisMaximum = newValue
}
}
//2016-06-12 update
public var factor: CGFloat
{
let content = _viewPortHandler.contentRect
return min(content.width / 2.0, content.height / 2.0)
/ CGFloat(_yAxis.axisRange)
}
RadarChartView will calculator a factor to transform values into pixels.
Maybe,you can use axisMinValue and axisMaxValue to control autoscale.

SHLineGraphView - Set graph origin value

Using SHLineGraphView
I want to specify the origin of my graph to a different value other than 0.
The issue was already created here Min/Max draw Y axis but the owner seems uninterested in solving it.
This is what I have now
SHLineGraphView.m
#define BOTTOM_MARGIN_TO_LEAVE 30.0
#define TOP_MARGIN_TO_LEAVE 30.0
#define INTERVAL_COUNT 10
//INTERVAL_COUNT - 3 -> Limits the y-axis to 60 but
//not the entire graph.
- (void)drawYLabels:(SHPlot *)plot {
double yRange = [_yAxisRange doubleValue]; // this value will be in dollars
double yIntervalValue = yRange / INTERVAL_COUNT;
double intervalInPx = (self.bounds.size.height - BOTTOM_MARGIN_TO_LEAVE ) / (INTERVAL_COUNT - 3);
NSLog(#"interval px %f",intervalInPx);
NSMutableArray *labelArray = [NSMutableArray array];
float maxWidth = 0;
for(int i= 0; i <= INTERVAL_COUNT - 3 ; i++){
CGPoint currentLinePoint = CGPointMake(_leftMarginToLeave, i * intervalInPx);
CGRect lableFrame = CGRectMake(0, currentLinePoint.y - (intervalInPx / 2), 100, intervalInPx);
NSLog(#"label frame %f", lableFrame.origin.y);
//if(i != 0) {
UILabel *yAxisLabel = [[UILabel alloc] initWithFrame:lableFrame];
yAxisLabel.backgroundColor = [UIColor clearColor];
yAxisLabel.font = (UIFont *)_themeAttributes[kYAxisLabelFontKey];
yAxisLabel.textColor = (UIColor *)_themeAttributes[kYAxisLabelColorKey];
yAxisLabel.textAlignment = NSTextAlignmentCenter;
float val = (yIntervalValue * (10 - i));
NSLog(#"value %f", val);
if(val > 0){
yAxisLabel.text = [NSString stringWithFormat:#"%.1i%#", (int)val, _yAxisSuffix];
} else {
yAxisLabel.text = [NSString stringWithFormat:#"%.0f", val];
}
[yAxisLabel sizeToFit];
CGRect newLabelFrame = CGRectMake(0, currentLinePoint.y - (yAxisLabel.layer.frame.size.height / 2), yAxisLabel.frame.size.width, yAxisLabel.layer.frame.size.height);
yAxisLabel.frame = newLabelFrame;
if(newLabelFrame.size.width > maxWidth) {
maxWidth = newLabelFrame.size.width;
}
[labelArray addObject:yAxisLabel];
[self addSubview:yAxisLabel];
//}
}
viewController.m
_graphView.yAxisRange = #(200);
The y-axis is ok but the graph is still plotted from origin 0.
Create a yAxisMinValue property
#property (nonatomic, strong) NSNumber *yAxisMinValue;
...and update your drawYLabels function as follows:
- (void)drawYLabels:(SHPlot *)plot {
double yRange = [_yAxisRange doubleValue]; // this value will be in dollars
double yRangeMin = [_yAxisMinValue doubleValue];
NSLog(#"yRange: %f", yRange);
NSLog(#"yRangeMin: %f", yRangeMin);
double yIntervalValue = (yRange - yRangeMin) / INTERVAL_COUNT;
NSLog(#"yIntervalValue: %f", yIntervalValue);
double intervalInPx = (self.bounds.size.height - BOTTOM_MARGIN_TO_LEAVE ) / (INTERVAL_COUNT +1);
NSMutableArray *labelArray = [NSMutableArray array];
float maxWidth = 0;
for(int i= INTERVAL_COUNT + 1; i >= 0; i--){
NSLog(#"i = %d",i);
CGPoint currentLinePoint = CGPointMake(_leftMarginToLeave, i * intervalInPx);
CGRect lableFrame = CGRectMake(0, currentLinePoint.y - (intervalInPx / 2), 100, intervalInPx);
if(i != 0) {
UILabel *yAxisLabel = [[UILabel alloc] initWithFrame:lableFrame];
yAxisLabel.backgroundColor = [UIColor clearColor];
yAxisLabel.font = (UIFont *)_themeAttributes[kYAxisLabelFontKey];
yAxisLabel.textColor = (UIColor *)_themeAttributes[kYAxisLabelColorKey];
yAxisLabel.textAlignment = NSTextAlignmentCenter;
float val = (yIntervalValue * (10 - i)) + yRangeMin;
if(val > yRangeMin){
yAxisLabel.text = [NSString stringWithFormat:#"%.1f%#", val, _yAxisSuffix];
NSLog(#"%.1f%#", val, _yAxisSuffix);
} else {
yAxisLabel.text = [NSString stringWithFormat:#"%.1f", val];
NSLog(#"%.1f", val);
}
[yAxisLabel sizeToFit];
CGRect newLabelFrame = CGRectMake(0, currentLinePoint.y - (yAxisLabel.layer.frame.size.height / 2), yAxisLabel.frame.size.width, yAxisLabel.layer.frame.size.height);
yAxisLabel.frame = newLabelFrame;
if(newLabelFrame.size.width > maxWidth) {
maxWidth = newLabelFrame.size.width;
}
[labelArray addObject:yAxisLabel];
[self addSubview:yAxisLabel];
}
}

How to generate random letters as per the word

I’m developing word puzzle game,where one word is given.according to that word the random letters are generated…for that, i applied below logic but some how the random letters not generated as per the given word.
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc]
initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",
nil];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
for(int i =0;i<32;i++)
{
NSUInteger randomIndex = arc4random() %(ArrOfABCD.count);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:[NSString stringWithFormat:#"%#",ArrOfABCD[randomIndex]]
forState:UIControlStateNormal];
[self.view addSubview:btnLetter];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}
can any one suggest me that where i made mistake?
You should generate the unique random number
NSMutableArray* ArrOfWords = [[NSMutableArray alloc] initWithObjects:#"Good",#"Home",#"Beauty",#"Good",nil];
NSMutableArray *ArrOfABCD = [[NSMutableArray alloc] initWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
NSMutableArray *arrDuplicate=[[NSMutableArray alloc]init];
float x = 70;
float y = 100;
float width = 30;
float height = 20;
NSInteger rowIndex=4;
NSString *dataString=[ArrOfWords objectAtIndex:0];
NSMutableArray *arrNumber = [[NSMutableArray alloc]init];
for (int i = 0; i < [dataString length]; i++) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
NSNumber *number=[NSNumber numberWithInt:index];
while ([arrDuplicate containsObject:number] ) {
NSInteger index=arc4random_uniform(rowIndex)+rowIndex;
number=[NSNumber numberWithInt:index];
}
[arrNumber addObject:number];
[arrDuplicate addObject:number];
}
[arrDuplicate removeAllObjects];
NSMutableArray *arrayChar = [NSMutableArray array];
for (int i = 0; i < [dataString length]; i++) {
[arrayChar addObject:[NSString stringWithFormat:#"%C", [dataString characterAtIndex:i]]];
}
for(int i =0;i<32;i++)
{
NSString *str=[ArrOfABCD objectAtIndex:arc4random_uniform(ArrOfABCD.count)];
if ([arrNumber containsObject:[NSNumber numberWithInt:i]] ) {
str=[arrayChar objectAtIndex:arrDuplicate.count];
[arrDuplicate addObject:str];
}
NSLog(#"%#",str);
UIButton *btnLetter = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btnLetter setFrame:CGRectMake(x, y, width, height)];
[btnLetter setTitle:str forState:UIControlStateNormal];
x = x + width + 30;
if((i+1)%4==0)
{
x = 70;
y = y + height + 20;
}
}

Resources