開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第10章(配列)10.9(練習問題)練習10-4を解いてみる。
その他参考書籍
練習10-4.
コード
using System;
using System.Text.RegularExpressions;
class Tester
{
public void Run()
{
const int rows = 8;
const int cols = 8;
string[,] chessboard = new string[rows, cols];
for (int i = 0; i < rows; i++)
{
if (i % 2 == 0)
{
for (int j = 0; j < cols; j++)
{
chessboard[i, j] = j % 2 == 0 ? "●" : "○";
}
}
else
{
for (int j = 0; j < cols; j++)
{
chessboard[i, j] = j % 2 == 0 ? "○" : "●";
}
}
}
Console.WriteLine("チェス盤");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write(chessboard[i, j]);
}
Console.WriteLine();
}
Regex reg = new Regex(@"^\s*$");
while (true)
{
try
{
Console.WriteLine("座標(x, y)を入力");
string m = Console.ReadLine();
if (reg.IsMatch(m)) break;
string n = Console.ReadLine();
Console.WriteLine("色: {0}",
chessboard[Convert.ToInt16(m) - 1, Convert.ToInt16(n) - 1]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
入出力結果(Console Window)
チェス盤 ●○●○●○●○ ○●○●○●○● ●○●○●○●○ ○●○●○●○● ●○●○●○●○ ○●○●○●○● ●○●○●○●○ ○●○●○●○● 座標(x, y)を入力 5 5 色: ● 座標(x, y)を入力 5 6 色: ○ 座標(x, y)を入力 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var rows = 8;
var cols = 8;
var chessboard = [];
for(var i = 0; i < rows; i++){
chessboard[i] = [];
if(i % 2 === 0){
for(var j = 0; j < cols; j++){
chessboard[i][j] = j % 2 === 0 ? "●" : "○";
}
} else {
for(var j = 0; j < cols; j++){
chessboard[i][j]= j % 2 === 0 ? "○" : "●";
}
}
}
var result = "チェス版\n";
for(var i = 0; i < rows; i++){
for(var j = 0; j < cols; j++){
result += chessboard[i][j];
}
result += "\n";
}
var x = parseInt($('#t0').val());
var y = parseInt($('#t1').val());
result += "色: " + chessboard[x - 1][y - 1];
$('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
rows = 8
cols = 8
chessboard = []
for i in range(rows):
chessboard.append([])
if i % 2 == 0:
for j in range(cols):
chessboard[i].append("●" if j % 2 == 0 else "○")
else:
for j in range(cols):
chessboard[i].append( "○" if j % 2 == 0 else "●")
print("チェス版")
for i in range(rows):
print("".join(chessboard[i]))
import re
while True:
x = input("x座標: ")
if re.search(r"^\s*$", x): break
try:
x = int(x)
y = int(input("y座標: "))
print("色: {0}".format(chessboard[x][y]))
except Exception as err:
print(err)
入出力結果(Terminal)
$ ./sample.py チェス版 ●○●○●○●○ ○●○●○●○● ●○●○●○●○ ○●○●○●○● ●○●○●○●○ ○●○●○●○● ●○●○●○●○ ○●○●○●○● x座標: 5 y座標: 5 色: ● x座標: 5 y座標: 6 色: ○ x座標: 10 y座標: 10 list index out of range x座標: $
0 コメント:
コメントを投稿