Shuffling and rotating output in Velocity

I wrote earlier about using Velocity's $math.random() for basic A/B testing. Here are some other things you can do in the same vein by referencing Java's java.util.Collections object.

Collections offers a bunch of static methods to operate on collections (like the ArrayLists of Custom Objects that Marketo creates for you). Most of them, though, are hard to call from VTL (in some cases, much as I have tried, impossible).

Two methods that are easy to use from Velocity are [shuffle()](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List,\ java.util.Random) and [rotate()](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#rotate(java.util.List,\ int).

About shuffle()

shuffle() randomly rearranges a list. If $list = [1,2,3,4] then shuffle($list) will turn the list into [2,3,4,1], [1,4,2,3], etc. at random each time it's run.

About rotate()

rotate() rearranges a list by shifting by a fixed number of indexes left or right, wrapping shifted items around to the other side. (Clumsy to explain in words, but easy to show in code!)

If $list starts off as ["apple", "berry", "cake", "dog"] then shuffle($list,1) will turn it into ["dog", "apple", "berry", "cake"]. Running shuffle($list,1) again on the same $list will turn it into ["cake", "dog", "apple", "berry"].

As you can see, all the elements shift N positions in one direction, and the ones that get bumped off wrap around the other side.

With a negative number as the second arg, the shift goes left. If $list is ["apple", "berry", "cake", "dog"] then shuffle($list,-1) will turn it into ["berry", "cake", "dog", "apple"].

What does this have to do with email content?

Well, maybe nothing.

But if you let your mind wander, you can see how changing the order of a list of, say, blog article links to different segments can help you measure different engagement. Doing this without Velocity would mean creating N variants of your emails, which would be a real pain.

Here's an example to get you started:

#set( $promos = [
   'Get What You Want <a href="http://exam.pl/8357821">This Time</a>',
   'Get your hands in <a href="http://exam.pl/24878723">these gloves</a>',
   'Here&apos;s the one you <a href="http://exam.pl/3987343">CAN have</a>',
   'A Rush and a Push and this landing page <a href="http://exam.pl/1287345">is yours</a>'
])
#set ($Collections = $context.getClass().forName("java.util.Collections"))
#if (!$promos.isEmpty())   
#set ($void = $Collections.rotate($promos, $lead.TestCohort))
$display.list($promos,"<br>","<br>")
#end

This code assumes you've sorted leads into one of 4 cohorts (in this case, a custom Integer field TestCohort but you could also use true Segments). It then outputs the links in wraparound order using rotate() (thus it's not full random order, the important diff between shuffle() and rotate()).