Determine if an integer is a palindrome in a given radix (base)
GolfScript, 10 characters
~base.-1%=
That is an easy one for GolfScript if we do it the straightforward way. The output is 0
/1
for false/true.
~ # Take input and evaluate it (stack: num rdx)
base # Fortunately the stack is in the correct order for
# a base transformation (stack: b[])
. # Duplicate top of stack (stack: b[] b[])
-1% # Reverse array (stack: b[] brev[])
= # Compare the elements
J (23 char) and K (19) double feature
The two languages are very similar, both in general and in this specific golf. Here is the J:
(-:|.)#.^:_1~/".1!:1,~1
,~1
- Append the number 1 to itself, making the array1 1
.1!:1
- Read in two strings from keyboard (1!:1
is to read, and1
is the file handle/number for keyboard input).".
- Convert each string to a number.#.^:_1~/
-F~/ x,y
means to findy F x
. OurF
is#.^:_1
, which performs the base expansion.(-:|.)
- Does the argument match (-:
) its reverse (|.
)?1
for yes,0
for no.
And here is the K:
a~|a:_vs/|.:'0::'``
0::'``
- Read in (0::
) a string for each ('
) line from console (`
is the file handle for this)..:'
- Convert (.:
) each ('
) string to a number._vs/|
- Reverse the pair of numbers, so that the radix is in front of the number, and then insert (/
) the base expansion function_vs
("vector from scalar") between them.a~|a:
- Assign this resulting expansion toa
, and then check ifa
matches (~
) its reverse (|
). Again,1
for yes,0
for no.
APL (20)
⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
Outputs 0
or 1
, e.g:
⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
⎕:
5
⎕:
5
0
⎕{≡∘⌽⍨⍵⊤⍨⍺/⍨⌊1+⍺⍟⍵}⎕
⎕:
16781313
⎕:
64
1
Explanation:
⎕{
...}⎕
: read two numbers, pass them to the function.⍵
is the first number and⍺
is the second number.⌊1+⍺⍟⍵
:floor(1+⍺ log ⍵)
, number of digits necessary to represent⍵
in base⍺
.⍺/⍨
: the base for each digit, so⍺
replicated by the number we just calculated.⍵⊤⍨
: represent⍵
in the given base (using numbers, so it works for all values of⍺
).≡∘⌽⍨
: see if the result is equal to its reverse.