DEV Community

Arjun Rajkumar
Arjun Rajkumar

Posted on • Updated on

Write better code: Day 2 - Single Riffle Shuffle

This post originally appeared on Arjun Rajkumar 's blog. Arjun is a web developer based in Bangalore, India.

--

This was the previous question I solved today.

Day 2: Question 2

Write a method to tell us if a full deck of cards shuffled_deck is a single riffle of two other halves half1 and half2.

We'll represent a stack of cards as an array of integers in the range 1..52 (since there are 52 distinct cards in a deck).

SingleRiffle:
SingleRiffle

Question from InterviewCake

If you want to follow along, feel free to post your answers in the comment.
My answers are in the comments.

Top comments (1)

Collapse
 
arjunrajkumar profile image
Arjun Rajkumar • Edited

Logic was to get the shuffled deck and check if the last card in shuffled deck belongs to the top of half 1 of half 2.

-do while loop until shuffled deck is empty.
-pick a card from the shuffled deck - check if it's the top card of half 1 or half2.
-if it matches top of half1 - pop it from half1, pop from deck.
-else if is top of half2, repeat.
-if the card does not match the top of either halves, it's not a single shuffle.

code

I think I could improve this. I am not sure yet what the complexity of using pop is.
If its always O[1] then this logic is good. But anyhow since the max deck of cards is always 52, change in performance wont make much difference even with better code than this.