10分でコーディング
10分でコーディング | プログラミングに自信があるやつこい!!をJava+Eclipseでやってみて1時間以上かけたあげく下記のプログラムの足下にも及ばなかった。。。orz
さらすにはあまりにはずかしいけどいちおうさらしとく。悪い例と言うことで。
public class Cards { public static String[] deal(int numPlayers, String deck) { String[] answers = new String[numPlayers]; int length = deck.length(); if (length / numPlayers == 0) { for (int i = 0; i < numPlayers; i++) { answers[i] = ""; } return answers; } StringBuilder[] answersb = new StringBuilder[numPlayers]; for (int i = 0; i < length; i++) { if (i != 0 && i == length - 1 && length % numPlayers != 0) { break; } char c = deck.charAt(i); if (answersb[i % numPlayers] == null) { answersb[i % numPlayers] = new StringBuilder(); } answersb[i % numPlayers].append(c); } for (int j = 0; j < numPlayers; j++) { answers[j] = answersb[j].toString(); } return answers; } public static void main(String[] args) { String[] deal = deal(Integer.parseInt(args[0]), args[1]); StringBuilder sb = new StringBuilder(); sb.append("Returns: {"); for (String string : deal) { sb.append("\"" + string + "\", "); } System.out.println(sb.substring(0, sb.length() - 2) + "}"); } }
ついでに下記を今勉強中のPythonでやってみた。これもたぶん1時間以上かかってる。なんかもっといいやりかたがある気もするが。
topcoderの道1 | プログラミングに自信があるやつこい!!
decode.py
def decode(ciphertest, shift): """ >>> decode("VQREQFGT", 2) 'TOPCODER' >>> decode("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10) 'QRSTUVWXYZABCDEFGHIJKLMNOP' >>> decode("TOPCODER", 0) 'TOPCODER' >>> decode("LIPPSASVPH", 4) 'HELLOWORLD' """ result = "" for c in ciphertest: ch = ord(c) - shift if ch < ord('A'): result += chr(ch - ord('A') + 1 + ord('Z')) else: result += chr(ord(c) - shift) return result if __name__ == '__main__': import doctest doctest.testmod()
実行結果
$ python decode.py -v Trying: decode("VQREQFGT", 2) Expecting: 'TOPCODER' ok Trying: decode("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10) Expecting: 'QRSTUVWXYZABCDEFGHIJKLMNOP' ok Trying: decode("TOPCODER", 0) Expecting: 'TOPCODER' ok Trying: decode("LIPPSASVPH", 4) Expecting: 'HELLOWORLD' ok 1 items had no tests: __main__ 1 items passed all tests: 4 tests in __main__.decode 4 tests in 2 items. 4 passed and 0 failed. Test passed.