为196算法编写一个简短的程序。该算法从整数开始,然后向其加反数,直到达到回文。
例如
input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232
输入项
一个不是lyrchrel数的整数(也就是说,在此算法下,它最终会产生回文,而不是无限地继续)
输出量
回文达到了。
为196算法编写一个简短的程序。该算法从整数开始,然后向其加反数,直到达到回文。
例如
input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232
输入项
一个不是lyrchrel数的整数(也就是说,在此算法下,它最终会产生回文,而不是无限地继续)
输出量
回文达到了。
Answers:
{a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
这在Dyalog APL中有效。这是从右到左的解释:
{ ... }⍞
:从用户那里获得字符(⍞
)的输入,并将其输入到我们的函数({ ... }
)中。⋄
分隔语句,因此我们从左到右查看它们):
a≡⌽a←⍕(⍎⍵)+⍎⌽⍵ : a
:评估(⍎
)正确的论点(⍵
)反向(⌽
),并将其添加到评估的正确论点本身。然后,格式化结果(⍕
;即给出其字符表示形式),将其赋给←
变量a
,最后测试a
'reverse是否等效于a
(即a
回文?)。如果为true,则返回a
;除此以外...∇a
:反馈a
到我们的函数中(∇
是隐式的自引用)。例:
{a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
412371
585585
{⍵=A←⍎⌽⍕⍵:⍵⋄∇A+⍵}⎕
。您保存大括号,反向和评估。
~]{{.`.-1%.@={;0}{~+1}if}do}%
精选评论
do
当然,程序的核心是循环。所以我只介绍一下。
.`
复制数字并将其字符串化。.-1%
复制该字符串版本并将其反转。.@
复制反向版本,并将原始非反向版本放在最前面。因此,数字为5280。在此阶段,堆栈为:5280 "0825" "0825" "5280"
。为进行比较设置了阶段。(比较之后,5280 "0825"
无论如何都将保留堆栈---弹出要比较的项目。)
;
)并返回0(以结束do
循环)即可。~
)颠倒的字符串(使其成为数字),将(+
)添加到原始数字,然后返回1(继续do
循环)。遵循JPvdMerwe的建议:
n=input()
while`n`!=`n`[::-1]:n+=int(`n`[::-1])
print n
Python 2、62:
n=raw_input()
while n!=n[::-1]:n=`int(n)+int(n[::-1])`
print n
n
将int视为可以缩短6个字符的代码,请检查以下代码:meta.codegolf.stackexchange.com/q/75/62
仅锻炼我的Pyth技能,而不是认真的竞争者。
L?bqb_by`+vbi_bTyz
等同于Python 3:
y=lambda b:b if b==b[::-1] else y(str(eval(b)+int(b[::-1],10)))
print y(input())
CJam是在询问此问题后创建的,因此从技术上讲,它是无效的提交。但是我发现这个问题很有趣,所以去了:
r{__W%:X=0{~X~+s1}?}g
说明:
r{ }g "Read the input number as string and enter a while-do loop";
__ "Make 2 copies of the string number";
W%:X "Reverse the second and store it in X";
= "Check if the number is already palindrome";
0{ }? "Put 0 on stack if it is palindrome, else, run the code block";
~ "Convert the string to int";
X~ "Put the reverse string on stack and convert it to int too";
+s "Add the two numbers and covert back the result to string";
核心逻辑是,在每次执行时迭代中,您首先要检查回文是否实现。如果没有,请在数字后加上反号。算法几乎是什么!
Perl,40个字符
$_=<>;$_+=$r while$_!=($r=reverse);print
不竞争,只是对我的语言有所了解,
期望stdin有一个数字
T~d{DddgCi+dgdC=n}uSP
说明
T~ Get a line of input, and eval to an integer
d Duplicate (for first round)
{Ddd Drop last and duplicate twice
gCi Convert to string, reverse, and convert back to integer
+d Add to original and duplicate
gdC Convert to string, duplicate, reverse
=n} If it isn't a palindrome, keep going
uSP Run until palindrome reached, then print output number
不竞争,因为该语言推迟了挑战。
码:
[DÂQ#Â+
说明:
[ # Infinite loop.
DÂ # Duplicate and bifurcate (which duplicates it and reverses the duplicate).
Q# # If the number and the number reversed are equal, break.
Â+ # Add the reversed number to the initial number.
使用CP-1252编码。在线尝试!。
hello
。分叉将保留原始字符串,并推回该字符串。它是重复和反向的缩写。
↔?|↔;?+↰
与Brachylog简介视频中我看到并感兴趣的第一个Brachylog程序之一有些相似。
?↔?.|↔;?+↰. (initial ? and the .s are implicit)
?↔? % If the input and its reverse are the same,
. % then the input is the output
|↔;?+↰ % Or, add the input and its reverse, and call this predicate recursively
. % The result of that is the output
<?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s;
测试:
$ php 196.php <<< 5280
23232
$str =
猫的东西,以备将来打高尔夫球。比使用更好的东西STDIN
,仍然比$argv[0]
。
X=`rev<<<$1|sed s/^0*//`;[ $1 = $X ]&&echo $1||. $0 $(($1+$X))
致电:bash <文件名> <号码>
r=input()
while 1:
r=`r`
if r==r[::-1]:
break
else:
r=int(r)+int(r[::-1])
print r
蟒蛇。85个字符:
s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n));print n
如果您不想在每次迭代中输出:
s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n))
print n
(少一个字符)
for($a=+"$input";-join"$a"[99..0]-ne$a){$a+=-join"$a"[99..0]}$a
I still hate it that there is no easy way to reverse a string.
long
as well which is the largest integral type PowerShell supports anyway but still, I waste two chars.
Haskell 89 87 chars
r=read.reverse.show
main=getLine>>=print.head.filter(\x->x==r x).iterate(\x->x+r x).read
Somewhat readable version:
myFind p = head . filter p
rev = read . reverse . show
isPalindrome x = x == rev x
next x = x + rev x
sequence196 = iterate next
palindrome196 = myFind isPalindrome . sequence196
main = getLine >>= print . palindrome196 . read
The golfed version was created by manual inlining and renaming the remaining functions to single character names.
until
from the Prelude, as well as extracting the pattern of applying a binary operator to x
and r x
. Also, use readLn
instead of getLine
and read
. The result saves 20 characters: f%x=f x$read.reverse.show$x;main=readLn>>=print.until((==)%)((+)%)
r=(=<<read.reverse.show)
and just use r(==)`until`r(+)
. Apart from that saving, it doesn't need to be a full program, a valid submission could just be the unnamed function from before. This brings you down to 41 bytes: Try it online!
"KCTS"4(&:0\v
\T\a*+\:0`jv>:a%\a/
0:+_v#-TD2$<^\
@.<
though the code is places in a 4x19 grid, so might call it 76.
#include<cstdio>
#define Y(A,B,C,D)template<int N>struct A<C,D>{enum{v=B};};
#define Z(A)template<int N,int M>struct A{enum{v=
#define n 5194
Z(R)R<N/10,M*10+N%10>::v};};Y(R,N,0,N)Z(S)S<N+M,R<N+M,0>::v>::v};};Y(S,N,N,N)main(){printf("%d",S<n+R<n,0>::v,0>::v);}
This version could be shortened a bit, but a 256-character answer is hard to pass up. Here's an un-golfed version:
#include <iostream>
template<size_t N>
class Reverse
{
template<size_t M, size_t R>
struct Inner
{
enum { value = Inner<M/10, R*10 + M%10>::value };
};
template<size_t R>
struct Inner<0, R>
{
enum { value = R };
};
public:
enum { value = Inner<N, 0>::value };
};
template<size_t N>
class OneNineSix
{
template<size_t M, size_t R=Reverse<M>::value>
struct Inner
{
enum { value = OneNineSix<M + R>::value };
};
template<size_t M>
struct Inner<M, M>
{
enum { value = M };
};
public:
enum { value = Inner<N + Reverse<N>::value>::value };
};
int main()
{
const size_t N = 4123;
std::cout << OneNineSix<N>::value << std::endl;
}
D`_b]D$XIsr)h
`_b - int(reversed(str(num))
D ] - [num, ^]
D - _ = ^
$ - delta(^)
XI - if ^:
s - num = sum(_)
r - goto_start()
h - _[0]
L,BDbRBv
D,f,@,1]A+
D,g,@,1]A=
D,h,@,{f}A{g}Q{h}
L,{h}2/i
L, ; Create a function 'lambda 1'
; Example argument: [5280]
BD ; Digits; STACK = [[5 2 8 0]]
bR ; Reverse; STACK = [[0 8 2 5]]
Bv ; Undigits; STACK = [825]
D,f,@, ; Define a monadic function 'f'
; Example argument: [5280]
1] ; Call 'lambda 1'; STACK = [825]
A+ ; Add the argument; STACK = [6105]
D,g,@, ; Define a monadic function 'g'
; Example argument: [5280]
1] ; Call 'lambda 1'; STACK = [825]
A= ; Equal to argument; STACK = [0]
D,h,@, ; Define a monadic function 'h'
; Example argument: [5280]
{f} ; Call 'f'; STACK = [6105]
A{g} ; If 'g'...
Q ; Return
{h} ; Else call 'h'
L, ; Define a function, 'lambda 2'
; Example argument: [5280]
{h} ; Call 'h'; STACK = [46464]
2/i ; Halve; STACK = [23232]
-1 byte thanks to @AdmBorkBork
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s
Test script:
$f = {
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s
}
&$f 5280
;
between param($m)
and for
.
Requires GNU dc, min version 1.4 (for R
command).
[O~3RO*+rd0<R]sR[+lfx]sg[ddO~rd0<R+d3R!=g]dsfx
Input and output are top-of-stack, as usual. It takes a surprising amount of code to reverse digits in dc (unless I'm missing something, which is far from impossible). It does have the numeric range to behave nicely with inputs such as these (which will overflow 32-bit unsigned arithmetic, for example):
# Reverse digits, starting after first digit extracted
[O~3RO*+r d0<R]sR
# Recursion helper - add and recurse
[+ lfx]sg
# Main recursive function
[dd O~r d0<R+ d3R !=g]dsfx
R
command. Good solution, though!
R
was new. Looking forward to seeing your method!
-84 bytes thanks to Giuseppe! -4 byes thanks to JayCe!
function(x){"-"=utf8ToInt
S=strtoi
"!"=rev
while({z=paste(S(x)+S(intToUtf8(!-x),10));any(-z!=!-z)})x=z
z}
strsplit(x,"")
is shorter than strsplit(x,NULL)
, and el(L)
is shorter than L[[1]]
. as.double
is shorter than as.numeric
and strtoi
is shorter than both; instead of setting t
just use it directly in your if
statement. also this is a recursive function if I'm not mistaken, so you need to put f=
as part of your submission.
utf8ToInt
to convert to digits and intToUtf8
to convert back. That'll be a big byte saving!
-
in place of U
. I also replaced rev
with !
but it does not save any byte...