Joel on software に書いてあった面接の仕方について

昔、Joel on softwareを上司にもらった。
なぜか知らないけど、上司のサインつきだった

「for the Great Programmer - Jeff」
上司の名前はJeffじゃなかったけど、Jeffとなっていた。


まあ、それはさておき Joel on Software の中に、「ゲリラ的雇用面接のすすめ」という章の中で
「面接時に面接を受ける人にソースコードを書いてもらう」ということをやっていた。

例題として下記のような項目がある。

  1. 文字列をインプレイスで反転させる
  2. 単リストを末尾から先頭に反転させる

......

とりあえず、上記の文字列をインプレイスで反転させるコードを書いてみる。

PHPで、後ろから取り出して、配列にぶちこんで、Join()

<?php
$source = "abcde";
$dest = array();
for( $i = 0; $i < strlen($source); $i++ )
{
  $dest[] = $source[strlen($source)-$i-1];
}
echo( join("",$dest) );
?>

うーん、あんまり美しくない。しかもインプレイスってなんだ?

Cで書いてみることにしよう。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc,char argv[])
{
  char *source = "abcde";
  int length = strlen(source);
  char *dest = (char *)malloc(length+1);
  for( int i = 0;  i < length; i++ )
  {
       dest[i] = source[length-i-1];
  }
  dest[length+1] = '\0';

  printf("%s\n",dest);
  free(dest);
}

うーん、長いな。
もっと短くできないかな。

そうだ、2つの整数値をそれぞれXORすると値を交換できることを利用しよう。
交換例:

#include <stdio.h>

int main(int argc,char argv[])
{
  int a = 0x0F;
  int b = 0x11;

  a ^= b;
  b ^= a;
  a ^= b;

  printf("a = %x, b = %x\n", a, b);
  // a = 11, b = f  
}

あと、for() のループのiは、交換していくと、iの位置が中間に来たときにすべての文字の走査が終るので、
length / 2 回カウントすればよさそうだ。
しかも奇数の時には、真ん中の文字は交換しなくていいので、特別に処理を分ける必要もない。

#include <stdio.h>
#include <string.h>

int main(int argc,char argv[])
{
  char source[] = "abcde";
  int length = strlen(source);
  for( int i = 0;  i < length/2; i++ )
  {
       source[i]          ^= source[length-i-1];
       source[length-i-1] ^= source[i];
       source[i]          ^= source[length-i-1];
  }

  printf("%s\n",source);
}

というわけでできたソース。
レベルの低い操作だとPHPよりCの方が楽な気がしてたまらない今日この頃。
なんか脳みその違うところを使っている感じ。

Joel on Software はココでも読めるし、
http://japanese.joelonsoftware.com/Articles/Interviewing.html

僕の貼り付けた広告を踏んでくれてもいいよ。*1

Joel on Software

Joel on Software

ソースを書いてもらう方法だと、面接受けるほうも楽しそうだし、出すほうも面白そうだ。
どこの会社でもやったらいいのに。

*1:オススメ!