Equivalent of BP Shuffle Array for C++ TArrays?

Hi guys,
can’t figure out how to shuffle a TArray, there’s no documented function I’m able to find.
My TArray is like this:

TArray<MatrixCell *> somelist;

MatrixCell is a struct defined as:

struct MatrixCell { int32 a; int32 b; int32 c; int32 d; };

What I would do with standard library is:

std::vector<MatrixCell *> somelist;
std::shuffle(somelist.begin(), somelist.end(), rng_seed);

Hope someone can help!

Well this is kind of an old unanswered one. I stumbled upon it because I need it to.

If found this : Using C++ shuffle - C++ Programming - Unreal Engine Forums

In my case, the last answer will do the trick at least :

void AMyActor::ShuffleArray(TArray<FName>& myArray)
{
     if (myArray.Num() > 0)
     {
          int32 LastIndex = myArray.Num() - 1;
          for (int32 i = 0; i <= LastIndex; ++i)
          {
               int32 Index = FMath::RandRange(i, LastIndex);
               if (i != Index)
               {
                    myArray.Swap(i, Index);
               }
          }
     }
}

Well, I went searching the whole engine code just in case I would find a solution, and the only thing I found was more or less the same in file
UE_4.22\Engine\Source\Runtime\AnimGraphRuntime\Private\AnimNodes\AnimNode_RandomPlayer.cpp(322)

	// Shuffle the list
	const int32 NumShuffles = ShuffleList.Num() - 1;
	for(int32 i = 0 ; i < NumShuffles ; ++i)
	{
		int32 SwapIdx = RandomStream.RandRange(i, NumShuffles);
		ShuffleList.Swap(i, SwapIdx);
	}

If Epic does it this way, maybe they don’t have a better one yet.

Math and container operation node functions are usually in kismet libraries, as C++ equivalents are not reflected.

You generally should shuffle array yourself optimized to specific case as Koulounil suggests, but if you really want to use exact same code as in blueprint use this function… which is not much diffrent from what Koulounil shown:

void UKismetArrayLibrary::GenericArray_Shuffle(void* TargetArray, const UArrayProperty* ArrayProp)
{
	if (TargetArray)
	{
		FScriptArrayHelper ArrayHelper(ArrayProp, TargetArray);
		int32 LastIndex = ArrayHelper.Num() - 1;
		for (int32 i = 0; i <= LastIndex; ++i)
		{
			int32 Index = FMath::RandRange(i, LastIndex);
			if (i != Index)
			{
				ArrayHelper.SwapValues(i, Index);
			}
		}
	}
}

template
void Shuffle(TArray &arr)
{
for (int i = arr.Num() - 1; i >= 0; --i)
{
int j = FMath::Rand() % (i + 1);
if (i != j) arr.Swap(i, j);
}
}

2 Likes