openstackid/app/libs/Utils/MathUtils.php

59 lines
1.7 KiB
PHP

<?php namespace Utils;
/**
* Copyright 2016 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
/**
* Class MathUtils
* @package Utils
*/
abstract class MathUtils
{
/**
* @param $p
* @param $size
* @return bool
*
* @see http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm
*
*/
static public function nextPermutation($p, $size)
{
// slide down the array looking for where we're smaller than the next guy
for ($i = $size - 1; $i >= 0 && $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;
}
}