Jump to content

Recommended Posts

This is a little game that I have played, basically what is supposed to happen is this:
[b]- Someone posts a Simple - Intermediate PHP challenge.
- Other users try to solve the challenge
- The fist person to solve the challenge gets to create the next PHP challenge[/b]

[b]Rules[/b]:
[b][color=red]- No asking for help in other boards
- Must have a working example
- Must have the code to go along with the example
- Don't post school homework asignments or work assignments, be creative
- No database challenges (since some people don't have access to a database) - Flatfile is fine
- Rules may change if needed[/color][/b]

Since I posted, I guess I'll have to start this off

Write a function that checks if a number is a prime.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/
Share on other sites

  • Replies 88
  • Created
  • Last Reply

Top Posters In This Topic

[code]<?php

//checks if a neutral number is prime
function check($num)
{
$root = (int) sqrt($num);
for ($i=2; $i<=$root; $i++)
{
if($num % $i == 0)
return FALSE;
}

return TRUE;
}

?>[/code]


[b]Write a function that inverts the letters of a string.[/b] (a becomes z, b becomes y, c becomes x... DONT use 13/26 ifs/replace etc', do it with a bit of math/logic and ASCII)

Orio.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-144797
Share on other sites

[quote author=Orio link=topic=119299.msg488528#msg488528 date=1166568757]
[b]Write a function that inverts the letters of a string.[/b] (a becomes z, b becomes y, c becomes x... DONT use 13/26 ifs/replace etc', do it with a bit of math/logic and ASCII)
[/quote]
That's known as the atbash cipher: [code]<?php
function atbash($plaintext)
{
$ciphertext = '';

for($i=0; $i<strlen($plaintext); $i++)
{
$ciphertext .= chr(155-ord(strtoupper(substr($plaintext,$i,1))));
}

return $ciphertext;
}

echo atbash("test");
?>[/code]

[b]Next challenge:[/b]
[s]I'll stick with cryptography... make a function that uses the substitution cipher Vigenère (look it up).[/s]

Edit: I'm afraid it might be too difficult and if it is that it would ruin the game. So here is a new one: Make an ASCII <--> Binary convertor
If anybody should have solved my original challenge I guess it will be accepted as well.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-144828
Share on other sites

Well here was the code, It may be too much but I'm not sure:

[code]<?php
function ascii_binary($prefex,$letter){
$num1 = array("128 => 1","64 => 0","32 => 0","16 => 0","8 => 1","4 => 0","2 => 1","1 => 0");
#$num2 = array("1","0","0","0","1","0","1","0");
if($prefex == 1){
$pre = "010";
}elseif($prefex == 2){
$pre = "011";
}
$letters_binary = array(
"a" => "00001",
"b" => "00010",
"c" => "00011",
"d" => "00100",
"e" => "00101",
"f" => "00110",
"g" => "00111",
"h" => "01000",
"i" => "01001",
"j" => "01010",
"k" => "01011",
"l" => "01100",
"m" => "01101",
"n" => "01110",
"o" => "01111",
"p" => "10000",
"q" => "10001",
"r" => "10010",
"s" => "10011",
"t" => "10100",
"u" => "10101",
"v" => "10110",
"w" => "10111",
"x" => "11000",
"y" => "11001",
"z" => "11010"
);
if($prefex == 1){
$letters_ascii = array(
"a" => "&amp;#065",
"b" => "&amp;#066",
"c" => "&amp;#067",
"d" => "&amp;#068",
"e" => "&amp;#069",
"f" => "&amp;#070",
"g" => "&amp;#071",
"h" => "&amp;#072",
"i" => "&amp;#073",
"j" => "&amp;#074",
"k" => "&amp;#075",
"l" => "&amp;#076",
"m" => "&amp;#077",
"n" => "&amp;#078",
"o" => "&amp;#079",
"p" => "&amp;#080",
"q" => "&amp;#081",
"r" => "&amp;#082",
"s" => "&amp;#083",
"t" => "&amp;#084",
"u" => "&amp;#085",
"v" => "&amp;#086",
"w" => "&amp;#087",
"x" => "&amp;#088",
"y" => "&amp;#089",
"z" => "&amp;#090"
);
}elseif($prefex == 2){
$letters_ascii = array(
"a" => "&amp;#097",
"b" => "&amp;#098",
"c" => "&amp;#099",
"d" => "&amp;#100",
"e" => "&amp;#101",
"f" => "&amp;#102",
"g" => "&amp;#103",
"h" => "&amp;#104",
"i" => "&amp;#105",
"j" => "&amp;#106",
"k" => "&amp;#107",
"l" => "&amp;#108",
"m" => "&amp;#109",
"n" => "&amp;#110",
"o" => "&amp;#111",
"p" => "&amp;#112",
"q" => "&amp;#113",
"r" => "&amp;#114",
"s" => "&amp;#115",
"t" => "&amp;#116",
"u" => "&amp;#117",
"v" => "&amp;#118",
"w" => "&amp;#119",
"x" => "&amp;#120",
"y" => "&amp;#121",
"z" => "&amp;#122"
);
}
$final = '<b>Binary:</b> '.$pre.$letters_binary[$letter];
$final .= '<br><b>Ascii:</b> '.$letters_ascii[$letter];

return $final;
}

if(!isset($_POST['submit'])){
echo'
<form action="'.$_SERVER['PHP_SELF'].'" method="post">
Enter a letter: <input type="text" maxlength="1" name="letter"><br>
<select name="prefix">
<option value="1">Uppercase</option>
<option value="2">Lowercase</option>
</select><br>
<input type="submit" name="submit" value="Convert">
</form>
';

}else{
echo ascii_binary($_POST['prefix'],$_POST['letter']);
}
?>[/code]

So.. Then Here is another challenge:

write a function that will output a person's zodiac sign, from a form that that asks for their birthday -- Please Post a link to your example for testing.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-144958
Share on other sites

Cant think of a nicer way doing that...

[code]<?php

if(!isset($_POST['submit']))
form();



switch($_POST['mon'])
{
case 1:
if($_POST['day'] <= 20)
form("Capricorn");
else
form("Aquarius");
break;

case 2:
if($_POST['day'] <= 18)
form("Aquarius");
else
form("Pisces");
break;

case 3:
if($_POST['day'] <= 20)
form("Pisces");
else
form("Aries");
break;

case 4:
if($_POST['day'] <= 20)
form("Aries");
else
form("Taurus");
break;

case 5:
if($_POST['day'] <= 21)
form("Taurus");
else
form("Gemini");
break;

case 6:
if($_POST['day'] <= 21)
form("Gemini");
else
form("Cancer");
break;

case 7:
if($_POST['day'] <= 23)
form("Cancer");
else
form("Leo");
break;

case 8:
if($_POST['day'] <= 23)
form("Leo");
else
form("Virgo");
break;

case 9:
if($_POST['day'] <= 23)
form("Virgo");
else
form("Libra");
break;

case 10:
if($_POST['day'] <= 23)
form("Libra");
else
form("Scorpio");
break;

case 11:
if($_POST['day'] <= 22)
form("Scorpio");
else
form("Sagittarius");
break;

case 12:
if($_POST['day'] <= 21)
form("Sagittarius");
else
form("Capricorn");
break;

default:
form("??");
}


function form($text="")
{
echo $text;
echo '<hr>';
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
echo 'Month: <select name="mon">';
for($i=1; $i<=12; $i++)
echo '<option value="'.$i.'">'.$i.'</option>';
echo '</select><br>';
echo 'Day: <select name="day">';
for($i=1; $i<=31; $i++)
echo '<option value="'.$i.'">'.$i.'</option>';
echo '</select>';
echo '<br><br><input type="submit" value="Zodiac me!" name="submit">';
echo '</form>';
echo '<hr>';
die();
}

?>[/code]

You can test it [url=http://www.oriosriddle.com/zodiac.php]over here[/url].

[hr]

[b][u]Next challenge[/u]:[/b]
I dont know if this is too hard so there's a second challenge that is easier:
1) Make a script that will take a picture and show it using colorful # (every pixel will be "replaced" by a # in the pixel's color). Some kind of image to ASCII converter.
2) If number 1 is too hard, make a function that recieves a string and prints the string with it's prime positioned letters in bold (Example- "Hello World!" Will become "[b]Hel[/b]l[b]o[/b] [b]W[/b]orl[b]d[/b]!" Becuase the bolded letters are in positions 1,2,3,5,7,11).

Good luck.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-145037
Share on other sites

here is my example: http://viplyrics.com/webdeveloper/image_to_ascii.php

Here is my code:
[code]<html>
<head>
<title>Ascii</title>
<style>
body{
line-height:12px;
font-size:15px;
}
</style>
</head>
<body>
<?php
function getext($filename) {
$pos = strrpos($filename,'.');
$str = substr($filename, $pos);
return $str;
}
if(!isset($_POST['submit'])){
?>
<form action="<?echo $_SERVER['PHP_SELF'];?>" method="post">
JPG img URL: <input type="text" name="image"><br>
<input type="submit" name="submit" value="Create">
</form>
<?php
}else{
$ext = getext($image);
if($ext == ".jpg"){
$img = ImageCreateFromJpeg($image);
}
else if($ext == ".gif"){
$img = ImageCreateFromGif($image);
}
$width = imagesx($img);
$height = imagesy($img);

for($h=1;$h<$height;$h++){
for($w=1;$w<=$width;$w++){
$rgb = ImageColorAt($img, $w, $h);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
echo '<span style="color:rgb('.$r.','.$g.','.$b.');">#</span>';
if($w == $width){
echo '<br>';
}
}
}
}
?>
</body>
</html>[/code]

Here is the next challenge:

Lets take this one step further, and instead of using just # use different symbols, one for light areas of the image, one for dark areas of the image, and others for in between areas, the end result must be an all black colored image, no color at all... just the symbols to emphisize the different shades.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-145258
Share on other sites

This doesnt work for me. Sometimes it gives me an error and sometimes it's just displays the form...
My version, with both color and black-white:
[code]<?php
echo "<html><head><title>Image to ASCII converter</title></head>";
if(!isset($_POST['submit']))
{
?>
<form enctype="multipart/form-data" action="<?php echo basename($_SERVER['PHP_SELF']); ?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file: <input name="uploadedfile" type="file" /><br>
(file must be gif/jpg/png, 400x400 maximum)<br><input type="checkbox" name="blk"> Do in black and white<br><br>
<input type="submit" value="Upload File" name="submit" />
</form>
<?php
die();
}

$allowed_ext = array("jpg", "jpeg", "gif", "png");

//rand name for tmp upload
$upload_path = "tmp/".time().rand(10,99).$_FILES['uploadedfile']['name'];

//check if file is not too big
if($_FILES['uploadedfile']['size'] > 1048576)
die("Image too big- 1 mega max please");

$filename = $upload_path;
$ext = strtolower(substr(strrchr($filename,"."),1));

//prevent hacker attacks
if(!in_array($ext, $allowed_ext))
die("Invalid image type!");

//upload the file temporarly
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload_path))
die("An error occured. Please retry.");

//create image resource by extenstion
if($ext == "gif")
$image = @imagecreatefromgif($filename);
elseif($ext == "jpg" || $ext == "jpeg")
$image = @imagecreatefromjpeg($filename);
elseif($ext == "png")
$image = @imagecreatefrompng($filename);
else
die("Invalid image type");

//delete temporary file
unlink($upload_path);


//If image is ok, display it with ASCII art.
if($image != "")
{
$width = imagesx($image);
$height = imagesy($image);
if($height > 400 || $width > 400)
die("Image too big! Height and width must be under 400x400!");

//color
if(!isset($_POST['blk']))
{
echo "<body bgcolor=\"black\"><center><pre style=\"font: 2px/1px Arial;\">";
for($y = 0; $y < $height; $y++)
{
for($x = 0; $x < $width; $x++)
{
$thiscol = imagecolorat($image, $x, $y);
$rgb = imagecolorsforindex($image, $thiscol);
$hex = sprintf("#%2X%2X%2X",$rgb['red'],$rgb['green'],$rgb['blue']);
echo "<font color=\"".$hex."\">#</font>";
}
echo "\n";
}
}
//black and white
else
{
$asciichars = array("#","@","+","*",";",":",",",".","'"," ");
echo "<body bgcolor=\"white\"><center><pre style=\"font: 1px/1px Courier New;\">";
for($y = 0; $y < $height; $y++)
{
for($x = 0; $x < $width; $x++)
{
$thiscol = imagecolorat($image, $x, $y);
$rgb = imagecolorsforindex($image, $thiscol);
$brightness = round(($rgb['red']+$rgb['green']+$rgb['blue']) / 85);
echo $asciichars[$brightness];
}
echo "\n";
}
}
imagedestroy($image);
echo "</pre></center></body>";
}
else
echo "Broken Image- Make sure the pic is ok";

?>[/code]

You can test it [url=http://www.oriosriddle.com/tools/img2ascii.php]here[/url].

I think this is becoming to hard. Back to the second challenge I offered:
Make a function that recieves a string and prints the string with it's prime positioned letters in bold (Example- "Hello World!" Will become "Hello World!" Becuase the bolded letters are in positions 1,2,3,5,7,11).

Good luck.

Orio.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-145344
Share on other sites

[quote author=The Little Guy link=topic=119299.msg488996#msg488996 date=1166632935]
Lets take this one step further, and instead of using just # use different symbols, one for light areas of the image, one for dark areas of the image, and others for in between areas, the end result must be an all black colored image, no color at all... just the symbols to emphisize the different shades.
[/quote]

i stoled your code and made a few rough mods to it :

I also limited the dimension to 100x50 in this code, so it will truncate larger pictures.
[code]
<html>
<head>
<title>Ascii</title>
<style>
body{
line-height:12px;
font-size:15px;
}
</style>
</head>
<body>
<?php
// array of symbols to use, from "darkest" to "lightest"
$symbols = array('#','@','8','O','o',':','.',' ');

function getext($filename) {
$pos = strrpos($filename,'.');
$str = substr($filename, $pos);
return $str;
}
if(!isset($_POST['submit'])){
?>
<form action="<?echo $_SERVER['PHP_SELF'];?>" method="post">
JPG img URL: <input type="text" name="image"><br>
<input type="submit" name="submit" value="Create">
</form>
<?php
}else{
 
$image = $_POST['image'];
$ext = getext($image);
if($ext == ".jpg"){
$img = ImageCreateFromJpeg($image);
}
else if($ext == ".gif"){
$img = ImageCreateFromGif($image);
}
$width = 100; //imagesx($img);
$height = 50; //imagesy($img);
echo "<table cellspacing='0' cellpadding='0'><tr>";
for($h=0;$h<=$height;$h++){
for($w=0;$w<=$width;$w++){
$rgb = ImageColorAt($img, $w, $h);
  $r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
     
// find out the average from the rgb values
$shade = round(($r+$g+$b) / 3);
// use the # of symbols to find out range they have
      $range = 256/(count($symbols)-1);
// divide the average by the range to find out what
// position in the symbols element to use
$pos = round($shade/$range);
// assign symbol to variable
$symbol = $symbols[$pos];
// echo symbol
      echo "<td><center><font size = '1'>$symbol</font></center></td>";
if($w == $width){
echo '</tr>';
}
}
}
}
echo "</table>";
?>
</body>
</html>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-145424
Share on other sites

[code]<?php
  function is_prime($num) {
    if ($num === 0) return FALSE;
    for ($i = 2, $root = (int)sqrt($num); $i <= $root; $i++) if (($num % $i) === 0) return FALSE;
    return TRUE;
    }

  function print_primes_bold($text) {
    $text = (string)$text;
    for ($i = 0, $text_len = strlen($text); $i < $text_len; $i++) {
      if (is_prime($i)) echo "<b>{$text[$i]}</b>";
      else echo $text[$i];
      }
    }
  ?>[/code]

Next challenge: Write a script that takes a date (Day, Month, Year) and then tells the user what day of the week it is (i.e., Sunday, Monday, Tuesday, etc.). (Hint: Set a seed date/day-of-week combination and then find the offset of the entered date)
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146240
Share on other sites

This isn't quite what you were looking for, I'm sure, but here it is. :) It requires the calendar extension.

[code]<?php
function getDayOfWeek($day, $month, $year)
{
    return JDDayOfWeek(cal_to_jd(CAL_GREGORIAN, $month, $day, $year), 1);
}
?>[/code]

And for the next challenge: Create a function that takes a phrase, paragraph, what-have-you, and mixes up the letters in each of the words, except leaves the first and last letters untouched. This is to illustrate that the mind doesn't read the whole word. Rather, it just scans over them, and as long as the first and last letters are left alone, you can read the phrase with little or no trouble.

In exemplum: "This is a simple test to see if your brain can read this correctly." turns into something like "Tihs is a sipmle tset to see if yuor brian can raed this croctlrey."
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146259
Share on other sites

Here you go:
[code]<?php
/**
* Mix up letters
*
* This function mix up the letters in words except the first and last one.
* This is to illustrate that the brain does not read the whole word as you
* should be able to read the sentence disregardless of the middle characters'
* positions.
*
* Note: There may be no punctation in the sentence.
*
* @author Daniel Egeberg
* @param str $str The sentence
* @return str
*/
function mix_up_letters($str)
{
$words = explode(' ',$str);

foreach($words as $key => $word)
{
if(strlen($word)>2)
{
$words[$key] = substr($word,0,1).str_shuffle(substr($word,1,-1)).substr($word,-1);
}
}

return join(' ',$words);
}

echo mix_up_letters("This is an example of a script that mixes up the middle letters in a sentence");
// Example output: Tihs is an ealxmpe of a sicprt taht miexs up the mdidle ltetres in a sneetcne
?>[/code]

Next challenge:
Make a function that will convert hexadecimal color codes to RGB and vice versa.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146314
Share on other sites

[code]<?php
/**
* Converts a hexadecimal color code to a color in R, G, B format.
*
* @param mixed $colorCode The hexadecimal color code to be converted.
* @access public
* @return string The color in R, G, B format.
*/
function hexToRGB($colorCode)
{
    $red = substr($colorCode, 0, 2);
    $green = substr($colorCode, 2, 2);
    $blue = substr($colorCode, 4, 2);

    return hexdec($red).", ".hexdec($green).", ".hexdec($blue);
}

/**
* Converts a color in R, G, B form to hexadecimal color code.
*
* @param int $red The red component of the color.
* @param int $green The green component of the color.
* @param int $blue The blue component of the color.
* @access public
* @return string
*/
function RGBToHex($red, $green, $blue)
{
    $red = $red == 0 ? "00" : dechex($red);
    $green = $green == 0 ? "00" : dechex($green);
    $blue = $blue == 0 ? "00" : dechex($blue);

    return $red.$green.$blue;
}

echo hexToRGB("FFOOFF");
// returns "255, 0, 255"

echo RGBToHex(255, 0, 255);
//returns "ff00ff"

?>[/code]

[b]Next challenge: [/b] Think up a challenge. I've got nothin'.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146440
Share on other sites

Well since I was at work and didn't have time to finish my hex class ... how about this:

write a function to decrpyt md5......


JK!

Write a function that will spider through a directory and ftp that directory to a remote location and chmod it for bonus points.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146455
Share on other sites

[code]<?php

function ftp_dir($ftp_stream, $dir, $rmode=0755, $tmode=FTP_BINARY) {
  // ftp_stream is...the ftp stream (i.e., the resource returned by ftp_connect)
  // dir is the directory to upload
  // rmode is the read mode (like the values you set when using chmod)
  // tmode is the transfer mode (FTP_ASCII or FTP_BINARY only)
  if ((!is_dir($dir)) || (($tmode !== FTP_ASCII) && ($tmode !== FTP_BINARY))) return FALSE;
  if (!@ftp_chdir($ftp_stream, $dir)) {
    if (!@ftp_mkdir($ftp_stream, $dir)) return FALSE;
    ftp_chdir($ftp_stream, $dir);
    }
  $rmode = intval($rmode, 8);
  $dir_files = scandir($dir);
  for ($i = 2, $dir_size = sizeof($dir_files); $i < $dir_size; $i++) {
    ftp_put($ftp_stream, $dir_files[$i], $dir . "/" . $dir_files[$i], $tmode);
    ftp_chmod($ftp_stream, $rmode, $dir_files[$i]);
    }
  return TRUE;
  }

?>[/code]

It can't be so hard if I can figure it out! :P

[b][EDIT:][/b]

2 posts while I figured it out but still...

Hmmm....totally n00b'd right here. Can someone please help me figure out why I can't delete these files...? :o (I'm not that familiar with read permissions so I may have set them wrong (0755)...but....)

[i]Modified version of the above:[/i]

[code]<?php

function ftp_dir($ftp_stream, $dir, $rmode=0755, $tmode=FTP_BINARY, $ormode=array(), $otmode=array()) {
  if ((!is_dir($dir)) || (($tmode !== FTP_ASCII) && ($tmode !== FTP_BINARY)) || (!is_array($ormode)) ||
  (!is_array($otmode))) return FALSE;
  if (!@ftp_chdir($ftp_stream, $dir)) {
    if (!@ftp_mkdir($ftp_stream, $dir)) return FALSE;
    ftp_chdir($ftp_stream, $dir);
    }
  $rmode = intval($rmode, 8);
  $dir_files = scandir($dir);
  for ($i = 2, $dir_size = sizeof($dir_files); $i < $dir_size; $i++) {
    if (isset($ormode[$dir_files[$i]])) $ormode[$i] = $ormode[$dir_files[$i]];
    if (isset($otmode[$dir_files[$i]])) $otmode[$i] = $otmode[$dir_files[$i]];
    if ((isset($otmode[$i])) && (($otmode[$i] !== FTP_BINARY) && ($otmode[$i] !== FTP_ASCII))) $otmode[$i] = $tmode;
    ftp_put($ftp_stream, $dir_files[$i], "./" . $dir . "/" . $dir_files[$i], (isset($otmode[$i]) ? $otmode[$i] : $tmode));
    ftp_chmod($ftp_stream, (isset($ormode[$i]) ? intval($ormode[$i], 8) : $rmode), $dir_files[$i]);
    }
  return TRUE;
  }

?>[/code]

I've added two optional parameters, [color=green]$ormode[/color] and [color=green]$otmode[/color]. Both are arrays designed to override the [color=green]$rmode[/color] and [color=green]$tmode[/color] parameters respectively. That way you can set file permissions/transfer mode on a file-per-file basis.

[code]<?php

$conn = @ftp_connect($host);
if ((!$conn) || (!@ftp_login($conn, $user, $pass))) die("Error connecting to FTP.");
ftp_dir($conn, $dir, 0755, FTP_BINARY, array("robots.txt" => 0600), array("robots.txt" => FTP_ASCII)) or die("Error uploading directory."); // uploads all files in DIR in FTP_BINARY mode and CHMODs them to mode 0755 EXCEPT robots.txt which is uploaded in FTP_ASCII mode and CHMODed to mode 0600
ftp_close($conn);

?>[/code]

[b]Next Challenge:[/b] Do that thing that makeshift_theory said since I can't think of anything right now! ;)
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146592
Share on other sites

I dont get the challenge, it's just adding one line to echo the color in the bg for an example...

Here's a challenge:
Make a function that will output the first, let's say, 40 Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34 .... Google if you need an explanation about these numbers). If you can do it recursive- that's even better :)

Orio
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146610
Share on other sites

I think he was saying to do basically the same thing...but only use php/GD functions (no custom functions)...?

I'm actually working on something else right now (plus I just did the last challenge) though the Fibonacci numbers sounds fun. I could use a refresher on scripting that (I've done the same thing in C++ but it's been a while). :)
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146613
Share on other sites

[code]<?php
  function fib($which) {
    static $fibs = array();
    $which = intval($which);
    if (isset($fibs[$which])) return $fibs[$which];
    $neg = (($which < 0) && (($which % 2) === 0));
    if ($which < 0) $which *= -1;
    if (($which === 0) || ($which === 1)) return $which;
    $rval = fib($which - 2) + fib($which - 1);
    $rval = ($neg ? $rval * -1 : $rval);
    $fibs[($neg ? $which * -1 : $which)] = $rval;
    return $rval;
    }

  for ($i = 0; $i < 40; $i++) echo fib($i) . (($i % 10) === 0 ? "<br />" : " ");
  ?>[/code]

At 40 levels of recursion this was starting to run extremely slowly...timing out in fact...storing the previously called Fibonacci numbers in a static array sped it up immensely.

[b]Next Challenge:[/b] I want to see someone write a function to get the day of the week without using any calendar functions. Basically I want a form where I can enter any date and it will tell me the day of the week.

If requesting the same thing again seems drab or whatever anybody who feels compelled to set a different challenge feel free. This is just something I'd like to see someone work out in PHP (without using those dreadful extensions that do all the work for them :P).
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146737
Share on other sites

You're asking someone to write a script that uses the mysql_connect function? Or what are you asking?

[b][EDIT:][/b]

You do of course realize that I was joking about "the dreadful extensions"? I just wanted to see if anyone would actually take the time to work it out without these pre-built functions.
Link to comment
https://forums.phpfreaks.com/topic/31283-the-php-challenge/#findComment-146782
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.