The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number, then it sums every other odd digit to form a partial sum (s1). For the even digits, it multiplies each by two and sums the digits if the result is greater than nine to form another partial sum (s2). If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The code tests this functionality with the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670.


<?php //Josephus.php
function Jotapata($n=41,$k=3,$m=1){$m--;
	$prisoners=array_fill(0,$n,false);//make a circle of n prisoners, store false ie: dead=false
	$deadpool=1;//count to next execution
	$order=0;//death order and *dead* flag, ie. deadpool
	while((array_sum(array_count_values($prisoners))<$n)){//while sum of count of unique values dead times < n (they start as all false)
		foreach($prisoners as $thisPrisoner=>$dead){
			if(!$dead){//so yeah...if not dead...
				if($deadpool==$k){//if their time is up in the deadpool...
					$order++;
					//set the deadpool value or enumerate as survivor
					$prisoners[$thisPrisoner]=((($n-$m)>($order)?$order:(($n)==$order?'Call me *Titus Flavius* Josephus':'Joe\'s friend '.(($order)-($n-$m-1)))));
					$deadpool=1;//reset count to next execution
				}else{$duckpool++;}
			}
		}
	}
	return $prisoners;
}
echo '<pre>'.print_r(Jotapata(41,3,5),true).'<pre>';

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is "ha" and 5, the output will be "hahahahaha". Similarly, if the input is "*" and 5, the output will be "*****".


Works with: PHP version 5.2.0
$string = 'I am a string';
# Test
if (preg_match('/string$/', $string))
{
    echo "Ends with 'string'\n";
}
# Replace
$string = preg_replace('/\ba\b/', 'another', $string);
echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";

"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression."


<?php
$a = fgets(STDIN);
$b = fgets(STDIN);

echo
    "sum:                 ", $a + $b, "\n",
    "difference:          ", $a - $b, "\n",
    "product:             ", $a * $b, "\n",
    "truncating quotient: ", (int)($a / $b), "\n",
    "flooring quotient:   ", floor($a / $b), "\n",
    "remainder:           ", $a % $b, "\n",
    "power:               ", $a ** $b, "\n"; // PHP 5.6+ only
?>

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


<?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


Translation of: Java
function move($n,$from,$to,$via) {
    if ($n === 1) {
        print("Move disk from pole $from to pole $to");
    } else {
        move($n-1,$from,$via,$to);
        move(1,$from,$to,$via);
        move($n-1,$via,$to,$from);
    }
}

"Implement a recursive solution to solve the Towers of Hanoi problem."


<?php
$n=5;
$k=3;
function factorial($val){
    for($f=2;$val-1>1;$f*=$val--);
    return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>

function binomial_coefficient($n, $k) {
  if ($k == 0) return 1;
  $result = 1;
  foreach (range(0, $k - 1) as $i) {
    $result *= ($n - $i) / ($i + 1);
  }
  return $result;
}

The code calculates any binomial coefficient, specifically able to output the binomial coefficient of 5 and 3, which is 10. It uses the formula for binomial coefficients and also considers combinations and permutations, both with and without replacement. The code also includes an alternative version not based on factorial.


function shellSort($arr)
{
	$inc = round(count($arr)/2);
	while($inc > 0)
	{
		for($i = $inc; $i < count($arr);$i++){
			$temp = $arr[$i];
			$j = $i;
			while($j >= $inc && $arr[$j-$inc] > $temp)
			{
				$arr[$j] = $arr[$j - $inc];
				$j -= $inc;
			}
			$arr[$j] = $temp;
		}
		$inc = round($inc/2.2);
	}
	return $arr;
}

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


class BitmapGrayscale extends Bitmap {
  public function toGrayscale(){
    for ($i = 0; $i < $this->h; $i++){
      for ($j = 0; $j < $this->w; $j++){
        $l = ($this->data[$j][$i][0] * 0.2126)
           + ($this->data[$j][$i][1] * 0.7152)
           + ($this->data[$j][$i][2] * 0.0722);
        $l = round($l);
        $this->data[$j][$i] = array($l,$l,$l);
      }
    }
  }
}

$b = new BitmapGrayscale(16,16);
$b->fill(0,0,null,null, array(255,255,0));
$b->setPixel(0, 15, array(255,0,0));
$b->setPixel(0, 14, array(0,255,0));
$b->setPixel(0, 13, array(0,0,255));
$b->toGrayscale();
$b->writeP6('p6-grayscale.ppm');

extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa using the CIE recommended formula for luminance. The code ensures no rounding errors that could cause run-time issues or distort results when storing luminance as an unsigned integer. It also uses the Bitmap class for writing a PPM file.


$val = 0;
do {
   $val++;
   print "$val\n";
} while ($val % 6 != 0);

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


<?php
foreach (array('møøse', '𝔘𝔫𝔦𝔠𝔬𝔡𝔢', 'J̲o̲s̲é̲') as $s1) {
   printf('String "%s" measured with strlen: %d mb_strlen: %s grapheme_strlen %s%s',
                  $s1, strlen($s1),mb_strlen($s1), grapheme_strlen($s1), PHP_EOL);
}

String "møøse" measured with strlen: 7 mb_strlen: 7 grapheme_strlen 5
String "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" measured with strlen: 28 mb_strlen: 28 grapheme_strlen 7
String "J̲o̲s̲é̲" measured with strlen: 13 mb_strlen: 13 grapheme_strlen 4

The code calculates the character and byte length of a string, considering UTF-8 encoding. It correctly handles non-BMP code points and provides actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes if the programming language supports it.


<?php
echo substr("knight", 1), "\n";       // strip first character
echo substr("socks", 0, -1), "\n";    // strip last character
echo substr("brooms", 1, -1), "\n";   // strip both first and last characters
?>

The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.


Translation of: C++
	class SudokuSolver {
		protected $grid = [];
		protected $emptySymbol;
		public static function parseString($str, $emptySymbol = '0')
		{
			$grid = str_split($str);
			foreach($grid as &$v)
			{
				if($v == $emptySymbol)
				{
					$v = 0;
				}
				else
				{
					$v = (int)$v;
				}
			}
			return $grid;
		}

		public function __construct($str, $emptySymbol = '0') {
			if(strlen($str) !== 81)
			{
				throw new \Exception('Error sudoku');
			}
			$this->grid = static::parseString($str, $emptySymbol);
			$this->emptySymbol = $emptySymbol;
		}

		public function solve()
		{
			try
			{
				$this->placeNumber(0);
				return false;
			}
			catch(\Exception $e)
			{
				return true;
			}
		}

		protected function placeNumber($pos)
		{
			if($pos == 81)
			{
				throw new \Exception('Finish');
			}
			if($this->grid[$pos] > 0)
			{
				$this->placeNumber($pos+1);
				return;
			}
			for($n = 1; $n <= 9; $n++)
			{
				if($this->checkValidity($n, $pos%9, floor($pos/9)))
				{
					$this->grid[$pos] = $n;
					$this->placeNumber($pos+1);
					$this->grid[$pos] = 0;
				}
			}
		}

		protected function checkValidity($val, $x, $y)
		{
			for($i = 0; $i < 9; $i++)
			{
				if(($this->grid[$y*9+$i] == $val) || ($this->grid[$i*9+$x] == $val))
				{
					return false;
				}
			}
			$startX = (int) ((int)($x/3)*3);
			$startY = (int) ((int)($y/3)*3);

			for($i = $startY; $i<$startY+3;$i++)
			{
				for($j = $startX; $j<$startX+3;$j++)
				{
					if($this->grid[$i*9+$j] == $val)
					{
						return false;
					}
				}
			}
			return true;
		}

		public function display() {
			$str = '';
			for($i = 0; $i<9; $i++)
			{
				for($j = 0; $j<9;$j++)
				{
					$str .= $this->grid[$i*9+$j];
					$str .= " ";
					if($j == 2 || $j == 5)
					{
						$str .= "| ";
					}
				}
				$str .= PHP_EOL;
				if($i == 2 || $i == 5)
				{
					$str .=  "------+-------+------".PHP_EOL;
				}
			}
			echo $str;
		}

		public function __toString() {
			foreach ($this->grid as &$item)
			{
				if($item == 0)
				{
					$item = $this->emptySymbol;
				}
			}
			return implode('', $this->grid);
		}
	}
	$solver = new SudokuSolver('009170000020600001800200000200006053000051009005040080040000700006000320700003900');
	$solver->solve();
	$solver->display();

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


//The Fisher-Yates original Method
function yates_shuffle($arr){
	$shuffled = Array();
	while($arr){
		$rnd = array_rand($arr);
		$shuffled[] = $arr[$rnd];
		array_splice($arr, $rnd, 1);
	}
	return $shuffled;
}

//The modern Durstenfeld-Knuth algorithm
function knuth_shuffle(&$arr){
	for($i=count($arr)-1;$i>0;$i--){
		$rnd = mt_rand(0,$i);
		list($arr[$i], $arr[$rnd]) = array($arr[$rnd], $arr[$i]);
	}
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


<?php
function last_friday_of_month($year, $month) {
  $day = 0;
  while(True) {
    $last_day = mktime(0, 0, 0, $month+1, $day, $year);
    if (date("w", $last_day) == 5) {
      return date("Y-m-d", $last_day);
    }
    $day -= 1;
  }
}

function print_last_fridays_of_month($year) {
  foreach(range(1, 12) as $month) {
    echo last_friday_of_month($year, $month), "<br>";
  }
}

date_default_timezone_set("GMT");
$year = 2012;
print_last_fridays_of_month($year);
?>

The code takes a year as input and returns the dates of the last Fridays of each month for that given year. The input year can be provided through any simple method like command line or standard input. The code does not include a command-line component as it is typically used for web applications in PHP.


"Display the string 'Goodbye, World!' without appending a newline at the end."


<?php
function caesarEncode( $message, $key ){
    $plaintext = strtolower( $message );
    $ciphertext = "";
    $ascii_a = ord( 'a' );
    $ascii_z = ord( 'z' );
    while( strlen( $plaintext ) ){
        $char = ord( $plaintext );
        if( $char >= $ascii_a && $char <= $ascii_z ){
            $char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a;
        }
        $plaintext = substr( $plaintext, 1 );
        $ciphertext .= chr( $char );
    }
    return $ciphertext;
}

echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?>

implement a Caesar cipher for both encoding and decoding. The cipher rotates the alphabet letters based on a key ranging from 1 to 25. It replaces each letter with the next 1st to 25th letter in the alphabet, wrapping Z to A. The key 2 encrypts "HI" to "JK", while key 20 encrypts "HI" to "BC". The code also highlights that this cipher provides minimal security as the encoded message can be easily decrypted. It also mentions that the Caesar cipher is identical to the Vigenère cipher with a key length of 1 and to the Rot-13 with a key of 13. The PHP's strtr() function is used in the implementation.


Translation of: D
echo lcm(12, 18) == 36;

function lcm($m, $n) {
    if ($m == 0 || $n == 0) return 0;
    $r = ($m * $n) / gcd($m, $n);
    return abs($r);
}

function gcd($a, $b) {
    while ($b != 0) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


function IsCusip(string $s) {
    if (strlen($s) != 9) return false;
    $sum = 0;
    for ($i = 0; $i <= 7; $i++) {
        $c = $s[$i];
        if (ctype_digit($c)) {
            // if character is numeric, get character's numeric value
            $v = intval($c);
        } elseif (ctype_alpha($c)) {
            // if character is alphabetic, get character's ordinal position in alphabet
            $position = ord(strtoupper($c)) - ord('A') + 1;
            $v = $position + 9;
        } elseif ($c == "*") {
            $v = 36;
        } elseif ($c == "@") {
            $v = 37;
        } elseif ($c == "#") {
            $v = 38;
        } else {
            return false;
        }
        // is this character position even?
        if ($i % 2 == 1) {
            $v *= 2;
        }
        // calculate the checksum digit
        $sum += floor($v / 10 ) + ( $v % 10 );
    }
    return ord($s[8]) - 48 == (10 - ($sum % 10)) % 10;
}

$cusips = array("037833100",
                "17275R102",
                "38259P508",
                "594918104",
                "68389X106",
                "68389X105");

foreach ($cusips as $cusip) echo $cusip . " -> " . (IsCusip($cusip) ? "valid" : "invalid") . "\n";

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


foreach ($collect as $i) {
   echo "$i\n";
}

foreach ($collect as $key => $i) {
   echo "\$collect[$key] = $i\n";
}

Iterates over each element in a collection in sequence using a "for each" loop or an alternative loop if "for each" is not available. It can also iterate over all visible fields of an object.


Works with: PHP version 5.x
<?php
$str = 'Hello,How,Are,You,Today';
echo implode('.', explode(',', $str));
?>

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


Iterative[edit]
function gcdIter($n, $m) {
    while(true) {
        if($n == $m) {
            return $m;
        }
        if($n > $m) {
            $n -= $m;
        } else {
            $m -= $n;
        }
    }
}
Recursive[edit]
function gcdRec($n, $m)
{
    if($m > 0)
        return gcdRec($m, $n % $m);
    else
        return abs($n);
}

calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.


$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket, '127.0.0.1', 12321);
socket_listen($socket);

$client_count = 0;
while (true){
  if (($client = socket_accept($socket)) === false) continue;
  $client_count++;

  $client_name = 'Unknown';
  socket_getpeername($client, $client_name);
  echo "Client {$client_count} ({$client_name}) connected\n";
  $pid = pcntl_fork();
  if($pid == -1) die('Could not fork');
  if($pid){
    pcntl_waitpid(-1, $status, WNOHANG);
    continue;
  }

  //In a child process
  while(true){
    if($input = socket_read($client, 1024)){
      socket_write($client, $input);
    } else {
      socket_shutdown($client);
      socket_close($client);
      echo "Client {$client_count} ({$client_name}) disconnected\n";
      exit();
    }
  }
}

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


<?php
$string = '123';
if(is_numeric(trim($string))) {
}
?>

"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax."


Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


$radians = M_PI / 4;
$degrees = 45 * M_PI / 180;
echo sin($radians) . " " . sin($degrees);
echo cos($radians) . " " . cos($degrees);
echo tan($radians) . " " . tan($degrees);
echo asin(sin($radians)) . " " . asin(sin($radians)) * 180 / M_PI;
echo acos(cos($radians)) . " " . acos(cos($radians)) * 180 / M_PI;
echo atan(tan($radians)) . " " . atan(tan($radians)) * 180 / M_PI;

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


Translation of: Perl
<?php
declare(ticks = 1);

$start = microtime(true);

function mySigHandler() {
  global $start;
  $elapsed = microtime(true) - $start;
  echo "Ran for $elapsed seconds.\n";
  exit();
}

pcntl_signal(SIGINT, 'mySigHandler');

for ($n = 0; ; usleep(500000)) // 0.5 seconds
   echo ++$n, "\n";
?>

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


<?php

/*
 This works with dirs and files in any number of combinations.
*/

function _commonPath($dirList)
{
	$arr = array();
	foreach($dirList as $i => $path)
	{
		$dirList[$i]	= explode('/', $path);
		unset($dirList[$i][0]);

		$arr[$i] = count($dirList[$i]);
	}

	$min = min($arr);

	for($i = 0; $i < count($dirList); $i++)
	{
		while(count($dirList[$i]) > $min)
		{
			array_pop($dirList[$i]);
		}

		$dirList[$i] = '/' . implode('/' , $dirList[$i]);
	}

	$dirList = array_unique($dirList);
	while(count($dirList) !== 1)
	{
		$dirList = array_map('dirname', $dirList);
		$dirList = array_unique($dirList);
	}
	reset($dirList);

	return current($dirList);
}

 /* TEST */

$dirs = array(
 '/home/user1/tmp/coverage/test',
 '/home/user1/tmp/covert/operator',
 '/home/user1/tmp/coven/members',
);

if('/home/user1/tmp' !== common_path($dirs))
{
  echo 'test fail';
} else {
  echo 'test success';
}

?>

<?php

/* A more compact string-only version, which I assume would be much faster */
/* If you want the trailing /, return $common; */

function getCommonPath($paths) {
	$lastOffset = 1;
	$common = '/';
	while (($index = strpos($paths[0], '/', $lastOffset)) !== FALSE) {
		$dirLen = $index - $lastOffset + 1;	// include /
		$dir = substr($paths[0], $lastOffset, $dirLen);
		foreach ($paths as $path) {
			if (substr($path, $lastOffset, $dirLen) != $dir)
				return $common;
		}
		$common .= $dir;
		$lastOffset = $index + 1;
	}
	return substr($common, 0, -1);
}

?>

"Output: The code creates a routine that finds the common directory path from a set of given directory paths using a specified directory separator character. It has been tested with '/' as the directory separator and three specific strings as input paths. The routine returns the valid common directory, not the longest common string."


function sattoloCycle($items) {
   for ($i = 0; $i < count($items); $i++) {
        $j = floor((mt_rand() / mt_getrandmax()) * $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
    return $items;
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


Works with: PHP version 5.0.0+
<?php
//load the wsdl file
$client = new SoapClient("http://example.com/soap/definition.wsdl");
//functions are now available to be called
$result = $client->soapFunc("hello");
$result = $client->anotherSoapFunc(34234);

//SOAP Information
$client = new SoapClient("http://example.com/soap/definition.wsdl");
//list of SOAP types
print_r($client->__getTypes());
//list if SOAP Functions
print_r($client->__getFunctions());
?>

The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http://example.com/soap/wsdl. Note, the task and corresponding code may require further clarification.


function median($arr)
{
    sort($arr);
    $count = count($arr); //count the number of values in array
    $middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
    if ($count % 2) { // odd number, middle is the median
        $median = $arr[$middleval];
    } else { // even number, calculate avg of 2 medians
        $low = $arr[$middleval];
        $high = $arr[$middleval+1];
        $median = (($low+$high)/2);
    }
    return $median;
}

echo median(array(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n";  // 4.4
echo median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . "\n";       // 4.25

"Output: The code calculates the median value of a vector of floating-point numbers. It handles cases with an even number of elements by returning the average of the two middle values. The code uses the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The median calculation uses a sorting method."


if/else ladder approach[edit]
<?php
for ($i = 1; $i <= 100; $i++)
{
    if (!($i % 15))
        echo "FizzBuzz\n";
    else if (!($i % 3))
        echo "Fizz\n";
    else if (!($i % 5))
        echo "Buzz\n";
    else
        echo "$i\n";
}
?>
Concatenation approach[edit]

<?php
for ( $i = 1; $i <= 100; ++$i )
{
     $str = "";

     if (!($i % 3 ) )
          $str .= "Fizz";

     if (!($i % 5 ) )
          $str .= "Buzz";

     if ( empty( $str ) )
          $str = $i;

     echo $str . "\n";
}
?>
Concatenation approach without if-s[edit]
<?php
for (
    $i = 0;
    $i++ < 100;
    $o = ($i % 3 ? '' : 'Fizz') . ($i % 5 ? '' : 'Buzz')
)
    echo $o ? : $i, PHP_EOL;
?>
One Liner Approach[edit]
<?php
for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i);
?>
Compact One Liner Approach[edit]
for($i=0;$i++<100;)echo($i%3?'':'Fizz').($i%5?'':'Buzz')?:$i,"\n";
Array One Liner Approach[edit]
for($i = 0; $i++ < 100;) echo [$i, 'Fizz', 'Buzz', 'FizzBuzz'][!($i % 3) + 2 * !($i % 5)], "\n";

The code prints integers from 1 to 100. For multiples of three, it prints 'Fizz' and for multiples of five, it prints 'Buzz'. For numbers that are multiples of both three and five, it prints 'FizzBuzz'. It uses PHP's concatenation operator to build the output string, appending 'Buzz' to 'Fizz' when necessary. It avoids checking if a number is divisible by both 3 and 5 by resetting the string to an empty string when necessary and includes a separate check to see if the string is empty, indicating the number was not divisible by 3 or 5.


Library: GD Graphics Library
Works with: PHP version 5.3.5
Sample output
$min_x=-2;
$max_x=1;
$min_y=-1;
$max_y=1;

$dim_x=400;
$dim_y=300;

$im = @imagecreate($dim_x, $dim_y)
  or die("Cannot Initialize new GD image stream");
header("Content-Type: image/png");
$black_color = imagecolorallocate($im, 0, 0, 0);
$white_color = imagecolorallocate($im, 255, 255, 255);

for($y=0;$y<=$dim_y;$y++) {
  for($x=0;$x<=$dim_x;$x++) {
    $c1=$min_x+($max_x-$min_x)/$dim_x*$x;
    $c2=$min_y+($max_y-$min_y)/$dim_y*$y;

    $z1=0;
    $z2=0;

    for($i=0;$i<100;$i++) {
      $new1=$z1*$z1-$z2*$z2+$c1;
      $new2=2*$z1*$z2+$c2;
      $z1=$new1;
      $z2=$new2;
      if($z1*$z1+$z2*$z2>=4) {
        break;
      }
    }
    if($i<100) {
      imagesetpixel ($im, $x, $y, $white_color);
    }
  }
}

imagepng($im);
imagedestroy($im);

generate and draw the Mandelbrot set using various available algorithms and functions.


$array = array(1,2,3,4,5,6,7,8,9);
echo array_sum($array);
echo array_product($array);

Calculate the sum and product of all integers in an array.


<?php
function isLeapYear($year) {
    if ($year % 100 == 0) {
        return ($year % 400 == 0);
    }
    return ($year % 4 == 0);
}

<?php
function isLeapYear($year) {
    return (date('L', mktime(0, 0, 0, 2, 1, $year)) === '1')
}

"Determines if a given year is a leap year in the Gregorian calendar using date('L')."


<?php

$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
    for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
        $fire = 12 - $police - $sanitation;
        if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
            echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
            $valid++;
        }
    }
}
echo $valid, ' valid combinations found.', PHP_EOL;

all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.


"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable."


<?php
function F($n)
{
  if ( $n == 0 ) return 1;
  return $n - M(F($n-1));
}

function M($n)
{
  if ( $n == 0) return 0;
  return $n - F(M($n-1));
}

$ra = array();
$rb = array();
for($i=0; $i < 20; $i++)
{
  array_push($ra, F($i));
  array_push($rb, M($i));
}
echo implode(" ", $ra) . "\n";
echo implode(" ", $rb) . "\n";
?>

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.


$arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];

demonstrate how to select a random element from a list.


<?php
$encoded = "http%3A%2F%2Ffoo%20bar%2F";
$unencoded = rawurldecode($encoded);
echo "The unencoded string is $unencoded !\n";
?>

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


function binary_search( $array, $secret, $start, $end )
{
        do
        {
                $guess = (int)($start + ( ( $end - $start ) / 2 ));

                if ( $array[$guess] > $secret )
                        $end = $guess;

                if ( $array[$guess] < $secret )
                        $start = $guess;

                if ( $end < $start)
                        return -1;

        } while ( $array[$guess] != $secret );

        return $guess;
}

function binary_search( $array, $secret, $start, $end )
{
        $guess = (int)($start + ( ( $end - $start ) / 2 ));

        if ( $end < $start)
                return -1;

        if ( $array[$guess] > $secret )
                return (binary_search( $array, $secret, $start, $guess ));

        if ( $array[$guess] < $secret )
                return (binary_search( $array, $secret, $guess, $end ) );

        return $guess;
}

Implement a binary search algorithm that divides a range of values into halves until it finds the target value. The algorithm can be implemented both recursively and iteratively. It also handles multiple equal values and returns the index of the target value if found, or the index where it would be inserted if not found. The code also includes variations for finding the leftmost and rightmost insertion points. It ensures no overflow bugs occur during the calculation of the mid-point.


<?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);

are designed to retrieve the list of command-line arguments provided to the program. The arguments are stored in the special variables $argv and $argc, which represent the array of arguments and the number of arguments respectively. The program name is passed as the first argument. The code also includes an example command line for reference. For intelligent parsing of these arguments, additional functionality is referenced.


<?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON."


Implement the principal nth root algorithm for a positive real number A.


echo $_SERVER['HTTP_HOST'];

echo php_uname('n');

Works with: PHP version 5.3+
echo gethostname();

"Determines and outputs the hostname of the current system where the routine is running."


Translation of: Perl
#!/usr/bin/env php
The 24 Game

Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.

An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24

Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

<?php

while (true) {
    $numbers = make_numbers();

    for ($iteration_num = 1; ; $iteration_num++) {
        echo "Expresion $iteration_num: ";

        $entry = rtrim(fgets(STDIN));

        if ($entry === '!') break;
        if ($entry === 'q') exit;

        $result = play($numbers, $entry);

        if ($result === null) {
            echo "That's not valid\n";
            continue;
        }
        elseif ($result != 24) {
            echo "Sorry, that's $result\n";
            continue;
        }
        else {
            echo "That's right! 24!!\n";
            exit;
        }
    }
}

function make_numbers() {
    $numbers = array();

    echo "Your four digits: ";

    for ($i = 0; $i < 4; $i++) {
        $number = rand(1, 9);
        // The check is needed to avoid E_NOTICE from PHP
        if (!isset($numbers[$number])) {
            $numbers[$number] = 0;
        }
        $numbers[$number]++;
        print "$number ";
    }

    print "\n";

    return $numbers;
}

function play($numbers, $expression) {
    $operator = true;
    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
        $character = $expression[$i];

        if (in_array($character, array('(', ')', ' ', "\t"))) continue;

        $operator = !$operator;

        if (!$operator) {
            if (!empty($numbers[$character])) {
                $numbers[$character]--;
                continue;
            }
            return;
        }
        elseif (!in_array($character, array('+', '-', '*', '/'))) {
            return;
        }
    }

    foreach ($numbers as $remaining) {
        if ($remaining > 0) {
            return;
        }
    }

    return eval("return $expression;");
}
?>

"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits."


<?php
function encode($str)
{
    return preg_replace_callback('/(.)\1*/', function ($match) {
        return strlen($match[0]) . $match[1];
    }, $str);
}

function decode($str)
{
    return preg_replace_callback('/(\d+)(\D)/', function($match) {
        return str_repeat($match[2], $match[1]);
    }, $str);
}

echo encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL;
echo decode('12W1B12W3B24W1B14W'), PHP_EOL;
?>

implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.


<?php
$s = "hello";
echo $s . " literal" . "\n";
$s1 = $s . " literal";
echo $s1 . "\n";
?>

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


<?php
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?>

"Implement a function to convert a given string into URL encoding format. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code, with space character encoding as %20. Characters outside the range of 0-9, A-Z, and a-z are converted. The function also supports variations like lowercase escapes and different encoding standards like RFC 3986, HTML 5, and encodeURI in Javascript. An optional feature is the use of an exception string for symbols that don't need conversion. The function can also encode spaces as '+' signs similar to urlencode()."


/* Added by @1x24. Translated from C++. Uses the PHP 7.x spaceship operator */
$data = [
			[
				'name'=>'beef',
				'weight'=>3.8,
				'cost'=>36,
			],
			[
				'name'=>'pork',
				'weight'=>5.4,
				'cost'=>43,
			],
			[
				'name'=>'ham',
				'weight'=>3.6,
				'cost'=>90,
			],
			[
				'name'=>'greaves',
				'weight'=>2.4,
				'cost'=>45,
			],
			[
				'name'=>'flitch',
				'weight'=>4.0,
				'cost'=>30,
			],
			[
				'name'=>'brawn',
				'weight'=>2.5,
				'cost'=>56,
			],
			[
				'name'=>'welt',
				'weight'=>3.7,
				'cost'=>67,
			],
			[
				'name'=>'salami',
				'weight'=>3.0,
				'cost'=>95,
			],
			[
				'name'=>'sausage',
				'weight'=>5.9,
				'cost'=>98,
			],
		];

uasort($data, function($a, $b) {
    return ($b['cost']/$b['weight']) <=> ($a['cost']/$a['weight']);
});

$limit = 15;

foreach ($data as $item):
	if ($limit >= $item['weight']):
		echo "Take all the {$item['name']}
";
	else:
		echo "Take $limit kg of {$item['name']}
";
		break;
	endif;
	$limit -= $item['weight'];
endforeach;

Take all the salami
Take all the ham
Take all the brawn
Take all the greaves
Take 3.5 kg of welt

"Output: The code calculates the optimal combination of items a thief can carry in his knapsack, given a maximum weight limit of 15 kg. The items can be cut to fit the weight limit, with the price proportionally reduced. The goal is to maximize the total value of the items in the knapsack."


<?php
$words = explode("\n", file_get_contents('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'));
foreach ($words as $word) {
    $chars = str_split($word);
    sort($chars);
    $anagram[implode($chars)][] = $word;
}

$best = max(array_map('count', $anagram));
foreach ($anagram as $ana)
    if (count($ana) == $best)
        print_r($ana);
?>

"Code identifies sets of anagrams with the most words from the provided word list."


<?php

function isSierpinskiCarpetPixelFilled($x, $y) {
    while (($x > 0) or ($y > 0)) {
        if (($x % 3 == 1) and ($y % 3 == 1)) {
            return false;
        }
        $x /= 3;
        $y /= 3;
    }
    return true;
}

function sierpinskiCarpet($order) {
    $size = pow(3, $order);
    for ($y = 0 ; $y < $size ; $y++) {
        for ($x = 0 ; $x < $size ; $x++) {
            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';
        }
        echo PHP_EOL;
    }
}

for ($order = 0 ; $order <= 3 ; $order++) {
    echo 'N=', $order, PHP_EOL;
    sierpinskiCarpet($order);
    echo PHP_EOL;
}

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.


Works with: PHP version 5.3+
Translation of: Python (not exactly)
<?php
function encode($symb2freq) {
    $heap = new SplPriorityQueue;
    $heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
    foreach ($symb2freq as $sym => $wt)
        $heap->insert(array($sym => ''), -$wt);

    while ($heap->count() > 1) {
        $lo = $heap->extract();
        $hi = $heap->extract();
        foreach ($lo['data'] as &$x)
            $x = '0'.$x;
        foreach ($hi['data'] as &$x)
            $x = '1'.$x;
        $heap->insert($lo['data'] + $hi['data'],
                      $lo['priority'] + $hi['priority']);
    }
    $result = $heap->extract();
    return $result['data'];
}

$txt = 'this is an example for huffman encoding';
$symb2freq = array_count_values(str_split($txt));
$huff = encode($symb2freq);
echo "Symbol\tWeight\tHuffman Code\n";
foreach ($huff as $sym => $code)
    echo "$sym\t$symb2freq[$sym]\t$code\n";
?>

The code generates a Huffman encoding for each character in the given string "this is an example for huffman encoding". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.


Implement a for loop that counts down from 10 to 0.


Translation of: C
<?php

$str = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
$key = "VIGENERECIPHER";

printf("Text: %s\n", $str);
printf("key:  %s\n", $key);

$cod = encipher($str, $key, true); printf("Code: %s\n", $cod);
$dec = encipher($cod, $key, false); printf("Back: %s\n", $dec);

function encipher($src, $key, $is_encode)
{
    $key = strtoupper($key);
    $src = strtoupper($src);
    $dest = '';

    /* strip out non-letters */
    for($i = 0; $i <= strlen($src); $i++) {
        $char = substr($src, $i, 1);
        if(ctype_upper($char)) {
            $dest .= $char;
        }
    }

    for($i = 0; $i <= strlen($dest); $i++) {
        $char = substr($dest, $i, 1);
        if(!ctype_upper($char)) {
            continue;
        }
        $dest = substr_replace($dest,
            chr (
                ord('A') +
                ($is_encode
                   ? ord($char) - ord('A') + ord($key[$i % strlen($key)]) - ord('A')
                   : ord($char) - ord($key[$i % strlen($key)]) + 26
                ) % 26
            )
        , $i, 1);
    }

    return $dest;
}

?>

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


<?php
foreach (range(2, 8, 2) as $i)
    echo "$i, ";
echo "who do we appreciate?\n";
?>

demonstrate a for-loop with a step-value greater than one.


$i;
function sum (&$i, $lo, $hi, $term) {
    $temp = 0;
    for ($i = $lo; $i <= $hi; $i++) {
        $temp += $term();
    }
    return $temp;
}

echo sum($i, 1, 100, create_function('', 'global $i; return 1 / $i;')), "\n";
//

implement Jensen's Device, a programming technique devised by Jørn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.


header("Content-Type: image/png");

$w = 256;
$h = 256;

$im = imagecreate($w, $h)
    or die("Cannot Initialize new GD image stream");

$color = array();
for($i=0;$i<256;$i++)
{
        array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14/256))*128+128,$i/2,$i));
}

for($i=0;$i<$w;$i++)
{
        for($j=0;$j<$h;$j++)
        {
                imagesetpixel($im,$i,$j,$color[$i^$j]);
        }
}

imagepng($im);
imagedestroy($im);

"Generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table."


<?php
class Maze
{
    protected $width;
    protected $height;
    protected $grid;
    protected $path;
    protected $horWalls;
    protected $vertWalls;
    protected $dirs;
    protected $isDebug;

    public function __construct($x, $y, $debug = false)
    {
        $this->width = $x;
        $this->height = $y;
        $this->path = [];
        $this->dirs = [ [0, -1], [0, 1], [-1, 0], [1, 0]]; // array of coordinates of N,S,W,E
        $this->horWalls = []; // list of removed horizontal walls (---+)
        $this->vertWalls = [];// list of removed vertical walls (|)
        $this->isDebug = $debug; // debug flag

        // generate the maze:
        $this->generate();
    }

    protected function generate()
    {
        $this->initMaze(); // init the stack and an unvisited grid
        // start from a random cell and then proceed recursively
        $this->walk(mt_rand(0, $this->width-1), mt_rand(0, $this->height-1));
    }

    /**
    * Actually prints the Maze, on stdOut. Put in a separate method to allow extensibility
    * For simplicity sake doors are positioned on the north wall and east wall
    */
    public function printOut()
    {
        $this->log("Horizontal walls: %s", json_encode($this->horWalls));
        $this->log("Vertical walls: %s", json_encode($this->vertWalls));

        $northDoor = mt_rand(0,$this->width-1);
        $eastDoor = mt_rand(0, $this->height-1);

        $str = '+';
        for ($i=0;$i<$this->width;$i++) {
            $str .= ($northDoor == $i) ? '   +' : '---+';
        }
        $str .= PHP_EOL;
        for ($i=0; $i<$this->height; $i++) {

            for ($j=0; $j<$this->width; $j++) {
                $str .= (!empty($this->vertWalls[$j][$i]) ? $this->vertWalls[$j][$i] : '|   ');
            }
            $str .= ($i == $eastDoor ? '  ' : '|').PHP_EOL.'+';
            for ($j=0; $j<$this->width; $j++) {
                $str .= (!empty($this->horWalls[$j][$i]) ? $this->horWalls[$j][$i] : '---+');
            }
            $str .= PHP_EOL;
        }
        echo $str;
    }

    /**
    * Logs to stdOut if debug flag is enabled
    */
    protected function log(...$params)
    {
        if ($this->isDebug) {
            echo vsprintf(array_shift($params), $params).PHP_EOL;
        }
    }

    private function walk($x, $y)
    {
        $this->log('Entering cell %d,%d', $x, $y);
        // mark current cell as visited
        $this->grid[$x][$y] = true;
        // add cell to path
        $this->path[] = [$x, $y];
        // get list of all neighbors
        $neighbors = $this->getNeighbors($x, $y);
        $this->log("Valid neighbors: %s", json_encode($neighbors));

        if(empty($neighbors)) {
            // Dead end, we need now to backtrack, if there's still any cell left to be visited
            $this->log("Start backtracking along path: %s", json_encode($this->path));
            array_pop($this->path);
            if (!empty($this->path)) {
                $next = array_pop($this->path);
                return $this->walk($next[0], $next[1]);
            }
        } else {
            // randomize neighbors, as per request
            shuffle($neighbors);

            foreach ($neighbors as $n) {
                $nextX = $n[0];
                $nextY = $n[1];
                if ($nextX == $x) {
                    $wallY = max($nextY, $y);
                    $this->log("New cell is on the same column (%d,%d), removing %d, (%d-1) horizontal wall", $nextX, $nextY, $x, $wallY);
                    $this->horWalls[$x][min($nextY, $y)] = "   +";
                }
                if ($nextY == $y) {
                    $wallX = max($nextX, $x);
                    $this->log("New cell is on the same row (%d,%d), removing %d,%d vertical wall", $nextX, $nextY, $wallX, $y);
                    $this->vertWalls[$wallX][$y] = "    ";
                }
                return $this->walk($nextX, $nextY);
            }
        }
    }

    /**
    * Initialize an empty grid of $width * $height dimensions
    */
    private function initMaze()
    {
        for ($i=0;$i<$this->width;$i++) {
            for ($j = 0;$j<$this->height;$j++) {
                $this->grid[$i][$j] = false;
            }
        }
    }

    /**
    * @param int $x
    * @param int $y
    * @return array
    */
    private function getNeighbors($x, $y)
    {
        $neighbors = [];
        foreach ($this->dirs as $dir) {
            $nextX = $dir[0] + $x;
            $nextY = $dir[1] + $y;
            if (($nextX >= 0 && $nextX < $this->width && $nextY >= 0 && $nextY < $this->height) && !$this->grid[$nextX][$nextY]) {
                $neighbors[] = [$nextX, $nextY];
            }
        }
        return $neighbors;
    }
}

$maze = new Maze(10,10);
$maze->printOut();

generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and processes its neighbors. If a neighbor is unvisited, it removes the wall between the current cell and the neighbor, then recursively applies the same process to the neighbor. The code is inspired by D and Python solutions and includes a debug flag for tracking the process. It is compatible with PHP versions greater than 5.6.


function ackermann( $m , $n )
{
    if ( $m==0 )
    {
        return $n + 1;
    }
    elseif ( $n==0 )
    {
        return ackermann( $m-1 , 1 );
    }
    return ackermann( $m-1, ackermann( $m , $n-1 ) );
}

echo ackermann( 3, 4 );
// prints 125

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


<title>
n x n Queen solving program
</title>

<?php
echo "
n x n Queen solving program
";

//Get the size of the board
$boardX = $_POST['boardX'];
$boardY = $_POST['boardX'];

// Function to rotate a board 90 degrees
function rotateBoard($p, $boardX) {
    $a=0;
    while ($a < count($p)) {
        $b = strlen(decbin($p[$a]))-1;
        $tmp[$b] = 1 << ($boardX - $a - 1);
        ++$a;
    }
    ksort($tmp);
    return $tmp;
}

// This function will find rotations of a solution
function findRotation($p, $boardX,$solutions){
    $tmp = rotateBoard($p,$boardX);
    // Rotated 90
    if (in_array($tmp,$solutions)) {}
    else {$solutions[] = $tmp;}

    $tmp = rotateBoard($tmp,$boardX);
    // Rotated 180
    if (in_array($tmp,$solutions)){}
    else {$solutions[] = $tmp;}

    $tmp = rotateBoard($tmp,$boardX);
    // Rotated 270
    if (in_array($tmp,$solutions)){}
    else {$solutions[] = $tmp;}

    // Reflected
    $tmp = array_reverse($p);
    if (in_array($tmp,$solutions)){}
    else {$solutions[] = $tmp;}

    $tmp = rotateBoard($tmp,$boardX);
    // Reflected and Rotated 90
    if (in_array($tmp,$solutions)){}
    else {$solutions[] = $tmp;}

    $tmp = rotateBoard($tmp,$boardX);
    // Reflected and Rotated 180
    if (in_array($tmp,$solutions)){}
    else {$solutions[] = $tmp;}

    $tmp = rotateBoard($tmp,$boardX);
    // Reflected and Rotated 270
    if (in_array($tmp,$solutions)){}
    else {$solutions[] = $tmp;}
    return $solutions;
}

// This is a function which will render the board
function renderBoard($p,$boardX) {
$img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAAAABmJLR0QA/wD/AP+gvaeTAAAGFUlEQVRYhe2YXWibVRjHf2lqP9JmaRi4YW1IalY3rbZsaddMgsquBm676b6KyNDhLiaUeSEMvPNCcNuNyJjgLiboCnoxKFlv6lcHy7AtMhhaWTVZWhisjDTEtEuW5PHiPWnfvH2TvNk6vekfDm/O+Z/zPP/3PM/5eAMb2MAG/nfYn4LNVuBj4ENgB/Ar8Ogp+KkJbwLfqvKGgbMBPwKiK+Oq3aqNdcebQEEnqAC8ruO7KBVcLF012KiKuhpFv0/prNlU239qw0x0pdBJFXt30NJDjx9Uu1Ub1TSYdq4UutcNfI61oW0Bflb8T6quRzUbNafPFdbm4zcmTucV91kZO18o/osy/GeKnzcRVFWDMT2shO4X4IL6/UqZPv2GpxHFcReUvVo1lMAYunKh+UTxeeB5A/cMkFF8RtX1eF6NE2XHTIN+ltekoHGmf0HLqe9V3Qb8ZWK4Xjf+HQP3KtCgfjeouh7v6PzWsxZ6f98De1kbjbIovumoCfcp2gzkgb8p3cJOUjpTJ3WcTfXPq/Gfmtge1Y01RaV9+jv1fAsYMnAu3XgfENJxfUoU6tmn40Kqf9Gvi1IMKX96/zWJnlLP4i7wrIEvzkQeeFfXvltnt07Vi3iX1RcyzuSzrO46ev81YS+rYcqjbUVFfIl2CSryS4ATcKCF3biQHIpf0rU/UnaKuMLqAhXlv2a4Dc4FOKi4bwyiBTgBvGYyRlT7CUPbI1b334MmY9zlhFVKjwQQ09ULaDNTNKYPbx54j9L81aNP8XldW3G8W9kt6LiY8m8Ksy1Hj0mgA+3eXYeWd2eBRkpf2A4MoO3JOYPdHPA2sMtgu07ZOavsFnegvPL72PiItWEroB0axtwtmPStxOeUHbNxH1USVe1qOm3SVkA7NIwX+1phU3YKJpyZX8swW4y1FOMsVotG1UUI1mbrH9ZeL/UQi3b0C7dS/2W0LbIsqi1E0K6PL5oRdrudHTt22Px+Pz6fD6/XS3NzM21tbSt9FhcXWVpaIhqN2mKxGLOzs8zMzJDP581MQukHw2OLPgt8VRQZDAbZv38/wWCQnTt30tKyGoRUKsWDBw/IZrOkUimcTicNDQ1s3rwZp9O50i+dTjM9Pc2NGzcIh8NEIhH9S3xuQVNV2IArp06dkoWFBRERefjwoUxMTMi5c+fk8OHD0tPTIy6Xq2Keulwu6enpkSNHjsj58+dlYmJCMpmMiIgsLCzIxYsXBe1UfNIFvoL6M2fO/Hn58uXC4OCgtLa2PsniXClOp1MGBwfl0qVLhdOnT/+BtcjX9FYe4Pe+vj6Hy+Vat9lIJpMyOTm5BLwExNfL7gpCodAFeQoIhUIXqntfhaVwFHH9+nXp7+8vuFyuWv8vKYtkMlmYnJwse+F/Urzi9/ulqanJ6gFhqTQ1NeW7u7sF6Fx3xd3d3bdERNLptITDYRkeHpZgMCgOh6MmkQ6HQ/bs2SPDw8MSDoclnU6LiMju3buvlHG9BlYX1F5gfGhoiEAgwL59+9i+fTsAuVyOWCxGPB4nHo+TSCTIZrMkEgncbjeNjY243W46OjrweDx4vV7q67WsnJmZYWxsjGvXrjE+Pm5Zj1XRX3d2dg7Nz8/bs9ksAFu2bGHXrl0EAgG2bduG1+vF4/HgdDrZtGkTdrudXC5HKpUilUpx9+5dYrEYd+7cYXp6mqmpKe7fvw9AQ0MDXV1d3L59+2Xgd4uaKqO3t/cnEZFkMikjIyNy9OhRaW9vf6Jcbm9vl2PHjsnIyIgkk0kRETl06NAHVvRYnenA8ePHJ4PBIAcOHGDr1q0AxONxbt68yezsLNFolLm5ORKJBMvLy6TTaVpaWmhubl5JD5/Ph9/vZ2BgAI/HA8C9e/cYHR3l6tWry2NjY88Bi+slGqAHOFVXVxfq7e3tGhgYqAsGgwQCAfH5fLbGxsaqBjKZDNFoVKampmyRSIRIJFK4devWn4VC4TpwEfjNipDHPdlagADaf3X9NpvthY6Ojk6Px+Mq3vLsdjv5fJ7FxUWWl5eJx+OJubm5mIjMon1O/Yr2N0G6VufrdhwrtAJtaN9+bWihzqB9pNYsbgMbeAz8C3N/JQD4H5KCAAAAAElFTkSuQmCC';
echo "
";
for ($y = 0; $y < $boardX; ++$y) {
	echo '
';
	for ($x = 0; $x < $boardX; ++$x){
	if (($x+$y) & 1) { $cellCol = '#9C661F';}
	else {$cellCol = '#FCE6C9';}

	if ($p[$y] == 1 << $x) { echo "	";}
	else { echo " 	";}
	}
	echo '
';
}
echo '

&nbsp';

}

//This function allows me to generate the next order of rows.
function pc_next_permutation($p) {
    $size = count($p) - 1;
    // slide down the array looking for where we're smaller than the next guy

    for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }

    // if this doesn't occur, we've finished our permutations
    // the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
    if ($i == -1) { return false; }

    // slide down the array looking for a bigger number than what we found before
    for ($j = $size; $p[$j] <= $p[$i]; --$j) { }
    // swap them
    $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
    // now reverse the elements in between by swapping the ends
    for (++$i, $j = $size; $i < $j; ++$i, --$j)
    { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; }
    return $p;
}

//This function needs to check the current state to see if there are any
function checkBoard($p,$boardX) {
	$a = 0; //this is the row being checked
	while ($a < count($p)) {
		$b = 1;
		while ($b < ($boardX - $a)){
            $x = $p[$a+$b] << $b;
            $y = $p[$a+$b] >> $b;
            if ($p[$a] == $x | $p[$a] == $y) {
                return false;
            }
            ++$b;
		}
	++$a;
	}
	return true;
}

if (isset($_POST['process']) && isset($_POST['boardX']))
{
//Within here is the code that needs to be run if process is clicked.

//First I need to create the different possible rows
for ($x = 0; $x < $boardX; ++$x){
	$row[$x] = 1 << $x;
}

//Now I need to create all the possible orders of rows, will be equal to [boardY]!
$solcount = 0;
$solutions = array();
while ($row != false) {
	if (checkBoard($row,$boardX)){
	if(!in_array($row,$solutions)){
		$solutions[] = $row;
			renderBoard($row,$boardX);
			$solutions = findRotation($row,$boardX,$solutions);
			++$solcount;
		}

	}
	$row = pc_next_permutation($row);
}
echo "

&nbsp&nbsp&nbsp&nbspRows/Columns: ".$boardX."
&nbsp&nbsp&nbsp&nbspUnique Solutions: ".$solcount."
&nbsp&nbsp&nbsp&nbspTotal Solutions: ".count($solutions)."  - Note: This includes symmetrical solutions
";
//print_r($solutions);
}

//This code collects the starting parameters
echo <<<_END
<form name="input" action="index.php" method="post">
&nbsp&nbsp&nbsp&nbspNumber of columns/rows <select name="boardX" />
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4" >Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8" selected="selected">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
    <input type="hidden" name="process" value="yes" />
&nbsp<input type="submit" value="Process" />
</form>

_END;

?>

"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N."


$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);

demonstrate how to concatenate two arrays.


#########################################################
# 0-1 Knapsack Problem Solve with memoization optimize and index returns
# $w = weight of item
# $v = value of item
# $i = index
# $aW = Available Weight
# $m = Memo items array
# PHP Translation from Python, Memoization,
# and index return functionality added by Brian Berneker
#
#########################################################

function knapSolveFast2($w, $v, $i, $aW, &$m) {

	global $numcalls;
	$numcalls ++;
	// echo "Called with i=$i, aW=$aW
";

	// Return memo if we have one
	if (isset($m[$i][$aW])) {
		return array( $m[$i][$aW], $m['picked'][$i][$aW] );
	} else {

		// At end of decision branch
		if ($i == 0) {
			if ($w[$i] <= $aW) { // Will this item fit?
				$m[$i][$aW] = $v[$i]; // Memo this item
				$m['picked'][$i][$aW] = array($i); // and the picked item
				return array($v[$i],array($i)); // Return the value of this item and add it to the picked list

			} else {
				// Won't fit
				$m[$i][$aW] = 0; // Memo zero
				$m['picked'][$i][$aW] = array(); // and a blank array entry...
				return array(0,array()); // Return nothing
			}
		}

		// Not at end of decision branch..
		// Get the result of the next branch (without this one)
		list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);

		if ($w[$i] > $aW) { // Does it return too many?

			$m[$i][$aW] = $without_i; // Memo without including this one
			$m['picked'][$i][$aW] = $without_PI; // and a blank array entry...
			return array($without_i, $without_PI); // and return it

		} else {

			// Get the result of the next branch (WITH this one picked, so available weight is reduced)
			list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);
			$with_i += $v[$i];  // ..and add the value of this one..

			// Get the greater of WITH or WITHOUT
			if ($with_i > $without_i) {
				$res = $with_i;
				$picked = $with_PI;
				array_push($picked,$i);
			} else {
				$res = $without_i;
				$picked = $without_PI;
			}

			$m[$i][$aW] = $res; // Store it in the memo
			$m['picked'][$i][$aW] = $picked; // and store the picked item
			return array ($res,$picked); // and then return it
		}
	}
}

$items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book");
$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);
$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);

## Initialize
$numcalls = 0; $m = array(); $pickedItems = array();

## Solve
list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);

# Display Result
echo "Items:
".join(", ",$items4)."
";
echo "Max Value Found:
$m4 (in $numcalls calls)
";
echo "Array Indices:
".join(",",$pickedItems)."
";

echo "Chosen Items:
";
echo "
";
echo "
Item	Value	Weight
";
$totalVal = $totalWt = 0;
foreach($pickedItems as $key) {
	$totalVal += $v4[$key];
	$totalWt += $w4[$key];
	echo "
".$items4[$key]."	".$v4[$key]."	".$w4[$key]."
";
}
echo "
Totals	$totalVal	$totalWt
";
echo "

";

The code is designed to solve the 0-1 Knapsack problem. It helps a tourist to determine the best combination of items to pack for a trip to maximize the total value without exceeding a weight limit of 4kg. The items, their weights, and values are listed in a table, and the code ensures only whole units of any item are considered, and each item can only be taken once. The algorithm is implemented based on a minimal PHP algorithm.


<?php
$words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");

function canMakeWord($word) {
    $word = strtoupper($word);
    $blocks = array(
            "BO", "XK", "DQ", "CP", "NA",
            "GT", "RE", "TG", "QD", "FS",
            "JW", "HU", "VI", "AN", "OB",
            "ER", "FS", "LY", "PC", "ZM",
    );

    foreach (str_split($word) as $char) {
        foreach ($blocks as $k => $block) {
            if (strpos($block, $char) !== FALSE) {
                unset($blocks[$k]);
                continue(2);
            }
        }
        return false;
    }
    return true;
}

foreach ($words as $word) {
    echo $word.': ';
    echo canMakeWord($word) ? "True" : "False";
    echo "\r\n";
}

"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed."


$string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );

implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5/Implementation for a scratch implementation.


$socket = fsockopen('localhost', 256);
fputs($socket, 'hello socket world');
fclose($socket);

opens a socket to localhost on port 256, sends the message "hello socket world", and then closes the socket.


mail('hello@world.net', 'My Subject', "A Message!", "From: my@address.com");

Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.


generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


function swap(&$a, &$b) {
    list($a, $b) = array($b, $a);
}

implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.


<?php
function is_palindrome($string) {
  return $string == strrev($string);
}
?>

<?php
function is_palindrome($string) {
  return preg_match('/^(?:(.)(?=.*(\1(?(2)\2|))$))*.?\2?$/', $string);
}
?>

The code includes a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case differences. It also includes a string reversal function and may be used to test other functions. The solution is based on regular expressions.


demonstrate how to retrieve a specific environment variable from the process's environment in Unix systems, such as PATH, HOME, or USER, using the $_ENV associative array.


implement the Sudan function, a non-primitive recursive function. The function takes two parameters x and y, and returns their sum if the recursion depth is zero, returns x if y is zero, and for other cases, it recursively calls itself with updated parameters.


Works with: Visual Basic version 6
Debug.Print VBA.StrReverse("Visual Basic")

Reverses a given string while preserving Unicode combining characters. For instance, it transforms "asdf" to "fdsa" and "as⃝df̅" to "f̅ds⃝a".


Translation of: BBC BASIC
Works with: Visual Basic version VB6 Standard
Sub mersenne()
    Dim q As Long, k As Long, p As Long, d As Long
    Dim factor As Long, i As Long, y As Long, z As Long
    Dim prime As Boolean
    q = 929   'input value
    For k = 1 To 1048576   '2**20
        p = 2 * k * q + 1
        If (p And 7) = 1 Or (p And 7) = 7 Then    'p=*001 or p=*111
            'p is prime?
            prime = False
            If p Mod 2 = 0 Then GoTo notprime
            If p Mod 3 = 0 Then GoTo notprime
            d = 5
            Do While d * d <= p
                If p Mod d = 0 Then GoTo notprime
                d = d + 2
                If p Mod d = 0 Then GoTo notprime
                d = d + 4
            Loop
            prime = True
        notprime:   'modpow
            i = q: y = 1: z = 2
            Do While i   'i <> 0
                On Error GoTo okfactor
                If i And 1 Then y = (y * z) Mod p  'test first bit
                z = (z * z) Mod p
                On Error GoTo 0
                i = i \ 2
            Loop
            If prime And y = 1 Then factor = p: GoTo okfactor
        End If
    Next k
    factor = 0
okfactor:
    Debug.Print "M" & q, "factor=" & factor
End Sub

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


Works with: Visual Basic version 5
Works with: Visual Basic version 6

Sub QuickSort(arr() As Integer, ByVal f As Integer, ByVal l As Integer)
    i = f 'First
    j = l 'Last
    Key = arr(i) 'Pivot
    Do While i < j
        Do While i < j And Key < arr(j)
            j = j - 1
        Loop
        If i < j Then arr(i) = arr(j): i = i + 1
        Do While i < j And Key > arr(i)
            i = i + 1
        Loop
        If i < j Then arr(j) = arr(i): j = j - 1
    Loop
    arr(i) = Key
    If i - 1 > f Then QuickSort arr(), f, i - 1
    If j + 1 < l Then QuickSort arr(), j + 1, l
End Sub

implement the Quicksort algorithm for sorting an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts both partitions and joins them together with the pivot. The codes also include an optimized version of Quicksort that sorts the array in place by swapping elements, reducing memory allocation. The pivot selection method is not specified.


Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function 'small Helper-Function

Sub Main()
Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5
Dim P&, I&, G&, A&, M, Cur(Value To Volume)
Dim S As New Collection: S.Add Array(0) '<- init Solutions-Coll.

Const SackW = 25, SackV = 0.25
Dim Panacea: Panacea = Array(3000, 0.3, 0.025)
Dim Ichor:     Ichor = Array(1800, 0.2, 0.015)
Dim Gold:       Gold = Array(2500, 2, 0.002)

  For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume)))
    For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume)))
      For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume)))
        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next
        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _
          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1
  Next G, I, P

  Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount"
  For Each M In S '<- enumerate the Attributes of the Maxima
    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)
  Next
End Sub

The code determines the maximum value of items a traveler can carry in his knapsack, given the weight and volume constraints. It considers items such as panacea, ichor, and gold, each with specific values, weights, and volumes. The code provides one of the four possible solutions to maximize the value of items carried.


Works with: Visual Basic version VB6 Standard

The code checks if a given string starts with, contains, or ends with another string. It can also print the location of the match and handle multiple occurrences of the string.


Translation of: VBA
Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version Access 97
Works with: VBA version 6.5
Works with: VBA version 7.1
Option Explicit

Dim total As Long, prim As Long, maxPeri As Long

Public Sub NewTri(ByVal s0 As Long, ByVal s1 As Long, ByVal s2 As Long)
Dim p As Long, x1 As Long, x2 As Long
    p = s0 + s1 + s2
    If p <= maxPeri Then
        prim = prim + 1
        total = total + maxPeri \ p
        x1 = s0 + s2
        x2 = s1 + s2
        NewTri s0 + 2 * (-s1 + s2), 2 * x1 - s1, 2 * (x1 - s1) + s2
        NewTri s0 + 2 * x2, 2 * x1 + s1, 2 * (x1 + s1) + s2
        NewTri -s0 + 2 * x2, 2 * (-s0 + s2) + s1, 2 * (-s0 + x2) + s2
    End If
End Sub

Public Sub Main()
    maxPeri = 100
    Do While maxPeri <= 10& ^ 8
        prim = 0
        total = 0
        NewTri 3, 4, 5
        Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
        maxPeri = maxPeri * 10
    Loop
End Sub

The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.


Sub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = "$", Optional Sp% = 1)
Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)

  For j = 0 To UBound(W)
    W(j) = Split(Lines(j), Sep)
    If UBound(W(j)) > UBound(C) Then ReDim Preserve C(UBound(W(j)))
    For i = 0 To UBound(W(j)): If Len(W(j)(i)) > C(i) Then C(i) = Len(W(j)(i))
  Next i, j

  For j = 0 To UBound(W): For i = 0 To UBound(W(j))
    D = C(i) - Len(W(j)(i))
    L = Choose(Align + 1, 0, D, D \ 2)
    R = Choose(Align + 1, D, 0, D - L) + Sp
    Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf);
  Next i, j
End Sub
Usage:Sub Main() 'usage of the above
Const Text$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & vbLf & _
              "are$delineated$by$a$single$'dollar'$character,$write$a$program" & vbLf & _
              "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & vbLf & _
              "column$are$separated$by$at$least$one$space." & vbLf & _
              "Further,$allow$for$each$word$in$a$column$to$be$either$left$" & vbLf & _
              "justified,$right$justified,$or$center$justified$within$its$column."

  Debug.Print vbLf; "-- Left:":   AlignCols Split(Text, vbLf), vbLeftJustify
  Debug.Print vbLf; "-- Center:": AlignCols Split(Text, vbLf), vbCenter
  Debug.Print vbLf; "-- Right:":  AlignCols Split(Text, vbLf), vbRightJustify
End Sub

The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.


Works with: Visual Basic version VB6 Standard
Function ROT13(ByVal a As String) As String
  Dim i As Long
  Dim n As Integer, e As Integer

  ROT13 = a
  For i = 1 To Len(a)
    n = Asc(Mid$(a, i, 1))
    Select Case n
      Case 65 To 90
        e = 90
        n = n + 13
      Case 97 To 122
        e = 122
        n = n + 13
      Case Else
        e = 255
    End Select

    If n > e Then
      n = n - 26
    End If
    Mid$(ROT13, i, 1) = Chr$(n)
  Next i
End Function

Sub Main()
  Debug.Assert ROT13("abc") = "nop"
  Debug.Assert ROT13("nop") = "abc"
End Sub

implement a rot-13 function that encodes every line of input from each file listed on its command line or acts as a filter on its standard input. This function replaces every letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. It preserves case and passes all non-alphabetic characters in the input stream without alteration. It can be optionally wrapped in a utility program.


Works with: Visual Basic version 6
Option Explicit

Function DotProduct(a() As Long, b() As Long) As Long
Dim l As Long, u As Long, i As Long
  Debug.Assert DotProduct = 0 'return value automatically initialized with 0
  l = LBound(a())
  If l = LBound(b()) Then
    u = UBound(a())
    If u = UBound(b()) Then
      For i = l To u
        DotProduct = DotProduct + a(i) * b(i)
      Next i
    Exit Function
    End If
  End If
  Err.Raise vbObjectError + 123, , "invalid input"
End Function

Sub Main()
Dim a() As Long, b() As Long, x As Long
  ReDim a(2)
  a(0) = 1
  a(1) = 3
  a(2) = -5
  ReDim b(2)
  b(0) = 4
  b(1) = -2
  b(2) = -1
  x = DotProduct(a(), b())
  Debug.Assert x = 3
  ReDim Preserve a(3)
  a(3) = 10
  ReDim Preserve b(3)
  b(3) = 2
  x = DotProduct(a(), b())
  Debug.Assert x = 23
  ReDim Preserve a(4)
  a(4) = 10
  On Error Resume Next
  x = DotProduct(a(), b())
  Debug.Assert Err.Number = vbObjectError + 123
  Debug.Assert Err.Description = "invalid input"
End Sub

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


generate an array, list, or string of all lower case ASCII characters from 'a' to 'z'. It demonstrates both accessing a standard library sequence and generating a similar sequence manually, using a reliable coding style and strong typing if available. The code avoids manually enumerating all the lowercase characters to prevent bugs. It is also compatible with VB6 without any changes.


Works with: Visual Basic version VB6 Standard
Public Function Bin(ByVal l As Long) As String
Dim i As Long
  If l Then
    If l And &H80000000 Then 'negative number
      Bin = "1" & String$(31, "0")
      l = l And (Not &H80000000)

      For i = 0 To 30
      If l And (2& ^ i) Then
        Mid$(Bin, Len(Bin) - i) = "1"
      End If
      Next i

    Else                     'positive number
      Do While l
      If l Mod 2 Then
        Bin = "1" & Bin
      Else
        Bin = "0" & Bin
      End If
      l = l \ 2
      Loop
    End If
  Else
    Bin = "0"                'zero
  End If
End Function

'testing:
Public Sub Main()
  Debug.Print Bin(5)
  Debug.Print Bin(50)
  Debug.Print Bin(9000)
End Sub

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


' Configuration file parser routines.
'
' (c) Copyright 1993 - 2011 Mark Hobley
'
' This configuration parser contains code ported from an application program
' written in Microsoft Quickbasic
'
' This code can be redistributed or modified under the terms of version 1.2 of
' the GNU Free Documentation Licence as published by the Free Software Foundation.

Sub readini()
  var.filename = btrim$(var.winpath) & ini.inifile
  var.filebuffersize = ini.inimaxlinelength
  Call openfileread
  If flg.error = "Y" Then
    flg.abort = "Y"
    Exit Sub
  End If
  If flg.exists <> "Y" Then
    flg.abort = "Y"
    Exit Sub
  End If
  var.inistream = var.stream
readinilabela:
  Call readlinefromfile
  If flg.error = "Y" Then
    flg.abort = "Y"
    Call closestream
    flg.error = "Y"
    Exit Sub
  End If
  If flg.endoffile <> "Y" Then
    iniline$ = message$
    If iniline$ <> "" Then
      If Left$(iniline$, 1) <> ini.commentchar AND Left$(iniline$, 1) <> ini.ignorechar Then
        endofinicommand% = 0
        For l% = 1 To Len(iniline$)
          If Mid$(iniline$, l%, 1) < " " Then
            endofinicommand% = l%
          End If
          If Not (endofinicommand%) Then
            If Mid$(iniline$, l%, 1) = " " Then
              endofinicommand% = l%
            End If
          End If
          If endofinicommand% Then
            l% = Len(iniline$)
          End If
        Next l%
        iniarg$ = ""
        If endofinicommand% Then
          If endofinicommand% <> Len(iniline$) Then
            iniarg$ = btrim$(Mid$(iniline$, endofinicommand% + 1))
            If iniarg$ = "" Then
              GoTo readinilabelb
            End If
            inicommand$ = Left$(iniline$, endofinicommand% - 1)
          End If
        Else
          inicommand$ = btrim$(iniline$)
        End If
readinilabelb:
        'interpret command
        inicommand$ = UCase$(inicommand$)
        Select Case inicommand$
          Case "FULLNAME"
            If iniarg$ <> "" Then
              ini.fullname = iniarg$
            End If
          Case "FAVOURITEFRUIT"
            If iniarg$ <> "" Then
              ini.favouritefruit = iniarg$
            End If
          Case "NEEDSPEELING"
            ini.needspeeling = "Y"
          Case "SEEDSREMOVED"
            ini.seedsremoved = "Y"
          Case "OTHERFAMILY"
            If iniarg$ <> "" Then
              ini.otherfamily = iniarg$
              CALL familyparser
            End If
          Case Else
            '!! error handling required
        End Select
      End If
    End If
    GoTo readinilabela
  End If
  Call closestream
  Exit Sub
readinierror:

End Sub

Sub openfileread()
  flg.streamopen = "N"
  Call checkfileexists
  If flg.error = "Y" Then Exit Sub
  If flg.exists <> "Y" Then Exit Sub
  Call getfreestream
  If flg.error = "Y" Then Exit Sub
  var.errorsection = "Opening File"
  var.errordevice = var.filename
  If ini.errortrap = "Y" Then
    On Local Error GoTo openfilereaderror
  End If
  flg.endoffile = "N"
  Open var.filename For Input As #var.stream Len = var.filebuffersize
  flg.streamopen = "Y"
  Exit Sub
openfilereaderror:
  var.errorcode = Err
  Call errorhandler
  resume '!!
End Sub

Public Sub checkfileexists()
  var.errorsection = "Checking File Exists"
  var.errordevice = var.filename
  If ini.errortrap = "Y" Then
    On Local Error GoTo checkfileexistserror
  End If
  flg.exists = "N"
  If Dir$(var.filename, 0) <> "" Then
    flg.exists = "Y"
  End If
  Exit Sub
checkfileexistserror:
  var.errorcode = Err
  Call errorhandler
End Sub

Public Sub getfreestream()
  var.errorsection = "Opening Free Data Stream"
  var.errordevice = ""
  If ini.errortrap = "Y" Then
    On Local Error GoTo getfreestreamerror
  End If
  var.stream = FreeFile
  Exit Sub
getfreestreamerror:
  var.errorcode = Err
  Call errorhandler
  resume '!!
End Sub

Sub closestream()
  If ini.errortrap = "Y" Then
    On Local Error GoTo closestreamerror
  End If
  var.errorsection = "Closing Stream"
  var.errordevice = ""
  flg.resumenext = "Y"
  Close #var.stream
  If flg.error = "Y" Then
    flg.error = "N"
    '!! Call unexpectederror
  End If
  flg.streamopen = "N"
  Exit Sub
closestreamerror:
  var.errorcode = Err
  Call errorhandler
  resume next
End Sub

Sub readlinefromfile()
  If ini.errortrap = "Y" Then
    On Local Error GoTo readlinefromfileerror
  End If
  If EOF(var.stream) Then
    flg.endoffile = "Y"
    Exit Sub
  End If
  Line Input #var.stream, tmp$
  message$ = tmp$
  Exit Sub
readlinefromfileerror:
  var.errorcode = Err
  Call errorhandler
  resume '!!
End Sub

Public Sub errorhandler()
  tmp$ = btrim$(var.errorsection)
  tmp2$ = btrim$(var.errordevice)
  If tmp2$ <> "" Then
    tmp$ = tmp$ + " (" + tmp2$ + ")"
  End If
  tmp$ = tmp$ + " : " + Str$(var.errorcode)
  tmp1% = MsgBox(tmp$, 0, "Error!")
  flg.error = "Y"
  If flg.resumenext = "Y" Then
    flg.resumenext = "N"
'    Resume Next
  Else
    flg.error = "N"
'    Resume
  End If
End Sub

Public Function btrim$(arg$)
  btrim$ = LTrim$(RTrim$(arg$))
End Function

read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.


Library: Microsoft.WinHttp
Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version Access 97
Works with: VBA version 6.5
Works with: VBA version 7.1
Sub Main()
Dim HttpReq As WinHttp.WinHttpRequest
'  in the "references" dialog of the IDE, check
'  "Microsoft WinHTTP Services, version 5.1" (winhttp.dll)
Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2
#Const USE_PROXY = 1
  Set HttpReq = New WinHttp.WinHttpRequest
  HttpReq.Open "GET", "http://rosettacode.org/robots.txt"
#If USE_PROXY Then
  HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "my_proxy:80"
#End If
  HttpReq.SetTimeouts 1000, 1000, 1000, 1000
  HttpReq.Send
  Debug.Print HttpReq.ResponseText
End Sub

Print the content of a specified URL to the console using HTTP request.


Works with: Visual Basic version VB6 Standard
Public Function LuhnCheckPassed(ByVal dgts As String) As Boolean
Dim i As Long, s As Long, s1 As Long
  dgts = VBA.StrReverse(dgts)
    For i = 1 To Len(dgts) Step 2
        s = s + CInt(Mid$(dgts, i, 1))
    Next i
    For i = 2 To Len(dgts) Step 2
        s1 = 2 * (CInt(Mid$(dgts, i, 1)))
        If s1 >= 10 Then
            s = s - 9
        End If
        s = s + s1
    Next i
  LuhnCheckPassed = Not CBool(s Mod 10)
End Function

Sub Main()
  Debug.Assert LuhnCheckPassed("49927398716")
  Debug.Assert Not LuhnCheckPassed("49927398717")
  Debug.Assert Not LuhnCheckPassed("1234567812345678")
  Debug.Assert LuhnCheckPassed("1234567812345670")
End Sub

The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number, then calculates two partial sums: s1 from the sum of every other odd digit, and s2 from the sum of each even digit multiplied by two (if the result is greater than nine, the digits are summed). If the total sum (s1 + s2) ends in zero, the number is validated as a credit card number. The function is used to validate four specific numbers.


Works with: Visual Basic version VB6 Standard

Public Function StrRepeat(s As String, n As Integer) As String
	Dim r As String, i As Integer
	r = ""
	For i = 1 To n
		r = r & s
	Next i
	StrRepeat = r
End Function

Debug.Print StrRepeat("ha", 5)

"Code repeats a given string or character a specified number of times."


Sub arrShellSort(ByVal arrData As Variant)
  Dim lngHold, lngGap As Long
  Dim lngCount, lngMin, lngMax As Long
  Dim varItem As Variant
  '
  lngMin = LBound(arrData)
  lngMax = UBound(arrData)
  lngGap = lngMin
  Do While (lngGap < lngMax)
    lngGap = 3 * lngGap + 1
  Loop
  Do While (lngGap > 1)
    lngGap = lngGap \ 3
    For lngCount = lngGap + lngMin To lngMax
      varItem = arrData(lngCount)
      lngHold = lngCount
      Do While ((arrData(lngHold - lngGap) > varItem))
        arrData(lngHold) = arrData(lngHold - lngGap)
        lngHold = lngHold - lngGap
        If (lngHold < lngMin + lngGap) Then Exit Do
      Loop
      arrData(lngHold) = varItem
    Next
  Loop
  arrShellSort = arrData
End Sub'

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


Works with: Visual Basic version 5
Works with: Visual Basic version 6
Library: Win32
Option Explicit

Private Type BITMAP
  bmType As Long
  bmWidth As Long
  bmHeight As Long
  bmWidthBytes As Long
  bmPlanes As Integer
  bmBitsPixel As Integer
  bmBits As Long
End Type

Private Type RGB
  Red As Byte
  Green As Byte
  Blue As Byte
  Alpha As Byte
End Type

Private Type RGBColor
  Color As Long
End Type

Public Declare Function CreateCompatibleDC Lib "gdi32.dll" (ByVal hdc As Long) As Long
Public Declare Function GetObjectA Lib "gdi32.dll" (ByVal hObject As Long, ByVal nCount As Long, ByRef lpObject As Any) As Long
Public Declare Function SelectObject Lib "gdi32.dll" (ByVal hdc As Long, ByVal hObject As Long) As Long
Public Declare Function GetPixel Lib "gdi32.dll" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long
Public Declare Function SetPixel Lib "gdi32.dll" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal crColor As Long) As Long
Public Declare Function DeleteDC Lib "gdi32.dll" (ByVal hdc As Long) As Long

Sub Main()
Dim p As stdole.IPictureDisp
Dim hdc As Long
Dim bmp As BITMAP
Dim i As Long, x As Long, y As Long
Dim tRGB As RGB, cRGB As RGBColor

Set p = VB.LoadPicture("T:\TestData\Input_Colored.bmp")
GetObjectA p.Handle, Len(bmp), bmp

hdc = CreateCompatibleDC(0)
SelectObject hdc, p.Handle

For x = 0 To bmp.bmWidth - 1
  For y = 0 To bmp.bmHeight - 1
    cRGB.Color = GetPixel(hdc, x, y)
    LSet tRGB = cRGB
    i = (0.2126 * tRGB.Red + 0.7152 * tRGB.Green + 0.0722 * tRGB.Blue)
    SetPixel hdc, x, y, RGB(i, i, i)
  Next y
Next x

VB.SavePicture p, "T:\TestData\Output_GrayScale.bmp"
DeleteDC hdc

End Sub

extend the data storage type to support grayscale images, define operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors or distorted results occur when storing calculated luminance as an unsigned integer.


VERSION 5.00
Begin VB.Form Form1
   Begin VB.Timer Timer1
      Interval = 250
   End
   Begin VB.Label Label1
      AutoSize = -1  'True
      Caption  = "Hello World! "
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'Everything above this line is hidden when in the IDE.

Private goRight As Boolean

Private Sub Label1_Click()
    goRight = Not goRight
End Sub

Private Sub Timer1_Timer()
    If goRight Then
        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)
    Else
        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)
    End If
    Label1.Caption = x
End Sub

create a GUI window displaying a rotating "Hello World!" text. The rotation direction of the text changes whenever the user clicks on it. The rotation is achieved by periodically moving one letter from the end of the string to the front. The animation remains responsive to user interactions.


determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. The character count is based on individual Unicode code points, not user-visible graphemes. The code also handles non-BMP code points correctly, providing the actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes if the language supports it.


Works with: Visual Basic version 4
Works with: Visual Basic version 5
Works with: Visual Basic version 6
Dim onlyInstance as Boolean
onlyInstance = not App.PrevInstance

"Check if an application instance is already running, display a message if so, and terminate the program."


Method 1[edit]

TYPE syswindowstru
  screenheight AS INTEGER
  screenwidth AS INTEGER
  maxheight AS INTEGER
  maxwidth AS INTEGER
END TYPE

DIM syswindow AS syswindowstru

' Determine the height and width of the screen

syswindow.screenwidth = Screen.Width / Screen.TwipsPerPixelX
syswindow.screenheight=Screen.Height / Screen.TwipsPerPixelY

' Make adjustments for window decorations and menubars

Method 2[edit]

determine the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers. It either queries the screen dimensions and subtracts pixels used by the frame and desktop bars, or creates a maximized form and queries its dimensions.


The code enables the input of a string and the integer 75000 via a graphical user interface, potentially using a form created in the IDE. This functionality can be implemented using Visual Basic, with possible adaptations from VBScript or PowerBASIC examples.


Library: Microsoft.WinHttp
Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version Access 97
Works with: VBA version 6.5
Works with: VBA version 7.1
Sub Main()
Dim HttpReq As WinHttp.WinHttpRequest
'  in the "references" dialog of the IDE, check
'  "Microsoft WinHTTP Services, version 5.1" (winhttp.dll)
Const HTTPREQUEST_PROXYSETTING_PROXY        As Long = 2
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1     As Long = &H80&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1   As Long = &H200&
Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2   As Long = &H800&
#Const USE_PROXY = 1
  Set HttpReq = New WinHttp.WinHttpRequest
  HttpReq.Open "GET", "https://groups.google.com/robots.txt"
  HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _
                                                         WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _
                                                         WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2
#If USE_PROXY Then
  HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "my_proxy:80"
#End If
  HttpReq.SetTimeouts 1000, 1000, 1000, 1000
  HttpReq.Send
  Debug.Print HttpReq.ResponseText
End Sub

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version 6.5
Works with: VBA version 7.1
Public Function CommonDirectoryPath(ParamArray Paths()) As String
Dim v As Variant
Dim Path() As String, s As String
Dim i As Long, j As Long, k As Long
Const PATH_SEPARATOR As String = "/"

  For Each v In Paths
    ReDim Preserve Path(0 To i)
    Path(i) = v
    i = i + 1
  Next v

  k = 1

  Do
    For i = 0 To UBound(Path)
      If i Then
        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
          Exit Do
        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then
          Exit Do
        End If
      Else
        j = InStr(k, Path(i), PATH_SEPARATOR)
        If j = 0 Then
          Exit Do
        End If
      End If
    Next i
    s = Left$(Path(0), j + CLng(k <> 1))
    k = j + 1
  Loop
  CommonDirectoryPath = s

End Function

Sub Main()

' testing the above function

Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/home/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members") = _
 "/home/user1/tmp"

 Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/home/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members", _
 "/home/user1/abc/coven/members") = _
 "/home/user1"

Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/hope/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members") = _
 "/"

End Sub

The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.


retrieve and print the list of command-line arguments provided to the program. It also parses the arguments intelligently. For instance, if the command line is 'myprogram -c "alpha beta" -h "gamma"', the code will handle these arguments appropriately. In Visual Basic, these arguments are returned in the built-in variable Command$.


Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version Access 97
Works with: VBA version 6.5
Works with: VBA version 7.1
Option Explicit

Private Declare Function GetComputerName Lib "kernel32.dll" Alias "GetComputerNameW" _
  (ByVal lpBuffer As Long, ByRef nSize As Long) As Long

Private Const MAX_COMPUTERNAME_LENGTH As Long = 31
Private Const NO_ERR As Long = 0

Private Function Hostname() As String
Dim i As Long, l As Long, s As String
  s = Space$(MAX_COMPUTERNAME_LENGTH)
  l = Len(s) + 1
  i = GetComputerName(StrPtr(s), l)
  Debug.Assert i <> 0
  Debug.Assert l <> 0
  Hostname = Left$(s, l)
End Function

Sub Main()
  Debug.Assert Hostname() = Environ$("COMPUTERNAME")
End Sub

"Determines and outputs the hostname of the current system where the routine is running."


Works with: Visual Basic version VB6 Standard

initializes two string variables, concatenates the second string with another string literal, and displays the content of the variables.


VERSION 5.00
Begin VB.Form Form2
   Caption         =   "There have been no clicks yet"
   ClientHeight    =   2940
   ClientLeft      =   60
   ClientTop       =   600
   ClientWidth     =   8340
   LinkTopic       =   "Form1"
   ScaleHeight     =   2940
   ScaleWidth      =   8340
   StartUpPosition =   3  'Windows Default
   Begin VB.CommandButton Command1
      Caption         =   "Click me!"
      Height          =   495
      Left            =   3600
      TabIndex        =   0
      Top             =   1200
      Width           =   1215
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'-----user-written code begins here; everything above this line is hidden in the GUI-----
Private clicked As Long

Private Sub Command1_Click()
    clicked = clicked + 1
    Me.Caption = clicked & " clicks."
End Sub

implement a windowed application in VB. The application features a label initially displaying "There have been no clicks yet" and a button labeled "click me". The label updates to show the number of times the button has been clicked each time the button is clicked. The window creation process is typically handled in the IDE and the generated code is usually hidden from the programmer.


Works with: Visual Basic version 5
Works with: Visual Basic version 6
Works with: VBA version Access 97
Works with: VBA version 6.5
Works with: VBA version 7.1
Option Explicit

Sub Main()
Const VECSIZE As Long = 3350
Const BUFSIZE As Long = 201
Dim buffer(1 To BUFSIZE) As Long
Dim vect(1 To VECSIZE) As Long
Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long

  For n = 1 To VECSIZE
    vect(n) = 2
  Next n
  For n = 1 To BUFSIZE
    karray = 0
    For l = VECSIZE To 1 Step -1
      num = 100000 * vect(l) + karray * l
      karray = num \ (2 * l - 1)
      vect(l) = num - karray * (2 * l - 1)
    Next l
    k = karray \ 100000
    buffer(n) = more + k
    more = karray - k * 100000
  Next n
  Debug.Print CStr(buffer(1));
  Debug.Print "."
  l = 0
  For n = 2 To BUFSIZE
    Debug.Print Format$(buffer(n), "00000");
    l = l + 1
    If l = 10 Then
      l = 0
      Debug.Print 'line feed
    End If
  Next n
End Sub

are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.


Translation of: Rexx
Works with: Visual Basic version VB6 Standard
Option Explicit
Dim calls As Long
Sub main()
    Const maxi = 4
    Const maxj = 9
    Dim i As Long, j As Long
    For i = 0 To maxi
        For j = 0 To maxj
            Call print_acker(i, j)
        Next j
    Next i
End Sub 'main
Sub print_acker(m As Long, n As Long)
    calls = 0
    Debug.Print "ackermann("; m; ","; n; ")=";
    Debug.Print ackermann(m, n), "calls="; calls
End Sub 'print_acker
Function ackermann(m As Long, n As Long) As Long
    calls = calls + 1
    If m = 0 Then
        ackermann = n + 1
    Else
        If n = 0 Then
            ackermann = ackermann(m - 1, 1)
        Else
            ackermann = ackermann(m - 1, ackermann(m, n - 1))
        End If
    End If
End Function 'ackermann

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.


Works with: Visual Basic version VB6 Standard
Translation of: BBC BASIC
'N-queens problem - non recursive & structured - vb6 - 25/02/2017
Sub n_queens()
    Const l = 15  'number of queens
    Const b = False  'print option
    Dim a(l), s(l), u(4 * l - 2)
    Dim n, m, i, j, p, q, r, k, t, z
    For i = 1 To UBound(a): a(i) = i: Next i
    For n = 1 To l
        m = 0
        i = 1
        j = 0
        r = 2 * n - 1
        Do
            i = i - 1
            j = j + 1
            p = 0
            q = -r
            Do
                i = i + 1
                u(p) = 1
                u(q + r) = 1
                z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)
                p = i - a(i) + n
                q = i + a(i) - 1
                s(i) = j
                j = i + 1
            Loop Until j > n Or u(p) Or u(q + r)
            If u(p) = 0 Then
                If u(q + r) = 0 Then
                    m = m + 1  'm: number of solutions
                    If b Then
                        Debug.Print "n="; n; "m="; m
                        For k = 1 To n
                            For t = 1 To n
                                Debug.Print IIf(a(n - k + 1) = t, "Q", ".");
                            Next t
                            Debug.Print
                        Next k
                    End If
                End If
            End If
            j = s(i)
            Do While j >= n And i <> 0
                Do
                    z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)
                    j = j - 1
                Loop Until j < i
                i = i - 1
                p = i - a(i) + n
                q = i + a(i) - 1
                j = s(i)
                u(p) = 0
                u(q + r) = 0
            Loop
        Loop Until i = 0
        Debug.Print n, m  'number of queens, number of solutions
    Next n
End Sub 'n_queens

"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N."