MATLAB,360个363 290 304 295字节
请参阅文章底部的内容,了解如何使用Octave测试旧代码。
由于规则已更改,因此该代码采用元素的名称(包括Kalium等)并以ascii格式显示输出。
f=input('');e=1;a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl ilgae eie '];for s=a;n=s(s~=32);if strncmpi(n,f,nnz(n));break;end;e=mod(e,20)+1;end;s=spiral(10);p=[8,18,33,28,23,39,60,53,46,95];p=[p;p+1];o=s*0;o(ismember(s,p(1:21-e)))='x';o(45:46)=a(:,e+20);char(o')
自从我编写代码以要求ASCII输出以来,规则发生了变化。我已经更新了代码,以14个字节为代价。通过消除reshape()并让a
矩阵成为正确的形状,我节省了9个字节。
以下是其工作原理的说明:
%Get the name - actually we only need at most the first two characters, but the whole thing will do
f=input('');
e=1;
%This bit makes a map which allows us to find the element (including with
%the names like Kalium. All of the elements appear twice, with the actual
%symbols being the second set. The first set gets all those whose names are
%either more than one character, or don't begin with the first two
%characters of the short for (e.g. Sodium). The string is reshaped into a
%2x40 array. 'Natrium' is a pain in the neck as it as it would get caught
%by 'N' for 'Nitrogen'. I have reversed the element order - so that all the
%ones beginning with N come before N. Some maths is done later on to
%correct for the number of electrons - basically 21-e so 1 becomes 20.
a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl ilgae eie '];
%For each group of 2 in the array of elements
for s=a
%Remove any spaces from the name
n=s(s~=32);
%Do a comparison of the first one or two characters of the requested string
if (strncmpi(n,f,nnz(n)))
%break once the element is found
break;
end
%If not this element add another electron. We wrap around after 20 as there are two copies of each
e=mod(e,20)+1;
end
%e is now number of electrons
%Generate an array of points for each electron
s=spiral(10);
p=[8,18,33,28,23,39,60,53,46,95];p=[p;p+1];
%make an output array
o=s*0;
%Plot all the points in is up to and including the number of electrons (see the notes above for why 21-e)
o(ismember(s,p(1:21-e)))='x';
%And add the text in the centre - we extract the element name from the second group appearance in the 'a' array, hence adding 20.
o(45:46)=a(:,e+20);
%Display the result
char(o')
这是氢气的输出(忽略点,它们是为了避免在此处显示时删除线):
.
.
.
.
xH .
.
.
.
.
.
这是钙的输出。
.
xx .
xx .
.
xxxCa xxx.
xxx xxx.
.
xx .
xx .
.
而且Natrium的输出现在可以正常工作(在Natrium之前会产生氮!)。
.
x .
xx .
.
xxNa x .
xx x .
.
xx .
.
.
新版本的代码不适用于Octave,因为它使用了spiral()
仅在MATLAB中提供的Octave 。
但是,您可以使用Octave在线解释器测试旧代码:
f=input('');e=1;a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl ilgae eie '];for s=a;n=s(s~=32);if strncmpi(n,f,nnz(n));break;end;e=mod(e,20)+1;end;u=14:(34-e);r=floor(u/8);t=u*pi/4;polar(t,r,'o');text(0,0,a(:,e+20)','horizontalalignment','c')
运行该命令,然后输入一个字符串,例如:'Hydrogen'(包括引号)。完成后,您将必须单击“扩展绘图”按钮(在解释器的右上角看起来像一个小图形符号)以使其完整显示。不幸的是,在Octave中添加了连接点的线,这在MATLAB中不会发生。但是至少它允许您测试其背后的逻辑。就像我说的那样,这仍然是图形输出,但是您可以了解如何查找元素。