ikemonn's blog

技術ネタをちょこちょこと

SRM 636 Div2 250 GameOfStones

問題文

Limak has found a large field with some piles of stones.

Limak likes perfection. It would make him happy if every pile had the same number of stones. He is now going to move some stones between the piles to make them all equal.

However, there is a catch. Limak's perfectionism does not allow him to carry just one stone at a time. As he has two hands, he must always carry exactly two stones: one in each hand. Thus, he can only make one type of an action: pick up two stones from one of the piles and carry both of them to some other pile. He is not allowed to remove a pile completely. Therefore, he cannot pick up stones from a pile that currently contains fewer than 3 stones.

You are given a int[] stones. Each element of stones is the initial number of stones in one of the piles. Compute and return the smallest number of actions Limak has to perform in order to make all piles equal. If it is impossible to make all piles equal using the allowed type of actions, return -1 instead.

書いた

# -*- coding: utf-8 -*-
import math,string,itertools,fractions,heapq,collections,re,array,bisect

class GameOfStones:
    def count(self, stones):
        if len(stones) <= 1:
            return 0
        sum_stones = sum(stones)

        if sum_stones % len(stones) != 0:
            return -1
        avg = sum_stones / len(stones)

        sum_gt_avg = 0
        for i in stones:
            if i > avg:
                diff = i - avg
                if (i-avg) % 2 != 0:
                    return -1
                sum_gt_avg += diff

        if sum_gt_avg % 2 != 0:
            return -1
        return sum_gt_avg / 2

他の参加者のコードみたあと

class GameOfStones:
    def count(self, stones):
        if len(stones) <= 1:
            return 0
        sum_stones = sum(stones)
        if sum_stones % len(stones) != 0:
            return -1
        avg = sum_stones / len(stones)

        result = 0
        for i in stones:
            if (i-avg) % 2 != 0:
                return -1
            if i > avg:
                result += (i-avg)/2

        return result

SRM 635 div2 250 IdentifyingWood

Problem Statement

We call a pair of Strings (s, t) "wood" if t is contained in s as a subsequence. (See Notes for a formal definition.)

Given Strings s and t, return the String "Yep, it's wood." (quotes for clarity) if the pair (s, t) is wood and "Nope." otherwise.

書いた

class IdentifyingWood:
    def check(self, s, t):
        if len(t) > len(s):
            return "Nope."
        match_cnt = 0
        s_start = 0
        for t_i in xrange(len(t)):
            for s_i in xrange(s_start, len(s)):
                if t[t_i] == s[s_i]:
                    s_start = s_i + 1
                    match_cnt += 1
                    break
        if match_cnt == len(t):
            return "Yep, it's wood."
        return "Nope."

他の参加者のコード読んだあと

class IdentifyingWood:
    def check(self, s, t):
        is_match = True
        for t_w in t:
            if t_w in s:
                index = s.index(t_w)
                s = s[index+1:]
            else:
                is_match = False
                break
                
        if is_match:
            return "Yep, it's wood."
        return "Nope."

文字列を1つずつ舐めていくのは、 for in で出来るのか。 マッチしたら次からはマッチした文字以降の文字列と比較すれば良いので、indexでマッチした部分を見つけて切っていくのよい。

【vim】vim <tab>で ファイル名を補完しようとすると、エラーが出る時の解決方法

症状

oh-my-zshを入れたあとに、vim でTabを使ってファイル名を保管しようとすると_vim_files: function definition file not foundというエラーがでる。

解決方法

# 下記のファイルのあとに自分のMacの名前が付いていることがあるので、ls -la等のコマンドで確認
$ rm ~/.zcompdump
$ exec zsh

参考

arguments:448: vim_files: function definition file not found · Issue #518 · robbyrussell/oh-my-zsh

【Underscore.js】_.matcherを読んだ

jashkenas/underscore_.matcherを読んだ。

概要

_.matcher(attrs)

引数の「key : val」と同じものがあるかを判別する部分適用した関数を返す。

var matcher = _.matcher({age: 20, sex: "male"});
console.log(matcher({age: 20, sex: "male", country: "JP", name: "HOGA"})); // true

ソースコード

_.matcher = _.matches = function(attrs) {
    attrs = _.extendOwn({}, attrs);
    return function(obj) {
      return _.isMatch(obj, attrs);
    };
  };

引数をshallow-copyして、それを_.isMatchに渡した関数を返している。

参考

jashkenas/underscore

【Underscore.js】_.omitを読んだ

jashkenas/underscore_.omitを読んだ。

概要

_.omit(object, *keys) 

第1引数から第2引数以降で指定したkey値以外のkey値とその値で構成されたObjectを返す。

var x = _.omit( {age: 20, sex: "male", country: "JP", name: "HOGA"}, ['age', 'sex']);
console.log(x); // {country: "JP", name: "HOGA"}

ソースコード

_.omit = function(obj, iteratee, context) {
    if (_.isFunction(iteratee)) {
      iteratee = _.negate(iteratee);
    } else {
      var keys = _.map(flatten(arguments, false, false, 1), String);
      iteratee = function(value, key) {
        return !_.contains(keys, key);
      };
    }
    return _.pick(obj, iteratee, context);
  };
var keys = _.map(flatten(arguments, false, false, 1), String);

をしているのは、JSのobjectのkeyはString型であり、_.containsは===で比較するため。

参考

jashkenas/underscore

【Underscore.js】_.pickを読んだ

jashkenas/underscore_.pickを読んだ。

概要

_.pick(object, *keys)

第一引数から第2引数以降で指定したkey値とその値で構成されたObjectを返す。

var x = _.pick({age: 20, sex: "male", country: "JP", name: "HOGA"}, 'age', 'country');
console.log(x); // {age: 20, country: "JP"}

var y = _.pick(list, function(val, key, obj){
    return _.isNumber(val);
});

console.log(y); // {age: 20}

ソースコード

_.pick = function(object, oiteratee, context) {
    var result = {}, obj = object, iteratee, keys;
    if (obj == null) return result;
    if (_.isFunction(oiteratee)) {
      keys = _.allKeys(obj);
      iteratee = optimizeCb(oiteratee, context);
    } else {
      keys = flatten(arguments, false, false, 1);
      iteratee = function(value, key, obj) { return key in obj; };
      obj = Object(obj);
    }
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      var value = obj[key];
      if (iteratee(value, key, obj)) result[key] = value;
    }
    return result;
  };

第二引数が関数の場合、各プロパティに対して渡した関数実行される。 関数でない場合は、指定したkeyのプロパティを第一引数のobjectから取得している。

参考

jashkenas/underscore

AtomでXcodeのようにcmd-shift-jで、現在開いているファイルをTree View上で見つける

f:id:ikemonn:20151022181649g:plain

Atom -> 個人設定 -> Keybindings -> “your keycap file”  で下記を追記すればOK。

# 現在開いているファイルをTreeViewで指定する
'.platform-darwin':
  'cmd-shift-j': 'tree-view:reveal-active-file'