LLMS_Quiz_Attempt::randomize_attempt_questions( array $questions )

Randomize attempt questions.


Description Description

Logic moved from LLMS_Quiz_Attempt::get_new_questions().


Top ↑

Parameters Parameters

$questions

(array) (Required) Array of attempt's questions (each question is an array itself).


Top ↑

Return Return

(array.)


Top ↑

Source Source

File: includes/models/model.llms.quiz.attempt.php

	public static function randomize_attempt_questions( $questions ) {

		if ( empty( $questions ) ) {
			return $questions;
		}

		// Array of indexes that will be locked during shuffling.
		$locks = array();
		foreach ( $questions as $index => $question_array ) {
			$question = llms_get_post( $question_array['id'] );
			// If randomization is enabled, store the questions index so we can lock it during randomization.
			if ( $question->supports( 'random_lock' ) ) {
				$locks[] = $index;
			}
		}

		// Lifted from https://stackoverflow.com/a/28491007/400568.
		// I generally comprehend this code but also in a truer way i have no idea...
		$inc = array();
		$i   = 0;
		$j   = 0;
		$l   = count( $questions );
		$le  = count( $locks );
		while ( $i < $l ) {
			if ( $j >= $le || $i < $locks[ $j ] ) {
				$inc[] = $i;
			} else {
				++$j;
			}
			++$i;
		}

		// Fisher-yates-knuth shuffle variation O(n).
		$num = count( $inc );
		while ( $num-- ) {
			$perm                       = wp_rand( 0, $num );
			$swap                       = $questions[ $inc[ $num ] ];
			$questions[ $inc[ $num ] ]  = $questions[ $inc[ $perm ] ];
			$questions[ $inc[ $perm ] ] = $swap;
		}

		return $questions;
	}


Top ↑

Changelog Changelog

Changelog
Version Description
7.4.1 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.