Integer partitioning in PHP - php

This feels like a very simple problem, but I can't manage to make it elegant and 'feels right'. Here's the problem:
Giving a number T, print out all possible ways to get to T.
For example :
T = 5
1 + 1 + 1 +1 + 1
2 + 1 + 1 + 1
3 + 1 + 1
2 + 2 + 1
4 + 1
3 + 2
Note that, 3 + 2 is equal than 2 + 3, so you don´t have to print both cases.
I have to do it in PHP, hope anyone can help :).

One easy way to solve this problem is to solve it recursively. Following is a sample code,
<?php
function recursion($left, $last, $ar) {
if($left == 0) {
foreach ($ar as $n) {
printf("%d ", $n);
}
print "<br>";
return;
}
for($n = $last; $n <= $left; $n++) {
$b = $ar;
array_push($b, $n);
recursion($left - $n, $n, $b);
}
}
recursion(5, 1, []);
Output:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5
Note that, this bruteforce recursive solution won't work for bigger T. There exist some dynamic programming solutions which can solve this problm for numbers in a larger range.

Related

Get previous one item and next two item of current item in PHP. with max limit and current index only using for loop

i need to get previous value and next two values of a current_selected_val with max value stating in the starting only. Currently I am using this and not getting actual results. Can someone please help me in this
<?php
$pager_max = 8;
$current = 3;
for($i = 1; $i <= $pager_max; $i++) {
if ($i > ($current - $pager_max ) + 6 && $i < $current + 3) {
echo $i . '<br>';
}
}
?>
Here are the results which I wanted
If I select $current as
1 - 1 2 3 4
2 - 1 2 3 4
3 - 2 3 4 5
4 - 3 4 5 6
5 - 4 5 6 7
6 - 5 6 7 8
7 - 5 6 7 8
8 - 5 6 7 8
If I change $pager_max to any other value, then behaviour should be same. I need to use only formulas but not any functions here. Thanks in advance
function getValues(int $pager_max, int $current) {
if ($current === 1) {
return range(1, 4);
} elseif ($current + 2 >= $pager_max) {
return range($pager_max - 3, $pager_max);
} else {
return range($current - 1, $current + 2);
}
}

What makes this work?

I am trying to use this chunk of code as template, but Im not fully understanding of how one line works. I'll first provide the full chunk, then I'll single out the line I don't understand.
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
if(!file_exists($thumbnail_image)) {
$extension = get_file_extension($thumbnail_image);
if($extension) {
make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
}
}
echo '<img src="',$thumbnail_image,'" />';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
echo '<div class="clear"></div>';
}
else {
echo '<p>There are no images in this gallery.</p>';
}
I understand how everything with the exception of this line works.
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
I know it is getting its value from this line:
$images_per_row = 3;
But what actually makes this work? Im still pretty new to php, and I would like a better understanding of the code Im about to use before I use it.
Any answers at all would be appreciative!
$index % $images_per_row == 0
The % means "mod", example 4 mod 2 = 0.
A % B = the remainder when we divide A by B.
In your script, the condition is met (valued to 'true') when the remainder of $index divided by $images_per_row equals 0, meaning the divisibility of $index by $images_per_row.
Hope it helps!
% is the modulo operator. It divides the two numbers and then returns the remainder after the division.
It is quite easy to understand if you remember your fractions and how to reduce them to their lowest terms.
So, if we make 5 % 2 into a fraction and reduce it:
5 1 (this is the remainder)
--- → 2 ---
2 2
So, 5 % 2 = 1.
If we take 8 % 3 we can do the same thing:
8 2 (this is the remainder)
--- → 2 ---
3 3
So, 8 % 3 = 2.
If there is no remainder, such as in 9 % 3 then you will get 0 back. See:
9 0 (this is the remainder)
--- → 3 ---
3 3
You can write some PHP to see what the values are when doing the modulo operations:
$perRow = 3;
for ($i = 0; $i < 10; $i++) {
echo "$i % $perRow = ", $i % $perRow, ' | ', "$i / $perRow = ", ($i / $perRow), "\n";
}
Output:
0 % 3 = 0 | 0 / 3 = 0
1 % 3 = 1 | 1 / 3 = 0.33333333333333
2 % 3 = 2 | 2 / 3 = 0.66666666666667
3 % 3 = 0 | 3 / 3 = 1
4 % 3 = 1 | 4 / 3 = 1.3333333333333
5 % 3 = 2 | 5 / 3 = 1.6666666666667
6 % 3 = 0 | 6 / 3 = 2
7 % 3 = 1 | 7 / 3 = 2.3333333333333
8 % 3 = 2 | 8 / 3 = 2.6666666666667
9 % 3 = 0 | 9 / 3 = 3

Finding out combinations of x amount of integers to sum a given number

I am trying to figure out how I can loop out possible combinations of a x amount of integers to sum a specifik number.
Let's say, I have number 7 and I need to figure out how I can sum that number with integers in pairs 3.
1+2+4 = 7
3+3+1 = 7
5+1+1 = 7
2+2+3 = 7
Repeated combinations of numbers doesn't interest me, e.g.:
1+2+4 = 7
2+4+1 = 7
4+2+1 = 7
Anyone got any ideas of how I should proceed to reach this result?
Thanks.
Here is the solution for your problem.
function printPartitions($target, $max, $s){
if($target === 0 )
echo $s;
else
{
if($max > 1)
{
printPartitions($target, $max-1, $s);
}
if($max <= $target)
{
printPartitions($target-$max, $max, $max . " " . $s);
}
}
}
printPartitions(5, 5, "<br/>");
You have to specify the $target Value, $max value.
e.g.
printPartitions(7, 7, "<br/>");
It will give you output like:
1 1 1 1 1 1 1
1 1 1 1 1 2
1 1 1 2 2
1 2 2 2
1 1 1 1 3
1 1 2 3
2 2 3
1 3 3
1 1 1 4
1 2 4
3 4
1 1 5
2 5
1 6
7
I've got a solution to my problem. I feel I should defientely share it here, if anyone would ever need it. My solutions is based on this post: https://stackoverflow.com/a/19067884/3293843
<?php
function sampling($chars, $size, $combinations = array()) {
# if it's the first iteration, the first set
# of combinations is the same as the set of characters
if (empty($combinations)) {
$combinations = $chars;
}
# we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
# initialise array to put new values in
$new_combinations = array();
# loop through existing combinations and character set to create strings
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination .'#'. $char;
}
}
# call same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
// example
$chars = array('1', '2', '3','4');
$target = 7;
$maxLengthOfIntegers = 3;
$output = sampling($chars, $maxLengthOfIntegers);
$repeatedEntries = array();
//presenting the output
foreach($output as $out){
$explodeOut = explode('#',$out);
sort($explodeOut);
if(array_sum($explodeOut) == $target){
$sortedPattern = implode('',$explodeOut);
if(!in_array($sortedPattern,$repeatedEntries)){
echo $sortedPattern.'<br/>';
$repeatedEntries[] = $sortedPattern;
}
}
}
?>
Thank you for your time and efforts.
Regards,
Jacob
you can try this algorithm
$ans = array();
for($i=1;$i<=5;$i++)
{
$i1 = 7-$i;
$i2 = intval($i1 - $i);
$value = $i."+".$i1."+".$i2;
$ans = array_unshift($ans,$value);
}
print_r($ans);
hope this helps.. PLease let me know

PHP add to modulo

I want to display rows with 4 items, per row but I want to complete my rows
How can I always get : count(myarray) % 4 = 0 ?
let's say I have : count = 29 , how can I get : 3 ?
29 + 3 = 32 --> 32 % 4 = 0
$foo = 29;
$rounded_up = $foo + (4 - ($foo % 4));
29 % 4 -> 1
4 - 1 -> 3
29 + 3 -> 32
32 % 4 -> 0
This is a math question, not a programming question. But to answer it: the missing number is (4-(count % 4)) % 4. Example: count=29 , count%4=1, 4-1=3. The extra %4 is to catch edge cases like 28: 28%4=0; 4-0=4; 4%4=0.
How about
4 - count(myarray) % 4
x - count(myarray) % x
It will give you the rest.
And as pointed out by the comment below, if you want to avoid having 4 as the result of a complete row, use this :
(4 - count(myarray) % 4) % 4
(x - count(myarray) % x) % x
Try with:
$count = count($array);
$modulo = 4;
$result = $modulo - $count % $modulo;

PHP Counting Negative Numbers and Bold Only Even Numbers

On a form, I used PHP to display every number from 1 to the entered number. For example, if I enter 10 on the form, it displays 1 2 3 4 5 6 7 8 9 10. Now, I want it to be able to handle negative numbers by counting up to 0 (-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0) and make every even number in the results bold, e.g., 2 4 6 8 10, etc.). I've searched exhaustively for the answers without any luck. How would any of you suggest doing this? My code for the first part is displayed below. Thank you in advance.
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
echo ($counter).'<br>';
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
You can do this
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
if( $counter % 2 == 0 )
{
echo "<strong>" . $counter . "</strong><br />";
}
else
{
echo ($counter).'<br>';
}
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
Solution 1
Ok, some more information about the %. This is a modulo. It gives you back the remaining number if you divide it by the mod number. For example
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1 this because 3 / 2 = 1 and a bit,
you can't divide the last 1 completely by 2. So remain 1
4 % 2 = 0
Solution 2
Like crush said, you can use $counter & 1. What does this do?
If you look at a number bitwise. You want to AND it wit 1.
Bitwise number 2 = 0010 AND it with 0001 and your return will be 0000 (zero).
Bitwise number 3 = 0011 AND it with 0001 and your result will be 0001 (one).
If you ceep that going and only check the last bit, you can see if it is a even number. More about bitwise operations.

Categories