# 三角剖分文字

39

``````R
``````

`````` c
a t
``````

``````  m
o n
k 3 y
``````

``````   m
e a
n I n
g f u 1
``````

``````   ^
/ \
/ | \
/ [ ] \
``````

``````Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?
``````

``````              T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e d a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
``````

geokavel 2015年

@geokavel它适用于您的语言通常可以处理的任何长度的字符串。

11

9

# Pyth，22个字节

``````jua+L\ GjdHfTczsM._UzY
``````

### 说明：

``````jua+L\ GjdHfTczsM._UzY   implicit: z = input string
Uz    create the list [0, 1, ..., len(z)-1]
._      all prefixes of this list: [[0], [0,1], [0,1,2], ...]
sM        sum up each sublist: [0, 1, 3, 6, 10, ...]
cz          split z at these indices
fT            remove all the unnecessary empty strings
this gives us the list of strings of the triangle
u                   Y   reduce this list, with the initial value G = []
+L\ G                    prepend a space to each string in G
jdH                 join the current string with spaces
a                         and append it to G
j                        print each string on a separate line
``````

12

## Python，81个字节

``````def f(s,p=''):
i=-int(len(2*s)**.5)
if s:f(s[:i],p+' ');print p+' '.join(s[i:])
``````

``def f(s,p=''):i=-int(len(2*s)**.5);s and[f(s[:i],p+' '),print(p+' '.join(s[i:]))]``

``def f(s,p=''):i=-int(len(2*s)**.5);''<s!=f(s[:i],p+' ')!=print(p+' '.join(s[i:]))``

1

xsot

6

## 视网膜，108 102 94 87 82 64 63字节

``````S_`(?<=^(?<-1>.)*(?:(?<=\G(.)*).)+)
.
\$0
m+`^(?=( *)\S.*\n\1)
<space>
``````

### 说明

``````S_`(?<=^(?<-1>.)*(?:(?<=\G(.)*).)+)
``````

``````(?<=
^         # And we ensure that we can reach the beginning of the stack by doing so.
# The first time this is possible will be exactly when tri(m-1) == tri(n-1),
# i.e. when m == n. Exactly what we want!
(?<-1>.)* # Now we keep matching individual characters while popping from group <1>.
\G        # We've now matched m characters, while pushing i-1 captures for each i
# between 1 and m, inclusive. That is, group <1> contains tri(m-1) captures.
(?:
(?<=
\G    # The \G anchor matches at the position of the last match.
(.)*  # ...push one capture onto group <1> for each character between here
# here and the last match.
)       # Then we use a lookahead to...
.       # In each iteration we match a single character.
)+        # This group matches all the characters up to the last match (or the beginning
# of the string). Call that number m.
)           # If the previous match was at position tri(n-1) then we want this match
# to happen exactly n characters later.
``````

``````.
\$0
``````

``````m+`^(?=( *)\S.*\n\1)
<space>
``````

``````^      # Match the beginning of a line.
(?=    # A lookahead which checks if the matched line needs another space.
( *) # Capture the indent on the current line.
\S   # Match a non-space character to ensure we've got the entire indent.
.*\n # Match the remainder of the line, as well as the linefeed.
\1   # Check that the next line has at least the same indent as this one.
)
``````

@ _ @这到底是做什么的？
n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 2015年

@ n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳现在，Kobi提供了更多100％的惊奇。

6

# 糖果，67 59 57字节

`&iZ1-=yZ1+Z*2/>{0g}0=z@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`

`&1-8*1+r1-2/=y@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`

`&8*7-r1-2/=y@1i&{|.}bYR(" ";=)ZR(=a&{;}" ";)"\n";Y1-=ya1j`

``````          &
8 *
7 - r
1 - 2 /
= y @ 1 i
& { | . } b
Y R ( "   " ;
= ) Z R ( = a &
{ ; } "   " ; ) "
\ n " ; Y 1 - = y a
1 j
``````

``````stackSz
digit8    # Y = (sqrt((numCh - 1) * 8 + 1) - 1) / 2   using pythagorean
mult      # Y = (sqrt(numCh * 8 - 7) - 1) / 2  equivalent but shorter
digit7
sub
root
digit1
sub
digit2
div
popA
YGetsA
label digit1
incrZ
stackSz   # bail if we're out of letters
if
else
retSub
endif
stack2
pushY     # print the leading spaces (" " x Y)
range1
while
" " printChr
popA
endwhile
pushZ
range1      # output this row of characters (Z of them)
while
popA
stack1
stackSz
if
printChr    # bail on unbalanced tree
endif
" " printChr
endwhile
"\n" printChr
pushY
digit1
sub
popA
YGetsA
stack1
digit1 jumpSub   # loop using recursion
``````

5

## CJam，27 26字节

``````Lq{' @f+_,)@/(S*N+a@\+\s}h
``````

### 说明

``````L        e# Push an empty array to build up the lines in.
{        e# While the top of the stack is truthy (non-empty)...
' @f+  e#   Prepend a space to each line we already have.
_,)    e#   Get the number of lines we already have and increment.
@/     e#   Split the input into chunks of that size.
(S*    e#   Pull off the first chunk (the next line) and join with spaces.
N+     e#   Append a linefeed.
a@\+   e#   Append it to our list of lines.
\s     e#   Pull up the other chunks of the input and join them back into one string.
}h
``````

geokavel

@geokavel因为`S`是字符串而不是字符，所以`f`将映射在该字符串而不是行列表上。

geokavel

@geokavel不，我不知道。

5

# Ruby，84 77 73字节

``````->v{1.upto(n=v.size**0.5*1.4){|i|puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "}}
``````

77字节

``````->v{0.upto(n=(v.size*2)**0.5-1){|i|puts" "*(n-i)+v[i*(i+1)/2,i+1].chars*" "}}
``````

`r`按照steveverrill的建议，通过删除变量减少了更多的字节。

84字节

``````->v{n=(v.size*2)**0.5-1;0.upto(n){|i|puts" "*(n-i)+v[(r=i*(i+1)/2)..r+i].chars*" "}}
``````

``````->v {
1.upto(n=v.size**0.5*1.4) { |i|
puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "
}
}
``````

``````n=v.size**0.5*1.4
``````

``````puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "
``````

`[[0,0],[1,2],[3,5],[6,9]]`

``````f=->v{1.upto(n=v.size**0.5*1.4){|i|puts" "*(n-i)+v[i*(i-1)/2,i].chars*" "}}
f["Thisrunofcharactersismeanttohavealengththatcanbeexpressesasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?"]
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e s a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
``````

4

# Pyth，27个字节

``````Js.IsSGlzWz+*-J=hZdjd<~>zZZ

z = input()
Z = 0
d = ' '
sSG                        G -> tri(G)
.I   lz                      Find the (float) input whose output is len(z).
s                             Convert to int.
J                              Save as J.
Wz                    while z:
=hZ             Z += 1
*-J  Zd            Generate J-Z spaces.
~>zZ     Remove the first Z characters from z.
<    Z    Generate those first Z characters.
jd          Join on spaces.
+                   Add the two together and print.
``````

4

# C，138个136 134字节

``````j,r,k,a;f(char*s){j=strlen(s);r=k=sqrt(1+8*j)/2;for(;r--;printf("\n")){for(j=r;j--;)printf(" ");for(j=k-r;j--;)printf("%c ",s[a++]);}}
``````

Mark K Cowan

@MarkKCowan是的，显然。我希望我做得更小！:)
Sahil Arora 2015年

@SahilArora -可以更换`printf(" ")`，并`printf("\n")``puts(" ")``puts("\n")`。每次替换将为您节省2个字节。:)
enhzflep

@enhzflep我已经尝试过了，它给出了一个模棱两可的输出！
Sahil Arora 2015年

enhzflep

4

# Ruby方法2修订版1，76字节

``````->s{s=s.chars*' '
0.upto(w=s.size**0.5-1){|i|puts' '*(w-i)+s[i*i+i,i*2+2]}}
``````

# Ruby方法2修订0，93个字节

``````->s{s=s.chars.to_a.join(' ')
w=(s.size**0.5).to_i
w.times{|i|puts' '*(w-i-1)+s[i*i+i,i*2+2]}}
``````

# Ruby方法1，94个字节

``````->s{n=-1;w=((s.size*2)**0.5).to_i
(w*w).times{|i|print i/w+i%w<w-1?'':s[n+=1],-i%w==1?\$/:' '}}
``````

`w` 包含底部行中的可打印字符数，或等效地，行数。

3

## Minkolang 0.14，42字节

``````(xid2;\$I2*`,)1-[i1+[" "o]lrx" "\$ii-1-D\$O].
``````

### 说明

``````(                Open while loop
x               Dump top of stack
i              Loop counter (i)
d2;           Duplicate and square
\$I2*       Length of input times two
`,     Push (i^2) <= (length of input)
)    Close for loop; pop top of stack and exit when it's 0

1-[                              Open for loop that repeats sqrt(len(input))-1 times
i1+[                          Open for loop that repeats (loop counter + 1) times
" "o                      Push a space then read in character from input
]                     Close for loop
l                    Push 10 (newline)
r                   Reverse stack
x                  Dump top of stack
" "               Push a space
\$i             Push the max iterations of for loop
i-           Subtract loop counter
1-         Subtract 1
D        Pop n and duplicate top of stack n times
\$O      Output whole stack as characters
].    Close for loop and stop.
``````

2

TanMath

1
@TanMath但42不是三角形数字！

3

# Python 2，88 85字节

``````s=t=raw_input()
i=1
while s:print' '*int(len(t*2)**.5-i)+' '.join(s[:i]);s=s[i:];i+=1
``````

xnor 2015年

xsot

xnor 2015年

xsot

pinkfloydx33

3

# CJam，50字节

``````q:QQ,1>{,{),:+}%:RQ,#:IR2ew<{~Q<>:LS*L,I+(Se[N}%}&
``````

``````q:QQ,1>{  e# Only proceed if string length > 1, otherwise just print.
,{),:}%:R e# Generates a list of sums from 0 to k, where k goes from 0 to the length of the string [0,1,3,6,10,15,21,...]
Q,#:I     e# Find the index of the length of the string in the list
R2ew<     e# Make a list that looks like [[0,1],[1,3],[3,6],...,[?,n] ]where n is the length of the string
{~Q<>:L   e# Use that list to get substrings of the string using the pairs as start and end indices
S*        e# Put spaces between the substrings
L,I+(Se[N e# (Length of the substring + Index of string length in sum array -1) is the length the line should be padded with spaces to. Add a new line at the end.
%}&
``````

2

# JavaScript（ES6），135个字节

``w=>{r='';for(s=j=0;j<w.length;j+=s++);for(i=j=0;w[j+i];j+=++i)r+=Array(s-i-1).join` `+w.slice(j,i+j+1).split``.join` `+'<br>';return r}``

``````function t(w) {
r = '';
for (s = j = 0; j < w.length; j += s++);
for (i = j = 0; w[j + i]; j += ++i) r += Array(s - i - 1).join` ` + w.slice(j, i + j + 1).split``.join` ` + '<br>';
return r;
}

document.write('<pre>' + t(prompt()));``````

Ismael Miguel

nicael 2015年

2

# Java中，258 194

``String f(String a){String r="";int t=(((int)Math.sqrt(8*a.length()+1))-1)/2-1;int i=0,n=0;while(n++<=t){for(int s=-1;s<t-n;++s)r+=" ";for(int j=0;j<n;++j)r+=a.charAt(i++)+" ";r+="\n";}return r;}``

``````public class TriangulatingText {

public static void main(String[] a) {
// @formatter:off
String[] testData = new String[] {
"R",
"cat",
"monk3y",
"meanIngfu1",
"^/\\/|\\/[]\\",
"Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?",
};
// @formatter:on

for (String data : testData) {
System.out.println("f(\"" + data + "\")");
System.out.println(new TriangulatingText().f(data));
}
}

// Begin golf
String f(String a) {
String r = "";
int t = (((int) Math.sqrt(8 * a.length() + 1)) - 1) / 2 - 1;
int i = 0, n = 0;
while (n++ <= t) {
for (int s = -1; s < t - n; ++s)
r += " ";
for (int j = 0; j < n; ++j)
r += a.charAt(i++) + " ";
r += "\n";
}
return r;
}
// End golf
}``````

``````f("R")
R

f("cat")
c
a t

f("monk3y")
m
o n
k 3 y

f("meanIngfu1")
m
e a
n I n
g f u 1

f("^/\/|\/[]\")
^
/ \
/ | \
/ [ ] \

f("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?")
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e d a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ? ``````

RAnders00 2015年

`import static System.out;`是25个字节，`System.`是7个字节。它使用了3次，且21 <25，因此实际上会将大小增加 4个字节。但是，好的线索可以节省空间，而且并不是每个人都知道它们。

1

1

# JavaScript（ES6），106个字节

``````a=>(y=z=0,(f=p=>p?" ".repeat(--p)+a.split``.slice(y,y+=++z).join` `+`
`+f(p):"")(Math.sqrt(2*a.length)|0))``````

``````1/2 * n^2 + 1/2 * n - T_n = 0

a = 1/2, b = 1/2, c = -T_n

-1/2 + sqrt(1/2^2 - 4*1/2*-T_n)
------------------------------- = sqrt(1/4 + 2*T_n) - 1/2
2*1/2
``````

1

# TeaScript，44 字节

``````r(m=\$s(2*xn)|0)ßp.R(m-i)+x·.S(v,v+=Æw)jø+§)µ
``````

### 不打高尔夫球

``````r(m=\$s(2*xn)|0)m(#p.R(m-i)+xs``.S(v,v+=++w)j` `+`
`)j``
``````

1

# Powershell，69个字节

``(\$args|% t*y|?{\$r+="\$_ ";++\$p-gt\$l}|%{\$r;rv r,p;\$l++})|%{' '*--\$l+\$_}``

``````\$f = {

(
\$args|% t*y|?{  # test predicate for each char in a argument string
\$r+="\$_ "   # add current char to the result string
++\$p-gt\$l   # return predicate value: current char posision is greater then line num
}|%{            # if predicate is True
\$r          # push the result string to a pipe
rv r,p      # Remove-Variable r,p. This variables will be undefined after it.
\$l++        # increment line number
}

)|%{                # new loop after processing all characters and calculating \$l
' '*--\$l+\$_     # add spaces to the start of lines
}                   # and push a result to a pipe

}

@(
,("R",
"R ")

,("cat",
" c ",
"a t ")

,("monk3y",
"  m ",
" o n ",
"k 3 y ")

,("meanIngfu1",
"   m ",
"  e a ",
" n I n ",
"g f u 1 ")

,("^/\/|\/[]\",
"   ^ ",
"  / \ ",
" / | \ ",
"/ [ ] \ ")

,("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Ican'tcountverywell,ok?",
"              T ",
"             h i ",
"            s r u ",
"           n o f c ",
"          h a r a c ",
"         t e r s i s ",
"        m e a n t t o ",
"       h a v e a l e n ",
"      g t h t h a t c a ",
"     n b e e x p r e s s ",
"    e d a s a t r i a n g ",
"   u l a r n u m b e r . D ",
"  i d i t w o r k ? Y o u t ",
" e l l m e , I c a n ' t c o ",
"u n t v e r y w e l l , o k ? ")

,("*/\/|\/|o\/|o|\/o|o|\/||o|o\/o|||o|\/o||o|||\/||o|||o|\/|o|||o||o\",
"          * ",
"         / \ ",
"        / | \ ",
"       / | o \ ",
"      / | o | \ ",
"     / o | o | \ ",
"    / | | o | o \ ",
"   / o | | | o | \ ",
"  / o | | o | | | \ ",
" / | | o | | | o | \ ",
"/ | o | | | o | | o \ ")

) | % {
\$s,\$expected = \$_
\$result = &\$f \$s
"\$result"-eq"\$expected"
\$result
}``````

``````True
R
True
c
a t
True
m
o n
k 3 y
True
m
e a
n I n
g f u 1
True
^
/ \
/ | \
/ [ ] \
True
T
h i
s r u
n o f c
h a r a c
t e r s i s
m e a n t t o
h a v e a l e n
g t h t h a t c a
n b e e x p r e s s
e d a s a t r i a n g
u l a r n u m b e r . D
i d i t w o r k ? Y o u t
e l l m e , I c a n ' t c o
u n t v e r y w e l l , o k ?
True
*
/ \
/ | \
/ | o \
/ | o | \
/ o | o | \
/ | | o | o \
/ o | | | o | \
/ o | | o | | | \
/ | | o | | | o | \
/ | o | | | o | | o \``````

0

## C＃，202

``````string r(string s,List<string> o,int i=1){o=o.Select(p=>" "+p).ToList();o.Add(String.Join(" ",s.Substring(0,i).ToCharArray()));return s.Length==i?String.Join("\n",o):r(s.Substring(i,s.Length-i),o,i+1);}
``````

`````` r("1",new List<string>());
r("123", new List<string>());
r("123456", new List<string>());
r("Thisrunofcharactersismeanttohavealengththatcanbeexpressedasatriangularnumber.Diditwork?Youtellme,Icanstcountverywell,ok?",new List<string>());
``````

0

# C，102字节

``````i,j;main(n,s){for(n=sqrt(strlen(gets(s))*2);j<n;printf("%*.1s",i>1?2:i*(n-j),i++>j?i=!++j,"\n":s++));}
``````

0

# Bash + sed，87

``````for((;i<\${#1};i+=j));{
a+=(\${1:i:++j})
}
printf %\${j}s\\n \${a[@]}|sed 's/\S/ &/g;s/.//'``````

0

# R，142字节

``````f=function(a){n=nchar(a);l=which(cumsum(1:n)==n);w=strsplit(a,c())[[1]];for(i in 1:l){cat(rep(" ",l-i),sep="");cat(w[1:i],"\n");w=w[-(1:i)]}}
``````

``````f=function(a){
n = nchar(a)                 #number of characters
l= which(cumsum(1:n)==n)     #which triangle number
w= strsplit(a,c())[[1]]      #Splits string into vector of characters
for (i in 1:l) {
cat(rep(" ",l-i),sep="") #preceeding spaces
cat(w[1:i],"\n")         #Letters
w=w[-(1:i)]              #Shifts removes letters (simplifies indexing)
}
}
``````