示例#1
0
 /**
  * @dataProvider dataSrc
  */
 public function testBinarySearch($list, $item, $expected)
 {
     if (!function_exists('binary_search')) {
         $this->load('search.binary');
         $this->assertTrue(function_exists('binary_search'));
     }
     $this->assertEquals($expected, binary_search($list, $item));
 }
示例#2
0
function binary_search_rec($search, $list, $left, $right)
{
    if ($left > $right) {
        return -1;
    }
    $mid = $left + $right >> 1;
    if ($list[$mid] == $search) {
        return $mid;
    } elseif ($list[$mid] > $search) {
        return binary_search($search, $list, $left, $mid - 1);
    } elseif ($list[$mid] < $search) {
        return binary_search($search, $list, $mid + 1, $right);
    }
}
/**
 * 
 * @param unknown $array
 * @param unknown $search
 * @param unknown $from
 * @param unknown $to
 * @return int $result The index of the $search in the array
 * or -1 if not found 
 */
function binary_search($array, $search, $from, $to)
{
    if ($from > $to) {
        return -1;
    }
    $middle = (int) (($from + $to) / 2);
    if ($search == $array[$middle]) {
        return $middle;
    } else {
        if ($search > $array[$middle]) {
            return binary_search($array, $search, $middle + 1, $to);
        } else {
            return binary_search($array, $search, $from, $middle - 1);
        }
    }
}
示例#4
0
    while ($low <= $high) {
        $mid = intval(($low + $high) / 2);
        if ($arr[$mid] == $target) {
            return $mid;
        } else {
            if ($arr[$mid] < $target) {
                $low = $mid + 1;
            } else {
                if ($arr[$mid] > $target) {
                    $high = $mid - 1;
                }
            }
        }
    }
    return -1;
}
$arr_str = "2 3 4 1 50 2 3 4 5";
$arr = explode(" ", $arr_str);
sort($arr);
$high = count($arr) - 1;
$target = 70;
$index = binary_search($arr, $target, 0, $high);
if ($index == -1) {
    echo "target not found in array";
} else {
    echo "target index is :" . $index;
}
?>
	</body>
	
</html>
$settings = load_config();
$mysql_user = $settings[0];
$mysql_host = $settings[1];
$mysql_pass = $settings[2];
$mysql_database = $settings[3];
// Establish connection to the database
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_database);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    $log_message = "CRITICAL: Failed to connect to database while attempting to update the database tables! Please check your database and database settings!";
    log_to_file($log_message);
}
mysqli_query($con, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
$ground_gear_raw_data = get_ground_gear_data($con);
// $ground_gear_raw_data[0] contains all augment names
$search_result = binary_search($ground_gear_raw_data[0], $_GET["gear"]);
?>
	<head>
		<meta charset="ISO-8859-1">
		<title>
            <?php 
// Print out the current augment as the page title.
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    if (empty($_GET["gear"])) {
        print "Ground Armor List";
    } else {
        if (strcasecmp($ground_gear_raw_data[0][$search_result], $_GET["gear"]) != 0) {
            print "Ground Armor List ";
        } else {
            print $ground_gear_raw_data[0][$search_result];
        }
示例#6
0
    echo '</ul>
								</ul>';
}
?>
				<div class="col-md-1"></div>
			</div>
		</div>
		<div class="conflict-box">
			<input type="checkbox" />
			<label data-expanded="Conflicts" data-collapsed="Conflicts"></label>
			<div class="conflict-box-content">
				<ul class="sortable">
					<li id="placeholder" class="course placeholder">Course Placeholder</li>
					<?php 
foreach ($conflicts as $value) {
    $aCourse = binary_search($courses, 0, $value[courseID]);
    echo '<li id="' . $aCourse[courseNo] . '" class="course conflict" data-section="' . $value[sectionID] . '">' . $aCourse[courseNo] . '</li>';
}
?>
				</ul>
			</div>
		</div>
		<script src="http://code.jquery.com/jquery.js"></script>
		<script src="js/bootstrap.min.js"></script>		
		<script src="js/fileinput.js"></script>
		<script src="js/chimi.min.js"></script>
		<script src="js/intro.min.js"></script>
		<script src="js/zepto.min.js"></script>
		<script>
			$(document).ready(function() {
				// the two functions below are fixing issues with modal window not animating properly
function parse_sql_file($file_name, $is_olc_file, &$tables, &$text_array, &$insert_array, &$text_array_search, &$keys_array, &$table_charset, $default_charset, &$struct_count, &$data_count)
{
    if (defined('TABLE_PREFIX_COMMON')) {
        $error0 = 'Fehler beim Öffnen der Datei "#"!';
        $fp = @fopen($file_name, 'r');
        if ($fp) {
            $not_is_olc_file = !$is_olc_file;
            $check_charset = true;
            $not_is_olc_file && $not_is_version_5;
            $charset_len = strlen(DEFAULT_CHARSET);
            $not_found_charset = true;
            $file_offset = 0;
            $not_insert_into_found = true;
            while ($line = fgets($fp)) {
                $line = trim($line);
                $struct_count++;
                if ($line) {
                    $char1 = substr($line, 0, 1);
                    if (strpos(COMMENTS, $char1) !== false) {
                        continue;
                    } elseif (strpos($line, SEMI_COLON) !== false) {
                        if ($not_is_olc_file) {
                            if ($check_charset) {
                                $pos = strpos($line, DEFAULT_CHARSET);
                                if ($pos !== false) {
                                    $pos += $charset_len;
                                    $pos1 = strpos($line, BLANK, $pos);
                                    if ($pos1 === false) {
                                        $pos1 = strpos($line, SEMI_COLON, $pos);
                                    }
                                    $charset = strtolower(substr($line, $pos, $pos1 - $pos));
                                    $table_charset[$table_name] = $charset;
                                }
                            }
                        }
                    } else {
                        $uc_line = strtoupper($line);
                        if (strpos($uc_line, MY_INSERT_INTO) === false) {
                            if (strpos($uc_line, DROP_TABLE) === false) {
                                $pos = strpos($uc_line, CREATE_TABLE);
                                if ($pos !== false) {
                                    //Set new table name
                                    $line = rtrim(str_replace(LPAREN, EMPTY_STRING, $line));
                                    $pos = strrpos($line, BLANK);
                                    $table_name = substr($line, $pos + 1);
                                    if (REMOVE_PREFIX) {
                                        $table_name_p = $table_name;
                                        $table_name = str_replace(TABLE_PREFIX_COMMON, EMPTY_STRING, $table_name);
                                    }
                                    $table_name = strtolower(str_replace(APOS_S, EMPTY_STRING, $table_name));
                                    if ($is_olc_file) {
                                        $tables[] = $table_name;
                                        if ($check_charset) {
                                            $status_query = str_replace(HASH, $table_name_p, SHOW_TABLE_STATUS);
                                            $status = olc_db_query($status_query);
                                            if (olc_db_num_rows($status) > 0) {
                                                $status = olc_db_fetch_array($status);
                                                $charset = $status[COLLATION_FIELD];
                                                $table_charset[$table_name] = $charset;
                                            }
                                        }
                                    }
                                } else {
                                    if (strpos($line, KEY) !== false) {
                                        if ($not_is_olc_file) {
                                            $keys_array[$table_name][] = $line;
                                        }
                                    } else {
                                        //Found field, extract field name
                                        $line = str_replace(APOS_S, EMPTY_STRING, $line);
                                        if (substr($line, -1) == COMMA) {
                                            $line = substr($line, 0, strlen($line) - 1);
                                        }
                                        $line = TILDE . $line;
                                        if ($not_is_olc_file) {
                                            $text_array[] = $table_name . $line;
                                        }
                                        $pos = strpos($line, BLANK);
                                        if ($pos !== false) {
                                            $line = substr($line, 0, $pos);
                                        }
                                        $line = $table_name . $line;
                                        if ($is_olc_file) {
                                            $text_array[] = $line;
                                        } else {
                                            $text_array_search[] = $line;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    /*
                    else
                    {
                    $not_insert_into_found=false;
                    break;
                    }
                    */
                }
                //$file_offset=ftell($fp);		//Get current file pointer position
            }
            if ($is_olc_file) {
                sort($text_array);
            }
            $open_new_file = $is_olc_file || $not_insert_into_found;
            if ($open_new_file) {
                fclose($fp);
                if ($is_olc_file) {
                    $file_name = OLCOMMERCE_SQL;
                } else {
                    global $import_data_file_name;
                    $file_name = $import_data_file_name;
                }
            } else {
                fseek($fp, $file_offset);
                //reposition file to last line
            }
            //Identify/remove "INSERT INTO"s, which must not be applied from the import data!
            if ($open_new_file) {
                $fp = @fopen($file_name, 'r');
            }
            if ($fp) {
                if ($not_is_olc_file) {
                    //sort($text_array_search);
                    $data_for_table_len = strlen(DATA_FOR_TABLE);
                    $data_for_table_len_1 = strlen(DATA_FOR_TABLE_1);
                    $pos = strrpos($file_name, DOT);
                    $fp1 = substr($file_name, $pos);
                    $file_name_1 = str_replace($fp1, '_neu' . $fp1, $file_name);
                    @unlink($file_name_1);
                    $fp1 = @fopen($file_name_1, 'w');
                    if ($fp1) {
                        $insert_into_active = false;
                        fputs($fp1, NEW_LINE);
                    } else {
                        return str_replace(HASH, str_replace(ADMIN_PATH_PREFIX, EMPTY_STRING, $file_name_1), $error0);
                    }
                }
                $insert_into_len = strlen(MY_INSERT_INTO);
                while ($line = fgets($fp)) {
                    $data_count++;
                    if ($line) {
                        $pos = strpos($line, MY_INSERT_INTO);
                        $tline = trim($line);
                        if ($pos === false || $insert_into_active) {
                            if ($not_is_olc_file) {
                                if ($insert_into_active) {
                                    $insert_into_active = substr($tline, -1) != SEMI_COLON;
                                } elseif (REMOVE_PREFIX) {
                                    $pos = strpos($line, DATA_FOR_TABLE);
                                    if ($pos === false) {
                                        $pos = strpos($line, DATA_FOR_TABLE_1);
                                        $len = $data_for_table_len_1;
                                    } else {
                                        $len = $data_for_table_len;
                                    }
                                    if ($pos !== false) {
                                        $s = trim(substr($line, $pos + $len));
                                        $s1 = str_replace(APOS_S, EMPTY_STRING, $s);
                                        if (binary_search($tables, $s1)) {
                                            //Only apply prefix to tables belonging to OL-Commerce!
                                            $line = str_replace($s1, TABLE_PREFIX_COMMON . $s1, $line);
                                        }
                                    }
                                }
                                if ($not_is_in_ignore_table) {
                                    fputs($fp1, $line);
                                }
                            }
                        } else {
                            $pos += $insert_into_len;
                            $pos1 = strpos($line, BLANK, $pos);
                            $table_name = substr($line, $pos, $pos1 - $pos);
                            if ($is_olc_file) {
                                $table_name = str_replace(INSTALL_TABLE_PREFIX_COMMON, EMPTY_STRING, $table_name);
                            } else {
                                if (REMOVE_PREFIX) {
                                    $line = str_replace(TABLE_PREFIX_COMMON, EMPTY_STRING, $line);
                                }
                            }
                            $table_name = str_replace(APOS_S, EMPTY_STRING, $table_name);
                            $is_in_ignore_table = binary_search($insert_array, $table_name);
                            //in_array($table_name,$insert_array);
                            $not_is_in_ignore_table = !$is_in_ignore_table;
                            if ($not_is_olc_file) {
                                if ($is_in_ignore_table) {
                                    $not_is_in_ignore_table = strpos(ALLOW_IMPORT_TABLES, $table_name) !== false;
                                    if ($not_is_in_ignore_table) {
                                        $is_in_ignore_table = false;
                                        $s = $table_name;
                                        if (REMOVE_PREFIX) {
                                            $s = TABLE_PREFIX_COMMON . $s;
                                        }
                                        fputs($fp1, TRUNCATE_TABLE . APOS_S . $s . APOS_S . SEMI_COLON . NEW_LINE);
                                    }
                                }
                            }
                            if ($is_in_ignore_table) {
                                if ($insert_into_active) {
                                    $insert_into_active = substr($tline, -1) != SEMI_COLON;
                                }
                            } else {
                                if ($is_olc_file) {
                                    //Identify "INSERT INTO"s, which must not be applied from the import data!
                                    $insert_array[] = $table_name;
                                } else {
                                    //Modify "INSERT INTO"s!
                                    $insert_into_active = substr($tline, -1) != SEMI_COLON;
                                    $line = str_replace(MY_INSERT_INTO, INSERT_IGNORE_INTO, $line);
                                    if (REMOVE_PREFIX) {
                                        if (binary_search($tables, $table_name)) {
                                            //Only apply prefix to tables belonging to OL-Commerce!
                                            $pos = strpos($line, $table_name);
                                            $line = substr($line, 0, $pos) . TABLE_PREFIX_COMMON . substr($line, $pos);
                                        }
                                    }
                                    fputs($fp1, $line);
                                }
                            }
                        }
                    }
                }
                if ($is_olc_file) {
                    sort($insert_array);
                } else {
                    fclose($fp1);
                    $import_data_file_name = $file_name_1;
                }
                return true;
            } else {
                $show_error = true;
            }
        } else {
            $show_file_error = true;
        }
        if ($show_file_error) {
            $error = str_replace(HASH, str_replace(ADMIN_PATH_PREFIX, EMPTY_STRING, $file_name), $error0);
        }
    } else {
        $error = 'Unzulässiges System';
    }
    return $error;
}
<?php

require_once 'binarysearch.php';
$array = [12, 25, 30, 31, 35, 39, 41, 56];
$result = binary_search($array, 200, 0, count($array) - 1);
var_dump($result);
示例#9
0
}
$building_result = mysql_query("SELECT * FROM Building WHERE sessionID='" . $sessionID . "'");
$buildings = mysql_fetch_all($building_result);
$dept_result = mysql_query("SELECT * FROM Department WHERE sessionID='" . $sessionID . "'");
$departments = mysql_fetch_all($dept_result);
for ($i = 0; $i < count($instructors); ++$i) {
    $section_result = mysql_query("SELECT * FROM Section WHERE sessionID='" . $sessionID . "' AND instructorID='" . $instructors[$i]["instructorID"] . "'");
    $sections = mysql_fetch_all($section_result);
    echo $instructors[$i]["lastName"] . ", " . $instructors[$i]["firstName"];
    echo "<br><br>";
    start_schedule_table();
    // only print the sections which belong to the containing department?
    for ($j = 0; $j < count($sections); ++$j) {
        $roomID = slotID_to_roomID($sections[$j]["slotID"], $num_of_slots_per_room);
        $building = binary_search($buildings, "buildingID", $rooms[$roomID]["buildingID"]);
        $course = binary_search($courses, "courseID", $sections[$j]["courseID"]);
        $available = $sections[$j]["maxEnrollment"] - $sections[$j]["preliminaryEnrollment"];
        $dayOfWeek = slotID_to_dayOfWeek($sections[$j]["slotID"], $num_of_slots_per_room, count($periods));
        $period = get_period_from_slotID($sections[$j]["slotID"], $num_of_slots_per_room, $periods, count($periods));
        $startTime = convert_int_to_standard_time($period["startTime"]);
        $endTime = convert_int_to_standard_time($period["endTime"]);
        echo "<tr>";
        echo "<td>" . $building["buildingAbbr"] . "</td>";
        echo "<td>" . $rooms[$roomID]["roomNo"] . "</td>";
        echo "<td>" . $course["courseNo"] . "</td>";
        echo "<td>" . $instructors[$i]["lastName"] . " " . $instructors[$i]["firstName"][0] . "</td>";
        echo "<td>" . $course["courseName"] . "</td>";
        echo "<td>" . $course["creditHours"] . "</td>";
        echo "<td>" . $sections[$j]["maxEnrollment"] . "</td>";
        echo "<td>" . $sections[$j]["preliminaryEnrollment"] . "</td>";
        echo "<td>" . $available . "</td>";
示例#10
0
$ar = array("Kagia" => ["C++", "JavaScript", "Python", "PHP"], "Stacey" => ["C", "JavaScript", "PHP"], "Alex" => ["C", "JavaScript", "Python"], "Brian" => ["C++", "JavaScript", "Python", "PHP"]);
// to access items in the array
$ar["Kagia"];
foreach ($ar as $key => $value) {
    echo $key . ": " . sizeof($value) . "\n";
}
// binary search function
// to explain While loop
if (!function_exists("binary_search")) {
    function binary_search($array)
    {
        $l = 0;
        $u = count($array) - 1;
        while ($l <= $u) {
            $m = floor(($u + $l) / 2);
            if ($array[$m] == $item) {
                return $m;
            } else {
                if ($array[$m] > $item) {
                    $u = $m - 1;
                } else {
                    $l = $m + 1;
                }
            }
        }
        return -1;
    }
}
$haystack = range(10, 45);
echo binary_search($haystack, 22) . "\n";
 public function testNotTarget()
 {
     $this->assertEquals(-1, binary_search(array(), "Hello, world!"));
 }
示例#12
0
function binary_search($x, $list, $left, $right)
{
    if ($left > $right) {
        return -1;
    }
    $mid = ($left + $right) / 2;
    if ($list[$mid] == $x) {
        return $mid;
    } else {
        if ($list[$mid] > $x) {
            return binary_search($x, $list, $left, $mid - 1);
        } else {
            if ($list[$mid] < $x) {
                return binary_search($x, $list, $mid + 1, $right);
            }
        }
    }
    return -1;
}
示例#13
0
print_r(binary_search(6, [1, 3, 5]));
print -1;
print "<br/>";
print_r(binary_search(1, [1, 3, 5, 7]));
print 0;
print "<br/>";
print_r(binary_search(3, [1, 3, 5, 7]));
print 1;
print "<br/>";
print_r(binary_search(5, [1, 3, 5, 7]));
print 2;
print "<br/>";
print_r(binary_search(7, [1, 3, 5, 7]));
print 3;
print "<br/>";
print_r(binary_search(0, [1, 3, 5, 7]));
print -1;
print "<br/>";
print_r(binary_search(2, [1, 3, 5, 7]));
print -1;
print "<br/>";
print_r(binary_search(4, [1, 3, 5, 7]));
print -1;
print "<br/>";
print_r(binary_search(6, [1, 3, 5, 7]));
print -1;
print "<br/>";
print_r(binary_search(8, [1, 3, 5, 7]));
print -1;
print "<br/>";
print "</pre>";
$settings = load_config();
$mysql_user = $settings[0];
$mysql_host = $settings[1];
$mysql_pass = $settings[2];
$mysql_database = $settings[3];
// Establish connection to the database
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_database);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    $log_message = "CRITICAL: Failed to connect to database while attempting to update the database tables! Please check your database and database settings!";
    log_to_file($log_message);
}
mysqli_query($con, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
$superweapons_raw_data = get_superweapons_data($con);
// $superweapons_raw_data[0] contains all augment names
$search_result = binary_search($superweapons_raw_data[0], $_GET["superweapon"]);
?>
	<head>
		<meta charset="ISO-8859-1">
		<title>
            <?php 
// Print out the current augment as the page title.
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    if (empty($_GET["superweapon"])) {
        print "Skell Superweapon List";
    } else {
        if (strcasecmp($superweapons_raw_data[0][$search_result], $_GET["superweapon"]) != 0) {
            print "Skell Superweapon List ";
        } else {
            print $superweapons_raw_data[0][$search_result];
        }
示例#15
0
    $length = count($array);
    if (0 === $length) {
        return false;
    }
    $left = 0;
    $right = $length;
    while ($left + 1 < $right) {
        $mid = $left + ($right - $left) / 2;
        $mid = (int) $mid;
        if ($value < $array[$mid]) {
            $right = $mid;
        } else {
            $left = $mid;
        }
    }
    return $value === $array[$left];
}
function timer(callable $callable, $runs)
{
    $start = microtime(true);
    do {
        $callable();
    } while (--$runs);
    $stop = microtime(true);
    return $stop - $start;
}
$value = 90000;
$array = range(1, 100000);
echo '二分探索', PHP_EOL, timer(function () use($value, $array) {
    binary_search($value, $array);
}, 200), PHP_EOL;
示例#16
0
}
// associative array
$ar = array("Kagia" => ["C++", "JavaScript", "Python", "PHP"], "Stacey" => ["C", "JavaScript", "PHP"], "Alex" => ["C", "JavaScript", "Python"], "Brian" => ["C++", "JavaScript", "Python", "PHP"]);
// accessing items in the ar array
foreach ($ar as $key => $value) {
    echo $key . ":" . sizeof($value) . "\n";
}
// binary search function
if (!function_exists("binary_search")) {
    function binary_search($array, $item)
    {
        $lower = 0;
        $upper = count($array) - 1;
        while ($lower <= $upper) {
            $mid = floor(($upper + $lower) / 2);
            if ($array[$mid] == $item) {
                return $mid;
            } else {
                if ($array[$mid] > $item) {
                    $upper = $mid - 1;
                } else {
                    $lower = $mid + 1;
                }
            }
        }
        return -1;
    }
}
$haystack = range(10, 45);
echo binary_search($haystack, 33) . "\n";
示例#17
0
$dept_result = mysql_query("SELECT * FROM Department WHERE sessionID='" . $sessionID . "'");
$departments = mysql_fetch_all($dept_result);
for ($i = 0; $i < count($rooms); ++$i) {
    $rangeStart = $i * $num_of_slots_per_room;
    $rangeEnd = $rangeStart + ($num_of_slots_per_room - 1);
    $section_result = mysql_query("SELECT * FROM Section WHERE sessionID='" . $sessionID . "' AND slotID BETWEEN " . $rangeStart . " AND " . $rangeEnd . " ORDER BY slotID");
    $sections = mysql_fetch_all($section_result);
    echo $rooms[$i]["roomNo"];
    echo "<br><br>";
    start_schedule_table();
    // only print the sections which belong to the containing department?
    for ($j = 0; $j < count($sections); ++$j) {
        $roomID = slotID_to_roomID($sections[$j]["slotID"], $num_of_slots_per_room);
        $building = binary_search($buildings, "buildingID", $rooms[$roomID]["buildingID"]);
        $course = binary_search($courses, "courseID", $sections[$j]["courseID"]);
        $instructor = binary_search($instructors, "instructorID", $sections[$j]["instructorID"]);
        $available = $sections[$j]["maxEnrollment"] - $sections[$j]["preliminaryEnrollment"];
        $dayOfWeek = slotID_to_dayOfWeek($sections[$j]["slotID"], $num_of_slots_per_room, count($periods));
        $period = get_period_from_slotID($sections[$j]["slotID"], $num_of_slots_per_room, $periods, count($periods));
        $startTime = convert_int_to_standard_time($period["startTime"]);
        $endTime = convert_int_to_standard_time($period["endTime"]);
        echo "<tr>";
        echo "<td>" . $building["buildingAbbr"] . "</td>";
        echo "<td>" . $rooms[$roomID]["roomNo"] . "</td>";
        echo "<td>" . $course["courseNo"] . "</td>";
        echo "<td>" . $instructor["lastName"] . " " . $instructor["firstName"][0] . "</td>";
        echo "<td>" . $course["courseName"] . "</td>";
        echo "<td>" . $course["creditHours"] . "</td>";
        echo "<td>" . $sections[$j]["maxEnrollment"] . "</td>";
        echo "<td>" . $sections[$j]["preliminaryEnrollment"] . "</td>";
        echo "<td>" . $available . "</td>";
示例#18
0
        for ($i = 0; $i < sizeof($value); $i++) {
            echo "\t" . $value[$i] . "\n";
        }
        continue;
    }
    echo $key . ": " . $value . "\n";
}
// Binary search function test
$haystack = range(20, 45);
// returns the index of the element if not found, -1 otherwise
function binary_search($anArray, $element)
{
    $left = 0;
    $right = count($anArray) - 1;
    while ($left <= $right) {
        $middle = (int) (($left + $right) / 2);
        if ($anArray[$middle] === $element) {
            return $middle;
        } else {
            if ($element > $anArray[$middle]) {
                $left = $middle + 1;
            } else {
                $right = $middle - 1;
            }
        }
    }
    return -1;
}
echo binary_search($haystack, 23) . "\n";
echo binary_search($haystack, 400) . "\n";
示例#19
0
<?php

function binary_search($arr, $val)
{
    $low = 0;
    $hight = count($arr) - 1;
    while ($low <= $hight) {
        $middle = floor(($low + $hight) / 2);
        if ($arr[$middle] == $val) {
            return $val;
        } elseif ($arr[$middle] > $val) {
            $hight = $middle - 1;
        } else {
            $low = $middle + 1;
        }
    }
    return false;
}
$data = array(1, 2, 3, 4, 5, 6, 6, 7, 8, 10, 13, 16, 50);
var_dump(binary_search($data, 6));
var_dump(binary_search($data, 10));
var_dump(binary_search($data, 20));
示例#20
0
<?php

function binary_search($value, $data = array())
{
    $lo = 0;
    $high = count($data) - 1;
    while ($lo <= $high) {
        $mid = $lo + floor(($high - $lo) / 2);
        if ($value < $data[$mid]) {
            $high = $mid - 1;
        } elseif ($value > $data[$mid]) {
            $lo = $mid + 1;
        } else {
            return $mid;
        }
    }
    return -1;
}
echo binary_search(78, array(30, 33, 44, 45, 50, 56, 78, 88, 89, 90, 92, 94, 99, 100));
function mpdGetAllArtistAlbums()
{
    global $mpd;
    if (mpd_connect() == 0) {
        return NULL;
    }
    /* Retrieve all albums from mpd */
    if (is_null($albums = $mpd->GetAlbums())) {
        return NULL;
    }
    if (is_null($artists = $mpd->GetArtists())) {
        return NULL;
    }
    $numalbums = count($albums);
    // each album can have multiple artists. we need to return the
    // combination artist, album for each of them.
    for ($albumidx = 0; $albumidx < $numalbums; $albumidx++) {
        $album = $albums[$albumidx];
        $artistsforalbum = $mpd->GetArtistsForAlbum($album);
        $numartistsforalbum = count($artistsforalbum);
        $albumnum = binary_search($albums, $album);
        for ($artistidx = 0; $artistidx < $numartistsforalbum; $artistidx++) {
            $artistnum = binary_search($artists, $artistsforalbum[$artistidx]);
            $album_id = "{$artistnum},{$albumnum}";
            $retitem['Artist'] = $artistsforalbum[$artistidx];
            $retitem['Album'] = $album;
            $retitem['AlbumId'] = $album_id;
            $retitem['ScreenName'] = $artistsforalbum[$artistidx] . " - " . $album;
            $ret[] = $retitem;
        }
    }
    usort($ret, cmpMpdFilesByScreenName);
    return $ret;
}
示例#22
0
<?php

function binary_search($arr, $target_value)
{
    $start = 0;
    $end = count($arr) - 1;
    while ($start <= $end) {
        $mid = intval(($start + $end) / 2);
        if ($target_value < $arr[$mid]) {
            $end = $mid - 1;
        } else {
            if ($target_value > $arr[$mid]) {
                $start = $mid + 1;
            } else {
                if ($target_value == $arr[$mid]) {
                    return $mid;
                }
            }
        }
    }
    return -1;
}
echo binary_search([1 => 2, 2 => 4, 3 => 5, 6 => 7], 7);
示例#23
0
 function next()
 {
     while ($rev = $this->_revisions->next()) {
         if (binary_search($rev->getName(), $this->links) != false) {
             return $rev;
         }
     }
     $this->free();
     return false;
 }
$settings = load_config();
$mysql_user = $settings[0];
$mysql_host = $settings[1];
$mysql_pass = $settings[2];
$mysql_database = $settings[3];
// Establish connection to the database
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_database);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    $log_message = "CRITICAL: Failed to connect to database while attempting to update the database tables! Please check your database and database settings!";
    log_to_file($log_message);
}
mysqli_query($con, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
$skell_frame_raw_data = get_skell_frame_data($con);
// $skell_frame_raw_data[0] contains all augment names
$search_result = binary_search($skell_frame_raw_data[0], $_GET["frame"]);
?>
	<head>
		<meta charset="ISO-8859-1">
		<title>
            <?php 
// Print out the current augment as the page title.
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    if (empty($_GET["frame"])) {
        print "Skell Frame List";
    } else {
        if (strcasecmp($skell_frame_raw_data[0][$search_result], $_GET["frame"]) != 0) {
            print "Skell Frame List ";
        } else {
            print $skell_frame_raw_data[0][$search_result];
        }
$settings = load_config();
$mysql_user = $settings[0];
$mysql_host = $settings[1];
$mysql_pass = $settings[2];
$mysql_database = $settings[3];
// Establish connection to the database
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_database);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    $log_message = "CRITICAL: Failed to connect to database while attempting to update the database tables! Please check your database and database settings!";
    log_to_file($log_message);
}
mysqli_query($con, "SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
$augment_raw_data = get_augment_data($con);
// $augment_raw_data[0] contains all augment names
$search_result = binary_search($augment_raw_data[0], $_GET["search_term"]);
?>
	<head>
		<meta charset="ISO-8859-1">
		<title>
            <?php 
// Print out the current augment as the page title.
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    if (empty($_GET["search_term"])) {
        print "Augment Search";
    } else {
        if (strcasecmp($augment_raw_data[0][$search_result], $_GET["search_term"]) != 0) {
            print "Augment Search";
        } else {
            print $augment_raw_data[0][$search_result];
        }
示例#26
0
Suzanna Vellacott-Ford, Richard Burks
*/
// include general functions
include "functions.php";
// connect to database
mysql_connect("localhost", "root", "thebigredmachine") or die(mysql_error());
mysql_select_db("chimi") or die(mysql_error());
// get the session ID
$sessionID = getSessionCookie();
// get starting and ending index for slots in the selected room
$startingIndex = $_GET["starting_index"] + 0;
$offset = $_GET["offset"] - 1;
$endingIndex = $startingIndex + $offset;
// get courses and instructors
$courses = jsonString2Obj($_GET["courses"]);
$instructors = jsonString2Obj($_GET["instructors"]);
// fetch new sections from database
$section_result = mysql_query("SELECT courseID, instructorID, slotID, sectionID FROM Section WHERE sessionID='" . $sessionID . "' AND slotID BETWEEN {$startingIndex} AND {$endingIndex} ORDER BY slotID");
$sections = mysql_fetch_all($section_result);
for ($i = 0; $i < count($sections); $i++) {
    // find matching course and instructor for new section
    $course = binary_search($courses, 0, $sections[$i][0]);
    $instructor = binary_search($instructors, 0, $sections[$i][1]);
    // append course and instructor to new section
    $sections[$i]['course'] = $course;
    $sections[$i]['instructor'] = $instructor;
}
// disconnect from database
mysql_close();
// return new sections to view
echo json_encode($sections);