Division between two strings

Inverse function of this challenge

To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).

Now, you are given the multiplied string and the result of multiplication, and your task is to output the multiplied integer.

You can assume such integer exist. If multiple exist, output any of them.

Test cases:

abc, cba => -1
abc, aabbcc => 2
abc, ccbbaa => -2
aaa, aaaaaa => 2 or -2
(empty), (empty) => any integer
aaa, aa => undefined behavior
abaa, aaaabbaa => -2
abaa, aabbaaaa => 2
hello, (empty) => 0
a, aaaaaaaaaaa => 11 or -11


This is , lowest byte count wins!

• Suggest adding a test case that can result in output 0. Jan 6 at 20:06
• Suggested test case: a, aaaa => 4 (output greater than 2) Jan 7 at 1:18

JavaScript (ES6), 61 bytes

Expects (original_string)(other_string).

a=>b=>b.match([...a].join({${q=b.length/a.length|0}}))?q:-q  Try it online! • +1 on strong use of allowance of UB – l4m2 Jan 7 at 3:02 • You can remove the () from #join, giving you something as so: .join{${q=b.length/a.length|0}} Jan 7 at 4:10
• Accepted as the only submission <s>shorter than</s> at least equal to Q132002
– l4m2
Jan 8 at 10:23
• @LeoDog896 Just to clarify why this would not work here: when you use FA${123}B, what is actually passed to F is ['A','B']. If coerced to a string, this is turned into 'A,B' (or '{,}' in that specific case). Jan 8 at 14:24 R, 100 98 bytes \(x,y,r=rle(x),s=rle(y))if(sum(t<-s$l),if(any(r$v!=s$v)|sd(c(a<-t/r$l,a)),-rev(t)/r$l,a)[1],0)


Attempt This Online!

Takes input as vectors of characters.

Japt, 16 15 bytes

Takes input in reverse order.

ÊzVÊ
*JpNÎÀVmpU


Try it

ÊzVÊ\n*JpNÎÀVmpU     :Implicit input of strings U=result & V=original
Ê                    :Length of U
z                   :(Floor) Divided by
VÊ                 :Length of V
\n               :Reassign to U
*              :Multiply U by
J             :-1
p            :Raised to the power of
N           :Array of all inputs
Î          :First element (original U)
À         :Is not equal to
Vm       :Map V
pU     :Repeat U times


J, 17 bytes

%&#*_1+2*[-:%&##]


Try it online!

• %&# Scaling factor -- longer length divided by shorter length
• #] Use that to duplicate the shorter string elementwise
• [-: Does that match the longer string? (will be 0 or 1)
• _1+2* Double and subtract 1. This will be -1 if the string was reversed and 1 otherwise.
• %&#* Multiply that by the scaling factor from step 1. Sadly repeating the 3 characters %&# is shorter than any other approach which re-uses the result, at least that I could find.

05AB1E, 16 12 bytes

gIg÷DI×S¹Êi(


Inputs in reversed order as lists of characters.
Will output the positive result for palindromes, where two results are possible.

Explanation:

g             # Push the length of the first (implicit) input-list
Ig           # Push the length of the second input-list
÷          # Integer-divide this longer first by the shorter second length
D         # Duplicate this integer
I×S      # Repeat each character in the second input-list that many times, and then
# convert it to a flattened list of characters
¹Êi   # If it's NOT equal to the first input-list:
(  #  Negate it
# (after which it is output implicitly as result)


Python, 60 bytes

-17 bytes thanks to l4m2 and -14 bytes thanks to friddo

lambda a,b:a and(a==b[::(d:=len(b)//len(a))or 1]or-1)*d or 0


Attempt This Online!

• – l4m2
Jan 9 at 11:51
• 64 bytes using a reverse approach in comparison Jan 10 at 19:57
• actually, 60 bytes with a small refactor Jan 10 at 20:21
• @friddo That's a really clever approach (using the string step slicing and the *d as a toggle for the edge cases). Thank you for sharing this. Jan 11 at 9:04

C (GCC), 141137 125 bytes

f(x,y,d,k,r,i,z)char*x,*y;{for(k=d=!!*y;r=1;(k=-k)>0&&++d){for(i=z=strlen(y);i--;)r&=y[k>0?i:z+~i]==x[i/d];if(r)return d*k;}}


Attempt This Online!

Elm, 108 107 bytes

-1 byte thanks to Wheat Wizard

f a b=if a>[]then let r=l b//l a in if List.concatMap(List.repeat r)a==b then r else-r else 0
l=List.length


Takes two lists of chars, the shorter one first. You can try it here. Here's a full test program:

import Html exposing (text)

f : List Char -> List Char -> Int
f a b=if a>[]then let r=l b//l a in if List.concatMap(List.repeat r)a==b then r else-r else 0
l=List.length

main =
f ['a','b','c'] ['c','c','b','b','a','a']
|> String.fromInt
|> text


Explanation

• If the shorter list a is not empty:
• Let r be the integer quotient of the length of b and the length of a
• Multiply a by r (approach copied from my Elm answer to the string-multiplication question)
• If the result equals b, return r
• If not, assume it's because a was reversed and return -r
• The only valid case when a is empty is both a and b empty; in this case, any number can be returned; we choose 0

Vyxal, 12 bytes

ȧ¹•nṠ¬ßṘ⁰=)N


Try it Online!

Outputs the smallest integer needed, with preference given to positive integers if there are 2 possible answers.

Explained

ȧ¹•nṠ¬ßṘ⁰=)N
)N # Find the first integer n (pos or neg) where:
¹•          #   the divisor with characters repeated
ȧ            #   abs(n) times
ßṘ     #   reversed if:
nṠ¬       #     n is negative
⁰=   #   equals the dividend


l=length
_#""=0
p#m=let q=l pdivl m in if p==concatMap(replicate q)m then q else -q


Try it online!

• There are a couple of ways you can bring this down. Here's a 66 byte version just based off of tips from our Haskell tips question. In general, concatMap, replicate, if and let are all things you can avoid, since they are really long. Jan 8 at 13:35

Charcoal, 24 bytes

Ｉ∧Ｌη×÷ＬηＬθ∨⁼⭆θ×ι÷ＬηＬθη±¹


Try it online! Link is to verbose version of code. Explanation:

   η                        Second input
Ｌ                         Take the length
∧                          Logical And
η                    Second input
Ｌ                     Take the length
÷                      Integer divided by
θ                  First input
Ｌ                   Take the length
×                       Multiplied by
θ              First input
⭆               Map over characters and join
ι            Current character
×             Repeated by
η         Second input
Ｌ          Take the length
÷           Integer divided by
θ       First input
Ｌ        Take the length
⁼                Is equal to
η      Second input
∨                 Logical Or
¹    Literal integer 1
±     Negated
Ｉ                           Cast to string
Implicitly print


Thunno, $$\ 30 \log_{256}(96) \approx \$$ 24.69 bytes

LDns1+:gD0<?z1r(z1(sZAZkz0=Pkw


Port of Kevin Cruijssen's 05AB1E answer. Append 0~ to the end if outputting [] for 0 isn't allowed.

Explanation

L         # Push the length of the first (implicit) input-string
Dn       # Duplicate and negate the top one
s1+    # Swap and add one to the top one
# (The range works like Python's in that range(a, b) will give [a..b))
:   # range of the two items on the stack
g  # Filter for items where the following is truthy:
D         #   Duplicate the number
0<?      #   If it's less than 0:
z1r   #     Push a reversed copy of the second (implicit) input
(  #   Else:
z1        #     Push the second (implicit) input
(       #   Endif
sZA    #   Get the absolute value of the integer
Zk  #   And uninterleave the string with a length of this integer
z0=       #   Check if each part is equal to the first input
P      #   Are all of these true?
k     # End filter
w    # Keep truthy items only
# (It was somehow including 0 in the output for all test cases, so I had to discard it)


Screenshots

• Does it output [] if result is 0?
– l4m2
Jan 8 at 8:38
• @l4m2 yes it does. Is that ok? Jan 8 at 9:18
• If your language's [] mean 0, I'd say
– l4m2
Jan 8 at 9:27
• @l4m2 I have edited my answer with an alternative solution which outputs 0 Jan 8 at 9:55

Python 3, 53 bytes

lambda x,y:len(y)and[d:=len(y)//len(x),-d][y[::d]!=x]


Try it online!

R, 62 bytes

\(a,b,?=length)if(k<-?b,(l=k/?a)*(-1)^any(a!=b[!1:l-1]),0)


Attempt This Online!

Test setup stolen from pajonk's R answer.

• One byte can be saved by taking input as vectors of codepoints: ato.pxeger.com/… Jan 12 at 13:39

Nibbles, 8 bytes (16 nibbles)

?,%$%;/,@,$_*~@

?,%$%;/,@,$_*~@
/            # divide
,@          #   length of arg2
,$# by length of arg1 ; # and save the result n; % _ # now get every n-th element of arg2 %$                # and use this to split arg1
# (result will be empty list if they're equal,
# or arg1 unchanged if they're unequal);
?,                  # if the length of this is nonzero
*~@    #   return n multiplied by -1
#   otherwise implicitly return n
`