TimothyQiu's Blog

Happy coding

libcurl
Lua 学习笔记:零

一道笔试题

timothyqiu posted @ 2010年10月29日 08:57 in 学习笔记 with tags c/c++ 算法 , 2168 阅读

虽说学校通知说今天晚上的是宣讲会,但结果竟然还有当场的笔试,一点心理准备都米有的我做完题目感觉非常蛋疼。

嘛~最后一题没有做出来,一直纠结到现在。题目是这样滴:

打印一个N*N的方阵,N为每边字符的个数(3〈N〈20),要求最外层为"X",第二层为"Y",从第三层起每层依次打印数字0,1,2,3,...例子:当N=5,打印出下面的图形。

也就是说,当N为7时,要输出:

XXXXXXX
XYYYYYX
XY000YX
XY010YX
XY000YX
XYYYYYX
XXXXXXX

貌似还留了一刻钟做题,没有做出来,果然理清思路是很重要的啊。

回来玩了会儿游戏便开始琢磨这个题目,憋出来一个很无语的解法:因为N是给定范围的,所以,可以先不直接输出,而是开一个20x20的数组,按规律填好(这个N/2+1个循环就可以搞定)。最后把这个数组输出。

于是我被自己这个解法囧到了,还是上网查吧。结果发现基本上都是这样开数组的解法,少数另类解法那程序写得要么长得要死,要么一堆 if switch 之类的,实在是看不上眼。

最后终于被我找到一个,虽说不是相同的题目,但是思路非常不错。像要输出下面的方阵,每个位置的值等于“横坐标和纵坐标到边界的距离中最小的一个”。

11111
12221
12321
12221
11111

于是茅塞顿开。终于写出了这道题目的解。

#include <iostream>
#include <cstdlib>
using namespace std;

int const N = 15;

int main()
{
	for (int row = 0; row < N; row++)
	{
		for (int col = 0; col < N; col++)
		{
			int distX = min(col, N - 1 - col);
			int distY = min(row, N - 1 - row);
			int id = min(distX, distY) - 2;

			switch (id)
			{
				case -2: cout << 'X'; break;
				case -1: cout << 'Y'; break;
				default: cout << id;  break;
			}
		}
		cout << endl;
	}
}
Avatar_small
Kflayca 说:
Nov 14, 2010 04:18:52 AM

打印类题目最让人头疼了……

seo service london 说:
May 18, 2024 07:32:51 PM

pressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter