Created
July 26, 2012 05:10
-
-
Save benjamw/3180375 to your computer and use it in GitHub Desktop.
create various repeating patterns of TRUE / FALSE in a loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// patterns | |
$patterns = array( ); | |
for ($i = 0; $i < 20; ++$i) { | |
// the generic alternating patterns | |
// 1, 0, 1, 0, ... | |
$patterns[0][] = (0 === ($i % 2)); | |
// 0, 1, 0, 1, ... | |
$patterns[1][] = (0 !== ($i % 2)); | |
// by increasing the value we modulo by, and dividing | |
// by half that amount, we can double up the pattern | |
// NOTE: the (int) _is_ important here | |
// 1, 1, 0, 0, 1, 1, 0, 0, ... | |
$patterns[2][] = (0 === (int) floor(($i % 4) / 2)); | |
// 0, 0, 1, 1, 0, 0, 1, 1, ... | |
$patterns[3][] = (0 !== (int) floor(($i % 4) / 2)); | |
// this process can be continued to higher values | |
// 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, ... | |
$patterns[4][] = (0 === (int) floor(($i % 6) / 3)); | |
// 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, ... | |
$patterns[5][] = (0 !== (int) floor(($i % 6) / 3)); | |
// the values do not have to be 2:1 related, or even | |
// 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, ... | |
$patterns[6][] = (0 === (int) floor(($i % 5) / 2)); | |
// by adding a value to $i before the modulus, the | |
// pattern can be shifted forward or backward | |
// 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, ... | |
$patterns[7][] = (0 === (int) floor((($i + 1) % 5) / 2)); | |
/* | |
all these patterns can be generalized to: | |
( 0 === (int) floor( ( ( $i + $shift ) % $length_of_pattern ) / $num_leading_values ) ) | |
where $length_of_pattern is the total length of the pattern before repeating (wavelength) | |
and $num_leading_values is the number of TRUE values at the start of | |
the pattern before it switches to FALSE. | |
$shift shifts the pattern by the given amount (+ = forward; - = backward) | |
$num_leading_values must be less than $length_of_pattern | |
$shift can be any integer, positive or negative, but the pattern will repeat | |
so -$length_of_pattern < $shift < $length_of_pattern | |
the whole pattern can be reversed by setting === to !== | |
leading TRUE becomes FALSE, and vice versa | |
*/ | |
} | |
g($patterns); | |
if ( ! function_exists('g')) { | |
function g($var = null) { | |
var_dump($var); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment