xxxxxxxxxx
84
// Week 2 - Randomly shuffle items in an array
// Randomly chooses groups of students
// Michael Ang for NYUADIM Intro to IM
// To change the list of students edit the students.csv
// in sketch files
// let demoStudents = ["Mang", "Jimbo", "Fatima"];
let students; // List of all students
let groupSize = 4; // How many students per group
let groups = []; // Array of groups
// Called *before* setup to allow loading any
// resources needed by the sketch. Preload waits
// until the resources are loaded before going to
// setup()
function preload() {
// Load a list of students stored in a text
// file that has been uploaded to teh sketch files
// See https://p5js.org/reference/#/p5/loadStrings
students = loadStrings("students.csv");
}
function setup() {
createCanvas(800, 500);
console.log(students);
makeGroups(students);
}
function draw() {
background(220);
}
// Print random pairs of items from the list
function makeGroups(students) {
// Randomize the array
// See https://p5js.org/reference/#/p5/shuffle
let shuffled = shuffle(students);
print("shuffled: " + shuffled);
// Make groups of students
let groupNumber = 1;
let counter = 0;
while (shuffled.length > 0 && counter < 16) {
// Make a new group
let group = [];
// Move students to group until group is full or no
// unassigned students left
for (let i = 0; i < groupSize; i++) {
group.push(shuffled.shift()); // Take the first name from shuffled and move to group
counter++;
// Check if we're out of studemts
if (shuffled.length == 0) {
// No students left
break;
}
}
print("Group ", groupNumber, str(group));
groups.push(group); // Add to global list of groups
}
if (shuffled.length > 0) {
groups[3].push(shuffled.shift());
}
}
function draw() {
// Set large text with 1.5 line spacing
let tSize = 20; // Text size
let spacingY = tSize * 1.5; // Vertical spacing of lines of text
let textX = 20;
let textY = spacingY * 2; // Start on second line
textSize(tSize);
// Draw text for each group
for (let i = 0; i < groups.length; i++) {
let theText = "Group " + (i + 1).toString() + ": " + groups[i].toString();
text(theText, textX, textY);
textY += spacingY; // Go to next line
}
}