Skip to content

Commit fa867ad

Browse files
committed
Implement shuffle command
The shuffle command uses the Fisher-Yates shuffle algorithm to randomize the order of elements in a queue. The do_shuffle function handles command execution, ensuring no arguments are provided and invoking q_shuffle on the current queue with proper error checking and display via q_show. The q_shuffle function iterates through the list from tail to head, swapping nodes at random indices selected via rand() from the remaining dis-shuffled portion. Change-Id: Iee0e1c3c650554ed5d5cf79f03012fa7339eb343
1 parent d64ace7 commit fa867ad

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

qtest.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,47 @@ typedef enum {
8686
/* Forward declarations */
8787
static bool q_show(int vlevel);
8888

89+
static void q_shuffle(struct list_head *head)
90+
{
91+
if (!head || list_empty(head) || list_is_singular(head))
92+
return;
93+
94+
int len = q_size(head);
95+
struct list_head *left;
96+
struct list_head *right = head;
97+
for (; len > 1; len--, right = right->prev) {
98+
int idx = rand() % len;
99+
if (idx == len - 1)
100+
continue;
101+
102+
left = head;
103+
while (idx--)
104+
left = left->next;
105+
list_move(right->prev, left);
106+
list_move_tail(left->next->next, right);
107+
}
108+
}
109+
110+
static bool do_shuffle(int argc, char *argv[])
111+
{
112+
if (argc != 1) {
113+
report(1, "%s takes no arguments", argv[0]);
114+
return false;
115+
}
116+
117+
bool ok = true;
118+
if (!current || !current->q)
119+
report(3, "Warning: Calling shuffle on null queue");
120+
error_check();
121+
122+
if (current && exception_setup(true))
123+
q_shuffle(current->q);
124+
exception_cancel();
125+
126+
q_show(3);
127+
return ok;
128+
}
129+
89130
static bool do_free(int argc, char *argv[])
90131
{
91132
if (argc != 1) {
@@ -1096,6 +1137,7 @@ static void console_init()
10961137
"");
10971138
ADD_COMMAND(reverseK, "Reverse the nodes of the queue 'K' at a time",
10981139
"[K]");
1140+
ADD_COMMAND(shuffle, "Shuffle the given queue", "");
10991141
add_param("length", &string_length, "Maximum length of displayed string",
11001142
NULL);
11011143
add_param("malloc", &fail_probability, "Malloc failure probability percent",

0 commit comments

Comments
 (0)