Latest Event Updates

How many threads can I run on my machine …?

Posted on

I was curious at one point how many threads I can run on my notebook in C++. To check you use the following:

/**
 * メイン
 */
int main()
{
        // ...
	unsigned int n = std::thread::hardware_concurrency();
	cout << n << " 本数のスレッドが実行可能です / No. of threads before you hit oversubscription" << endl;
        // ...
}

After checking on my machine..

➜  Benji:  clang++ -std=c++11 LOL_Machine.cpp
➜  Benji:  ./a.out
4 本数のスレッドが実行可能です / No. of threads before you hit oversubscription

So while searching for a command line how to check the statistics of my machine I came across an interesting thread from stack exchange. A guy called drfrogsplat had written a python script that checks all this for you. All you have to do is hit compile and done! Source code below:

# Author: drfrogsplat
# Link:   http://apple.stackexchange.com/questions/4286/is-there-a-mac-os-x-terminal-version-of-the-free-command-in-linux-systems

#!/usr/bin/python

import subprocess
import re

# Get process info
ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]

# Iterate processes
processLines = ps.split('\n')
sep = re.compile('[\s]+')
rssTotal = 0 # kB
for row in range(1,len(processLines)):
    rowText = processLines[row].strip()
    rowElements = sep.split(rowText)
    try:
        rss = float(rowElements[0]) * 1024
    except:
        rss = 0 # ignore...
    rssTotal += rss

# Process vm_stat
vmLines = vm.split('\n')
sep = re.compile(':[\s]+')
vmStats = {}
for row in range(1,len(vmLines)-2):
    rowText = vmLines[row].strip()
    rowElements = sep.split(rowText)
    vmStats[(rowElements[0])] = int(rowElements[1].strip('\.')) * 4096

print 'Wired Memory:\t\t%d MB' % ( vmStats["Pages wired down"]/1024/1024 )
print 'Active Memory:\t\t%d MB' % ( vmStats["Pages active"]/1024/1024 )
print 'Inactive Memory:\t%d MB' % ( vmStats["Pages inactive"]/1024/1024 )
print 'Free Memory:\t\t%d MB' % ( vmStats["Pages free"]/1024/1024 )
print 'Real Mem Total (ps):\t%.3f MB' % ( rssTotal/1024/1024 )

Compile using python vm_stat.py..

Wired Memory:		1793 MB
Active Memory:		3313 MB
Inactive Memory:	728 MB
Free Memory:		1912 MB
Real Mem Total (ps):	5599.785 MB

Link: http://apple.stackexchange.com/questions/4286/is-there-a-mac-os-x-terminal-version-of-the-free-command-in-linux-systems

Useful stuff. Moving along to some more coding fun!

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

The Angry GF (A non-released Unity, C# Game for Android & iOS)

Posted on Updated on

スクリーンショット 2015-10-31 10.29.39
For a few months I’ve been working on a simple retro-style “flicking” game for Android & iOS. A lot has changed during the production and well .. long story short: My idea wasn’t good enough.

So why not release it as open source? Makes sense. Plus a lot of people out there need some information which I’m giving away for free and that itself makes me happy 🙂

Enjoy!

You can download the entire source code and its resources (except BGM because I didn’t make them) from my Github: https://github.com/benji011/AngryGF

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.