Odwróć ciąg po kawałkach

34

Twoim zadaniem jest napisanie programu, który, biorąc pod uwagę liczbę i ciąg, dzieli ciąg na fragmenty tego rozmiaru i odwraca je.

Zasady

Twój program otrzyma dodatnią liczbę całkowitą n, a także ciąg so długości co najmniej jeden składający się tylko z drukowalnego ASCII (bez białych znaków). Łańcuch powinien być następnie podzielony na kawałki długości n, jeśli długość łańcucha nie jest podzielna przezn resztki na końcu, należy uznać za własny kawałek. Następnie odwróć kolejność kawałków i połącz je ponownie.

Przypadki testowe

n   s           Output

2   abcdefgh    ghefcdab
3   foobarbaz   bazbarfoo
3   abcdefgh    ghdefabc
2   a           a
1   abcdefgh    hgfedcba
2   aaaaaa      aaaaaa
2   baaaab      abaaba
50  abcdefgh    abcdefgh
6   abcdefghi   ghiabcdef

To jest , więc powinieneś dążyć do jak najmniejszej liczby bajtów.

Pavel
źródło
Związane .
AdmBorkBork

Odpowiedzi:

29

Galaretka , 2 bajty

sṚ

Pełny program, który drukuje wynik.

Wypróbuj online!

W jaki sposób?

sṚ - Main link: string, number                                   e.g. 'abcdefg', 3
s  - split string into chunks of length number (keeping any overflow) ["abc","def","g"]
 Ṛ - reverse the resulting list                                       ["g","def","abc"]
   - implicit print                                                   gdefabc
Jonathan Allan
źródło
28
Podoba mi się, jak dwa bajty wygenerowały 4 wiersze wyjaśnień.
Pavel
16

Python 3 , 35 bajtów

f=lambda s,n:s and f(s[n:],n)+s[:n]

Wypróbuj online!

Dennis
źródło
Jak anddziała tutaj słowo kluczowe? @Dennis
ShinMigami13 15.04.17
2
@ ShinMigami13 pusty ciąg znaków nie jest prawdą, więc to kończy rekurencję
Michael Klein
9

05AB1E , 5 4 3 bajty

-1 dzięki Dennis
-1 dzięki carusocomputing

ôRJ

Wypróbuj online!

     # Implicit: push input
 ô   # Split in pieces of length b
  RJ # Reverse and join
Riley
źródło
¹nie jest potrzebne.
Magic Octopus Urn
8

JavaScript (ES6), 37 bajtów

n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)

Pobiera dane wejściowe przez curry: najpierw liczba, a następnie ciąg znaków, jak f(2)("abcdefgh").

ETHprodukcje
źródło
7

Perl 6 ,  28  20 bajtów

{$^b.comb($^a).reverse.join}

Spróbuj

{[R~] $^b.comb($^a)}

Spróbuj

Rozszerzony:

{  # bare block lambda with placeholder parameters 「$a」 and 「$b」
  [R[~]] # reduce the following using the reverse meta operator `R`
         # combined with the string concatenation operator

    # `comb` with a number splits the invocant into chunks of that size
    $^b.comb($^a)
}
Brad Gilbert b2gills
źródło
7

Bash + coreutils, 22

fold -$1|tac|tr -d \\n

Wypróbuj online .

Cyfrowa trauma
źródło
1
Nauczyłem się w tym tygodniu 4 nowych komend linuxowych na folderze PPCG, dzięki!
Wossname
4

PHP, 53 bajtów

<?=join(array_reverse(str_split($argv[2],$argv[1])));
Jörg Hülsermann
źródło
4

Röda , 36 bajtów

f n{[[_]..[try head n-1]]|reverse|_}

Wypróbuj online!

Jest to funkcja, która wymaga jednego argumentu. Znaki ciągu muszą znajdować się w strumieniu.

trysłuży do odrzucania błędów w przypadku, gdy headfunkcja nie może odczytać n-1wartości.

Wyjaśnienie:

f n{[[_]..[try head n-1]]|reverse|_}
f n{                               } /* Function declaration */
                                     /* In a loop: */
      _                              /*   Pull one value */
           try head n-1              /*   Pull n-1 values (or less) */
     [ ]..[            ]             /*   Make an array */
    [                   ]            /*   Push it to the stream */
                         |reverse    /* Reverse all values in the stream */
                                 |_  /* Flat all arrays in the stream */
                                     /* Characters in the stream are printed */

Nie tak zaciemnione jak zwykle. Myślę, że to całkiem piękne. :)

fergusq
źródło
5
Udało ci się uczynić program mniej czytelnym niż roztwór galaretki.
Pavel
Dlaczego nie [[try head n]]działa zamiast [[_]..[try head n-1]]?
Kritixi Lithos
@KritixiLithos Ponieważ zapętla _wyrażenie. [[try head n]]przyjmie n wartości jeden raz , ale [[_]..[try head n-1]]przyjmie n wartości, o ile pozostaną wartości.
fergusq
4

CJam , 5 bajtów

q~/W%

Dane wejściowe to liczba i ciąg zamknięty w podwójnych cudzysłowach, oddzielone spacjami.

Wypróbuj online! Lub sprawdź wszystkie przypadki testowe .

Wyjaśnienie

q~   e# Read all input and evaluate: pushes a number and a string
/    e# Split string into chunks of that size. Last chunk may be
     e# smaller. Gives an array of strings
W%   e# Reverse the array. Implicitly display
Luis Mendo
źródło
4

Partia, 74 bajty

@if %2=="" (echo %~3)else set s=%~2&call %0 %1 "%%s:~%1%%" "%%s:~,%1%%%~3"

Raczej denerwująco kończy się to raczej rekurencyjnym niż rekurencyjnym.

Neil
źródło
4

V , 13 10 bajtów

òÀ|lDÏpòÍî

Wypróbuj online!

ò      ò    ' Recursively
 À|         ' Go to the "nth" column
   l        ' Move one character right (breaks loop when no more chunks)
    D       ' Delete from here to the end of the line
     Ï      ' Add a line above the current line (now contains one chunk)
      p     ' Paste the remainder of the line that was deleted
        Íî  ' Remove all newlines

W akcji:

abcdefghijkl

przemienia się w

efghijkl
abcd

która staje się

ijkl
efgh
abcd

zanim wszystkie nowe wiersze zostaną usunięte

nmjcman101
źródło
4

pieprzenie mózgu , 78 bajtów

,<<<+[[>]>+>[[>],<[<]>+>-]<-[->>[>]>>+<<<[<]<]>>]<<<<[[<]>[-[+.[-]]+>]<[<]<<<]

Pierwszy bajt danych wejściowych to wielkość porcji podana przez wartość bajtu. Resztę bajtów uważa się za ciąg.

Wypróbuj online!

Rozszerzony i skomentowany

Read the chunk size byte
This cell will become a counter cell
,

Move left a few cells an increment; 
this is to make the starting position 
line up with the relative positioning
needed to fit in with the loop
<<<+

While the current cell is nonzero:
[

 Move right to the first zero cell
 [>]

 Move right once and increment and then move right to the counter cell
 The increment is required because of "move to zero cell" loops
 >+>

 This loop will store one chunk of the input in consecutive memory cells
 [
  [>]   Move right until a zero cell is hit
  ,     Store 1 byte of input there
  <[<]  Move back left until a zero cell (other than the current one) is hit
  >+>-  Increment the temporary cell by 1 and decrement the counter
 ] (end loop once the counter hits zero)

 Decrement the temp cell (because we needed to have 1 there initially to make the cell location work)
 <-

 Move the temp cell to three cells after the end of the chunk
 This is the new counter cell for the next chunk
 [->>[>]>>+<<<[<]<]

 Move two cells right from where the temp cell was
 This is the first cell of the chunk; if it's 0
 then the input is finished and the loop should end
 >>
]

Due to the way the counter is kept track of the tape head
will always be four cells to the right of the last input cell
when the loops breaks
<<<<

Now the chunks are printed one by one
At the start of an iteration the tape head is at the end of a chunk
[
 Locate the start of the last chunk
 [<]>

 Print the chunk:
 [
  Print the byte held in the current cell if it isn't 1
  This is necessary because we left a stray 1 in a cell at
  the start which shouldn't be printed
  -[+.[-]]+

  Move to the next cell
  >
 ]

 Move to just left of the chunk
 <[<]

 Move three cells over to the end of the next chunk
 <<<
]
Business Cat
źródło
4

PowerShell, 56 49 bajtów

-7 bajtów dzięki mazzy

param($n,$s)$s-split"(.{$n})"-ne''|%{$r=$_+$r};$r

Wypróbuj online!

Andrei Odegov
źródło
1) 49 bytes 2) Please, post a full program, not a codesnippet. How to check? Extract your code in a separate file with the extension .ps1 and try calling this script instead of your code. If it works, then the test was successful.
mazzy
3

Mathematica, 46 bytes

""<>Reverse@Partition[Characters@#2,#,#,1,{}]&

Anonymous function. Takes a number and a string as input and returns a string as output. Not much to see here.

LegionMammal978
źródło
3

Javascript - 54 47 46 bytes

Remade:

(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()

Used as

f=(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()
alert(f("abcdefgh",2));

Thank you to @ETHproductions for some RegEx quickenning Thank you to @Shaggy for an extra byte in the eval!

Original:

(s,n)=>s.match(new RegExp('.{1,'+n+'}','g')).reverse()
Blue Okiris
źródło
1
Nice answer! I believe you can save a couple bytes by creating the regex with eval('/.{1,'+n+'}/g')
ETHproductions
@ETHproductions Ah yes. That's what I've been attempting to do. I wasn't familiar enough with regex to do it though!
Blue Okiris
I think you can save a byte with currying, s=>n=> ...
Pavel
Save a byte with eval("/.{1,${n}}/g"), using backticks instead of quotation marks.
Shaggy
3

Pyth, 5 bytes

s_c.*

Try it online.

Explanation

   .*  splat implicit input
  c    split into chunks length n
 _     reverse
s      join
Digital Trauma
źródło
3

Retina, 38 bytes

1 byte saved thanks to @LeakyNun

^

+`(.* (1)+¶)((?<-2>.)+)
$3$1
 1+¶

(Note the space on the second line, and the trailing space)

This program takes input as unary on the first line, and the string on the second.

Try it online!

Test Suite! (slightly modified)

Explanation

The first step is to prepend a space (will become important later on).

^
 

Now we reverse. This uses .NET's balancing groups. It is important to note that groups here act as stacks, so every match is essentially pushed onto the stack. Here we capture every digit in the unary number into group 2. Now each time a character in the string is found, a match is popped from group 2. This ensures the the number of characters does not exceed that of the unary number.

+`(.* (1)+¶)                       Capture the unary number in group 2
             ((?<-2>.)+)           Balancing group for substrings
$3$1                               Reverse

And finally remove the unary number and the newline.

 1+¶

Kritixi Lithos
źródło
I think it is acceptable to take the number in unary.
Leaky Nun
Anyhow, you can replace \d by . to save a byte.
Leaky Nun
The second ^ is also redundant.
Leaky Nun
@LeakyNun The program now takes input in unary, so I have no need for the \d anymore. And thanks for golfing away the caret :)
Kritixi Lithos
33 bytes by using lazy (non-greedy) match.
Leaky Nun
3

Java, 147 138 Bytes

String r(String s,int n){String r="";int l=s.length();for(int i=l/n*n;i>=0;i-=n)if(!(i>=l))r+=(i+n)>=l?s.substring(i):s.substring(i,i+n);return r;}

Saved 9 Bytes thanks to Kevin Cruijssen!

String r(String s,int n){String r="";int l=s.length(),i=l/n*n;for(;i>=0;i-=n)if(i<l)r+=i+n>=l?s.substring(i):s.substring(i,i+n);return r;}

In expanded form:

String r(String s,int n){
    String r="";
    int l=s.length(),i=l/n*n;
    for(;i>=0;i-=n)
        if(i<l)
            r+=i+n>=l?s.substring(i):s.substring(i,i+n);
    return r;
}

This is actually my first try to codegolf ever, so any feedback is welcome!

bruderjakob17
źródło
Welcome to PPCG!
Pavel
1
Hi, welcome to PPCG! This is already pretty good, but there are still a few things to golf some more: int l=s.length();for(int i=l/n*n; can be int l=s.length(),i=l/n*n;for(; so you only have int once. And if(!(i>=l)) can be if(l<i). And r+=(i+n)>=l? can be without the parenthesis: r+=i+n>=l?. Also, if you haven't seen it yet, I can recommend looking through Tips for Golfing in Java for some pretty cool golfing tips to use. :) Once again, welcome.
Kevin Cruijssen
3

Perl 5, 25 bytes

Uses the -lnM5.010 flags.

say reverse<>=~/.{1,$_}/g

Try it online!

Shoutout to Grinnz for telling me about =~ m/.{1,$n}/g

-M5.010 enables the use of the say function, which for our purposes is print with a shorter name.

-n puts the first line of input into $_, and -l chomps off the trailing newline.

We then get the second line of input using <>, and apply it to the regex .{1,$_}: any character, between 1 and $_ (the first input) times. Since this is greedy by default, it tries to always match $_ characters. The 1, is needed for the possible leftover chunk at the end.

The /g modifier gives us every match of that regex in the input string as a list, which is then reversed and printed. In Perl, passing a list to say joins it without any delimiter by default.

Pavel
źródło
3

Dyalog APL Extended, 16 15 bytes

{∊⌽⍵⊂⍨(≢⍵)⍴=⍳⍺}

Try it online!

dzaima
źródło
You don't need the f←
Pavel
Why, ,/
Adám
@Adám Oh hey that applies to my answer too, thanks
Pavel
Pavel: yep, obviously.. @Adám thanks!
dzaima
14: ∊∘⌽⊢⊂⍨≢⍤⊢⍴1↑⍨⊣
Ven
2

Python, 62 bytes

lambda n,s:''.join([s[i:i+n]for i in range(0,len(s),n)][::-1])

Try it online!

ovs
źródło
Python3 answer is shorter & also works for python 2.7: f=lambda n,s:s and f(n,s[n:])+s[:n]
F1Rumors
2

QBIC, 24 bytes

:;[1,_lA|,a|Z=_sA,b,a|+Z

This makes excellent use of the new substring-function I recently added to QBIC:

:;          Read in the cmd line params a (number) and A$ (text)
[1,_lA|,a|  Set up a FOR loop: FOR b = 1; b <= A$.length; b += a
Z=          Modify Z$; Z$ is autoprinted at the end of QBIC code
_sA,b,a|    SUBSTRING: _s is the function followed by the string 
               to take from, the starting pos and the # of chars
+Z          Take chunks from further into A$, put them before Z$
steenbergh
źródło
2

C, 69 bytes

i;f(s,n)char*s;{i=strlen(s);for(i-=i%n;printf("%.*s",n,s+i),i;i-=n);}

Result is printed out to the standard output.

2501
źródło
2

Scala, 57 55 bytes

(n:Int,s:String)=>(""/:s.grouped(n).toSeq.reverse)(_+_)

Thanks Jacob! Try it here.

Note: By using the symbol form of foldLeft ("/:"), I was able to take off a couple more bytes.

jkeatley
źródło
make it anonymous function, and use mkString instead of reduceLeft, and shave off 7 bytes: (n:Int,s:String)=>s.grouped(n).toSeq.reverse.mkString("")
Jacob
2

Ohm, 5 bytes

σ]QWJ

Try it online!

Explanation

σ]QWJ
σ         # Split input1 into input2 pieces
 ]        # Flatten array
  Q       # Reverses stack
   W      # Wraps stack to array
    J     # Joins stack
          # Implicit print
Datboi
źródło
2

R, 69 60 bytes

function(s,n)cat(substring(s,(x=nchar(s):0*n)+1,x+n),sep="")

Try it online!

Thanks to Kirill L. for the suggestion to remove seq.

Giuseppe
źródło
Looks like this works too for 66.
Kirill L.
@KirillL. we can go to 60 bytes if we reverse the order of arguments to : and some manipulation lets us get rid of the trailing -1.
Giuseppe
Smart, very nice!
Kirill L.