Tidak pernah aneh atau genap


15

Apakah Anda memperhatikan, bahwa ini adalah palindrome?

Input
angka integer non-negatif atau string yang mewakilinya

Keluaran
4 kemungkinan keluaran, mewakili dua sifat nomor:

  • apakah itu palindrome
  • rumit # 2

Properti Tricky # 2
Jika angka bukan palindrome, properti ini menjawab pertanyaan "Apakah angka pertama dan terakhir memiliki paritas yang sama?"
Jika angka adalah palindrom, properti ini menjawab pertanyaan "Apakah digit pertama dan tengah memiliki paritas yang sama?". Untuk panjang genap, digit tengah adalah salah satu dari dua digit tengah.

Contohnya

12345678 -> False False
Itu bukan palindrome, digit pertama dan terakhir memiliki paritas yang berbeda

12345679 -> False True
Itu bukan palindrome, digit pertama dan terakhir memiliki paritas yang sama

12344321 -> Benar Salah
Ini adalah palindrom, digit pertama 1 dan digit tengah 4 memiliki paritas yang berbeda

123454321 -> True True
Ini adalah palindrome, digit pertama 1 dan digit tengah 5 memiliki paritas yang sama

PS
Anda bebas menentukan jenis dan format keluaran. Ini bisa berupa 4 nilai berbeda. Sebut saja dalam jawaban Anda.


Tidak jelas apa arti "angka ini setengah". Saya pikir itu berarti n / 2, tetapi klarifikasi tampaknya menyiratkan itu adalah pertama atau terakhir secara paralel.
xnor

@xnor Ini secara saksama
Dead Possum

Saya telah mengedit apa yang menurut saya merupakan cara yang lebih sederhana untuk menyatakan aturan.
xnor

@ xnor Sepertinya bagus, terima kasih!
Dead Possum

Bisakah kita menganggap input integer non-negatif?
Titus

Jawaban:


6

05AB1E, 15 , 14 13 byte (Terima kasih kepada Riley dan carusocomputing)

ÐRQi2ä¨}ȹRÈQ

Coba online

Kembali dengan tanda kurung jika itu adalah palindrome

Kembali dengan 0 jika paritasnya berbeda, 1 jika sama

Ð Tambahkan input, sehingga saya memiliki input yang cukup untuk bekerja

R Membalikkan elemen terakhir dari tumpukan

Q Lihat apakah itu sama (ambil dua elemen teratas dan lakukan ==)

i Jika pernyataan, maka hanya melewati ketika itu adalah palindrome

2 Tekan angka 2

ä Bagi input menjadi 2 irisan yang sama

¨ Dorong elemen pertama dari pemecahan (126462 hasil dalam 1264)

} Berakhir jika

È Periksa apakah elemen terakhir genap

¹ Tekan kembali input pertama

R Balikkan input itu

È Periksa apakah sekarang

Q Periksa apakah hasil tersebut sama dan secara implisit dicetak


2
Apakah Anda akan memberikan penjelasan tentang kode Anda?
Dead Possum

Akan segera melakukannya
P. Knops

1
Anda bisa menggunakan ¨bukan .
Riley

Anda tidak membutuhkan akhir ,, keluaran tersirat. Juga bukan Anda dapat menggunakan membagi dlm dua cabang: Â; penghematan 2 byte untuk 12:ÐRQi¨}ȹRÈQ
Magic Octopus Mm

Saya akan menguji bagian bifurkasi, itu berperilaku aneh dalam skenario tertentu, tetapi itu ,akan mendorong Anda untuk memimpin;).
Magic Gurita Guci

8

PHP, 55 52 byte

echo$p=strrev($n=$argn)==$n,$n-$n[$p*log($n,100)]&1;

menerima input dari STDIN; jalankan bersama -R.

keluaran:

  • 10 untuk palindrom dan paritas yang sama
  • 11 untuk palindrome dan paritas yang berbeda
  • 0 untuk non-palindrome dan paritas yang sama
  • 1 untuk non-palindrome dan paritas yang berbeda

catatan:

  • strlen($n)/2== log($n,10)/2==log($n,100)
  • jika palindrome, bandingkan angka tengah $n[1*log($n,100)]
  • jika tidak, digit pertama $n[0*log($n,100)]
  • ... ke seluruh nomor (<- bit terendah <- digit terakhir)

Anda dapat menyimpan satu byte dengan menggunakan <?=alih-alih echo sandbox.onlinephpfunctions.com/code/…
roberto06

@ roberto06 $argnhanya didefinisikan dengan -R, dan itu tidak mengizinkan tag.
Titus

OKE, tidak tahu itu, terima kasih.
roberto06

@ roberto06 Tunggu ... $argnjuga tersedia dengan -F. Tapi nm.
Titus

7

Jelly , 16 14 byte

DµŒḂṄHC×LĊị+ḢḂ

Cobalah online!

Menghasilkan dua baris:

  • 1untuk palindrome, 0untuk tidak
  • 0untuk tricky # 2 , 1untuk tidak

Penjelasan

DµŒḂṄHC×LĊị+ḢḂ    Main link. Argument: n (number)
D                 Get the digits of n
 µ                Start a new monadic chain
  ŒḂ              Check if the digit array is a palindrome (1 if yes, 0 if no)
    Ṅ             Print the result with a newline
     H            Halve (0.5 if palindrome, 0 if not)
      C           Subtract from 1 (0.5 if palindrome, 1 if not)
       ×          Multiply by...
        L         ...length of array (length/2 if palindrome, length if not)
         Ċ        Round up
          ị       Take item at that index from the digits
           +      Add...
            Ḣ     ...first item of digits
             Ḃ    Result modulo 2

Saya selalu bertanya pada diri sendiri, berapa banyak karakter berbeda yang harus Anda pelajari untuk dapat menulis program dengan ini? Apakah Anda tahu semua arti dan semua karakter? Bisakah Anda mengetik karakter tanpa menggunakan tombol ALT atau tabel karakter? Seperti apa bentuk IDE untuk ini?
Daniel W.

3
@DanFromGermany Saya belum ingat sebagian besar karakter. Karena itu saya juga tidak harus mempelajari tata letak keyboard US International, jadi saya hanya menyalin karakter dari wiki . Pengembangan terjadi karena coba-coba di TIO.
PurkkaKoodari


5

PowerShell , 114 99 byte

param($n)((0,(($z=$n[0]%2)-eq$n[-1]%2)),(1,($z-eq$n[$n.length/2]%2)))[($n-eq-join$n[$n.length..0])]

Cobalah online!

Disimpan 15 byte berkat @Sinusoid.

Inputs as a string. Outputs an array of type (0|1) (True|False), with the 0 indicating "not a palindrome" and the 1 indicating "palindrome", and the True indicating parity matches and False otherwise.

This is done by using a pseudo-ternary and indexing into the appropriate place (a,b)[index]. The index ($n-eq-join$n[$n.length..0]) checks whether the input is a palindrome. If it is not, we take the a portion, which is a 0 coupled with whether the parity of the first digit $n[0] is -equal to the parity of the last digit $n[-1]. Otherwise, we're in the b portion, which is a 1 coupled with whether $z (the parity of the first digit) is -equal to the parity of the middle digit $n[$n.length/2].

Previously, I had "$($n[0])" to get the first digit to cast correctly as an integer, since $n[0] results in a char and the modulo operator % coalesces chars based on the ASCII value, not the literal value, whereas a string does the literal value. However, @Sinusoid helped me to see that 0,1,2,...,9 as literal values all have the same parity as 48,49,50,...,57, so if it uses the ASCII value we still get the same result.

That array is left on the pipeline, and output is implicit.


Out of curiosity, why did you have to use double quotes and an extra $ when you did modulus %2 to a number? I tried this myself and it wasn't necessary if I individually did each step, but it is when you put it inside an array? Does powershell treat it as a different variable type?
Sinusoid

@Sinusoid It's taking input as a string, so when $n[0] indexes, it comes out as a char. The cast from char to int forced by the % operator doesn't go from '1' to 1, but to the ASCII value, so it's 49. The "$( )" does an explicit cast to string instead, which properly converts it to 1. ... Although, now that you mention it, the parity of 0..9 is the same as ASCII 48..57, so I can probably golf that down. Thanks!
AdmBorkBork

@Sinusoid 15 bytes saved, thanks!
AdmBorkBork

3

VBA, 117 99 bytes

Saved 18 bytes thanks to Titus

Sub p(s)
b=s
If s=StrReverse(s)Then r=2:b=Left(s,Len(s)/2+.1)
Debug.?r+(Left(s,1)-b And 1);
End Sub

It doesn't expand much once formatted:

Sub p(s)
    b = s
    If s = StrReverse(s) Then r = 2: b = Left(s, Len(s) / 2 + 0.1)
    Debug.Print r + (Left(s, 1) - b And 1);
End Sub

Here are the given test case results:

s = 12345678     p(s) = 1 = False False
s = 12345679     p(s) = 0 = False True
s = 12344321     p(s) = 3 = True False
s = 123454321    p(s) = 2 = True True

Does VBA have bitwise operators? Try &1 instead of mod 2. You might also get rid of the If/Then with r=r+2-2*(left(s,1)-b &1) or even better If s = StrReverse(s) then r=2 and r=r+1-(left(s,1)-b &1) ... and 2 bytes off with reversing the Tricky#2: r=r+(left(s,1)-b &1); save more with printing it directly: Debug.Print r+(left(s,1)-b &1). Should be 95 bytes then; 98 if &1 does not work.
Titus

@Titus Thanks! I wasn't familiar with bitwise operations at all, actually. VBA does have bitwise operations but they use And instead of just &. I figured out how to implement your first suggestion but I couldn't figure out how you meant to change the 3rd line with StrReverse.
Engineer Toast

Sub p(s);b=s;If s=StrReverse(s)Then r=2:b=Mid(s,Len(s)/2+.1,1);Debug.?r+(Left(s,1)-b&1);End Sub -> 0/2 for palindromes, 1/0 for Tricky#2
Titus

Oh and you should be able to replace the Mid() with Left(s,Len(s)/2+1) or so.
Titus

1
@Titus Because VBA is stupid and doesn't always round up from 0.5. It uses round-to-even logic. If the string is 9 characters long, then Len(s)/2 = 4.5 which VBA will round to 4. If it's 7 characters long, then Len(s)/2 = 3.5 which VBA will also round to 4. Adding 0.1 corrects the lunacy.
Engineer Toast

3

Perl 6, 48 bytes

{($/=.flip==$_),[==] .ords[0,($/??*/2!!*-1)]X%2}

Try it

results in (True True) (True False) (False True) or (False False)

Expanded:

{                  # bare block lambda with implicit parameter 「$_」

  (
    $/ =           # store in 「$/」
    .flip == $_    # is 「$_」 equal backwards and forwards
  ),


  [==]             # reduce the following using &infix:<==> (are they equal)

    .ords\         # list of ordinals (short way to make 「$_」 indexable)
    [
      0,           # the first digit's ordinal
      (
        $/         # if the first test is True (palindrome)
        ??   * / 2 # get the value in the middle
        !!   * - 1 # else get the last value
      )
    ]
    X[%] 2         # cross those two values with 2 using the modulus operator
}

3

Java 8, 205 197 182 168 134 bytes

n->{int l=n.length(),a=n.charAt(0)%2;return n.equals(new StringBuffer(n).reverse()+"")?a==n.charAt(l/2)%2?4:3:a==n.charAt(l-1)%2?2:1;}

Outputs: 1 for false-false; 2 for false-true; 3 for true-false; 4 for true-true.

Explanation:

Try it here.

n->{                     // Method with String parameter and integer return-type
  int l=n.length(),      //  The length of the input String
      a=n.charAt(0)%2,   //  Mod-2 of the first digit
  return n.equals(new StringBuffer(n).reverse()+"")?
                         //  If the String is a palindrome
    a==n.charAt(l/2)%2?  //   And if the first and middle digits are both even/odd
     4                   //    return 4
    :                    //   Else
     3                   //    Return 3
   :a==n.charAt(l-1)%2 ? //  Else-if the first and last digits are both even/odd
    2                    //   Return 2
   :                     //  Else
    1;                   //   Return 1
}                        // End of method

1

Haskell, 89 bytes

(x:r)#y=mod(sum$fromEnum<$>[x,y])2
f x|reverse x/=x=2+x#last x|y<-length x`div`2=x#(x!!y)

Try it online! Usage: f "12345". Returns 0 for True True, 1for True False, 2 for False True and 3 for False False.

The function # converts both digit characters into their ascii character codes and sums them. If both are even or both are odd the sum will be even, otherwise if one is even and the other odd the sum will be odd. Calculating modulo two, # returns 0 for equal parity and 1 otherwise. f checks if the input string x is a palindrome. If not then # is called with x and the last character of x and two is added to the result, otherwise if x is palindromic call # with the middle character of x instead and leave the result as is.


1

Kotlin, 142 bytes

fun Char.e()=toInt()%2==0;
val y=x.reversed()==x;val z=x.first();println("${y},${if(y)z.e()==x.get(x.length/2).e();else z.e()==x.last().e()}")

Try it online!

fun Char.e() = toInt() % 2 == 0; //character extension function, returns if character(as int) is even

val y = x.reversed() == x
val z = x.first()

println(
"${y} //returns whether or not input is a palindrome
, //comma separator between the values
${if(y) z.e() == x.get(x.length/2).e() // if it's a palindrome compare first and middle parity
else z.e() == x.last().e()}" //else compare first and last parity
)

1

REXX, 104 100 bytes

arg a
parse var a b 2''-1 c
e=a=reverse(a)
b=b//2
if e then f=b&centre(a,1)//2
else f=b&c//2
say e f

Returns logical value pair 0 0, 0 1, 1 0 or 1 1.


1

R, 115 109 105 bytes

w=strtoi(el(strsplit(scan(,""),"")))
c(p<-all(w==rev(w)),w[1]%%2==switch(p+1,tail(w,1),w[sum(1|w)/2])%%2)

Takes input from stdin. Returns FALSE FALSE for False False, FALSE TRUE for False True, TRUE FALSE for True False, and TRUE TRUE for True True.


1

AWK, 97 96 bytes

{n=split($0,a,"")
for(;j<n/2;)s+=a[j+1]!=a[n-j++]
x=(a[1]%2==a[s?n:int(n/2)+1]%2)+(s?0:2)
$0=x}1

Simplest usage is to place the code into file: OddEven then do:

awk -f OddEven <<< "some number here"

Output is essentially the bit-sum of the comparisons in the Question, e.g.

0, Not palindrome and first and last digits have different parity
1, Not palindrome and first and last digits have same parity 
2, Palindrome and the first digit and middle digit have different parity
3, Palindrome and the first digit and middle digit have same parity

I tried removing the () from (s?0:2) but this messes up operator precedence somehow.


Saved a byte by moving the increment on j. This means the for() could be replaced with a while(), but no bytes would be saved in doing so :(
Robert Benson

1

CJam, 32 bytes

q:N_W%=N0=~2%NW=~2%N_,2/=~2%3$?=

Input is a number on top of the stack.

Explanation:

q                                 e# Read input:          | "12345679"
 :N                               e# Store in N:          | "12345679"
   _                              e# Duplicate:           | "12345679" "12345679"
    W%                            e# Reverse:             | "12345679" "97654321"
      =                           e# Check equality:      | 0
       N                          e# Push N:              | 0 "12345679"
        0=~                       e# First digit:         | 0 1
           2%                     e# Modulo 2:            | 0 1
             N                    e# Push N:              | 0 1 "12345679"
              W=~                 e# Get last digit:      | 0 1 9
                 2%               e# Modulo 2:            | 0 1 1
                   N              e# Push N:              | 0 1 1 "12345679"
                    _             e# Duplicate:           | 0 1 1 "12345679" "12345679"
                     ,            e# Length:              | 0 1 1 "12345679" 8
                      2/          e# Divide by 2:         | 0 1 1 "12345679" 4
                        =         e# Get digit (as char): | 0 1 1 '5
                         ~        e# Eval character       | 0 1 1 5
                          2%      e# Modulo 2:            | 0 1 1 1
                            3$    e# Copy stack element:  | 0 1 1 1 0
                              ?   e# Ternary operator:    | 0 1 1
                               =  e# Check equality:      | 0 1


1

Groovy, 326 303 bytes

Shrunk Code:

String str="12345678";char pal,par;pal=str==str.reverse()?'P':'N';if(pal=='P'){par=(int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'}else{par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'};print((String)pal+(String)par)

Original Code (with Explanation):

Declare str as String                        String str = "12345678"
Declare pal and par as char                  char pal, par
Check if Palindrome or not                   pal = str==str.reverse()?'P':'N'
If Palindrome...                             if (pal=='P') {
and has same parity (S) and if not (N)       par = (int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'
else if not palindrome...                    } else {
and has same parity (S) and if not (N)       par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'
closing tag for if                           }
Print desired output                         print((String)pal+(String)par)

Original Code (without Explanation):

String str = "12345678"
char pal, par
pal = str==str.reverse()?'P':'N'
if (pal=='P') {
    par = (int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'
} else {
    par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'
}
print((String)pal+(String)par)

Input:

Just change "12345678" to another set of non-negative digits.

Output:

"PS" - Palindrome with Same Parity
"PN" - Palindrome with Diff Parity
"NS" - Non-palindrome with Same Parity
"NN" - Non-palindrome with Diff Parity
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.