This question already has answers here:
Break long string into pieces php
(5 answers)
Closed 3 years ago.
I want to make a program which splits a long number into pieces of 13 digited number such that I can loop for every 13 digits just using php.
$number = 012345678901230123456789123
Should output
0123456789123
0123456789123
And it should be for any large number having the number of digit multiple of 13.It looks about looping and algorithm but I want to make it as short as possible and I have doubts on how to do it. So I am just asking about the main concept.
The most dynamic solution is probably to use array_functions on the string.
So str_split to make it array then chunk it in size 13 and implode the arrays.
$number = "012345678901230123456789123";
$arr = array_chunk(str_split($number), 13);
foreach($arr as &$val){
$val = implode($val);
}
https://3v4l.org/LsNFt
You can create a function where you can use your string and size as parameter and return an array of strings of the desired length:
function splitString($str, $packetSize) {
$output = [];
$size = strlen($str);
for ($i = 0; $i < $size; $i += $packetSize) {
if ($i + $packetSize < $size) {
$output[]= substr($str, $i, $packetSize);
} else {
$output[]=substr($str, $i);
}
}
return $output;
}
Related
This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 2 years ago.
we are trying to reorder the number
for example
5695479 to 9976554
48932 to 98432
means all bigger numbers then smaller number.
i was searching for some inbuilt function in php, we found sort function can do with array.
$numbers=array(4,6,2,22,11);
sort($numbers);
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
i have searched lot but i could not found any inbuilt functions.
There is no specific in-built function for this. However, you can use more than 1 inbuilt function to accomplish your task.
You can convert the integer to string usingstrval.
Now, split the string by each digit to get an array of integers.
Apply rsort() to sort them in descending order.
Implode() them back to get the number you desire.
Snippet:
<?php
$str = strval(5695479);
$nums = str_split($str);
rsort($nums);
echo implode("",$nums);
Another alterantive is to use counting sort for digits. Since digits will always be between 0-9, collect their count and loop from 9 to 0 and get the new number. This method would be faster than the first method if you have the number in string format with huge lengths.
Snippet:
<?php
$num = 48932; // if number is in string format, loop char by char using for loop
$count = [];
while($num > 0){
if(!isset($count[$num % 10])) $count[$num % 10] = 0;
$count[$num % 10]++;
$num = intval($num / 10);
}
$new_num = 0;
for($i = 9; $i >=0; --$i){
if(!isset($count[$i])) continue;
while($count[$i]-- > 0) $new_num = $new_num * 10 + $i; // you would rather concatenate here incase of string.
}
echo $new_num;
This question already has answers here:
Get the sum of all digits in a numeric string
(13 answers)
Closed 8 months ago.
I'm trying to adding all numbers from last 6 digit from substr(). Let say the number is 19283774616, I'm trying to have result from this: 7+7+4+6+1+6 = ?. Here is my current code
public function accountHash($accountNumber)
{
$result = 0;
$accountNumber = substr($accountNumber, -6);
for($i=0; $i<=strlen($accountNumber); $i++) {
$result += substr($accountNumber, $i, 1); // A non-numeric value encountered here
}
echo $result;
}
From the function above, "A non-numeric value encountered" error occurred. Need suggestion on how to do this. Thank you
You attempt to get more characters than string contains. Replace "<=" with "<" in your condition expression, i.e. change:
for($i=0; $i<=strlen($accountNumber); $i++) {
to
for($i=0; $i<strlen($accountNumber); $i++) {
You need to use < instead of <= in your for loop.
And you can do it a more simple way,
$result = 0;
for($i = 0; $i < 6; $i++){
$result += $string[-$i];
}
An alternative method without loops (or error checking, for what it's worth):
function accountHash($accountNumber)
{
return array_sum(
preg_split('//u', mb_substr($accountNumber, -6), null, PREG_SPLIT_NO_EMPTY)
);
}
Demo
This question already has answers here:
Generating all permutations of a given string
(57 answers)
Finding n-th permutation without computing others
(8 answers)
Closed 5 years ago.
I have difficult homework:
The list contains alphabetically all strings, which can form the letters A-K. The start of the list looks like this:
ABCDEFGHIJK,
ABCDEFGHIKJ,
ABCDEFGHJIK,
ABCDEFGHJKI, ...
The third string in the list is ABCDEFGHJIK. What is the list n's string?
I have made code to solve problem, but just to somewhere N value between 600 000 - 700 000. When I try to solve task with 700 000, I get 'Fatal error: Allowed memory size of 134217728 bytes exhausted'. And this is the trick of the task, automatic test number 11 is 1.6 million. So there must be a simpler algorithm, but I can not find it with search engine. So what would be algorithm? My code is:
<?php
$number = $_REQUEST['n'];
$lettering = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K");
$counter = $number;
$done = permute($lettering, $counter);
echo $done[$number-1]."<br>";
function permute($array, $counter) {
global $number;
if(1 === count($array))
return $array;
$result = array();
foreach($array as $key => $item)
foreach(permute(array_diff_key($array, array($key => $item)), $counter) as $p){
$result[] = $item.$p;
$counter--;
if($counter == 0) return $result;
}
return $result;
}
Let's take a look at how the permutation function is defined:
def permute(string):
for each char in string
sub <- remove char from string
return concat(char, permute(sub))
end
For a string of length L, the permute function returns an array of length L!. Thus we can see that the list of permutations starting with the char at index i in the string starts at the i*(L-1)! element in the final array.
Thus the find the permutation at index N, we need to iteratively narrow down our search space, by finding the character to append (index given by N / (M - 1)!) and its corresponding substring. We remove this character from the string, append it to the result, and repeat with N <- N % (M - 1)! on the substring (this is the offset index into the list of permutations of this substring).
PHP code:
function factorial($M) {
$N = 1;
for (;$M > 0;$M--)
$N *= $M;
return $N;
}
function remove_from_str($input, $index) {
$str1 = substr($input, 0, $index);
$str2 = substr($input, $index+1);
return $str1.$str2;
}
function get_permutation($input, $N) {
$L = strlen($input);
$result = "";
for ($M = $L; $M > 0; $M--) {
$F = factorial($M-1);
$j = intval(floor($N / $F));
$result = $result.$input[$j];
$input = remove_from_str($input, $j);
$N = $N % $F;
}
return $result;
}
Test:
echo get_permutation("ABCDEFGHIJK", 1600000); // Outputs "AFEIGCDJKBH"
(Note: N here starts at 0 rather than 1)
This question already has answers here:
Generating UNIQUE Random Numbers within a range
(14 answers)
Closed 7 years ago.
I am trying to find a solution in PHP that can generate three random numbers.
At the moment I have this that generates a random number that is different from $randNum;
The numbers need to be different from each other and also different from the variable $randNum
Thank you
$wrong = $randNum;
while ($wrong == $randNum) {
$wrong = rand(0,$max - 1);
}
<?php
$numbers = [];
for($i = 0; $i < 10; $i++){
$number = rand (1,15);
while (in_array($number, $numbers)){
$number = rand (1,15);
}
$numbers[] = $number;
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
This function generates unique 10 random numbers, range from 1-15 you can easy change this script to your needs.
This question already has answers here:
PHP random string generator
(68 answers)
Closed 7 years ago.
I'm trying to create a random string with numbers and letters and I found this function and thought it would be good, but I don't know if it is the correct way to create a true random string or if there is an easier way to do this? Below is what I have:
function randomGen() {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = strlen($chars);
$random;
for ($i = 0; $i < 8; $i++) {
$random = $chars[rand(0, $length - 1)];
}
return $random;
}
You could try using $random = substr(str_shuffle(MD5(microtime())), 0, 8);, which will output the same amount of random characters as you have in your example. I actually prefer this method over most as it doesn't require you to put in the expected characters and even more importantly, it can be done in one line of code!