Page 1 of 1

Question on Progressive Arrays

Posted: Tue Jul 20, 2010 2:31 pm
by kurbot
Hello Guys, Quick Question.

Ive been trying to build a script/function to loop through an array, and then when its done loop through it again but starting 1 number higher in the array and appending the number/numbers before it to the end of the array. I will try to explain this question in a diagram.

Sample Array

Code: Select all

$arrayList = array("SampleA","SampleB","SampleC","SampleD","SampleE");
Simple Loop

Code: Select all


$loops = 5; // This number is dynamic and changes so function below needs to by dynamic.

for($c=0;$c<$loops;$c++){
   for($i=0;$i<count($arrayList);$i++){
      print $arrayList[$i] .'<br />';
   }
}
What i would like is the following

Loop 1:
SampleA
SampleB
SampleC
SampleD
SampleE

Loop 2
SampleB
SampleC
SampleD
SampleE

SampleA

Loop 3
SampleC
SampleD
SampleE

SampleA
SampleB

Loop 4
SampleD
SampleE

SampleA
SampleB
SampleC

Loop 5

SampleE

SampleA
SampleB
SampleC
SampleD

Loop ETC - Would start the process over again
SampleA
SampleB
SampleC
SampleD
SampleE

Again the this would continue to cycle while it looped untill it ran out of loops.. Any suggestions would be greatly appreciated.

Thanks in advanced.

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 2:37 pm
by PHPHorizons
See how this does ya:

Code: Select all

$loops  = 5;  // This number is dynamic and changes so function below needs to by dynamic.
$arrayList  = array("SampleA","SampleB","SampleC","SampleD","SampleE");
$array_count = count($arrayList);
for($i=0;$i<$loops;$i++){
for($x = 0; $x < $array_count; $x++) {
$arrayList[] = array_shift($arrayList);
}
}

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 2:40 pm
by kurbot
well,

That seems to do the trick..

Thanks

-Dave

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 2:44 pm
by AbraCadaver
In your second loop just set $i=$c instead of $i=0.

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 2:53 pm
by PHPHorizons
You're welcome Dave ;)

@AbraCadaver
> "just set $i=$c instead of $i=0"
On the second loop, that would miss adding the first array element on to the end, and on the third loop it would miss the first and second elements, and so on and so forth. (I'm assuming that code applies to the op's original code)

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 2:55 pm
by AbraCadaver
PHPHorizons wrote:You're welcome Dave ;)

@AbraCadaver
> "just set $i=$c instead of $i=0"
On the second loop, that would miss adding the first array element on to the end, and on the third loop it would miss the first and second elements, and so on and so forth. (I'm assuming that code applies to the op's original code)
Yes, the original code, and I misread it anyway so disregard :(

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 4:06 pm
by kurbot
Bit of an extended Question to my initial question.. again best described with Diagrams from me..

What you provided earlier was great, however while i thought it would solve my issue it did not..

I guess ill see if you can shed some light on my over all goal that im trying to accomplish..

Brief Explanation to what I'm doing or trying to do.

I'm building a PHP auto scheduler for a hockey league, where I'm taking a list of available teams from a Database, and matching them up to other teams in there division/tier. Currently, what i already have working is, I can Create a Season where i include a Start Date and Close Date of that season. I do some basic conversions to get the number of DAYS are between that date range, and weeks within the start and end dates. From that point i loop through the Days and add them to a array variable $games[$i][$date]. This part works fine listing ALL available days to schedule teams into.. The part im having trouble with is looping through the Available Teams for TeamA, and matching them up to TeamB, Making sure no team plays themselves.. Once it made it through the full team list, it would start over again, just matching new teams up together again making sure teams havent already played other teams.. Im going to draw a simple diagram below to help explain my mumbo jumbo up above..

Code: Select all

$teams = array('Team1', 'Team2', 'Team3', 'Team4', 'Team5');
$gameDays = count_days( $od, $cd ); // This is a function to find the difference between two dates and convert it to days // OD = Open Date | CD = Close Date
$games = array();
$week = 1;
for($i=1; $i<=$gameDays; $i++){

   $date = date('l - m/d/Y',($startDate));

   // Define the easy array variables for template
   $games[$i]['gameNum'] = $i;
   $games[$i]['Date'] = $date;

  // Loop 1

    // Set Home Team ?? need to loop through TEAM A and list them Probably Somthing List this

      // Team1
      // Team3
      // Team5
      // Team2
      // Team4  

    // Set Away Team

      // Team2
      // Team4
      // Team1
      // Team3
      // Team5

  // Loop 2

    // Set Home Team

      // Team1
      // Team3
      // Team5
      // Team2
      // Team4  

    // Set Away Team

      // Team3
      // Team5
      // Team2
      // Team4
      // Team1

  // Loop 3

    // Set Home Team

      // Team1
      // Team3
      // Team5
      // Team2
      // Team4  

    // Set Away Team

      // Team4
      // Team1
      // Team3
      // Team5
      // Team2

  // Loop 4

    // Set Home Team

      // Team1
      // Team3
      // Team5
      // Team2
      // Team4  

    // Set Away Team

      // Team5
      // Team2
      // Team4
      // Team1
      // Team3

//ETC

  $startDate=strtotime(date('m/d/Y', $startDate). " +1 day ");

}
In short terms im matching team A to Team B on a scheduled date automatically, and cant seem to not get teams to overlapp or play each other..

Any thought would be appreciated..

Thanks

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 5:34 pm
by kurbot
N/m,

I was able to solve it with your array_push...

I also broke the teams into two Arrays Odds and Evens, and array_shifted through one side and once i ran out of combinations, i had the arrays swap with each other and continnue for another round.. resulting in all teams played each team on BOTH there home RINK and the Away Rink..


Thanks again :-)

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 6:27 pm
by kurbot
For those of you interested in what eventually solved it, im providing a copy of what i did to make this auto scheduler work..

Code: Select all

/////////////
// Project: HLMS (Hockey League Management Software)
// File: AutoScheduler.php
// Version: 0.9b
// Created By: David Kaplan
// Company: Kurbot llc
// website: http://kurbot.com
// Created: july 20th, 2010
// Copyright © 2010
// //////////////////////////////////////////
// This was created for a Hockey 
// League Management Software 
// to help assist League Managers
// find quick ways to generate schedules
// for their teams on a massive scale
// in just a few clicks
/////////////////////////////////////////////


// Pass a Global Variable from outside of function..
global $module;

// Config Variables, passed from previous script to this one
$teams										= $tm;
$teamNum 									= count($teams);
$teamMatch 									= 2;
$teamGames									= ($teamNum/$teamMatch);
$startDate 									= $od;
$startEnd 									= $cd;	
$gameWeeks									= round((count_days( $od, $cd )/7),0);
$gameDays									= $gameWeeks*7;
$diffDate 									= $startEnd-$startDate;	
$gameNums 									= $diffDate/($teamGames);
$tg 										= 0; 
$w										=1; 
$check										=0;

// Set Tmp Counter
$i=0;

// Start Initial Home Team Loop
foreach($teams as $team){
	
	// Check if Team is Odd
	if($i % 2){
		
		// Pass EVEN TeamA Array Elements only
		$teamA[] 							= $team[1];
		
		// Pass TMP EVEN TeamA Array Elements for use later in switch over
		$teamAtmp[] 							= $team[1];
	
	// Check if Team is Even
	}else{		
		// Do Nothing	
	}
	
	// Increase Counter	
	$i++;
}

// Set Tmp Counter
$i=0;

// Start Initial Visitor Team Loop
foreach($teams as $team){
	
	// Check if Team is Odd
	if($i % 2){
		
		// Do Nothing
		
	// Check if Team is Even
	}else{
		
		// Pass EVEN TeamB Array Elements only
		$teamB[] 							= $team[1];
		
		// Pass TMP EVEN TeamB Array Elements for use later in switch over
		$teamBtmp[] 							= $team[1];
	}
	
	// Increase Counter
	$i++;
}


// Start Games Loop
for($i=1; $i<=$gameDays+1; $i++){
	
		// Establish Starting Date
		$date 								= date('l - m/d/Y',($startDate));
		
		// Pass Game Number to Template Variable
		$games[$i]['gameNum'] 						= $i;
		
		// Pass Game Date to Template Variable
		$games[$i]['Date'] 						= $date;	
		

		
		// Loop Through Home Teams	
		for($ta=0; $ta<$teamNum;$ta++){
			
			// Pass Team A to Template Variable
			$games[$i]['teamA'] 					= $teamA[$tg] ;			
		}
			
		// Loop Through Visitor Teams	
		for($tb=0; $tb<$teamNum;$tb++){
			
			// Pass Team B to Template Variable
			$games[$i]['teamB'] 					= $teamB[$tg] ;			
		}
		
		// Increase Total Games Counter
		$tg++;
		
		// Check if Total Games is Greater Than How many Games are allowed
		if($tg >= $teamGames){
			
			// Advance The Calendar to Next Week
			$startDate						=strtotime(date('m/d/Y', $startDate). " Next Sunday ");
			
			// Shift the Home Team Array		
			$teamA[] 						= array_shift($teamA); 
			
			// New Week | All Teams Played
			$w++; 
						
			// Reset Games in Week Counter
			$tg=0;	
	
		}else{	
		
			// Advance The Calendar to Tomrrow
			$startDate						=strtotime(date('m/d/Y', $startDate). " +1 day ");
		}	
		
		
		// Check if Game Week Out Weighs the Number Possible Games
		if($w > $teamGames){

			// Check Flag to see if ALL teams played twice, once at Home Arena and Once at Visitors Arena
			if($check==0){	
				
				// Swap Teams if Flag Met, to swap Visitors To Home
				$teamA 						= $teamBtmp;
				
				// Swap Teams if Flag Met, to swap Home To Visitors
				$teamB 						= $teamAtmp;

				// Update the Flag so we dont Swap anymore
				$check						=1;
				
			// Check Flag Again
			}else if($check==1){
				
				// Return Function to Parent
				return;
			}
			
			// Reset Week Counter for Visitor / Home Swap
			$w							=1;
		}
}

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 7:30 pm
by PHPHorizons
Hello Dave,

You've done a good job getting that to work. I'm not sure I understand how your code works, but I thought I might take a stab at this problem and see what I could come up with. Maybe you might find something in this code useful. I would have preferred to encapsulate this in a class but I wasn't sure if you would find that useful since the code you posted here is procedural. But since everything is tucked into functions, it wouldn't be difficult to clean this up and make it a class.

Code: Select all

<?php
function get_teams() {
	$teams = array('Team1', 'Team2', 'Team3', 'Team4', 'Team5');
	return $teams;
}

function cycle_teams() {
	static $teams;
	if (empty($teams)) {
		$teams = get_teams();
	}
	$teams[] = array_shift($teams);
	return $teams;
}

function get_matches() {
	$game_days = 4;
	$num_teams = count(get_teams());
	$matchups = array();
	
	for ($game_day = 1; $game_day <= $game_days; $game_day++) {
		$matchups[$game_day] = array();
		$home_teams = get_teams();
		$away_teams = cycle_teams();
		foreach ($home_teams as $team_id => $home_team) {
			
			$temp_matchup_data = array('home' => $home_team, 'away' => array_shift($away_teams));
			if ($temp_matchup_data['home'] === $temp_matchup_data['away']) {
				continue;
			}
			$matchups[$game_day][] = $temp_matchup_data;
		}
	}
	return $matchups;
}
$matchups = get_matches();
var_dump($matchups);
Cheers

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 8:00 pm
by kurbot
Yea i was considering using classes.. But i have this whole system setup in a plugin basis.. Meaning.. i just drop the whole folder into the file tree and the CORE system which we setup adds it into the system as an available option.. creates the navigation array and builds the template and css for it automatically..

Also to clear up some confusion about how we built this.. ;-P

we have a loader.php file which is a master of all the available functions for a plugin..

and example loader.php file has a line in it that looks like:

Code: Select all

function generateSeason($tm, $od, $cd){ include($loadedFunc); return games; }
$loaded Function being a dynamically called and in this case being the script i pasted above.. which completes the function ;-) my methods are bizarre i know..

which is why you think its procedural.. its actually functional if thats even a word :-P

Really it was just this stinking auto scheduling feature that i spent the last 5 days wrapping my brain around.. Would finally get it working and the client would throw a curve ball at me.. after the fact.

I.E: any given team can only play once a week... OR some teams are day restricted to only play on mondays and tuesday..

all this setup auto so the client can press a button and generate a 99% accurate season schedule..

It works pretty good right now, the only last part im going to be adding in is the day restrictions which will be easy.. since all ill need to do is match the two playing teams to a day that they are both compatible with..

I know i can do this with classes too, just didnt cross my mind at the time and i was able to get the rest of the system built using traditional functions.. and it would be a big ordeal to go back and rebuild the CORE.. Plus its due friday :-P

Thanks again, i shot you over a PM with a testing environment example of what we needed this for.. incase your interested.

-Dave

Re: Question on Progressive Arrays

Posted: Tue Jul 20, 2010 10:31 pm
by PHPHorizons
Hopefully I didn't sound critical about your approach.
kurbot wrote:my methods are bizarre i know..
hehe, people tell me the same thing about my own framework code! Even if your methods are bizarre, it sounds like they're working pretty well.
kurbot wrote:Would finally get it working and the client would throw a curve ball at me.. after the fact.
Somewhere someone has written sad songs about these things :P I've been tempted to write my own about my experiences with client curve balls.