iPhone文字入れ替え

文字の両端を選択して、アルファベットを並べ替えるiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

#include <memory>

#include <vector>

using namespace std;

class LineSolver {

public:

    vector<char> solve(NSString *);

};

vector<char> LineSolver::solve(NSString *str) {

    int N = (int)str.length;

    char *S = (char *)[str UTF8String];

    char res[N];

    int a = 0, b = N – 1, cnt = 0;

    while (a <= b) {

        bool left = false;

        for (int i = 0; a + 1 <= b; i++) {

            if (S[a + i] < S[b – i]) {

                left = true;

                break;

            }

            else if (S[a + i] > S[b – i]) {

                left = false;

                break;

            }

        }

        res[cnt++] = left ? S[a++] : S[b–];

    }

    return vector<char>(res, res + sizeof res / sizeof res[0]);

}

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *words;

@end

@implementation ViewController

#define SEED [@“E R J S K E H T R B” componentsSeparatedByString:@” “]

– (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

    

    self.words = [NSMutableArray array];

    NSArray *seed = SEED;

    for (int i=0; i<seed.count; i++) {

        float x = (i % 10) * 30 + 50;

        float y = 100;

        NSString *s = seed[i];

        UILabel *l = [[UILabel alloc] init];

        l.text = s;

        l.font = [UIFont systemFontOfSize:30];

        l.textColor = [UIColor lightGrayColor];

        [l sizeToFit];

        l.center = CGPointMake(x, y);

        [self.view addSubview:l];

        

        [self.words addObject:l];

    }

}

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    shared_ptr<LineSolver> cppClass(new LineSolver());

    vector<char> res = cppClass->solve([SEED componentsJoinedByString:@””]);

    int cnt = 0;

    for (auto &s : res)

    {

        UILabel *first = ((UILabel *)self.words.firstObject);

        UILabel *last = ((UILabel *)self.words.lastObject);

        UILabel *select = nil;

        if ([[NSString stringWithFormat:@”%c”, s] isEqual:first.text]) {

            select = first;

        } else {

            select = last;

        }

        

        float x = (cnt % 10) * 30 + 50;

        float y = 200;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(cnt * 0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [UIView animateWithDuration:0.5 animations:^{

                select.center = CGPointMake(x, y);

            }];

        });

        [self.words removeObject:select];

        cnt++;

    }

}

@end