Расширить массив дополнительными требованиями - PullRequest
1 голос
/ 03 августа 2020

Я новичок в PHP, но я стараюсь. Пожалуйста, проявите ко мне терпение. :)

Вчера я уже задавал подобный вопрос, но сегодня я должен его расширить.

Исходная ситуация

В моей школе у ​​выпускников есть выбрать топи c для дипломной работы в последний год. Каждый ученик выбирает репетитора из одной предметной области, чтобы помочь ему.

Начальная позиция

  • Каждый ученик должен указать ровно три желания, которые отсортированы в порядке убывания предпочтения. Пример: Стейси выбирает мистера Джобса в дизайне в качестве своего первого sh, Карл также выбирает мистера Джобса в качестве своего первого sh, но в удобстве использования. Уильям выбирает мистера Гейтса по информатике в качестве своего первого выбора, Шарлотт выбирает мистера Гейтса по биологии в качестве своего первого выбора.
  • Каждый преподаватель может руководить максимум тремя учениками.
  • Каждый учитель может можно выбрать не более чем по двум предметам. Таким образом, мистер Джобс мог быть выбран по дизайну и удобству использования, мистер Гейтс по информатике и биологии, мистер Маск по физике и географии.

Пример возможных выборов:

Mr. Jobs -> Stacy (Design), Carl (Usability), Melody (Design)
Mr. Gates -> William (Computer Science), Eric (Biology), Charlott (Biology)
Mr. Musk -> Anthony (Physics), Sarah (Physics), Nelly (Geography)

Заключительные вопросы

  • Как я могу сделать так, чтобы как можно больше студентов получили свой первый wi sh? Из оставшихся студентов как можно больше должны получить второй wi sh, остальные - третьи wi sh. (готово? у вас есть чаевые?)
  • Как я могу расширить следующий сценарий так, чтобы учитывались разные предметы моих коллег, но никто не руководил более чем 3 студентами?
  • Как я могу сказать, что сценарий также выводит, является ли назначение первым wi sh, вторым wi sh или третьим wi sh?

User Rustyjim помогло меня вчера со следующим сценарием. Еще раз спасибо!

С наилучшими пожеланиями, оставайтесь здоровыми!

Скрипт пока

function shuffle_assoc($list) {
    if (!is_array($list)) return $list;
    $keys = array_keys($list);
    shuffle($keys);
    $random = array();
    foreach ($keys as $key) {
        $random[$key] = $list[$key];
    }
    return $random;
}
$preferencesOfStudents = [
    'students' => [
        'Stacy' => ['Mr Jobs','Mr Gates','Mr Musk'],
        'Carl' => ['Mr Jobs','Mr Gates','Mr Musk'],
        'Melody' => ['Mr Jobs','Mr Musk','Mr Gates'],
        'William' => ['Mr Musk','Mr Gates','Mr Jobs'],
        'Eric' => ['Mr Gates','Mr Jobs','Mr Musk'],
        'Charlott' => ['Mr Jobs','Mr Gates','Mr Musk'],
        'Anthony' => ['Mr Gates','Mr Musk','Mr Jobs'],
        'Sarah' => ['Mr Gates','Mr Jobs','Mr Musk'],
        'Nelly' => ['Mr Gates','Mr Musk','Mr Jobs']
    ]
];
// 1 = Jobs, 2 = Gates, 3 = Musk
$teachers = [
    'Mr Jobs' => [],
    'Mr Gates' => [],
    'Mr Musk' => []
];
$randomStudentsArray = shuffle_assoc($preferencesOfStudents['students']);
//print_r($randomStudentsArray);
foreach($randomStudentsArray as $name => $student){
    if(count($teachers[$student[0]]) < 3){
        $teachers[$student[0]][] = $name;
    } elseif(count($teachers[$student[1]]) < 3) {
        $teachers[$student[1]][] = $name;
    } else {
        $teachers[$student[2]][] = $name;
    }
}
print_r($teachers);

1 Ответ

1 голос
/ 03 августа 2020

РЕДАКТИРОВАТЬ: Это работает? Надеюсь на помощь!

Если есть максимум 2 специализации, возникает проблема: иногда не всех студентов можно назначить.

Но это старается изо всех сил и случайным образом, поэтому, если он не дает хорошего результата, просто попробуйте еще раз.

   <?php
function shuffle_assoc($list) {
    if (!is_array($list)) return $list;
    $keys = array_keys($list);
    shuffle($keys);
    $random = array();
    foreach ($keys as $key) {
        $random[$key] = $list[$key];
    }
    return $random;
}
function searchForId($id, $array) {
    foreach ($array as $key => $val) {
        if ($val['specializations'] === $id) {
            return $key;
        }
    }
    return null;
 }
$preferencesOfStudents = [
    'students' => [
        'Stacy' => ['Mr Jobs','Mr Gates','Mr Musk', 'Biology'],
        'Carl' => ['Mr Jobs','Mr Gates','Mr Musk', 'Design'],
        'Melody' => ['Mr Bezos','Mr Musk','Mr Gates', 'Usability'],
        'William' => ['Mr Musk','Mr Gates','Mr Jobs', 'Computer Science'],
        'Eric' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics'],
        'Charlott' => ['Mr Jobs','Mr Gates','Mr Musk', 'Geography'],
        'Anthony' => ['Mr Gates','Mr Musk','Mr Jobs', 'Geography'],
        'Sarah' => ['Mr Gates','Mr Jobs','Mr Musk', 'Design'],
        'Nelly' => ['Mr Gates','Mr Musk','Mr Jobs', 'Usability'],
        'Connor' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics'],
        'Frodo' => ['Mr Gates','Mr Musk','Mr Jobs', 'Computer Science'],
        'Achmed' => ['Mr Gates','Mr Jobs','Mr Musk', 'Computer Science']
    ]
];

$teachers = [
    'Mr Jobs' => [
        'students' => [],
        'specializations' => []
    ],
    'Mr Gates' => [
        'students' => [],
        'specializations' => []
    ],
    'Mr Musk' => [
        'students' => [],
        'specializations' => []
    ],
    'Mr Bezos' => [
        'students' => [],
        'specializations' => []
    ]
];
$unassigned = [];
$randomStudentsArray = shuffle_assoc($preferencesOfStudents['students']);
/*assign students to prefered spots randomly*/
foreach($randomStudentsArray as $name => $student){
    foreach ($teachers as $teacherName => $array) {
        if (in_array($student[3],$array['specializations'])) {
            $teachers[$teacherName]['students'][] = $name." (because of specialization) (".$student[3].")";
            $teachers[$teacherName]['specializations'][] = $student[3];
            break;
        }
    }
    if(count($teachers[$student[0]]['students']) < 5 && count($teachers[$student[0]]['specializations']) < 2){   
        $teachers[$student[0]]['students'][] = $name." (first choice) (".$student[3].")";
        $teachers[$student[0]]['specializations'][] = $student[3]; 
    } elseif(count($teachers[$student[1]]['students']) < 5 && count($teachers[$student[1]]['specializations']) < 2) {
        $teachers[$student[1]]['students'][] = $name." (second choice) (".$student[3].")";
        $teachers[$student[1]]['specializations'][] = $student[3];
    } elseif(count($teachers[$student[2]]['students']) < 5 && count($teachers[$student[2]]['specializations']) < 2)  {
        $teachers[$student[2]]['students'][] = $name." (third choice) (".$student[3].")";
        $teachers[$student[2]]['specializations'][] = $student[3];
    } else {
        $unassigned[$name] = $student;
    }
}
/*assign unassigned student to free spots*/
foreach($unassigned as $name => $student){
    foreach($teachers as $teacherName => $listOfStudents){
        if(count($listOfStudents['students']) < 5 && count($listOfStudents['specializations']) < 2){
            $teachers[$teacherName]['students'][] = $name." (none of prefered choices) (".$student[3].")";
            $teachers[$teacherName]['specializations'][] = $student[3];
        }
    }
}
print_r($teachers);

EDIT2:

<?php
function shuffle_assoc($list) {
    if (!is_array($list)) return $list;
    $keys = array_keys($list);
    shuffle($keys);
    $random = array();
    foreach ($keys as $key) {
        $random[$key] = $list[$key];
    }
    return $random;
}
function searchForId($id, $array) {
    foreach ($array as $key => $val) {
        if ($val['specializations'] === $id) {
            return $key;
        }
    }
    return null;
 }
$preferencesOfStudents = [
    'students' => [
        'Stacy' => ['Mr Jobs','Mr Gates','Mr Musk', 'Biology'],
        'Carl' => ['Mr Jobs','Mr Gates','Mr Musk', 'Design'],
        'Melody' => ['Mr Bezos','Mr Musk','Mr Gates', 'Usability'],
        'William' => ['Mr Musk','Mr Gates','Mr Jobs', 'Computer Science'],
        'Eric' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics'],
        'Charlott' => ['Mr Jobs','Mr Gates','Mr Musk', 'Geography'],
        'Anthony' => ['Mr Gates','Mr Musk','Mr Jobs', 'Geography'],
        'Sarah' => ['Mr Gates','Mr Jobs','Mr Musk', 'Design'],
        'Nelly' => ['Mr Gates','Mr Musk','Mr Jobs', 'Usability'],
        'Connor' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics'],
        'Frodo' => ['Mr Gates','Mr Musk','Mr Jobs', 'Computer Science'],
        'Achmed' => ['Mr Gates','Mr Jobs','Mr Musk', 'Computer Science']
    ]
];

$teachers = [
    'Mr Jobs' => [
        'students' => [],
        'specializations' => ['Biology', 'Design']
    ],
    'Mr Gates' => [
        'students' => [],
        'specializations' => ['Computer Science', 'Usability']
    ],
    'Mr Musk' => [
        'students' => [],
        'specializations' => ['Physics', 'Geography']
    ],
    'Mr Bezos' => [
        'students' => [],
        'specializations' => ['Usability', 'Biology']
    ]
];
$unassigned = [];
$randomStudentsArray = shuffle_assoc($preferencesOfStudents['students']);
/*assign students to prefered spots randomly*/
foreach($randomStudentsArray as $name => $student){
    if(count($teachers[$student[0]]['students']) < 5 && in_array($student[3],$teachers[$student[0]]['specializations'])){   
        $teachers[$student[0]]['students'][] = $name." (first choice) (".$student[3].")";
    } elseif(count($teachers[$student[1]]['students']) < 5 && in_array($student[3],$teachers[$student[1]]['specializations'])) {
        $teachers[$student[1]]['students'][] = $name." (second choice) (".$student[3].")";
    } elseif(count($teachers[$student[2]]['students']) < 5 && in_array($student[3],$teachers[$student[2]]['specializations']))  {
        $teachers[$student[2]]['students'][] = $name." (third choice) (".$student[3].")";
    } else {
        $unassigned[$name] = $student;
    }
}
/*assign unassigned student to free spots*/
foreach($unassigned as $name => $student){
    foreach($teachers as $teacherName => $listOfStudents){
        if(count($listOfStudents['students']) < 5 && count($listOfStudents['specializations']) < 2 && in_array($student[3],$teachers[$teacherName]['specializations'])){
            $teachers[$teacherName]['students'][] = $name." (none of prefered choices) (".$student[3].")";
        }
    }
}
print_r($teachers);

EDIT3:

<?php
function shuffle_assoc($list) {
    if (!is_array($list)) return $list;
    $keys = array_keys($list);
    shuffle($keys);
    $random = array();
    foreach ($keys as $key) {
        $random[$key] = $list[$key];
    }
    return $random;
}
function searchForId($id, $array) {
    foreach ($array as $key => $val) {
        if ($val['specializations'] === $id) {
            return $key;
        }
    }
    return null;
 }
$preferencesOfStudents = [
    'students' => [
        'Stacy' => ['Mr Jobs','Mr Gates','Mr Musk', 'Biology', 'Usability'],
        'Carl' => ['Mr Jobs','Mr Gates','Mr Musk', 'Design', 'Physics'],
        'Melody' => ['Mr Bezos','Mr Musk','Mr Gates', 'Usability', 'Physics'],
        'William' => ['Mr Musk','Mr Gates','Mr Jobs', 'Computer Science', 'Usability'],
        'Eric' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics', 'Design'],
        'Charlott' => ['Mr Bezos','Mr Gates','Mr Musk', 'Geography', 'Design'],
        'Anthony' => ['Mr Gates','Mr Musk','Mr Jobs', 'Geography', 'Computer Science'],
        'Sarah' => ['Mr Bezos','Mr Jobs','Mr Musk', 'Design', 'Physics'],
        'Nelly' => ['Mr Gates','Mr Musk','Mr Jobs', 'Usability', 'Design'],
        'Connor' => ['Mr Gates','Mr Bezos','Mr Musk', 'Physics', 'Usability'],
        'Frodo' => ['Mr Gates','Mr Musk','Mr Jobs', 'Computer Science', 'Geography'],
        'Achmed' => ['Mr Gates','Mr Jobs','Mr Musk', 'Computer Science', 'Geography'],
        'Charlie' => ['Mr Bezos','Mr Musk','Mr Gates', 'Usability', 'Physics'],
        'India' => ['Mr Musk','Mr Gates','Mr Jobs', 'Computer Science', 'Usability'],
        'Lima' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics', 'Design'],
        'Mike' => ['Mr Jobs','Mr Gates','Mr Musk', 'Geography', 'Design'],
        'Oscar' => ['Mr Gates','Mr Musk','Mr Jobs', 'Usability', 'Computer Science'],
        'Quentin' => ['Mr Gates','Mr Jobs','Mr Musk', 'Design', 'Physics'],
        'Sam' => ['Mr Gates','Mr Musk','Mr Jobs', 'Usability', 'Design'],
        'Victor' => ['Mr Gates','Mr Jobs','Mr Musk', 'Physics', 'Usability'],
        'Zach' => ['Mr Gates','Mr Musk','Mr Jobs', 'Computer Science', 'Geography'],
        'Arya' => ['Mr Gates','Mr Jobs','Mr Musk', 'Computer Science', 'Geography']
    ]
];

$teachers = [
    'Mr Jobs' => [
        'students' => [],
        'specializations' => ['Biology', 'Design']
    ],
    'Mr Gates' => [
        'students' => [],
        'specializations' => ['Computer Science', 'Usability']
    ],
    'Mr Musk' => [
        'students' => [],
        'specializations' => ['Physics', 'Geography']
    ],
    'Mr Bezos' => [
        'students' => [],
        'specializations' => ['Usability', 'Biology']
    ]
];
$unassigned = [];
$randomStudentsArray = shuffle_assoc($preferencesOfStudents['students']);
/*assign students to prefered spots randomly*/
foreach($randomStudentsArray as $name => $student){
    if(count($teachers[$student[0]]['students']) < 5 && (in_array($student[3],$teachers[$student[0]]['specializations']) || in_array($student[3],$teachers[$student[0]]['specializations']))){   
        $teachers[$student[0]]['students'][] = $name." (first choice) (".$student[3].")";
    } elseif(count($teachers[$student[1]]['students']) < 5 && (in_array($student[3],$teachers[$student[1]]['specializations']) || in_array($student[3],$teachers[$student[0]]['specializations']))) {
        $teachers[$student[1]]['students'][] = $name." (second choice) (".$student[3].")";
    } elseif(count($teachers[$student[2]]['students']) < 5 && (in_array($student[3],$teachers[$student[2]]['specializations']) || in_array($student[3],$teachers[$student[0]]['specializations'])))  {
        $teachers[$student[2]]['students'][] = $name." (third choice) (".$student[3].")";
    } else {
        $unassigned[$name] = $student;
    }
}
/*assign unassigned student to free spots*/
foreach($unassigned as $name => $student){
    foreach($teachers as $teacherName => $listOfStudents){
        if(count($listOfStudents['students']) < 5 && count($listOfStudents['specializations']) < 2 && ( in_array($student[3],$teachers[$teacherName]['specializations']) || in_array($student[4],$teachers[$teacherName]['specializations']) )){
            $teachers[$teacherName]['students'][] = $name." (none of prefered choices) (".$student[3].")";
        }
    }
}
print_r($teachers);
...