Skip to content

Commit ab1b1fd

Browse files
committed
Implement shuffle command
Added a new "shuffle" command to the qtest. The shuffle command applies Fisher-Yates algorithm to shuffle the elements of the queue. Ensured the correct queue manipulation and proper handling of different queue states. This change includes the addition of the "do_shuffle" function and the necessary updates to the command registration system. Change-Id: I116c76132f043134ce4e38e3da59eaf94e3f84fe
1 parent 6d84b0c commit ab1b1fd

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

qtest.c

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ typedef struct {
6565
} queue_chain_t;
6666

6767
static queue_chain_t chain = {.size = 0};
68-
static queue_contex_t *current = NULL;
68+
queue_contex_t *current = NULL;
6969

7070
/* How many times can queue operations fail */
7171
static int fail_limit = BIG_LIST_SIZE;
@@ -86,6 +86,54 @@ typedef enum {
8686
/* Forward declarations */
8787
static bool q_show(int vlevel);
8888

89+
void q_shuffle(struct list_head *head)
90+
{
91+
if (!head || list_empty(head) || head->next == head->prev)
92+
return;
93+
94+
int qsize = q_size(head);
95+
if (qsize < 2)
96+
return;
97+
98+
element_t **arr = malloc(qsize * sizeof(element_t *));
99+
if (!arr)
100+
return;
101+
102+
struct list_head *cur = head->next;
103+
for (int i = 0; i < qsize; i++, cur = cur->next)
104+
arr[i] = list_entry(cur, element_t, list);
105+
106+
// Fisher-Yates shuffle
107+
for (int i = qsize - 1; i > 0; i--) {
108+
int j = rand() % (i + 1);
109+
if (i != j) {
110+
// **交換陣列中的兩個元素**
111+
element_t *temp = arr[i];
112+
arr[i] = arr[j];
113+
arr[j] = temp;
114+
}
115+
}
116+
117+
// **重新組裝洗牌後的鏈結串列**
118+
INIT_LIST_HEAD(head);
119+
for (int i = 0; i < qsize; i++)
120+
list_add_tail(&arr[i]->list, head);
121+
122+
q_show(3);
123+
free(arr);
124+
}
125+
126+
static bool do_shuffle(int argc, char *argv[])
127+
{
128+
if (!current || !current->q) {
129+
report(1, "No queue created");
130+
return false;
131+
}
132+
133+
q_shuffle(current->q);
134+
return true;
135+
}
136+
89137
static bool do_free(int argc, char *argv[])
90138
{
91139
if (argc != 1) {
@@ -1096,6 +1144,7 @@ static void console_init()
10961144
"");
10971145
ADD_COMMAND(reverseK, "Reverse the nodes of the queue 'K' at a time",
10981146
"[K]");
1147+
ADD_COMMAND(shuffle, "Shuffle elements in queue", "str [n]");
10991148
add_param("length", &string_length, "Maximum length of displayed string",
11001149
NULL);
11011150
add_param("malloc", &fail_probability, "Malloc failure probability percent",

queue.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,4 +458,4 @@ int q_merge(struct list_head *head, bool descend)
458458

459459
main_ctx->size = total_size;
460460
return main_ctx->size;
461-
}
461+
}

0 commit comments

Comments
 (0)