Jadikan program Triangularity valid


19

Triangularity adalah esolang baru yang dikembangkan oleh Mr. Xcoder di mana struktur kode harus mengikuti pola yang sangat spesifik:

  • Untuk nbaris kode, pasti ada 2n-1karakter program di dalamnya. Ini menyebabkan bentuk segitiga / piramida, dengan baris pertama hanya memiliki satu karakter dan sisanya bertambah dengan penambahan 2.
  • Setiap baris harus diisi dengan .s di kiri dan kanan, sehingga karakter dipusatkan pada garis mereka dan semua garis empuk dengan panjang yang sama. Jika ldidefinisikan sebagai jumlah baris dalam program, setiap baris dalam program harus memiliki panjang2 * l - 1

Misalnya, program di sebelah kiri valid, tetapi program di sebelah kanan tidak:

 Valid    |  Invalid  
          |
...A...   |  ABCDE
..BCD..   |  FGH
.EFGHI.   |  IJKLMN
JKLMNOP   |  OPQRS

Ketika diletakkan dalam struktur yang valid, namanya menjadi jelas.

Tugas

Tugas Anda adalah mengambil string baris tunggal sebagai input, mewakili kode Triangularity, dan mengeluarkannya dikonversi menjadi kode yang valid seperti yang dijelaskan di atas.

Spesifikasi untuk I / O:

  • Input hanya akan berisi karakter dalam kisaran 0x20 - 0x7e
  • Panjang input akan selalu berupa angka kuadrat dan dengan demikian dapat dipadatkan dengan baik.
  • Anda harus menggunakan titik-titik untuk bantalan keluaran, bukan sesuatu yang lain.

Anda dapat input dan output melalui metode apa pun yang dapat diterima . Ini adalah sehingga kode terpendek dalam byte menang!

Uji kasus

input
----
output

g
----
g

PcSa
----
.P.
cSa

DfJ0vCq7G
----
..D..
.fJ0.
vCq7G

7xsB8a1Oqw5fhHX0
----
...7...
..xsB..
.8a1Oq.
w5fhHX0

QNYATbkX2sKZ6IuOmofwhgaef
----
....Q....
...NYA...
..TbkX2..
.sKZ6IuO.
mofwhgaef

ABCDEF"$%& G8"F@
----
...A...
..BCD..
.EF"$%.
& G8"F@

ab.c
----
.a.
b.c

Bagi mereka yang tahu Triangularity, Anda akan melihat dari test case terakhir bahwa string tidak harus ditangani



13
Saya menyadari ini mungkin sia-sia, tetapi akankah pemilih yang rendah hati menjelaskan suara mereka? Saya ingin meningkatkan tantangan dengan cara apa pun yang saya bisa.
caird coinheringaahing

Apakah memimpin atau mengikuti baris baru dapat diterima?
Arnauld

@Arnauld Ya, memimpin dan mengikuti ruang putih tidak masalah.
caird coinheringaahing

Apakah daftar garis baik-baik saja?
Tn. Xcoder

Jawaban:


19

Triangularity , 127 byte

.......).......
......2)1......
...../)IL^.....
....f)rMD@_....
...)2)1/)IL^...
..f+`"'.'*"+E..
.DWReD)2s^)Its.
D+@sh+s+})10cJ.

Cobalah online!

Penjelasan

Menghapus karakter yang menggantikan padding, kita mendapatkan program berikut:

)2)1/)IL^f)rMD@_)2)1/)IL^f+`"'.'*"+EDWReD)2s^)ItsD+@sh+s+})10cJ

... Yang mana cukup panjang, bukan? Mari kita hancurkan menjadi beberapa bagian.

Menghasilkan bilangan bulat [0 ... √len (input))

)2)1/)IL^f)r – Subprogram #1.
)            – Creates a new stack entry, equal to 0. This must precede any integer
               literal, because each character in '0123456789' isn't parsed on its
               own as a literal, but rather they are commands which multiply the ToS
               by 10 and add the value of their digit equivalent. 
 2           – ToS * 10 + 2 = 2.           || STACK: [2]
  )1         – The literal 1.              || STACK: [2, 1]
    /        – Division.                   || STACK: [1 / 2] = [0.5]
     )I      – Get the input at index 0.   || STACK: [0.5, input]
       L     – Length.                     || STACK: [0.5, len(input)]
        ^    – Exponentiation.             || STACK: [len(input) ** 0.5]
         f   – Trim decimals.              || STACK: [int(len(input) ** 0.5)] 
          )r – Create the list [0 .. ToS). || STACK: [[0 ... int(len(input) ** 0.5))]

Menghasilkan titik-titik

MD@_)2)1/)IL^f+`"'.'*"+E – Subprogram #2.
MD                       – For each integer in the range, run some code on a separate
                           stack, preinitialised to two copies of the argument.
  @_                     – Increment and negate the ToS.
    )2)1/)IL^f           – The square root of the length of the input, again.
              +          – Add the two.
               `         – And cast the integer given to a string.
                "'.'*"+  – Prepends the literal "'.'*" to the string representation.
                       E – Evaluate as a Python expression (basically string repetition).

Memotong karakter di depan

DWReD)2s^)It – Subprogram #3.
D            – Duplicate the result of the expression above.
 W           – Wrap the whole intermediate stack to an array.
  Re         – Reverse the stack and dump the contents separately onto the stack.
    D        – Duplicate the result.
     )2      – Push the literal 2.
       s^    – Swap and perform exponentiation.
         )It – Push the input and trim the characters before that index.

Memotong karakter di akhir

sD+@sh+s+ – Subprogram #4.
s         – Swap the top two elements on the stack.
 D+       – Double. Push twice and add.
   @      – Increment.
    sh    – Swap the top two elements and trim the characters after that index.
      +   – Append the first set of dots.
       s+ – And prepend the second set of dots.

Mengakhiri loop dan mencetak dengan cantik

})10cJ – Subprogram #5.
}      – End the loop.
 )10   – Push the literal 10.
    c  – Convert from code-point to character (yields '\n').
     J – And join the result by newlines.

apakah Anda harus mencetak byte untuk "." karakter jika mereka diamanatkan oleh intrinsik bahasa?
JDL

@JDL Ya, program tidak dapat berjalan dengan benar tanpa mereka, jadi saya harus memasukkannya dalam hitungan byte :-)
Mr. Xcoder

Apakah Anda perlu "memotong desimal", mengingat panjang input dijamin persegi? Anda juga harus bisa mendapatkan batang Jdi akhir dan menghasilkan array garis. Namun, tidak tahu apakah itu akan menyelamatkan Anda, jika akhir baris terakhir harus diisi dengan .untuk mengisi ruang yang tersisa.
Shaggy

1
@Shaggy 1) Ya, fdiperlukan karena range tidak dapat menerima argumen float (bahkan dengan .0) 2) Menyingkirkan Jtidak menyimpan byte karena padding, jadi saya memilih format output yang lebih cantik.
Tn. Xcoder

8

Japt , 15 14 10 byte

Menghasilkan array garis.

ò@°T¬v1Ãû.

Cobalah | Periksa semua test case


Penjelasan

ò@     Ã       :Partition at characters where the following function returns true
  °T           :  Increment T (initially 0)
    ¬          :  Square root
     v1        :  Divisible by 1?
               :(Or, in other words, split after every character with a 1-based index that's a perfect square)
        û.     :Centre pad each element with .s to the length of the longest element

Solusi Asli

ʬÆsTT±X+°XÃû.

Cobalah

Ê                  :Length of input
 ¬                 :Square root
  Æ        à       :Range [0,ʬ) and pass each X through a function
   s               :  Slice input
    T              :    from index T, initially 0
     T±X+°X        :    to index T incremented by X plus X incremented
            û.     :Centre pad each element with .s to the length of the longest element

7

Sekam , 15 byte

Ṡzö`JR2tR'.ṡCİ1

Cobalah online!

Penjelasan

Ṡzö`JR2tR'.ṡCİ1  Implicit input, say s = "DfJ0vCq7G".
             İ1  List of odd positive integers: [1,3,5,7,..
            C    Cut s to those lengths: x = ["D","fJ0","vCq7G"]
           ṡ     Reversed indices of x: y = [3,2,1]
Ṡz               Zip x and y using this function:
                  Arguments are a string and a number, e.g. r = "fJ0" and n = 2.
        R'.       n copies of '.': ".."
       t          Drop first element: "."
     R2           Two copies of this: [".","."]
  ö`J             Join by r: ".fJ0."
                 Result is ["..D..",".fJ0.","vCq7G"]; implicitly print on separate lines.

7

05AB1E , 20 19 18 byte

Menyimpan satu byte berkat Magic Octopus Guci

ā·<£õKRvy'.N×.ø}r»

Cobalah online!

Penjelasan

ā                    # push the list [1 ... len(input)]
 ·<                  # multiply each by 2 and decrement each, making a list of odd numbers
   £                 # split the input into chunks of these sizes
    õK               # remove empty strings
      R              # reverse list
       vy      }     # for each y in the list
             .ø      # surround it with
         '.N×        # "." (dot) repeated N times, where N is the current iteration index
                r    # reverse the stack
                 »   # join stack by newlines

ÅÉuntuk kemungkinan dapat membantu?
Magic Octopus Urn

Sesuatu seperti g;ÅÉ£Rvy'.N×.ø}r»,? Tapi bukan itu karena itu tidak benar lol.
Magic Octopus Urn

@ MagicOctopusUrn: ÅÉpasti akan membantu jika kita bisa mengetahui panjang baris bawah dalam 2 byte. Saya tidak tahu apakah kita bisa. Mungkin ada cara lain untuk menggabungkannya juga.
Emigna

@MagicOctopusUrn: Saya punya solusi yang sama ini sebelumnya kecuali saya menggunakan )Rbukannya ryang tidak menyimpan setiap byte: /
Emigna

Saya sedang berusaha menemukan cara untuk "membalikkan loop" untuk hanya mencetak saat itu terjadi, tidak ada ide tentang itu.
Guci Gurita Ajaib


5

Jelly ,  22  19 byte

J²‘Ṭœṗ⁸Ṛz”.Zµṙ"JC$Ṛ

Tautan monadik yang mengembalikan daftar daftar karakter (garis)

Cobalah online!

Bagaimana?

J²‘Ṭœṗ⁸Ṛz”.Zµṙ"JC$Ṛ - Link: list of characters e.g. "DfJ0vCq7G"
J                   - range of length               [1,2,3,4,5,6,7,8,9]
 ²                  - square (vectorises)           [1,4,9,16,25,36,49,64,81]
  ‘                 - increment                     [2,5,10,17,26,37,50,65,82]
   Ṭ                - untruth (1s at those indices) [0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,...]
      ⁸             - chain's left argument         "DfJ0vCq7G"
    œṗ              - partition at indexes          ["D","fJ0","vCq7G"]
       Ṛ            - reverse                       ["vCq7G","fJ0","D"]
         ”.         - literal '.'                   '.'
        z           - transpose with filler         ["vfD","CJ.","q0.","7..","G.."]
           Z        - transpose                     ["vCq7G","fJ0..","D...."]
            µ       - start a new monadic chain
                 $  - last two links as a monad:
               J    -   range of length             [1,2,3]
                C   -   complement (vectorises)     [0,-1,-2]
              "     - zip with:
             ṙ      -   rotate left by              ["vCq7G",".fJ0.","..D.."]
                  Ṛ - reverse                       ["..D..",".fJ0.","vCq7G"]

5

JavaScript (ES7), 82 78 byte

f=(s,k=1-s.length**.5*2,p='')=>s&&f(s.slice(0,k),k+2,p+'.')+`
`+p+s.slice(k)+p

Uji kasus

Berkomentar

f = (                       // f = recursive function taking:
  s,                        //   s = input string
  k = 1 - s.length**.5 * 2, //   k = additive inverse of the length of the base
  p = ''                    //   p = padding string
) =>                        //
  s &&                      // if s is not empty:
    f(                      //   do a recursive call with:
      s.slice(0, k),        //     s without the last -k characters
      k + 2,                //     the updated base length (2 less characters)
      p + '.'               //     the updated padding string
    ) +                     //   end of recursive call()
    `\n` +                  //   append a line feed
    p +                     //   append the left padding string
    s.slice(k) +            //   append the last -k characters of s
    p                       //   append the right padding string

[minor] simbol '/ n' menjadi
pemisah

@ G0BLiN ini adalah sebaliknya: ini adalah memang satu baris literal dalam kode golfed, yang diganti dengan istirahat garis lolos dalam versi ungolfed untuk kejelasan. :)
Arnauld

Ha, lelucon ada pada saya, lalu ... :-)
G0BLiN


2

MATL , 21 byte

tnX^eRP&1ZvGyg(46y~(!

Cobalah online!

Penjelasan

Pertimbangkan input 'DfJ0vCq7G'sebagai contoh. Isi tumpukan ditampilkan dipisahkan oleh koma, dengan elemen teratas yang terakhir. Baris dalam array 2D menggunakan tanda titik koma sebagai pemisah.

t      % Implicit input: string. Duplicate
       % STACK: 'DfJ0vCq7G',
                'DfJ0vCq7G'
nX^    % Number of elements. Square root
       % STACK: 'DfJ0vCq7G',
                3
e      % Reshape with that many rows (in column major order)
       % STACK: ['D0q';
                 'fv7';
                 'JCG']
R      % Upper triangular part: set elements below diagonal to char(0)
       % (displayed as space)
       % STACK: ['D0q';
                 ' v7';
                 '  G']
P      % Flip vertically
       % STACK: ['  G';
                 ' v7';
                 'D0q']
&1Zv   % Reflect vertically
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G']
G      % Push input again
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G'],
                'DfJ0vCq7G'
yg     % Duplicate from below and convert to logical. This gives true for
       % for nonzero chars (the entries where input chars will be written)
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G'],
                'DfJ0vCq7G',
                [0 0 1;
                 0 1 1;
                 1 1 1;
                 0 1 1;
                 0 0 1]
(      % Assignment indexing: write values at those positions
       % STACK: ['  v';
                 ' fC';
                 'DJq';
                 ' 07';
                 '  G']
46     % Push 46, which is ASCII for '.'
       % STACK: ['  v';
                 ' fC';
                 'DJq';
                 ' 07';
                 '  G'],
                 46
y~     % Duplicate from below and apply logical negate. This gives true
       % for char(0) (the entries where '.' will be written)
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G'],
                46
                [1 1 0;
                 1 0 0;
                 0 0 0;
                 1 0 0;
                 1 1 0]
(      % Assignment indexing: write value at those positions
       % STACK: ['..G';
                 '.v7';
                 'D0q';
                 '.v7';
                 '..G'],
!      % Transpose. Implicit display
       % STACK: ['..D..';
                 '.fJ0.';
                 'vCq7G']

2

Bersih , 107 94 89 88 byte

import StdEnv
@s _[]=s
@s n r= @([['.':l]++['.']\\l<-s]++[take n r])(n+2)(drop n r)

@[]1

Cobalah online! Contoh penggunaan: @[]1 ['ABCDEF"$%& G8"F@'].


1

Haskell , 84 68 byte

[]%1
(s%n)[]=s
(s%n)r=(['.':l++"."|l<-s]++[take n r])%(n+2)$drop n r

Cobalah online!

Contoh penggunaan: []%1 $ "abcd"menghasilkan daftar garis [".a.","bcd"].


1

Perl, 56 52 byte

Termasuk +3untuk-p

#!/usr/bin/perl -p
$_=("."x y///c**.5)=~s%.%$'@{[$&x/$`$`./g]}$'
%rg

Berikan input pada STDIN (pada prinsipnya tanpa baris akhir, tetapi itu hanya penting untuk input kosong)


1
menurut aturan PCG -pbiaya hanya 1 byte
mik

@mik Hanya jika kodenya tidak mengandung '. Tetapi kode ini tidak, jadi perlu dimasukkan ke dalam file (atau melarikan diri pada commandline) yang membutuhkan 3 karakter tambahan dibandingkan dengan #!baris normal . Jadi dalam hal ini adalah +3(untuk kode normal Anda akan melihat saya memang hanya menghitung +untuk p)
Ton Hospel

1

Merah , 227 203 byte

f: func[s][l: to-integer(length? s)** 0.5
n: 0 foreach m parse s[collect[(r: []repeat i l[append r reduce['keep i * 2 - 1
charset[not{Я}]]])r]][v: copy""insert/dup v"."l - n: n + 1 print rejoin[v m v]]]

Cobalah online!

Tidak Disatukan:

f: func[s][
l: to-integer (length? s) ** 0.5
n: 0
foreach m parse s [ 
    collect [
        (r: []
        repeat i l [ append r reduce [
            'keep i * 2 - 1 charset [ not{Я} ]]])
    r ]] 
    [v: copy ""
    insert/dup v "." l - n: n + 1
    print rejoin [v m v]]
]

1

Retina , 88 72 71 byte

S1`
+m`^(.)+¶(?>(?<-1>.)+)..(?!¶)
$&¶
P^'.m`^.(?=(..)*)(?<-1>.)*
P'.`.+

Cobalah online!Sunting: Disimpan 12 13 byte berkat @MartinEnder. Penjelasan:

S1`

Pisahkan karakter pertama ke dalam barisnya sendiri untuk membuat bola bergulir.

+m`^(.)+¶(?>(?<-1>.)+)..(?!¶)
$&¶

Potong setiap baris dua karakter lebih lama dari yang sebelumnya.

P^'.m`^.(?=(..)*)(?<-1>.)*

Kiri-pad paruh pertama setiap baris, secara efektif memusatkan mereka.

P'.`.+

Pad kanan semua garis.


1

Arang , 21 19 byte

UB.F₂Lθ«P✂θXι²X⊕ι²↙

Cobalah online! Tautan adalah untuk mengucapkan versi kode. Sunting: Disimpan 2 byte dengan menemukan SquareRoot. Penjelasan:

UB.                 Set the background fill to `.`
      θ             (First) input
     L              Length
    ₂               Square root
   F   «            Loop over implicit range
            ι   ι   Current value
               ⊕    Incremented
             ²   ²  Literal 2
           X  X     Power
         ✂θ         Slice the (first) input string
        P           Print without moving the cursor
                  ↙ Move down left

: / Ini hampir berhasil tetapi tampaknya Arang agak buggy. Ini bekerja, saya pikir?
ASCII

@ Hanya ASCII ... sihir hitam apa ini?
Neil

Isi dasarnya periksa null byte (yaitu karakter yang digunakan untuk ruang di mana tidak ada yang ditarik), jadi Anda bisa menggambar poligon dengan null byte (well, jika itu bekerja dengan benar> _>) dan isi itu. Jelas ini tidak tepat dimaksudkan karena Anda benar-benar dapat melihat byte nol bahkan sebelum mengisi untuk beberapa alasan> _>
ASCII-only

ini harus bekerja dengan baik tarikan berikutnya
hanya ASCII



0

Ruby , 73 66 byte

->s{(1..z=s.size**0.5).map{|q|s[q*q-2*q+1...q*q].center 2*z-1,?.}}

Cobalah online!

-5 byte: Mengembalikan array string daripada mencetaknya

-2 byte: Deklarasikan z di tempat dan bukan sebelumnya

Tidak Disatukan:

->s{
  (1..z=s.size**0.5).map{|q|   # Map the range [1,sqrt(s.size)]
    s[q*q-2*q+1...q*q]         # To the relevant portion of s,
      .center 2*z-1, ?.        #   padded left and right with . characters
  }
}

Mendeklarasikan variabel r=q-1sehingga saya bisa ambils[r*r...q*q] menyimpan tepat nol byte.

Menggunakan .centerbukannya padding secara manual juga menghemat nol byte, tapi saya lebih suka.


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.