diff --git a/Specialized Areas/Flow Actions/Create an Array of Item Pairs/README.md b/Specialized Areas/Flow Actions/Create an Array of Item Pairs/README.md new file mode 100644 index 0000000000..1344f6bc48 --- /dev/null +++ b/Specialized Areas/Flow Actions/Create an Array of Item Pairs/README.md @@ -0,0 +1,21 @@ +# Random Pair Generator + +## Overview +This script generates random pairs from an input array. +It is useful for creating **tournament matches**, **group assignments**, or **randomized pairings**. + +The script is structured to run in a scoped execution context (such as **ServiceNow Flow Designer Actions** or **Scripted REST Transforms**) where it accepts `inputs` and `outputs` objects. + +--- + +## How It Works +1. **Shuffle the Input Array** + - Implements the Fisher–Yates algorithm in `shuffleArray()` to randomize the array. + +2. **Create Random Pairs** + - Iterates through the shuffled array in steps of two. + - Forms pairs `[item1, item2]`. + - If the array has an odd length, the last item is placed in a single-element array `[item]`. + +3. **Return Results** + - The final set of pairs is returned as `outputs.match`. diff --git a/Specialized Areas/Flow Actions/Create an Array of Item Pairs/Shuffle Array Pairs b/Specialized Areas/Flow Actions/Create an Array of Item Pairs/Shuffle Array Pairs new file mode 100644 index 0000000000..3ed4612e7e --- /dev/null +++ b/Specialized Areas/Flow Actions/Create an Array of Item Pairs/Shuffle Array Pairs @@ -0,0 +1,32 @@ +(function execute(inputs, outputs) { + function shuffleArray(array) { + for (var i = array.length - 1; i > 0; i--) { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + return array; +} + +function createRandomPairs(array) { + var shuffledArray = shuffleArray(array.slice()); // Make a copy of the array and shuffle it + var pairs = []; + for (var i = 0; i < shuffledArray.length; i += 2) { + if (i + 1 < shuffledArray.length) { + pairs.push([shuffledArray[i], shuffledArray[i + 1]]); + } else { + pairs.push([shuffledArray[i]]); + } + } + return pairs; +} + + +var randomPairs = createRandomPairs(inputs.wheels); + + + + outputs.match = randomPairs; + +})(inputs, outputs);