离散贝克地图


15

介绍

贝克的地图是一个重要的动力系统表现出混沌行为。它是从单位平方到其直观定义的函数,如下所示。

  • 将正方形垂直切成两半,形成两个大小为的矩形0.5×1
  • 将右半部分堆叠在左上方,形成一个矩形大小 0.5×2
  • 将矩形压缩回1×1正方形。

在此挑战中,您将实现此转换的离散版本。

输入输出

您的输入是2D数组,可打印的ASCII字符和2m×2n某些字符的空白空间m, n > 0。您的输出是使用数组按以下方式获得的类似6×4数组

ABCDEF
GHIJKL
MNOPQR
STUVWX

举个例子。首先,将数组的右半部分堆叠在左半部分的顶部:

DEF
JKL
PQR
VWX
ABC
GHI
MNO
STU

然后,将这些列拆分为成对的字符,并分别将每对字符顺时针旋转90度,将高矩形“压缩”回原始形状:

JDKELF
VPWQXR
GAHBIC
SMTNUO

这是上述阵列的正确输出。

规则

输入和输出格式灵活。您可以使用换行符分隔的字符串,字符串列表或2D字符数组。但是,输入和输出必须具有完全相同的格式:您必须能够对任何有效输入进行任意次数的提交迭代。

您可以编写完整的程序或函数。最低字节数获胜,并且不允许出现标准漏洞。

测试用例

Input:
12
34

Output:
42
31

Input:
Hell
!  o
d  -
lroW

Output:
 lol
o W-
!H e
ldr 

Input:
ABCDEF
GHIJKL
MNOPQR
STUVWX

Output:
JDKELF
VPWQXR
GAHBIC
SMTNUO

Input:
*___  ___  o
o|__) |__) *
*|    |    o
o __   __  *
*|    | _  o
o|__  |__| *

Output:
|_____)   *o
 |_ _     *o
||_ __|   *o
o*|_____)   
o* |_ _     
o*||_ _     

Answers:


11

Pyth,25 19 18字节

msC_dcs_Cmck/lk2Q2

在线演示。它使用2D字符数组。

字符串数组长一个字符(19个字节)。在线演示

说明:

         m      Q    map each string k in input:
            /lk2        calculate half the line-length: len(k)/2
          ck/lk2        chop k into pieces of length len(k)/2
                        results in two pieces
        C            zip the resulting list
                     results in a tuple ([first half of strings], [second half of strings])
       _             invert the order ([second half of strings], [first half of strings])
      s              sum (combine the two lists to a big one
     c           2   chop them into tuples
m                          for each tuple of strings: 
 sC_d                        invert, zip, and sum

首先,最后一部分有些令人困惑。假设我们有元组['DEF', 'JKL'](我使用OP中的示例)。

    d  (('D', 'E', 'F'), ('J', 'K', 'L'))   just the pair of strings
   _d  (('J', 'K', 'L'), ('D', 'E', 'F'))   invert the order
  C_d  [('J', 'D'), ('K', 'E'), ('L', 'F')] zipped
 sC_d  ('J', 'D', 'K', 'E', 'L', 'F')       sum (combine tuples)

4
我不骗你,我只是写independantly的确切相同的解决方案,你没有。我没有掩盖所有答案以得到一个想法,但没有详细说明。
orlp

@orlp是的,Pyth中最直接的方法通常是最短的方法。因此,多个人可以轻松找到它。
2015年

@orlp顺便说一句,刚刚向Pyth仓库发出了拉取请求(尚未接受)。将来,您可以c2k代替ck/lk2c2k将字符串分成两个相等的部分。
2015年

9

朱莉娅(136)

一个非常简单的实现。这不是一个特别有竞争力的作品,但它很有趣!

A->(s=size(A);w=s[2];u=2;C=vcat(A[:,u+1:w],A[:,1:u]);D=cell(s);j=1;for i=1:2:size(C,1) D[j,:]=vec(flipdim(C[i:i+1,:],1));j+=1end;D)

这将创建一个lambda函数,该函数接受二维数组作为输入并返回转换后的二维数组。

取消+说明:

function f(A)

    # Determine bounds
    s = size(A)          # Store the array dimensions
    w = s[2]             # Get the number of columns
    u = w ÷ 2            # Integer division, equivalent to div(w, 2)

    # Stack the right half of A atop the left
    C = vcat(A[:, u+1:w], A[:, 1:u])

    # Initialize the output array with the appropriate dimensions
    D = cell(s)

    # Initialize a row counter for D
    j = 1

    # Loop through all pairs of rows in C
    for i = 1:2:size(C, 1)

        # Flip the rows so that each column is a flipped pair
        # Collapse columns into a vector and store in D
        D[j, :] = vec(flipdim(C[i:i+1, :], 1))

        j += 1
    end

    return D
end

要调用它,请为函数命名,例如f=A->(...)

输出示例:

julia> A = ["A" "B" "C" "D" "E" "F";
            "G" "H" "I" "J" "K" "L";
            "M" "N" "O" "P" "Q" "R";
            "S" "T" "U" "V" "W" "X"]
julia> f(A)

4x6 Array{Any,2}:
 "J"  "D"  "K"  "E"  "L"  "F"
 "V"  "P"  "W"  "Q"  "X"  "R"
 "G"  "A"  "H"  "B"  "I"  "C"
 "S"  "M"  "T"  "N"  "U"  "O"

julia> B = ["H" "e" "l" "l";
            "!" " " " " "o";
            "d" " " " " "-";
            "l" "r" "o" "W"]
julia> f(B)

4x4 Array{Any,2}:
 " "  "l"  "o"  "l"
 "o"  " "  "W"  "-"
 "!"  "H"  " "  "e"
 "l"  "d"  "r"  " "

并证明可以任意链接:

julia> f(f(B))

4x4 Array{Any,2}:
 "W"  "o"  "-"  "l"
 "r"  " "  " "  "e"
 "o"  " "  " "  "l"
 "l"  "!"  "d"  "H"

我们一如既往地欢迎您提出建议,我们乐意提供进一步的解释。


8

CJam,25个 24字节

qN/_0=,2/f/z~\+2/Wf%:zN*

直接规范的实施。说明:

qN/                       "Split input by rows";
   _0=,2/                 "Get half of length of each row";
         f/               "Divide each row into two parts";
           z              "Convert array of row parts to array of half columns parts";
            ~\+           "Put the second half of columns before the first half and join";
               2/         "Group adjacent rows";
                 Wf%      "Flip the row pairs to help in CW rotation";
                    :z    "Rotate pairwise column elements CW";
                      N*  "Join by new line";

在这里在线尝试


7

的JavaScript(ES6),104 141

编辑查看规范,我发现行数必须是偶数(之前我错过了)。因此,只需一步就可以为输出中的每个字符找到正确的源位置,这并不是太复杂。

F=a=>a.map((r,i)=>
  [...r].map((c,k)=>
     a[l=i+i]?a[(j=l+1)-k%2][(k+r.length)>>1]:a[l-j-k%2][k>>1]
  ).join('')
)

在Firefox / FireBug控制台中测试

;[["ABCDEF","GHIJKL","MNOPQR","STUVWX"]
 ,["12","34"], ["Hell","!  o","d  -","lroW"]
 ,["*___  ___  o","o|__) |__) *","*|    |    o","o __   __  *","*|    | _  o","o|__  |__| *"]
].forEach(v=>console.log(v.join('\n')+'\n\n'+F(v).join('\n')))

输出量

ABCDEF
GHIJKL
MNOPQR
STUVWX

JDKELF
VPWQXR
GAHBIC
SMTNUO

12
34

42
31

Hell
!  o
d  -
lroW

 lol
o W-
!H e
ldr 

*___  ___  o
o|__) |__) *
*|    |    o
o __   __  *
*|    | _  o
o|__  |__| *

|_____)   *o
 |_ _     *o
||_ __|   *o
o*|_____)   
o* |_ _     
o*||_ _     

5

J,45岁 39字节

   $$[:,@;@|.@|:([:,:~2,2%~1{$)<@|:@|.;.3]

J具有细分功能(cut ;.),该功能很有帮助。

   ]input=.4 6$97}.a.
abcdef
ghijkl
mnopqr
stuvwx

   ($$[:,@;@|.@|:([:,:~2,2%~1{$)<@|:@|.;.3]) input
jdkelf
vpwqxr
gahbic
smtnuo

我的回答另一种方式来解决J.挑战
FUZxxl

4

Haskell,128 127字节

import Control.Monad
f=g.ap((++).map snd)(map fst).map(splitAt=<<(`div`2).length)
g(a:b:c)=(h=<<zip b a):g c
g x=x
h(a,b)=[a,b]

用法:f ["12", "34"]->["42","31"]

怎么运行的:

                                 input list:
                                   ["abcdef", "ghijkl", "mnopqr", "stuvwx"]
==========================================================================

map(splitAt=<<(`div`2).length)   split every line into pairs of halves:
                                   -> [("abc","def"),("ghi","jkl"),("mno","pqr"),("stu","vwx")]
ap((++).map snd)(map fst)        take all 2nd elements of the pairs and
                                 put it in front of the 1st elements:
                                   -> ["def","jkl","pqr","vwx","abc","ghi","mno","stu"]
(    zip b a) : g c              via g: take 2 elements from the list and
                                 zip it into pairs (reverse order), 
                                 recur until the end of the list:
                                   -> [[('j','d'),('k','e'),('l','f')],[('v','p'),('w','q'),('x','r')],[('g','a'),('h','b'),('i','c')],[('s','m'),('t','n'),('u','o')]]
h=<<                             convert all pairs into a two element list
                                 and concatenate:
                                   -> ["jdkelf","vpwqxr","gahbic","smtnuo"]  

编辑:@Zgarb找到了要保存的字节。


真好!您可以g x=x为空列表案例节省1个字节。
Zgarb 2015年

3

GNU sed -r,179个字节

得分包括-rsed的+1 。

我花了一些时间弄清楚如何在中执行此操作sed,但是我想我现在有了:

# Insert : markers at start and end of each row
s/  /:  :/g
s/(^|$)/:/g
# Loop to find middle of each row
:a
# Move row start and end markers in, one char at a time
s/:([^  :])([^  :]*)([^ :]):/\1:\2:\3/g
ta
# Loop to move left half of each row to end of pattern buffer
:b
s/([^   :]+)::(.*)/\2   \1/
tb
# remove end marker
s/$/:/
# double loop to merge odd and even rows
:c
# move 1st char of rows 2 and 1 to end of pattern buffer
s/^([^  :])([^  ]*) ([^ ])(.*)/\2   \4\3\1/
tc
# end of row; remove leading tab and add trailing tab 
s/^ +(.*)/\1    /
tc
# remove markers and trailing tab
s/(:|   $)//g

注意上面的所有空格都应该是单个tab字符。注释不包括在高尔夫球成绩中。

还要注意,这大量使用了:标记字符。如果输入流包含:,则将发生未定义的行为。这可以通过替换所有来缓解:一些非印刷字符(例如BEL)字符负担,而不会给高尔夫球带来任何损失。

输入和输出是制表符分隔的字符串列表:

$ echo 'Hell
!  o
d  -
lroW' | paste -s - | sed -rf baker.sed | tr '\t' '\n'
 lol
o W-
!H e
ldr 
$ 

3

J,33 32个字符

一元动词。

0 2,.@|:_2|.\"1-:@#@{.(}.,.{.)|:

说明

让我们从定义Y为样本输入开始。

   ] Y =. a. {~ 65 + i. 4 6          NB. sample input
ABCDEF
GHIJKL
MNOPQR
STUVWX

第一部分(-:@#@{. (}. ,. {.) |:)分为Y两半,然后追加,然后结束:

   # {. Y                            NB. number of columns in Y
6
   -: # {. Y                         NB. half of that
3
   |: Y                              NB. Y transposed
AGMS
BHNT
CIOU
DJPV
EKQW
FLRX
   3 {. |: Y                         NB. take three rows
AGMS
BHNT
CIOU
   3 }. |: Y                         NB. drop three rows
DJPV
EKQW
FLRX
   3 (}. ,. {.) |: Y                 NB. stitch take to drop
DJPVAGMS
EKQWBHNT
FLRXCIOU

在第二部分(_2 |.\"1)中,我们将其分成两对并反转:

   R =. (-:@#@{. (}. ,. {.) |:) Y    NB. previous result
   _2 <\"1 R                         NB. pairs put into boxes
┌──┬──┬──┬──┐
│DJ│PV│AG│MS│
├──┼──┼──┼──┤
│EK│QW│BH│NT│
├──┼──┼──┼──┤
│FL│RX│CI│OU│
└──┴──┴──┴──┘
   _2 <@|.\"1 R                      NB. reversed pairs
┌──┬──┬──┬──┐
│JD│VP│GA│SM│
├──┼──┼──┼──┤
│KE│WQ│HB│TN│
├──┼──┼──┼──┤
│LF│XR│IC│UO│
└──┴──┴──┴──┘

最后(0 2 ,.@|:),我们根据需要转置矩阵并丢弃尾随轴:

   ] RR =. _2 |.\"1 R                NB. previous result
JD
VP
GA
SM

KE
WQ
HB
TN

LF
XR
IC
UO
   0 2 |: RR                         NB. transpose axes
JD
KE
LF

VP
WQ
XR

GA
HB
IC

SM
TN
UO
   ($ RR) ; ($ 0 2 |: RR)            NB. comparison of shapes
┌─────┬─────┐
│3 4 2│4 3 2│
└─────┴─────┘
   ,. 0 2 |: RR                      NB. discard trailing axis
JDKELF
VPWQXR
GAHBIC
SMTNUO

插入了空格的整个表达式:

0 2 ,.@|: _2 |.\"1 -:@#@{. (}. ,. {.) |:

作为显式动词:

3 : ',. 0 2 |: _2 |.\"1 (-: # {. y) (}. ,. {.) |: y'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.