Побудуйте прямокутний масив з кута


30

Я колись мав гарний прямокутний масив. Це було дуже симетрично, але, на жаль, воно розпалося і тепер у мене є лише лівий верхній кут. Вашим завданням буде відновити початковий масив.

Ваша програма отримає двовимірний масив цілих чисел. Для зручності розбору, ви можете припустити, що вони всі від 1 до 9. Ваше завдання полягає в тому, щоб повернути стовпці масиву, його рядки і обидва, з'єднати отримані кути і повернути отриманий масив.

Можна припустити, що розміри масиву будуть принаймні 1x1.

Тестові приклади:

Input:
1 2 3
4 5 6

Output:
1 2 3 3 2 1
4 5 6 6 5 4
4 5 6 6 5 4
1 2 3 3 2 1

Input:
1

Output:
1 1
1 1

Input:
9
9
9

Output:
9 9
9 9
9 9
9 9
9 9
9 9

Це , найменше виграш байтів!


1
Б'юсь об заклад, деревне вугілля може зробити це у віці до 10 років
FantaC

1
@tbfninja chat.stackexchange.com/transcript/message/43184083#43184083, але може бути коротшим із іншим форматом введення.
Павло

@MagicOctopusUrn так
Павло

2
@tfbninja WS⟦ι⟧‖M→↓можливо? 5 байт для зчитування введення та 4 для відображення.
Ніл

4
Я на 99% впевнений, що є язик, який робить це з (або якимсь подібним персонажем), просто не можу пригадати, з якого: c
Rod

Відповіді:


1

Протон , 29 байт

a=>[b+b[by-1]for b:a+a[by-1]]

Спробуйте в Інтернеті!

Однак є кілька інших цікавих підходів:

Протон , 29 байт

a=>map(g,(g=x=>x+x[by-1])(a))

Спробуйте в Інтернеті!

Ви можете визначити дзеркальну підфункцію gв рядку, тому що Протон. Це не коротше.

Протон , 36 байт

(a=>[x[0]for x:zip(*(a+a[by-1]))])*2

Спробуйте в Інтернеті!

Це має бути (a=>zip(*(a+a[by-1])))*224 байти, але функція zip повністю порушена. В основному, ви дзеркально відображаєте його та блискавки, а потім робите це двічі (ви можете помножити функцію на додатне ціле число, щоб застосувати функцію кілька разів).




5

Python 3, 38 bytes

lambda a:[b+b[::-1]for b in a+a[::-1]]

Try it online!

Takes a list of lists and returns a list of lists.

Explanation:

lambda a:                              # anonymous lambda function
                   for b in a+a[::-1]  # for each row in the array and the upside-down array
          b+b[::-1]                    # the row with its reverse appended
         [                           ] # return in a list


5

Retina, 13 bytes

\%`$
$^$`
Vs`

Try it online!

Explanation

\%`$
$^$`

On each line (%), match the end of the line ($), and insert the reverse ($^) of the entire line ($`) and print the result with a trailing linefeed (\). This does the reflection along the vertical axis and prints the first half of the output.

Vs`

This just reverses the entire string, which is equivalent to a 180° degree rotation, or in our case (due to the horizontal symmetry) a reflection along the horizontal axis. This way this works is that V's (reverse) default regex is (?m:^.*$), which normally matches each line of the string. However, we activate the singleline option s, which makes . match linefeeds as well and therefore this default regex actually matches the entire string.

The result of this is printed automatically at the end of the program, giving us the second half of the output.


This doesn't look like any regex flavor I know of :P
Pavel

@Pavel Because Retina isn't just regex. :)
Erik the Outgolfer

@Pavel the only part of that code that is an actual regex is the $ on the first line. ;) I'll add an explanation later.
Martin Ender

5

05AB1E, 2 bytes

∞∊

Try it online!


   # Input:Array of String | ['12','34']
---#-----------------------+------------------------------------------
∞  # Mirror horizontally.  | [12,34]       -> [1221,3443]
 ∊ # Mirror vertically.    | [1221,3443]   -> [1221\n3443\n3443\n1221]

Credit for Mr. Xcoder pointing out that arrays of string may count as 2D arrays and Pavel for confirming it.



For ease of parsing, you may assume they are all between 1 and 9 – So I think this is valid. Awaiting Pavel's confirmation, I guess
Mr. Xcoder

@Mr.Xcoder that was what I had initially, then the TIO 2D arrays as input was weird... so had to come up with that header stuff.
Magic Octopus Urn

A string is an array of characters, so a list of strings is still a 2d array. @Mr.Xcoder's solution is valid.
Pavel

Coolio, works for me.
Magic Octopus Urn


3

MATL, 5 bytes

,tPv!

Try it online!

Explanation:

(implicit input)
,               # do twice:
 t              # dup top of stack
 P              # flip vertically
 v              # vertically concatenate
 !              # transpose
(implicit output)





3

awk, 88 bytes

{s="";for(i=NF;i>0;i--)s=" "$i s" "$i;a[FNR]=s;print s}END{for(i=NR;i>0;i--)print a[i]}

3
Welcome to PPCG! Nice first answer :)
HyperNeutrino

2

Triangularity, 31 bytes

...)...
..IEM..
.DRs+}.
DRs+...

Try it online!

Explanation

Removing the characters that make up for the padding, here is what the program does:

)IEMDRs+}DRs+ – Full program. Takes a matrix as a 2D list from STDIN.
)             – Push a 0 onto the stack.
 I            – Take the input at that index.
  E           – Evaluate it.
   M    }     – For each row...
    DR        – Duplicate and replace the second copy by its reverse.
      s+      – Swap and append.
         DR   – Duplicate the result and replace the second copy by its reverse.
           s+ – Swap and append.








2

Ruby, 35 bytes

->a{r=->b{b+b.reverse}
r[a].map &r}

Try it online!

A lambda accepting a 2D array and returning a 2D array. It's straightforward, but here's the ungolfed version anyway:

->a{
  r=->b{ b+b.reverse } # r is a lambda that returns the argument and its reverse
  r[a].map &r          # Add the array's reverse, then add each row's reverse
}

2

Java 8, 140 131 bytes

m->{String r="";for(int a=m.length,b=m[0].length,i=a+a,j;i-->0;r+="\n")for(j=b+b;j-->0;)r+=m[i<a?i:a+a+~i][j<b?j:b+b+~j];return r;}

Explanation:

Try it online.

m->{                      // Method with integer-matrix parameter and String return-type
  String r="";            //  Result-String, starting empty
  for(int a=m.length,     //  Amount of rows of the input-matrix
          b=m[0].length,  //  Amount of columns of the input-matrix
          i=a+a,j;        //  Index integers
      i-->0;              //  Loop over double the rows
      r+="\n")            //    After every iteration: append a new-line to the result
     for(j=b+b;j-->0;)    //   Inner loop over double the columns
       r+=                //    Append the result with:
          m[i<a?          //     If `i` is smaller than the amount of rows
             i            //      Use `i` as index in the input-matrix
            :             //     Else:
             a+a+~i]      //      Use `a+a+i-1` as index instead
           [j<b?          //     If `j` is smaller than the amount of columns
             j            //      Use `j` as index in the input-matrix
            :             //     Else:
             b+b+~j];     //      Use `b+b+j-1` as index instead
  return r;}              //  Return the result-String

2

J, 11 bytes

Anonymous tacit prefix function.

|:@(,|.)^:2

Try it online!

|: transpose

@(…) the result of:

, the argument followed by

|. its reverse

^:2 and all this done twice


2

SNOBOL4 (CSNOBOL4), 119 113 bytes

	T =TABLE()
I	X =X + 1
	I =INPUT	:F(D)
	OUTPUT =T<X> =I REVERSE(I)	:(I)
D	X =X - 1
	OUTPUT =GT(X) T<X>	:S(D)
END	

Try it online!

Takes input as strings on STDIN, without spaces. This only works because the digits are 1-9 and would fail otherwise.


I can see why people don't use this language anymore. This is so weird.
Pavel

1
@Pavel SNOBOL is truly a terrible language to work with. this is a more modern C implementation of it which has additional builtin functions like REVERSE; the original only supported integer arithmetic as well, as far as I can tell.
Giuseppe

2

C (gcc), 114 111 bytes

j,i;f(A,w,h)int*A;{for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)printf("%d,",A[(i<h?i:h+h+~i)*w+(j<w?j:w+w+~j)]);}

Try it online!

C (gcc), 109 bytes (abusing ease of parsing)

  • Thanks to Kevin Cruijssen for suggesting to only allow one-digit input integers; saved two bytes.
j,i;f(A,w,h)int*A;{for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)putchar(A[(i<h?i:h+h+~i)*w+(j<w?j:w+w+~j)]+48);}

Try it online!


You can save 3 bytes by inverting the loops. for(i=h+h;i-->0;puts(""))for(j=w+w;j-->0;)
Kevin Cruijssen

Does not fulfill spec; prints the array, rather than returning it.

"For ease of parsing, you may assume they are all between 1 and 9.", so you can remove the comma in the printf("%d" for an additional -1 byte.
Kevin Cruijssen

@Rogem I would say printing the array falls under accepted i/o.
Jonathan Frech

1
@KevinCruijssen Thanks a lot; using the ease of parsing I managed to shave off another byte.
Jonathan Frech

2

Charcoal, 5 bytes

θ‖C→↓

Try it online!

Thanks to ASCII-only for a better input format.


I wonder if this input format is valid, since I'm afraid Charcoal can't handle input otherwise. If it isn't, I'll happily delete this answer.
Erik the Outgolfer

This is valid I/o.
Pavel

@Pavel I just wondered because you had said that "Your program will receive a 2 dimensional array of integers", while a string is 1-dimensional (and no, the outer [] don't exactly make it 2D).
Erik the Outgolfer

@ASCII-only Charcoal really needs a better I/O method...
Neil

@Neil He didn't get pinged here, but I pinged him over TNB. :)
Erik the Outgolfer


1

Julia 0.6, 55 49 bytes

~i=i:-1:1
!x=[x x[:,~end];x[~end,:] x[~end,~end]]

Try it online!

~(i) is a function to create slice from i down to 1.
So ~end gives the slice end:-1:1

!(x) is the function to do the rebuilding of the array.


1

V, 12 bytes

yGæGPÎy$æ_|P

Try it online!

Explanation:

yG              " Yank every line
  æG            " Reverse the order of the lines
    P           " Paste what we yanked
     Î          " On every line:
      y$        "   Yank the whole line
        æ_      "   Reverse the whole line
          |     "   Move to the beginning of the line
           P    "   Paste what we yanked
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.