Simulate D Flip-Flop
J, 27 23 bytes
-4 bytes thanks to Bubbler!
;@(<@({.\);.1~1,2</\}.)
Try it online!
CLK
is the left argument; D
is the right one. When CLK
doesn't start with 01
, the starting bits are the same as the first bit of D
.
;.1 - cut
] - the right argument (D)
( ) - where
2 /\ - the previous element
[ - of the left argument (CLK)
< - is smaller than the next one
}. - drop
1 - the first item
1, - prepend with 1 (for cutting)
( ) - for each cut group
$ - make a list
# - of the same length as the group
{. - with elements same as the first one
<@ - and box the list
; - unbox the sublists and flatten them
[: - function composition
K (oK), 27 23bytes
-4 bytes thanks to ngn!
{,/&\'|\'(0,&1_>':x)_y}
Try it online!
APL (Dyalog Extended), 16 bytes
∊⊣⊣\¨⍤⊂⍨1,1↓2</⊢
Try it online!
A dyadic tacit function whose right arg is CLK and left arg is D. Accepts both as Boolean vectors. The starting bit of Q follows that of D.
How it works
∊⊣⊣\¨⍤⊂⍨1,1↓2</⊢ ⍝ Input: left←D, right←CLK
2</⊢ ⍝ Detect rising edges of CLK
1,1↓ ⍝ Treat the very first tick as a rising edge
⊣ ⊂⍨ ⍝ Partition D into regions where
⍝ each rising edge marks the start of each region
⊣\¨⍤ ⍝ On each region, overwrite all elements with the first one
∊ ⍝ Enlist; form a simple vector
JavaScript (ES6), 40 39 bytes
Takes input as (clock)(data)
, where clock and data are arrays of binary digits.
C=>D=>D.map(c=>C[i]<C[++i]?p=c:p,i=p=0)
Try it online!