japanese life

Experience page

Posted on

Updated my experience page as a self reflection on what kind of technical skills I’ve learned here in Japan ( https://kagato0110.wordpress.com/programming-languages/ )

… turns out I know quite a bit (in terms of technology) lol

スクリーンショット 2015-11-02 12.24.44

Advertisements

Find all combinations with repetitions (Objective-C)

Posted on Updated on

Today after retouching on Objective-C for a few hours (from this Youtube video: https://www.youtube.com/watch?v=5esQqZIJ83g) I decided to recreate my C++ program that prints out all possible combinations of ABC (e.g. AAA, AAB, AAC, ABA … CCC) which I posted about here ( https://kagato0110.wordpress.com/2015/10/28/find-all-combinations-with-repetitions-c/ ) in Objective-C as a terminal based app.

Which was really fun to do! Wasn’t hard to do actually, pretty simple^^

Header file: GenerateSequence.h

/**
 *  GenerateSequence.h
 *
 *  Created by Benjamin Lo on 2015/10/30.
 *  Copyright (c) 2015年 BAD Games (Benjamin Lo). All rights reserved.
 */
#import <Foundation/Foundation.h>

@interface GenerateSequence : NSObject

@property NSMutableArray *_sequence;

- (void)         AssignValueForSequence;                            //  Begin letter sequence
- (void)         CheckIfEmpty       : (NSMutableArray *) _sequence; //  Check if array is empty
- (void)         GenerateSequence   : (NSMutableArray *) _sequence; //  Begin combinatorial sequence
@end

Implementation file: GenerateSequence.m

/**
 *  GenerateSequence.m
 *
 *  Created by Benjamin Lo on 2015/10/30.
 *  Copyright (c) 2015年 BAD Games (Benjamin Lo). All rights reserved.
 */
#import "GenerateSequence.h"

@implementation GenerateSequence


/**
 * Initialization
 */
- (instancetype)init
{
    self = [super init];
    if (self) {
        //  Do nothing lol
    }
    return self;
}


/**
 *  Begin letter sequence
 */
- (void) AssignValueForSequence
{
    NSMutableArray *_sequence = [NSMutableArray arrayWithCapacity: 3];

    [_sequence addObject: @"A"];
    [_sequence addObject: @"B"];
    [_sequence addObject: @"C"];
    
    [self CheckIfEmpty:_sequence];
}


/**
 *  Check if array is empty
 */
- (void) CheckIfEmpty: (NSMutableArray *) _sequence
{
    if (![_sequence isEqual: nil])
    {
        [self GenerateSequence:_sequence];
    }
}


/**
 *  Begin combinatorial sequence
 */
- (void) GenerateSequence : (NSMutableArray *) _sequence
{
    NSMutableString *_a;
    NSMutableString *_b;
    NSMutableString *_c;
    
    for (int i = 0; i < [_sequence count]; i++)
    {
        for (int j = 0; j < [_sequence count]; j++)
        {
            for (int k = 0; k < [_sequence count]; k++)
            {
                _a = [NSString stringWithFormat:@"%@", [_sequence objectAtIndex:i]];
                _b = [NSString stringWithFormat:@"%@", [_sequence objectAtIndex:j]];
                _c = [NSString stringWithFormat:@"%@", [_sequence objectAtIndex:k]];
                NSLog(@"%@%@%@", _a, _b, _c);
            }
        }
    }
}

@end

Main file: main.h

/**
 *  Main.m
 *
 *  Created by Benjamin Lo on 2015/10/30.
 *  Copyright (c) 2015年 BAD Games (Benjamin Lo). All rights reserved.
 */
#import <Foundation/Foundation.h>
#import "GenerateSequence.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {
//        GenerateSequence *gs = [[GenerateSequence alloc] initWithName:@"Generate sequence"];
        GenerateSequence *gs = [[GenerateSequence alloc] init];
        [gs AssignValueForSequence];
    }
    return 0;
}

You can git clone this from my Github: https://github.com/benji011/ABC_CombinationSequence/commits/master

Happy coding!

Find all combinations with repetitions (C++)

Posted on Updated on

One of the most mind boggling (yet very simple) programming problems I’ve found recently was to write a program that displays all combinations of a string with repetitions.

Lets say you have an array like so:

char _chars[] = {'A', 'B', 'C'};

Now write a function that creates the output like so:

AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC BBA BBB BBC BCA BCB BCC CAA CAB CAC CBA CBB CBC CCA CCB CCC

So how would we do this?
I would first store the char array into a vector like so:

std::string _tmpStr;
for (int i = 0; i < 3; i++)
{
     _tmpStr += _charArray[i];
}
std::vector<int> pos(_tmpStr.size(), 0);
Hoge::CombinationSequence(_tmpStr, pos, 0);  // call function to find all combinations

And somewhere in the source code I have declared and called the function like so:

/**
 *	可能な全ての組み合わせがを出力する
 */
void Hoge::CombinationSequence(const string& v, std::vector<int>& pos, int n)
{
    for (int i = 0; i < v.size(); i++)
    {
        for (int j = 0; j < v.size(); j++)
        {
            for (int k = 0; k < v.size(); k++)
            {
                cout << v[i] << v[j] << v[k] << " ";
            }
    }
}

Compiling and running this produces the output we expect.

Problem:
What if the input data increases by size?
How do we calculate a string of data that is maybe 100 elements long instead of 3?

Solution:
The simplest solution is to just add more for loops. But having 100 for loops is a pain in the butt. So Instead, we can use recursion, to call the function itself however times necessary. This means that the input data can change size and our function will automatically loop to different sized arrays, achieving a dynamic design.. Like so:

/**
 *	可能な全ての組み合わせがを出力する
 */
void Hoge::CombinationSequence(const string& v, std::vector<int>& pos, int n)
{
    if (n == v.size())
    {
        for (int i = 0; i != n; i++)
	{
	    cout << v[pos[i]];
	}
	cout << " ";
	return;
    }

    // Loop through the vector and update position to whichever element it is pointing to. Then pass that reference back to our function so we know which letter it is referring to.
    for (int i = 0; i != v.size(); i++)
    {
        pos[n] = i;
        Hoge::CombinationSequence(v, pos, n + 1);
    }
}

Hope this helps somebody out there. The solution was quite simple it didn’t even occur to me how simple it was.

By the way,
A, B, C = 3 types of data
3 x 3 = 9
9 x 3 = 27

We have with this example, 27 possible combinations.

Good tunes to listen to while programming

Posted on Updated on

I love programming. Especially as a job, i mean it’s like playing with computers all day and get paid for it!

But while coding all day is fun .. it’s not as fun to be in the zone without some good tunes pumping into your ears. So I decided to share some of my favourites!



Happy coding!

Updates on Japan

Posted on

My first year in Japan as a student was (by far) the best experience I’ve ever had. And my 2nd and a half year of living here working is also pretty good!

But there are things about Japan I just cant shake off or want to get used to and the mentality here is … you are either one of us (but not necessarily treated the same anyway) or you are not part of us at all. Especially the way people think here being so different and .. to be frank, more narrow than the west which got me thinking …

Should I relocate away from Fukuoka (or Japan even) a couple years time from now and find work elsewhere? Why not? I’m still before my 30s after 2 years from now and I’ve also dreamed about living in Canada for a while too.

I don’t know, lets wait and see.

“signal 11 (SIGSEGV), code 1” – (Cocos2dx, C++ with Android & Eclipse)

Posted on Updated on

The biggest drawback I’ve been having with Eclipse and cocos2dx (not sure if this also applies to Xcode …) I can think of is the annoying “Signal 11” error. But then I ran into this thread on StackOverFlow:

http://stackoverflow.com/questions/18436383/how-to-check-crash-log-using-android-ndk-in-cocos2d-x

I find the perfect answer in http://www.cocos2d-x.org/boards/6/topics/20437.

The solution is:

When you get errors like this on the LogCat, they are saved on $PROJECT_PATH/obj/local/armeabi where $PROJECT_PATH is the path to your cocos2d-x android project. To symbolicate the messages to something understandable, you can use the ndk-stack tool.

Open up the Terminal (or Cygwin, not sure though) and type in

cd $ANDROID_NDK
adb logcat | ./ndk-stack -sym $PROJECT_PATH/obj/local/armeabi

where:

$ANDROID_NDK is the path to your android NDK

$PROJECT_PATH is the path to your cocos2d-x android project

Wow! I just hit the jackpot! okay well time to switch over to my terminal and try this out. I then get the following crash dump:

********** Crash dump: **********
Build fingerprint: 'samsung/SC-04E/SC-04E:4.4.2/KOT49H/SC04EOMUFOB2:user/release-keys'
pid: 18875, tid: 18897, name: Thread-18051  >>> com.benji.etcetc <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000000
Stack frame #00  pc 00000000  <unknown>
Stack frame #01  pc 000de0b9  /data/app-lib/com.benji.etcetc/libcocos2dcpp.so (GameScene::onTouchBegan(cocos2d::Touch*, cocos2d::Event*)+232): Routine GameScene::onTouchBegan(cocos2d::Touch*, cocos2d::Event*) at /Users/benji0110/Downloads/cocos2d-x-3.3/etcetc/proj.android/jni/../../Classes/GameScene.cpp:355
Crash dump is completed

Awesome! Finally according to my crash dump I was able to locate where my app crashes at line 355 .. it turns out I had deleted a game object at runtime and read that objects size, but because it was now destroyed the object no longer existed causing the program to terminate.

What a treat to end an awesome Friday^^

How to traverse through a 2D CCArray – Cocos2dx, C++ on Android (and 5 month workout progress)

Posted on Updated on

Couldn’t find anything on making a multidimensonal CCArray anywhere so I’m leaving this here so I don’t forget later.

Objective:
Generate an array which holds an array that holds a sprite.

Adding into our 2D CCArray:
Lets open our text editor and write some code!

Somewhere in our header file

	// ... 
    Sprite*                     _spriteImage;
    CCArray*                    _arr_x;
    CCArray*                    _arr_y;
	// ...

Now in our implementation file:
cpp file:

/**
 * add sprites into a 2D CCArray
 */
void Hoge::addIntoMultiCCArray() {
    _arr_x = CCArray::create();

    for (int i = 0; i < ARRAY_SIZE; i++) {
        for (int j = 0; j < ARRAY_SIZE; j++) {
            _arr_y = CCArray::create();

				int randomized_tag  = rand();                                  // generate a random tag to identify which element
				int pos_x           = i * 100 / 1.5f;                          
				int pos_y           = j * 100 / 1.5f;                          
  
                _spriteImage   	   = MySprite::create();
                _spriteImage        -> setPosition(Point(visibleSize.width / 4 + pos_x, visibleSize.height / 2 + pos_y));
                _spriteImage   	  -> setTag(randomized_tag);
                _arr_y         	  -> addObject(_spriteImage);
                this           	  -> addChild(_spriteImage);

                _arr_x   -> addObject(_arr_y);            //  Where the magic happens
        }
    }
    _arr_x -> retain();
    _arr_y -> retain();
}

Adding into a multi CCArray is quite straight forward. For each element in the first CCArray you just need to create another CCArray to produce that multidimensional array.

Now we want to do something else besides adding.

Why the traditional way is a bad idea:
The traditional way of traversing through a 2D array is with for loops:

for (int x = 0; x < ARRAY_SIZE; x++) {
	for (int y = 0; y < ARRAY_SIZE; y++) {
		// do something
	}
}

Lets say we want to edit or delete something. We can’t just do the traditional way like above.

Compiling the code using this method is okay, but at runtime this will produce unexpected behavior and our app will crash due to memory leaks. So to counter this, we need to use CCArrays CCCARRAY_FOREACH method.

Solution:

// ... somewhere below our implementation file

    // traverse through our multi CCArray
    CCObject*   obj_x = NULL;
    CCObject*   obj_y = NULL;

    CCARRAY_FOREACH(_arr_x, obj_x) {
        CCArray* _obj_x_arr = (static_cast<CCArray*>(obj_x));

        CCARRAY_FOREACH(_obj_x_arr, obj_y) {
            Sprite* _spriteImage_y  = (static_cast<Sprite*>(obj_y));
            Rect rect_a         = IntersectionPoint_A -> getBoundingBox();
            Rect rect_b               = _spriteImage_y  -> getBoundingBox();

            if (rect_b.intersectsRect(rect_a)) {                
                // maybe delete this element from _arr_y?
                _obj_x_arr -> removeObject(_spriteImage_y);
                this       -> removeChildByTag(_spriteImage_y -> getTag());	
            }
        }

    }

Hopefully this will help someone out there. Maybe my coding still is weird (and if it is I would love some feedback on how to write better code^^)

Oh yeah before I forget, here is a recent picture of my arm after 5 months of workout!

Not bad eh? Gotta keep eating and working!
Happy coding!