2

How to check if the string is reshaped? Example: "aab" returns 0 because "a" can't be reshaped to this string nor any other shorter string.

Another example is "aabbaab" returns 1 because "aabb" can be reshaped to this string.

A lot of examples can found this:

Returns 1

101
abba
abcab
abacedabarab
abcdefedabc
!@#~€!

Returns 0

aA
~
[][][][]][-
abcac
aecec

Is there a lambda function that does this task?

NOTE: if you are not familiar with APL then read this

Fmbalbuena
  • 95
  • 1
  • 12

1 Answers1

5

The task essentially boils down to checking if we can cycle a certain substring of a given string, so that we get the aforementioned string back. A straightforward solution follows:

{(⊂⍵)∊(≢⍵)⍴¨¯1↓,\⍵}

or, tacit:

(⊂∊≢⍴¨¯1↓,\)

Let's unpack the dfn:

{(⊂⍵)∊(≢⍵)⍴¨¯1↓,\⍵}
               ,\⍵       prefixes of the input
            ¯1↓          ignore the last one
      (≢⍵)⍴¨             reshape each of the prefixes so
                         that it has the same length as input

 (⊂⍵)∊                   check if input appears anywhere in the list.

Prefixes is the following operation:

      ,\ 'Hello!'
┌─┬──┬───┬────┬─────┬──────┐
│H│He│Hel│Hell│Hello│Hello!│
└─┴──┴───┴────┴─────┴──────┘
Kamila Szewczyk
  • 1,874
  • 1
  • 16
  • 33