Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Below is a php script for this algorithmic problem:
The SHIELD is a secretive organization entrusted with the task of
guarding the world against any disaster. Their arch nemesis is the
organization called HYDRA. Unfortunately some members from HYDRA had
infiltrated into the SHIELD camp. SHIELD needed to find out all these
infiltrators to ensure that it was not compromised.
Nick Fury, the executive director and the prime SHIELD member figured out that every one in SHIELD could send a SOS signal to every
other SHIELD member he knew well. The HYDRA members could send bogus
SOS messages to others to confuse others, but they could never receive
a SOS message from a SHIELD member. Every SHIELD member would receive
a SOS message ateast one other SHIELD member, who in turn would have
received from another SHIELD member and so on till NickFury. SHIELD
had a sophisticated mechanism to capture who sent a SOS signal to
whom. Given this information, Nick needed someone to write a program
that could look into this data and figure out all HYDRA members.
Sample Input
Nick Fury : Tony Stark, Maria Hill, Norman Osborn
Hulk : Tony Stark, HawkEye, Rogers
Rogers : Thor,
Tony Stark: Pepper Potts, Nick Fury
Agent 13 : Agent-X, Nick Fury, Hitler
Thor: HawkEye, BlackWidow
BlackWidow:Hawkeye
Maria Hill : Hulk, Rogers, Nick Fury
Agent-X : Agent 13, Rogers
Norman Osborn: Tony Stark, Thor
Sample Output
Agent 13, Agent-X, Hitler
SCRIPT.php
<?php
//this is the input
$input="Nick Fury : Tony Stark, Maria Hill, Norman Osborn
Hulk : Tony Stark, HawkEye, Rogers
Rogers : Thor
Tony Stark: Pepper Potts, Nick Fury
Agent 13 : Agent-X, Nick Fury, Hitler
Thor: HawkEye, BlackWidow
BlackWidow:HawkEye
Maria Hill : Hulk, Rogers, Nick Fury
Agent-X : Agent 13, Rogers
Norman Osborn: Tony Stark, Thor";
/*this is an array for storing shield member names as
key-value pairs like Nick Fury=>Tony Stark, Maria Hill, Norman Osborn*/
$shield=array();
$keys=array(); //array for storing shield member names as keys
$values=array(); //array for storing shield member names as value
$shield_members=array(); //array which stores each valid shield member's name using below process
//$hydra=array();
$rows = explode("\n", $input); //creating array of given input row wise
$i=0;
//considering each row at once
while ($i<count($rows)) {
# code...
$temp=explode(":", $rows[$i]); //exploding row
$key=trim($temp[0]); //getting key
$value=trim($temp[1]); //getting value
$keys[]=$key; //storing each key in keys[]
$values[]=$value; //storing each value in values[]
$shield[$key]=$value; //storing these key-value pair as array in shield[]
$i++;
}
//loop to find all persons who are receiving messages from anyone
$i=0;
$recieiver_hydra=array(); //arrray to store all persons receiving messages
while($i<count($values)){
$temp = explode(",", $values[$i]); //exploding RHS values row wise
$j=0;
while ($j<count($temp)) {
# code...
if(!in_array($temp[$j], $recieiver_hydra)) //trying insert only unique values in recieiver_hydra[]
$recieiver_hydra[]=$temp[$j]; //========BUT NOT GETTING=======
$j++;
}
$i++;
}
$shield_members[]= "Nick Fury"; //starting from Nick Fury
$temp = explode(",",$shield["Nick Fury"]); //getting value from shield[] array for given key
$i=0;
while($i<count($temp)){
$shield_members[]= $temp[$i]; //adding shield members which are valid not the hydra people
$i++;
}
/* searching process for each valid shield member starting from nick fury upto last one found
and storing them in the sheil_members[] array */
for($i=1; $i<30; $i++){ //=============HERE DON'T GETTING WHAT SHOULD BE THE CONDITION TO STOP EXECUTING
if (array_key_exists(trim($shield_members[$i]),$shield))
$temp = explode(",",$shield[trim($shield_members[$i])]);
else continue;
$j=0;
while ($j<count($temp)) {
# code...
$shield_members[] = trim($temp[$j]);
$j++;
}
}
$i=0;
//printing all valid members added to shield_members[] including duplicate values
while ( $i<count($shield_members)) {
# code...
echo $shield_members[$i]."<br>";
$i++;
}
asort($shield_members); //sorting them
$res1 = array_diff($keys, $shield_members); //finding difference and getting HYDRA members from LHS
$res2= array_diff($recieiver_hydra, $shield_members); //finding difference and getting HYDRA members from RHS ======BUT NOT GETTING
/*
<form action=<?php echo $_SERVER["PHP_SELF"]?> method="POST">
**<i> Enter input in the textarea... </i>
<textarea name="input" rows="10" cols="90"></textarea><br>
<input type="submit" name="submit" value="Find HYDRA Members">
</form>
*/
?>
As per my coding and expectations, $res1 must be having all HYDRA members from LHS of inputs and $res2 must be having all HYDRA members from RHS of input.
But when printing them I am getting wrong results.
$res1 = Array ( [4] => Agent 13 [8] => Agent-X ) //THIS IS CORRECT
$res2 = Array ( [3] => HawkEye [4] => Rogers [7] => Nick Fury
[8] => Agent-X [9] => Hitler [11] => BlackWidow
[13] => Agent 13 [14] => Thor ) //WRONG RESULTS
Please help me knowing what am I doing wrong?
(I am not expert at algorithms. Whole this code I made using raw coding ideas and knowledge.)
This sounds like a exercise from some programming course. Normally i would say, that you should solve such a task by yourself (I think this will be the reason for the down votes of your question), but it is a funny problem, so here is my solution.
If i need to implement a new algorithm, i always try to split the problem into subproblems.
Doing so,
it is easier to find a good solution
as result you get a much more readable code
So problem number one is to transform the input into an array structure to work with:
function transformInput($input) {
foreach (explode("\n", $input) as $row) {
list($receiver, $senders) = explode(':', $row);
$memberTree[trim($receiver)] = array_map('trim', explode(',', $senders));
}
return $memberTree;
}
The second problem is to find all real SHIELD members:
function extractShieldMembers($memberTree, $startMember, $shieldMembers = array()) {
$shieldMembers[] = $startMember;
if (array_key_exists($startMember, $memberTree)) {
foreach ($memberTree[$startMember] as $member) {
if (!in_array($member, $shieldMembers)) {
$shieldMembers = array_merge(
$shieldMembers,
extractShieldMembers($memberTree, $member, $shieldMembers)
);
}
}
}
return $shieldMembers;
}
With this two functions in your library, it is very easy to get the list with all SHIELD members:
$memberTree = transformInput($input);
$shieldMembers = array_unique(extractShieldMembers($memberTree, 'Nick Fury'));
Now, after knowing who really belongs to SHIELD you can find all HYDRA members with this functon:
function getHydraMembers($memberTree, $shieldMembers){
$allMembers = array();
foreach ($memberTree as $key => $value) {
$allMembers[] = $key;
$allMembers = array_merge($allMembers, $value);
}
return array_unique(array_diff($allMembers, $shieldMembers));
}
$hydraMembers = getHydraMembers($memberTree, $shieldMembers);
Is this the best solution for this problem?
I don't think so, because it was just a quick approach.
But as you can see, if you try to split your code into small logic functions, you get more readable code, that you can better debug.
You also don't need as many temporary variables and counter.
Related
I want to build a Recommendation system that recommends people base on their preferences towards user details for example if User1 wants someone who is male and lives america, an array would be made of this being User1{male, america} while the second array would be the other users details for example user2 being female and from america her array would be User2{female, america}, user 3 being {male, america} I want to be able to find the similarity distance between user 1 and the other users array and base on the score it would be listed from the highest to the lowest.
The dirty way of doing it:
foreach($item in $array_one){
foreach($item_two in $array_two){
if($item == $item_two){
echo "Euston, we found a match!";
}
}
}
The clean way of doing it:
$intersection = array_intersect($array_one, $arrary_two);
if (in_array($value_to_look_for, $intersection)) {
echo "Euston, we have a match!";
}
I need some sort of database or feed to access live scores(and possibly player stats) for the NFL. I want to be able to display the scores on my site for my pickem league and show the users if their pick is winning or not.
I'm not sure how to go about this. Can someone point me in the right direction?
Also, it needs to be free.
Disclaimer: I'm the author of the tools I'm about to promote.
Over the past year, I've written a couple Python libraries that will do what you want. The first is nflgame, which gathers game data (including play-by-play) from NFL.com's GameCenter JSON feed. This includes active games where data is updated roughly every 15 seconds. nflgame has a wiki with some tips on getting started.
I released nflgame last year, and used it throughout last season. I think it is reasonably stable.
Over this past summer, I've worked on its more mature brother, nfldb. nfldb provides access to the same kind of data nflgame does, except it keeps everything stored in a relational database. nfldb also has a wiki, although it isn't entirely complete yet.
For example, this will output all current games and their scores:
import nfldb
db = nfldb.connect()
phase, year, week = nfldb.current(db)
q = nfldb.Query(db).game(season_year=year, season_type=phase, week=week)
for g in q.as_games():
print '%s (%d) at %s (%d)' % (g.home_team, g.home_score,
g.away_team, g.away_score)
Since no games are being played, that outputs all games for next week with 0 scores. This is the output with week=1: (of the 2013 season)
CLE (10) at MIA (23)
DET (34) at MIN (24)
NYJ (18) at TB (17)
BUF (21) at NE (23)
SD (28) at HOU (31)
STL (27) at ARI (24)
SF (34) at GB (28)
DAL (36) at NYG (31)
WAS (27) at PHI (33)
DEN (49) at BAL (27)
CHI (24) at CIN (21)
IND (21) at OAK (17)
JAC (2) at KC (28)
PIT (9) at TEN (16)
NO (23) at ATL (17)
CAR (7) at SEA (12)
Both are licensed under the WTFPL and are free to use for any purpose.
N.B. I realized you tagged this as PHP, but perhaps this will point you in the right direction. In particular, you could use nfldb to maintain a PostgreSQL database and query it with your PHP program.
So I found something that gives me MOST of what I was looking for. It has live game stats, but doesn't include current down, yards to go, and field position.
Regular Season:
http://www.nfl.com/liveupdate/scorestrip/ss.xml
Post Season:
http://www.nfl.com/liveupdate/scorestrip/postseason/ss.xml
I'd still like to find a live player stat feed to use to add Fantasy Football to my website, but I don't think a free one exists.
I know this is old, but this is what I use for scores only... maybe it will help someone some day. Note: there are some elements that you will not use and are specific for my site... but this would be a very good start for someone.
<?php
require('includes/application_top.php');
$week = (int)$_GET['week'];
//load source code, depending on the current week, of the website into a variable as a string
$url = "http://www.nfl.com/liveupdate/scorestrip/ss.xml"; //LIVE GAMES
if ($xmlData = file_get_contents($url)) {
$xml = simplexml_load_string($xmlData);
$json = json_encode($xml);
$games = json_decode($json, true);
}
$teamCodes = array(
'JAC' => 'JAX',
);
//build scores array, to group teams and scores together in games
$scores = array();
foreach ($games['gms']['g'] as $gameArray) {
$game = $gameArray['#attributes'];
//ONLY PULL SCORES FROM COMPLETED GAMES - F=FINAL, FO=FINAL OVERTIME
if ($game['q'] == 'F' || $game['q'] == 'FO') {
$overtime = (($game['q'] == 'FO') ? 1 : 0);
$away_team = $game['v'];
$home_team = $game['h'];
foreach ($teamCodes as $espnCode => $nflpCode) {
if ($away_team == $espnCode) $away_team = $nflpCode;
if ($home_team == $espnCode) $home_team = $nflpCode;
}
$away_score = (int)$game['vs'];
$home_score = (int)$game['hs'];
$winner = ($away_score > $home_score) ? $away_team : $home_team;
$gameID = getGameIDByTeamID($week, $home_team);
if (is_numeric(strip_tags($home_score)) && is_numeric(strip_tags($away_score))) {
$scores[] = array(
'gameID' => $gameID,
'awayteam' => $away_team,
'visitorScore' => $away_score,
'hometeam' => $home_team,
'homeScore' => $home_score,
'overtime' => $overtime,
'winner' => $winner
);
}
}
}
//see how the scores array looks
//echo '<pre>' . print_r($scores, true) . '</pre>';
echo json_encode($scores);
//game results and winning teams can now be accessed from the scores array
//e.g. $scores[0]['awayteam'] contains the name of the away team (['awayteam'] part) from the first game on the page ([0] part)
I've spent the last year or so working on a simple CLI tool to easily create your own NFL databases. It currently supports PostgreSql and Mongo natively, and you can programmatically interact with the Engine if you'd like to extend it.
Want to create your own different database (eg MySql) using the Engine (or even use Postgres/Mongo but with your own schema)? Simply implement an interface and the Engine will do the work for you.
Running everything, including the database setup and updating with all the latest stats, can be done in a single command:
ffdb setup
I know this question is old, but I also realize that there's still a need out there for a functional and easy-to-use tool to do this. The entire reason I built this is to power my own football app in the near future, and hopefully this can help others.
Also, because the question is fairly old, a lot of the answers are not working at the current time, or reference projects that are no longer maintained.
Check out the github repo page for full details on how to download the program, the CLI commands, and other information:
FFDB Github Repository
$XML = "http://www.nfl.com/liveupdate/scorestrip/ss.xml";
$lineXML = file_get_contents($XML);
$subject = $lineXML;
//match and capture week then print
$week='/w="([0-9])/';
preg_match_all($week, $subject, $week);
echo "week ".$week[1][0]."<br/>";
$week2=$week[1][0];
echo $week2;
//capture team, scores in two dimensional array
$pattern = '/hnn="(.+)"\shs="([0-9]+)"\sv="[A-Z]+"\svnn="(.+)"\svs="([0-9]+)/';
preg_match_all($pattern, $subject, $matches);
//enumerate length of array (number games played)
$count= count($matches[0]);
//print array values
for ($x = 0; $x < $count ; $x++) {
echo"<br/>";
//print home team
echo $matches[1][$x]," ",
//print home score
$matches[2][$x]," ",
//print visitor team
$matches[3][$x]," ",
//print visitor score
$matches[4][$x];
echo "<br/>";
}
I was going through problems finding a new source for the 2021 season. Well I finally found one on ESPN.
http://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard
Returns the results in JSON format.
I recommend registering at http://developer.espn.com and get access to their JSON API. It just took me 5 minutes and they have documentation to make pretty much any call you need.
My page lets the user choose a list of courses that they wish to attend from a list opened up by the .php script. The choices the user picks are set to an array of check boxes called courses[]. One the Result.php, the choices chosen are sent through a RegEx to extract the course names and the hours that each course requires. The course name is only outputted while the hours are added up to show the total hours needed each week.
My problem is, I have fixed all syntax, but nothing is returned when I call out my printf format. I tried to var_dump($courses) and ($courseLine) and it came out to NULL and NULL. I think I have a piece of logic error on Registration.php but I cant find where.
Below is my Result.php and I will include a sample of the course list text file
<table><tr><th>Courses</th><th>hours per Week</th></tr>
<?php
$courses = $_GET['courses'];
$courseHoursRegEx = "/\s[0-9]{1,2}\shrs/w/";//needs work
$courseNameRegEx = "/[a-zA-Z]{3}[0-9]{4}[A-Z]{0,1}\s?/[a-zA-Z]{3,40}/";
function GetCourseHours($couseLine)
{
if(!preg_match($courseHoursRegEx, $courseLine))
{
return $courseHour;
}
$totalHours += $courseHour;
}
function GetCourseName($courseLine)
{
if(!preg_match($courseNameRegEx, $courseLine))
{
return $courseInfo;
}
}
foreach($courses as $course)
{
$theCourse = GetCourseName($course);
$theHours = GetCourseHours($course);
}
for($i = 1; $i <= $courses; ++$i)
{
printf("<tr><td>\%</td><td>\%</td></tr>", $theCourse, $theHours);
}
?>
<tr>
<th>Total Hours</th><td><?php echo $totalHours ?> </td></tr>
</table>
Here is my starting page, so you have an idea what values are worked with (I did not include the validation functions due the the length of script.)
</table>
<?php
$courseFile = fopen("CourseList.txt", "r");
$courseHoursRegEx = "/\s[0-9]{1,2}\shrs/w/";
$courseNameRegEx = "/[a-zA-Z]{3}[0-9]{4}[A-Z]{0,1}\s?/[a-zA-Z]{3,40}/";
while(!feof($courseFile))
{
$courseLine = fgets($courseFile);
echo "<input type='checkbox' name='courses[]' value='$courseLine'/> $courseLine <br />";
}
fclose($courseFile);
function GetCourseHours($courseLine)
{
if(!preg_match($courseHoursRegEx, $courseLine))
{
return $courseLine;
}
}
function GetCourseName($courseLine)
{
if(!preg_match($courseNameRegEx, $courseLine))
{
return $courseLine;
}
}
?>
Here is a sample of what the text file looks like with course information
CON8101 Residential Building/Estimating 16 hrs/w
CON8411 Construction Materials I 4 hrs/w
CON8430 Computers and You 4 hrs/w
MAT8050 Geometry and Trigonometry 4 hrs/w
SAF8408 Health and Safety 5 hrs/w
while not specifically answering your question, try using the following regex on each line in your file;
preg_match('/(?P<courseid>[A-Z0-9]+) (?P<coursename>.*) (?P<coursehours>\d+) hrs/',$text,$matches);
this will create an array $matches in this case which you can then reference the elements more inately
Array
(
[0] => CON8101 Residential Building/Estimating 16 hrs
[courseid] => CON8101
[1] => CON8101
[coursename] => Residential Building/Estimating
[2] => Residential Building/Estimating
[coursehours] => 16
[3] => 16
)
which will simplify your code and addition functions immensely.
=+ is not a valid php operator try += If your using numbers try += if strings use .=. Hope that works.
This is my problem. I'm trying to retrieve a value from an XML url (from last.fm api). For example the biography of an artist.
I already know that I can do it simply like this (e.g. for Adele):
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
echo $info;
?>
This returns:
Adele Laurie Blue Adkins, (born 5 May 1988), is a Grammy Award-Winning English singer-songwriter from Enfield, North London. Her debut album, <a title="Adele - 19" href="http://www.last.fm/music/Adele/19" class="bbcode_album">19</a>, was released in January 2008 and entered the UK album chart at #1. The album has since received four-times Platinum certification in the UK and has sold 5,500,000 copies worldwide. The album included the hugely popular song <a title="Adele – Chasing Pavements" href="http://www.last.fm/music/Adele/_/Chasing+Pavements" class="bbcode_track">Chasing Pavements</a>. 19 earned Adele two Grammy Awards in February 2009 for Best New Artist and Best Female Pop Vocal Performance.
I would now like to put that result in a text file and store it on a folder on my website, for example: "http://mysite.com/artistdescriptions/adele.txt".
I've already tried:
<?php
$file_path = $_SERVER['DOCUMENT_ROOT'].'/artistdescriptions/adele.txt';
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
file_put_contents($file_path, serialize($info));
$file_contents = file_get_contents($file_path);
if(!empty($file_contents)) {
$data = unserialize($file_contents);
echo $data;
}
?>
But this unfortunately didn't work. Any help would be greatly appreciated!
Echo call magic method __toString(), but serialize doesn't, and in SimpleXMLElement isn't serialize allowed, so it throw an Exception. But you can call __toString() magic method by yourself, and this solve you problem.
Replace your line with mine
$info = $xml->artist->bio->summary->__toString();
I have the following MySQL table structure:
num field company phone website
1 Gas abcd 123456789 abcd.com
2 Water efgh 987654321 efgh.com
3 Water ijkl 321654987 ijkl.com
4 Heat mnop 987654321 mnop.com
5 Gas qrst 123789654 qrst.com
...
Is it possible with PHP (maybe using some mixture of GROUP_BY and ORDER_BY) to echo the data to the screen in the following format:
Gas:
abcd qrst
123456789 123789654
abcd.com qrst.com
Water:
efgh ijkl
987654321 321654987
efgh.com ijkl.com
Heat:
mnop
321654987
mnop.com
The exact format of it isn't important. I just need for the different rows of data to be listed under the appropriate field with none of the fields repeated. I've been trying to figure this out for a while now, but I'm new to PHP and I can't seem to figure out how to do this, if it's even possible, or if there's a better way to organize my data to make it easier.
To avoid performing a "Gas" query, a "Water" query and a "Heat" query, you could order the results by "field" and then handle the display in PHP...
SELECT
Field,
Company,
Phone,
Website
FROM
tblYourTable
ORDER BY
Field
In your PHP loop, you would need to keep tabs on your current "Field" and start a new list when it changes. For example:
$CurrentField = '';
... loop
if ($MyData->Field != $CurrentField) {
$CurrentField = $MyData->Field;
....
}
... end loop
I will assume that you know how to retrieve MySQL data into an array... so, we have:
[0] {
num => 1,
field => "Gas",
company => "abcd",
phone => "123456789",
website => "abcd.com"
}
[1] ... (so on)
Then create a loop like:
foreach($data as $row) {
$service = $row["field"]; //Water, Gas, etc...
unset($row["field"]); //do not add this
foreach($row as $key => $value) {
$field[$service][$key][] = $value;
}
}
The resulting array will be something like:
$field["Gas"]["company"][0] = "abcd";
$field["Gas"]["company"][1] = "qrst";
$field["Water"]["company"][0] = "efgh";
...
$field["Gas"]["phone"][0] = "123456789";
$field["Gas"]["phone"][1] = "123789654";
$field["Water"]["phone"][0] = "987654321";
...
In that way you can then generate the output:
foreach($field as $service => $infoarr) {
echo $service."\n";
foreach($infoarr as $info => $datarr) {
foreach($datarr as $datum) {
echo $datum."\t";
}
echo "\n";
}
echo "\n";
}
Theorically (untested) will output:
Gas
abcd qrst
123456789 123789654
Water
efgh ...
I hope you find it useful... There should be a better way, but I didn't thought
too much about it...