Continuously Count Consecutive Cases

Background

Imagine that I'm creating a really long necklace, consisting of only two characters, A and B. You must count the number of occurrences of the substring AB in the string.

However, since it's a necklace, you must also consider if the last character and the first character join to make AB. For example, in BBBA, there would be 1 occurrence of AB, as the final A would join to the first B.

Finally, since I'm not finished making the chain, you must continually accept an input. Every successive input after the first is intended to be appended to the current necklace. You must also provide the output for the entire appended necklace after each input. Due to I/O limitations however, these inputs will be given as an array.

• Sample input: An array consisting of strings consisting of any two different characters of your choosing, only. You must clarify in your answer what the substring you're checking for is (which is of length two, and contains both of the distinct characters you're using). You may not use a boolean array.

• Output: The number of occurrences of the substring, as an array of outputs.

Explained Examples

Input => Output
ABABA => 2
ABABA => 4

The chain at the second output would be ABABAABABA, which contains 4 ABs.

Input => Output
BA => 1
BABA => 3
BB => 3
BAAAAB => 4

The chain at the second output would be BABABA, which contains 3 ABs including the A at the end and the B at the start.
The chain at the third output would be BABABABB, which contains 3 ABs
The chain at the fourth output would be BABABABBBAAAAB, which contains 4 ABs


Test Cases

Input => Output
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
AB => 1
AAA => 1
B => 2
AB => 3
//
BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB => 1
A => 2
B => 2
A => 3
A => 3
B => 3
//
BABABABABABAB => 6
A => 7


This is , so shortest answer wins. (# of bytes)

• Not allowing a boolean array seems like needless restriction Commented Jul 24, 2023 at 9:23
• How can ABABA have 2 possible outputs? How do you know how often a chain repeats Commented Jul 24, 2023 at 9:26
• @mousetail - The input is an array of strings. In the first test-case, the input array is [ABABA,ABABA], with 2 outputs (one for each element of the array). In this case, the two elements of the array happen to be the same, which indeed makes it a little confusing at first... Commented Jul 24, 2023 at 13:04

Vyxal, 5 bytes

¦ƛǏ₀O


Try it Online!

Uses the characters 1 and 0, checks for substring 10.

Explained

¦ƛǏ₀O­⁡​‎‎⁪⁡⁪⁠⁪⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁪‏‏​⁡⁠⁡‌⁢​‎‎⁪⁡⁪⁠⁪⁣⁪‏‏​⁡⁠⁡‌⁣​‎‎⁪⁡⁪⁠⁪⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁪‏‏​⁡⁠⁡‌­
¦ƛ     # ‎⁡To each prefix of the input:
Ǐ    # ‎⁢  Append the first character to the end
₀O  # ‎⁣  And count the number of instances of "10" in that
💎


Created with the help of Luminespire.

JavaScript (ES6), 117 bytes

k=>{for(let i=1;i<=k.length;i++)console.log(((s=k.slice(0,i).join('')).match(/01/g)||[]).length+!(+s.at(-1)-~-s[0]))}


Uses 0 instead of A and 1 instead of B.

I could probably get rid of the first/last character special case by appending the first character at the end like Vyxal did using (k.slice(0,i).join('')+k[0][0]).match(/01/g) instead of (s=k.slice(0,i).join('')).match(/01/g) but I can't be bothered to rewrite my terrible explanation

Explained

// Take k ['01010', '01010']
// Convert it to s '01010'
// Then in the next loop s='0101001010'
// In s, count the occurences of 01
// Then count special case of first/last characters

// k has length N
k=>{for(let i=1;i<=k.length;i++) // Loop 'i' from 1 to N inclusive
console.log( // Output:

(
(s=k.slice(0,i).join('')) // Get bracelet up to current 'i'
.match(/01/g)             // List of occurences of '01'
||[]                    // Default to empty list
).length                    // Get length
+
!(+s.at(-1)-~-s[0]) // Is +s.at(-1)-~-s[0] equal to 0?
// (implicitly) convert to number

)}


But what is !(+s.at(-1)-~-s[0])?

s.at(-1) is the last element of s, and for the rest... well... I just threw a bunch of random stuff in there until it worked; please don't tell my coding teacher

With test cases

const f=

k=>{for(let i=1;i<=k.length;i++)console.log(((s=k.slice(0,i).join('')).match(/01/g)||[]).length+!(+s.at(-1)-~-s[0]))}


ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
ABABA => 2
ABABA => 4
//
BA => 1
BABA => 3
BB => 3
BAAAAB => 4
//
AB => 1
AAA => 1
B => 2
AB => 3
//
BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB => 1
A => 2
B => 2
A => 3
A => 3
B => 3
//
BABABABABABAB => 6
A => 7
.slice(1,-1).replaceAll('A','0').replaceAll('B','1').split('\n//\n').forEach(testCase => {
const parts = testCase.split('\n').map(x=>x.split(' => '));
const input_ = parts.map(x=>x[0]);
console.log('\n\nInput:',input_,'\nExpected output:');
parts.forEach(x=>console.log(+x[1]));
console.log('Output:');
f(input_);
});


05AB1E (legacy), 6 bytes

ηJεĆT¢


I/O as a list. Uses characters 1 and 0 for A and B respectively.

Uses the legacy version of 05AB1E, because the new version of 05AB1E has a bug with multi-digit integers and the count builtin ¢, so it would require an additional § after the T.

Explanation:

η       # Get the prefixes of the (implicit) input-list
J      # Join each inner list together to a single string
ε     # Map over each string:
Ć    #  Enclose; append its first character at the end
T¢  #  Count how many times "10" occurs in this string
# (after which the list of counts is output implicitly as result)

• I noticed your first TIO link lead to new 05AB1E, so I edited it to be legacy 05AB1E for you :p Commented Jul 24, 2023 at 12:36
• @lyxal Oh, I copy-pasted it from another answer of mine, so apparently I've done it incorrectly before. 😅 Commented Jul 24, 2023 at 12:45
• Copy-pasting does tend to be like that sometimes. Keeping track of a mental clipboard is hard :p Commented Jul 24, 2023 at 12:46
• Still not using TIO's own TIO link generator then?
– Neil
Commented Jul 25, 2023 at 6:15
• @Neil TIO's link generator links to the git home page, whereas I usually link to the Commands-page directly. For the legacy version, which is an older version of the new 05AB1E, I've apparently used the wrong git-hash before lyxal's edit. Commented Jul 25, 2023 at 6:26

Scala, 139 61 bytes

Port of @Gábor Fekete's Python answer in Scala.

Golfed version. Attempt This Online!

Saved 78 bytes thanks to the comment of @corvus_192

var c="";def f(i:Any)={c+=i;(c+c(0))sliding 2 count(_=="AB")}


Ungolfed version. Attempt This Online!

import scala.collection.mutable.ArrayBuffer

object Main {

var c: ArrayBuffer[String] = ArrayBuffer()

def f(i: String): Int = {
if (c.isEmpty) {
c += i
}
else {
c = ArrayBuffer(c.head + i)
}
}

def main(args: Array[String]): Unit = {
val cases = Array(
("ABABA", 2),
("ABABA", 4),
("//", 0),
("BA", 1),
("BABA", 3),
("BB", 3),
("BAAAAB", 4),
("//", 0),
("AB", 1),
("AAA", 1),
("B", 2),
("AB", 3),
("//", 0),
("BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB", 1),
("A", 2),
("B", 2),
("A", 3),
("A", 3),
("B", 3),
("//", 0),
("BABABABABABAB", 6),
("A", 7)
)

for (caseValue <- cases) {
caseValue._1 match {
case "//" =>
println("=" * 15)
c = ArrayBuffer()
case _ =>
val t = f(caseValue._1)
println(caseValue._1 + " " + caseValue._2 + " ; result: " + t)
}
}
}
}


• 61 bytes: var c="";def f(i:Any)={c+=i;(c+c(0))sliding 2 count(_=="AB")} Commented Jul 29, 2023 at 10:37

Charcoal, 19 bytes

ＷＳ«≔⁺ωιωＩ№⁺ω§ω⁰ABＤ⎚


Try it online! Link is to verbose version of code. Fully interactive version, so when run from the command line it will prompt for the next piece of necklace and output the count of ABs so far. Explanation:

ＷＳ«


Keep accepting pieces but stop when an empty piece is entered.

≔⁺ωιω


Concatenate the piece to the necklace so far.

Ｉ№⁺ω§ω⁰ABＤ⎚


Output the number of ABs so far.

Dyalog APL, 21 bytes

{∇⍵,⍞⊣⎕←+/'AB'⍷⍵,⊃⍵}⍞­⁡​‎‎⁪⁡⁪⁠⁪⁢⁢⁡⁪‏‏​⁡⁠⁡‌⁢​‎‎⁪⁡⁪⁠⁪⁢⁣⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁤⁪‏‏​⁡⁠⁡‌⁣​‎‎⁪⁡⁪⁠⁪⁣⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁣⁢⁪‏⁠⁪⁪‏​⁡⁠⁡‌⁤​‎‎⁪⁡⁪⁠⁪⁣⁣⁪‏⁠‎⁪⁡⁪⁠⁪⁣⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁤⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁤⁢⁪‏‏​⁡⁠⁡‌⁢⁡​‎‎⁪⁡⁪⁠⁪⁤⁣⁪‏⁠⁪⁪⁠⁪⁪⁠⁪⁪⁠⁪⁪‏​⁡⁠⁡‌⁢⁢​‎‎⁪⁡⁪⁠⁪⁤⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁢⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁣⁪‏‏​⁡⁠⁡‌⁢⁣​‎‎⁪⁡⁪⁠⁪⁢⁢⁪‏‏​⁡⁠⁡‌⁢⁤​‎‎⁪⁡⁪⁠⁪⁢⁪‏‏​⁡⁠⁡‌⁣⁡​‎‎⁪⁡⁪⁠⁪⁣⁪‏⁠‎⁪⁡⁪⁠⁪⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁪‏‏​⁡⁠⁡‌­
⍞  # ‎⁡Take a line from standard input, and pass it to the following function:
⎕←               # ‎⁢  print
+/             # ‎⁣  how many times
'AB'         # ‎⁤  the string AB
⍷        # ‎⁢⁡  appears in
⍵,⊃⍵    # ‎⁢⁢  the string formed by concatenating the input and its first element
⊣                 # ‎⁢⁣  , then,
∇                     # ‎⁢⁤  call the same function
⍵,⍞                  # ‎⁣⁡  passing the input concatenated with another line from standard input
💎


Created with the help of Luminespire.

Swift 5.7 -enable-bare-slash-regex, 95 bytes

{var x=""
return $0.map{x+=$0
return x.ranges(of:/AB/).count+("B"==x.first&&"A"==x.last ?1:0)}}


Try it on SwiftFiddle! Without the -enable-bare-slash-regex flag, the regex literal /AB/ would be spelled #/AB/# on macOS, or try!Regex("AB") on Linux, so the flag is obvious. SwiftFiddle enables it by default on Swift 5.7 and later.

The code should be fairly straightforward: append the new element to what's been seen so far, then count the ranges that match /AB/, and check whether it starts with "B" and ends with "A".

Python, 6765 55 bytes

lambda i,c=[]:c.extend(i)or''.join(c+c[:1]).count('AB')


Attempt This Online!

Using the default list argument to memorize the previous inputs.

edit: changed extend to append to save 2 bytes

edit: with the help of @Albert.Lang and @Jonathan Allan golfed an additional 10 bytes

• You can use extend like so f=lambda i,c=[]:[c.extend(i),''.join(c+c[:1]).count('AB')][1] for -4. Commented Jul 24, 2023 at 17:07
• Not sure if you need the f= as it's not self-referencing (one has to either redefine the function or reset a local scope c to reuse it anyway). You can save four more bytes with lambda i,c=[]:c.append(i)or(''.join(c)+c[0][0]).count('AB') regardless. Commented Jul 24, 2023 at 19:20
• Combining with Albert.Lang's suggestion that's 55 bytes. Commented Jul 24, 2023 at 19:24

Ruby-nl, 40 38 bytes

a="#{a}#$_" p (a+a[0]).scan('AB').size  Attempt This Online! ruby -nl # -n loops program over each line of input # -l automatically trims trailing newlines a=" " # Set a to... #{a} # a, if already set (empty string otherwise) #$_                   #  plus most recent line of input
(a+a[0])                   # Get a plus its first character
.scan('AB').size   #  and count all instances of AB
p                            # Print that number


Jelly, 7 bytes

;\ŒgẈ:2


Attempt This Online!

Port of my Nibbles answer.

;\ŒgẈ:2
;\      Concatenate all prefixes
For each concatenated prefix:
Œg     Group runs of equal elements
Ẉ    Length
:2  Floor divide by two

• Ah, I was basically trying this, but with nƝ instead. Off by one! Commented Jul 29, 2023 at 20:59

Nibbles, 6 bytes

$:/,=+~  Attempt This Online! Works with any two distinct characters. $:/,=+~
For each p in
\ :          prefixes of
$the input , length of =$    group runs of identical elements in
+$p concatenated / ~ floor-divided by 2  • Are you sure that this satisfies the "clarify in your answer what the substring you're checking for is" requirement? The substring checked-for seems to depend on the first character of the input... Commented Jul 27, 2023 at 15:06 • @DominicvanEssen Since the strings are treated as cyclic, the number of occurences of AB and BA is always equal. Commented Jul 27, 2023 at 15:07 • Aha! Very clever observation! Commented Jul 27, 2023 at 15:10 Excel, 80 bytes =MAP(SCAN("",A1#,LAMBDA(a,b,a&b)),LAMBDA(c,ROWS(TEXTSPLIT(RIGHT(c)&c,,"AB"))-1))  Input is vertical spilled range #A1. Thunno 2, 6 bytes ƒıJẹTc  Attempt This Online! Uses 1 and 0, and checks for the substring 10, like Vyxal and 05AB1E. Explanation ƒıJẹTc # Implicit input ƒı # Map over prefixes Jẹ # Join and append first character Tc # Count occurrences of "10" # Implicit output  Pyth, 11 bytes m/shBsdT._  Try it online! Uses characters "1" and "0" for "A" and "B" respectively. Explanation m/shBsdT._Q # implicitly add Q # implicitly assign Q = eval(input()) ._Q # prefixes of Q m # map over lambda d sd # concatenate list of strings hB # bifurcate into [str, first_char(str)] s # concatenate list of strings / T # count occurrences of "10"  Perl 5-pl, 28 bytes $,.=$_;$_=chop.$,;$_=s/AB//g


Try it online!

Jelly, 9 8 bytes

;\µṙ1<)§


Try it online!

Something cleverer still feels possible. Takes input as shown in the test cases, since counting substring occurrences is actually pretty expensive anyways.

;\          Scan by concatenate, creating a list of each cumulative necklace.
µ   )     For each:
ṙ1       rotate left once, and
§    count how many
<      are less than in the corresponding original positions.


Scala 3, 65 bytes

_.scanLeft("")(_+_).tail.map(s=>(s+s(0))sliding 2 count(_=="AB"))
`

Attempt This Online!