japanese life

Printing every possible combinations of ABC (Swift 2.2 )

Posted on Updated on

I had time this evening .. so I figured why not dig up some example code I copied from a tutorial online and modify it to show every possible combinations of the letters A, B and C.

Only this time instead of showing through a terminal I would print it on an iPhone app. So here it is ..

スクリーンショット 2016-03-28 21.19.43

Source code:

import UIKit

class ViewController: UIViewController
{
    @IBOutlet weak  var totalPermutations: UILabel!         // print total permutations count of ABC
    @IBOutlet weak  var _comboTextView: UITextView!         // print every combination of ABC
    @IBOutlet       var _outputLabel: UILabel!
                    var _currentCount = 0

    let combinationsArray: [String] = ["A", "B", "C"]

    /**
     * Initialization
     */
    override func viewDidLoad()
    {
        super.viewDidLoad()
        printCombinations()
    }

    /**
     * Print every combination of ABC
     */
    func printCombinations()
    {
        var totalCombinations = 0
        var str: String = ""
        for letter in combinationsArray {
            for nextLetter in combinationsArray {
                for nextNextLetter in combinationsArray {
                    totalCombinations++
                    str += (letter + nextLetter + nextNextLetter + "\n")
                }
            }
        }
        totalPermutations.text = ("Permutations: " + String(totalCombinations))
        _comboTextView.text = str
    }

    /**
     * Memory warning
     */
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }

    /**
     * Start counting
     */
    @IBAction func addOneButton(sender: UIButton)
    {
        _currentCount++
        _outputLabel.text = "クリック回数は:\(_currentCount)"
        _outputLabel.textColor = UIColor.redColor()
    }
}

Edit: Added total permutations counter
Github: https://github.com/benji011/counterApp

Git: Deleting stubborn untracked files

Posted on

Alright I’ve ran into this problem way too many times and not kept a note on this so to save myself the trouble (and to the poor donkeys out there who are on the same boat) I’m making a note now so I won’t forget … and to help everybody out there.

Lets say you’ve finished on your assignment and you hit git status before pushing your work into your remote repository. You get something like this:

Benji$  git status
On branch feature/LOLMACHINE
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	deleted:    Animations/nyancat.meta
	modified:   LOL_Game.unity

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	../ProjectSettings/stubbornfile.asset
	../ProjectSettings/stubbornfile2.asset
	../ProjectSettings/stubbornfile3.asset

Try as you might Git reset HEAD and Git reset doesn’t work.

Luckily you can get rid of untracked files using the simple git clean -xf

If you feel compelled to remove everything including the directories you worked on but might not necessarily be needed then you can use git clean -df and BOOM, all is good again.

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!