How to increment the integer using PHP? [duplicate] - codeigniter

I need a suggestion on a function for a php counter. Is there any function to have numbers with 5 digit as 00001, or 00123… this number should be not random but have to increase the value of a previous field.
If a number is $n=’00001’ there is a function to increase by one and get 00002 and not 2?
Thanks
F.

$n2 = str_pad($n + 1, 5, 0, STR_PAD_LEFT);
Use str_pad() by adding 0s (third parameter) to the left (fourth parameter) of the old number $n incremented by 1 (first parameter) until the length is 5 (second parameter).

$number = 1;
$number++;
echo str_pad($number, 5, "0", STR_PAD_LEFT); //00002

As an alternative, in case you are interested, you can use sprintf to pad this with 0's up to a certain number fairly easily.
$numbers = array(0,1,11,111,1111,11111,11111);
$padded = array();
foreach($numbers as $num)
$padded[] = sprintf('%1$05d', ++$num);
print_r($padded);
PHP almost always has numerous ways to do the same thing. :)

You need the str_pad() function to add leading zeros to your indexes.
$new_index = str_pad($index, 5, "0", STR_PAD_LEFT);
Where $index your incrementing index in circle, $new_index is your index with leading zeros.

Related

Euler Project #520, making current code more efficient for finding simber integers?

Recently, for my Computer Algebra Systems class to work on. I have been given a problem randomly assigned from Project Euler to solve (Problem 520). The question goes as follows:
"We define a simber to be a positive integer in which any odd digit,
if present, occurs an odd number of times, and any even digit, if
present, occurs an even number of times.
For example, 141221242 is a 9-digit simber because it has three 1's,
four 2's and two 4's.
Let Q(n) be the count of all simbers with at most n digits.
You are given Q(7) = 287975 and Q(100) mod 1 000 000 123 = 123864868.
Find (∑1≤u≤39 Q(2^u)) mod 1 000 000 123."
The class requires me to use Wolfram-Mathematica to solve the problem using efficient coding. The code below is what my function of Q(n). I've included comments to help navigate through my coding.
Q[x_] := (
s = 0; (*Initalizes simber count*)
For[i = 1, StringLength[ToString[i]] <= x,
i++,(*Starts at 1 and continues until number is no longer 'x' digits long*)
num = ToString[i]; (*Sets 'num' to 'i' in string form*)
While[num != "", (*Loops until 'num' string is blank*)
If[EvenQ[
ToExpression[
Characters[num][[
1]]]], (*If the first digit of 'num' is Even*)
If[EvenQ[
StringCount[num,
Characters[num][[
1]]]], (*Checks if there are an Even quantity of the first digit in the string*)
num =
StringDelete[num,
Characters[num][[
1]]]; (*Removes all digits in the string that is the first digit e.g. 43442421 => 3221*)
If[num == "", (*If string is blank, increase simber count*)
s++;
]
,(*else*)
num =
"" (*If first digit is Even but not and Even quanity sets num to "" to break loop *)
]
,(*If the first digit of 'num' is Odd*)
If[OddQ[
StringCount[num,
Characters[num][[
1]]]], (*Checks if there are an Odd quantity of the first digit in the string*)
num = StringDelete[num, Characters[num][[1]]];
(*Removes all digits in the string that is the first digit e.g.
3292133 => 2921*)
If[num == "",(*If string is blank, increase simber count*)
s++;
]
,(*else*)
num =
"" (*If first digit is Odd but not and Odd quanity sets num to "" to break loop *)
]
]
]
];
s (*Displays final simber count*)
)
I've tested this code with Q[7] to verify the result as 287975. However, the time to process Q[7] took 6 minutes. As the value of n increases, the time to process the code gets exponentially higher.
Any help or recommendations to cut this processing time, or have I approached the Euler Problem from the wrong angle?
First, your code is very, well, bloated. This can be written down easier
isSimber[int_Integer] := isSimber[IntegerDigits[int]];
isSimber[digits_List] := And ## Equal ### EvenQ[Tally[digits]]
q[n_] := Count[isSimber /# Range[0, 10^n - 1], True]
q[7] // Timing
(* {58.328, 287975} *)
Second, yes I believe you need to think about this further. Just look that you, with your approach, would need to iterate to a number with 2^39 digits. Look that a simple Do loop with u being only 3 takes already 21s. And absolutely nothing is happening there, let alone a computation:
Do[
x = i,
{i, 10^(2^3)}
] // Timing
And we haven't even started to think about the memory. So yes, your current approach will not work.

best way to rewind a variable at 1?

I have an array with 12 entries.
When doing 12+1, I want to get the entry 1 of the array
When doing 12+4, I want to get the entry 4 of the array
etc...
I'm done with
cases_to_increment.each do |k|
if k > 12
k = k-12
end
self.inc(:"case#{k}", 1)
end
I found a solution with modulo
k = 13%12 = 1
k = 16%12 = 4
I like the modulo way but 12%12 return 0 and I need only numbers between 1..12
There is a way to do that without condition ?
You almost had the solution there yourself. Instead of a simple modulo, try:
index = (number % 12) + 1
Edit: njzk2 is correct, modulo is a very expensive function if you are using it with a value that is not a power of two. If, however, your total number of elements (the number you are modulo-ing with) is a power of 2, the calculation is essentially free.

Combinations of numbers with weight

I have an array / list of numbers. Each number has a certain priority / importance.
I need an algorithm that generate all combinations of numbers, but begin form numbers with the most importance.
e.g. [number, priority]: [1,1], [2,3], [3,2]. Highest priority is 1.
Combinations:
1, 3, 2, 1 1, 1 3, 3 3, 3 1, 1 2, 3 2, 2 1, 2 2, 1 1 1, 1 1 3, 1 3 1...
Any idea how to do this?
Of course, I want to generate a certain number of combinations.
I changed my answer to an example code, this way you don't even need a recursion. You have to sort first the elements by the priority. The example is in Perl, which is not so far from Pseudocode
#numbers = (1, 3, 2, 4);
push(#result, #numbers);
push(#working_list, #numbers);
for ($i = 1; $i < #numbers; $i++) { # We loop exactly for the length of the array (-1 because the first iteration is already inside)
my #result_list;
for $result (#working_list) { # get the result of the last iteration of $i
for $number (#numbers) { # iterate the numbers
push (#result_list, "$result $number"); # adding the numbers
}
}
push(#result, #result_list); # push the last result to final result list
undef #working_list;
push(#working_list, #result_list); # use the last result as a start point for next $i iteration
}
print join(', ', #result);
It seems you are looking for all combinations not for all permutations(I do not see any set of numbers repeated so you only care about the set of numbers but not of the order within that set).
Here is a tip for you - first write down the code that will produce all the possible combinations of the numbers 1 to n and then do a simple bijection between those number and the ones you are given taking into account the weights.

Simply Pseudocode Question

I'm new to psuedocode, and I'm having trouble putting all the pieces together:
Here is the definition of a function named foo whose inputs are two integers and an array of integers a[1] ... a[n].
1 Foo(k,m, a[1],...,a[n])
2 if (k < 1 or m > n or k > m) return 0
3 else return a[k] + Foo(k+1,m,a[1],...,a[n])
Suppose that the input integers are k=2 and m=5 and the input array contains [5, 6, 2, 3, 4, 8, 2]. What value does Foo return? Using summation notation, give a general formula for what Foo computes.
This one is making my head hurt. Here's what I did so far:
Line 2 has three conditional statements:
If k<1 // if 2<1..this is false
If m>n // if 5 is greater than the amount of values in the array, which is 7, so this is false
If k>m // if 2>5, this is false
So this function will display line 3. Line 3 says:
return a[k] which is a[2] which is the second value of the array, which is 6. So take 6 and add it to (2+1, 5, a[1].....,a[n])
Is what I have done correct up there? If so, how would I know what a[n] is? Am I supposed to be finding that? What would be the final result of all this?
Simple answer: that function returns the sum of all the numbers a[k], a[k+1], ... a[m].
What you're doing is correct so far. The "n" is just a placeholder meaning the last element of the array. So if your input array is {5,6,2,3,4,8,2}, n = 7 (cause your have seven elements), and a[n] = 2.
But why it returns the sum of all numbers a[k], a[k+1], ... a[m], you should find out for yourself. Just continue with your analysis. :)
So take 6 and add it to (2+1, 5,
a[1].....,a[n])
Take 6 and add it to Foo(2+1, 5, a[1].....,a[n]). It's a recursive function. You have to evaluate the function again with k=3 and m=5.
I think you are confused because your pseudocode looks like real code to me. I may be wrong, but we are taught to write pseudocode differently, using plain English phrases.

Evenly select N elems from array

I need to evenly select n elements from an array. I guess the best way to explain is by example.
say I have:
array [0,1,2,3,4] and I need to select 3 numbers.. 0,2,4.
of course, if the array length <= n, I just need to return the whole array.
I'm pretty sure there's a defined algorithm for this, been trying to search, and I took a look at Introduction to algorithms but couldn't find anything that met my needs (probably overlooked it)
The problem I'm having is that I can't figure out a way to scale this up to any array [ p..q ], selecting N evenly elements.
note: I can't just select the even elements from the example above..
A couple other examples;
array[0,1,2,3,4,5,6], 3 elements ; I need to get 0,3,6
array[0,1,2,3,4,5], 3 elements ; I need to get 0, either 2 or 3, and 5
EDIT:
more examples:
array [0,1,2], 2 elems : 0,2
array [0,1,2,3,4,5,6,7], 5 elems : 0,2, either 3 or 4, 5,7
and yes, I'd like to include first and last elements always.
EDIT 2:
what I was thinking was something like .. first + last element, then work my way up using the median value. Though I got stuck/confused when trying to do so.
I'll take a look at the algo you're posting. thanks!
EDIT 3:
Here's a souped up version of incrediman solution with PHP. Works with associative arrays as well, while retaining the keys.
<?php
/**
* Selects $x elements (evenly distributed across $set) from $set
*
* #param $set array : array set to select from
* #param $x int : number of elements to select. positive integer
*
* #return array|bool : selected set, bool false on failure
*/
///FIXME when $x = 1 .. return median .. right now throws a warning, division by zero
function select ($set, $x) {
//check params
if (!is_array($set) || !is_int($x) || $x < 1)
return false;
$n = count($set);
if ($n <= $x)
return $set;
$selected = array ();
$step = ($n - 1) / ($x - 1);
$keys = array_keys ($set);
$values = array_values($set);
for ($i=0; $i<$x; $i++) {
$selected[$keys[round($step*$i)]] = $values[round($step*$i)];
}
return $selected;
}
?>
You can probably implement an Iterator but I don't need to take it that far.
Pseudo-code:
function Algorithm(int N,array A)
float step=(A.size-1)/(N-1) //set step size
array R //declare return array
for (int i=0, i<N, i++)
R.push(A[round(step*i)]) //push each element of a position which is a
//multiple of step to R
return R
Probably the easiest mistake to make here would be to cast step as an integer or round it at the beginning. However, in order to make sure that the correct elements are pulled, you must declare step as a floating point number, and round multiples of step as you are iterating through the array.
Tested example here in php:
<?
function Algorithm($N,$A){
$step=(sizeof($A)-1)/($N-1);
for ($i=0;$i<$N;$i++)
echo $A[round($step*$i)]." ";
echo "\n";
}
//some of your test cases:
Algorithm(3,array(1,2,3));
Algorithm(5,array(0,1,2,3,4,5,6,7));
Algorithm(2,array(0,1,2));
Algorithm(3,array(0,1,2,3,4,5,6));
?>
Outputs:
1 2 3
0 2 4 5 7
0 2
0 3 6
(you can see your test cases in action and try new ones here: http://codepad.org/2eZp98eD)
Let n+1 be the number of elements you want, already bounded to the length of the array.
Then you want elements at indices 0/n, 1/n, ..., n/n of the way to the end of the array.
Let m+1 be the length of the array. Then your indices are round(m*i/n) (with the division done with floating point).
Your step size is (ArraySize-1)/(N-1).
Just add the step size to a floating point accumulator, and round off the accumulator to get the array index. Repeat until accumulator > array size.
It looks like you want to include both the first and last elements in your list.
If you want to pull X items from your list of N items, your step size will be (N-1)/(X-1). Just round however you want as you pull out each one.
Based on #Rex's answer. Psuedocode! Or some might even say it's JS
/// Selects |evenly spaced| elements from any given array. Handles all the edge cases.
function select(array: [Int], selectionCount: Int) {
let iterationCount = array.length - 1; // Number of iterations
let expectedToBeSelected = selectionCount - 1; // Number of elements to be selected
let resultsArray: [Int] = []; // Result Array
if (selectionCount < 1 || selectionCount > array.length) {
console.log("Invalid selection count!");
return resultsArray;
}
var i;
for (i in array) {
if (selectionCount == 1) {
resultsArray.push(array[i]);
break;
}
let selectedSoFar = Math.round(iterationCount * i / expectedToBeSelected);
if (selectedSoFar < array.length) {
resultsArray.push(array[selectedSoFar]);
} else {
break; // If selectedSoFar is greater than the length then do not proceed further.
}
}
return resultsArray;
}

Resources