Skip to content

Instantly share code, notes, and snippets.

@mzsima
Last active September 15, 2015 13:20
Show Gist options
  • Save mzsima/18258d2bba7e1335a799 to your computer and use it in GitHub Desktop.
Save mzsima/18258d2bba7e1335a799 to your computer and use it in GitHub Desktop.
One Size Smaller
//
// ViewController.mm
// OneSizeSmaller
//
// Created by MizushimaYusuke on 9/15/15.
// Copyright (c) 2015 MizushimaYusuke. All rights reserved.
//
#import "ViewController.h"
#include <vector>
#include <memory>
using namespace std;
class FindOneSizeSmaller {
public:
int find(vector<int> heightList, int key) {
sort(heightList.begin(), heightList.end());
int l = 0;
int r = (int)heightList.size();
while (l < r) {
int mid = (l + r) / 2;
if (heightList[mid] == key)
return heightList[mid - 1];
else if (key < heightList[mid])
r = mid;
else
l = mid + 1;
}
return -1;
}
};
@interface ViewController () {
vector<int> heightList;
NSMutableArray *bars;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithHue:0.7 saturation:1 brightness:0.4 alpha:1];
for (int i=20; i<100; i++) {
int h = 3 * i + arc4random() % 2;
heightList.emplace_back(h);
}
random_shuffle(heightList.begin(), heightList.end());
bars = [NSMutableArray array];
for (int i=0; i<heightList.size(); i++) {
UIView *bar = [[UIView alloc] initWithFrame:CGRectMake(50 + i * 7, 100, 7, heightList[i] / 2.0)];
bar.layer.borderWidth = 1.5;
bar.layer.borderColor = self.view.backgroundColor.CGColor;
bar.tag = heightList[i];
bar.backgroundColor = [UIColor whiteColor];
[self.view addSubview:bar];
[bars addObject:bar];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint p = [[touches anyObject] locationInView:self.view];
UIView *hit = [self.view hitTest:p withEvent:nil];
if (hit.tag > 0) {
[bars enumerateObjectsUsingBlock:^(UIView *v, NSUInteger idx, BOOL *stop) {
v.backgroundColor = [UIColor whiteColor];
[UIView animateWithDuration:0.1 animations:^{
v.transform = CGAffineTransformIdentity;
}];
}];
hit.backgroundColor = [UIColor yellowColor];
shared_ptr<FindOneSizeSmaller> cppClass(new FindOneSizeSmaller());
int oneSmallerHeight = cppClass->find(heightList, (int)hit.tag);
UIView *oneSmaller = [self.view viewWithTag:oneSmallerHeight];
if (oneSmaller) {
oneSmaller.backgroundColor = [UIColor greenColor];
[UIView animateWithDuration:1.0 animations:^{
oneSmaller.transform = CGAffineTransformMakeTranslation(0, -30);
}];
}
}
}
@end
@mzsima
Copy link
Author

mzsima commented Sep 15, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment