Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm working on a url shortener. I based mine on this one https://github.com/phpmasterdotcom/BuildingYourOwnURLShortener and more or less took the function to create the short codes, because i couldn't come up with an algorithm myself:
<?php
convertIntToShortCode($_GET["id"]); // Test codes
function convertIntToShortCode($id) {
$chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
$id = intval($id);
if ($id < 1) {
echo "ERROR1";
}
$length = strlen($chars);
// make sure length of available characters is at
// least a reasonable minimum - there should be at
// least 10 characters
if ($length < 10) {
echo "ERROR2";
}
$code = "";
while ($id > $length - 1) {
// determine the value of the next higher character
// in the short code should be and prepend
$code = $chars[fmod($id, $length)] . $code;
// reset $id to remaining value to be converted
$id = floor($id / $length);
}
// remaining value of $id is less than the length of
// self::$chars
$code = $chars[$id] . $code;
echo $code;
}
?>
Although it works, some of my numbers (database id) output strange shortcodes:
1 -> 2
2 -> 3
...
10 -> c
11 -> d
12 -> e
...
Is there any easy way i can modify this code, so that my generated short codes are longer than just one character (at least two or three characters for every shortcode), even for integers like 1, 2, 3 etc.?
Also is there anybody who can tell me, how this algorithm above works to output short codes for integers?
Thanks in advance
What you would like to do is convert that number to a different notation - one that includes both letters and numbers like base 36 which is actually alphanumeric -> a-z + 0-9.
So what you would need to do is:
$string = base_convert ( $number , 10, 36 );
Documentation:
string base_convert ( string $number , int $frombase , int $tobase );
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to write a function that takes the following 2 parameters:
A sentence as a string
A number of lines as an integer
So if I was to call formatLines("My name is Gary", 2); ...
The possible outcomes would be:
array("My name is", "Gary");
array("My name", "is Gary");
array("My", "name is Gary");
It would return: array("My name", "is Gary"); because the difference in character counts for each line is as small as possible.
So the part I am ultimately stuck on is creating an array of possible outcomes where the words are in the correct order, split over x lines. Once I have an array of possible outcomes I would be fine working out the best result.
So how would I go about generating all the possible combinations?
Regards
Joe
It seems like doing this by creating all possible ways of splitting the text and then determining the best one would be unnecessarily inefficient. You can count the characters and divide by the number of lines to find approximately the right number of characters per line.
function lineSplitChars($text, $lines) {
if (str_word_count($text) < $lines) {
throw new InvalidArgumentException('lines must be fewer than word count', 1);
}
$width = strlen($text) / $lines; // initial width calculation
while ($width > 0) {
$result = explode("\n", wordwrap($text, $width)); // generate result
// check for correct number of lines. return if correct, adjust width if not
$n = count($result);
if ($n == $lines) return $result;
if ($n > $lines) {
$width++;
} else {
$width--;
};
}
}
An answer has been accepted here - but this strikes me as a rather cumbersome method for solving the problem when PHP already provides a wordwrap() function which does most of the heavy lifting:
function format_lines($str, $lines)
{
$guess_length=(integer)(strlen($str)/($lines+1));
do {
$out=explode("\n", wordwrap($str, $guess_length));
$guess_length++;
} while ($guess_length<strlen($str) && count($out)>$lines);
return $out;
}
As it stands, it is rather a brute force method, and for very large inputs, a better solution would use optimum searching (adding/removing a larger initial interval then decreasing this in iterations)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi am having 10 elements in array . Am trying to get my random element mostly from first 5 elements. Which means random element appearance from first 5 elements should be much greater than next 5 elements
$arr = array('a','b','c','d','e','f','g','h','i','j');
$random = $arr[array_rand($arr)];
Am using above one to get the random element normally
Use function rand(min_num, max_num):
function rand5($array) {
$part = rand(1, 10);
return ($part > 3) ? $array[rand(0, 4)] : $array[rand(5, 9)];
}
$arr = array('a','b','c','d','e','f','g','h','i','j');
$random = rand5($arr);
Try this simple and easy code :-
$arr = array('a','b','c','d','e','f','g','h','i','j');
$rand = rand(0,9);
echo $arr[($rand <= 6 ? ($rand%5) : $rand)];
You just have to get the random number between 0 to 9 and divide that number in 70%(0-6) and 30%(7-9). If its greater than 5 then only use the remainder else directly get that number
Here is the fiddle :- https://3v4l.org/TWGJJ
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I would like to create a website that allows a user to generate a selectable number of unique strings of text that all follow an algorithm but as it is website based I am not too sure about how I go about it.
For example user A wants to generate 20 strings of unique text that all follow say AA***B^^** where A&B is a constant that doesn't change, where * is a random number and ^ is a random letter.
Is that possible? I am thinking of using php rand for the number but not 100% sure.
Thanks
You could use something like this:
<?php
function randomGenerator($string)
{
$string_array = str_split( $string );
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
foreach ($string_array as $k => $v) {
if ($v == '*')
$string_array[$k] = rand(0,9);
if ($v == '^')
$string_array[$k] = $characters[rand(0,51)];
}
$string = implode('', $string_array);
return $string;
}
echo randomGenerator('AA***NN^^'); // may print AA478NNhU
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am just trying to figure out how I can get the actual digits of a figure that has been calculated within php and formatted to have 2 decimal places.
so say its calculated it to be 45.76 I am trying to figure out how I can get the 76 from it for an if statement. Basically I want it to look and just say that if it's 00 then remove them, if not, show them.
Thanks
Try :
function showDecimals($v){
$n = abs($v);
$whole = floor($n);
$fraction = $n - $whole;
return $fraction > 0
}
And...
if (showDecimals(10.15)){
//Show
}else{
//Remove?
}
You want to show a whole number if there is no decimal place, and 2 decimals of precision if not?
Method 1
function formatNumber($n) {
$n = round($n*100)/100;
return ''+$n;
}
This simply rounds it to 2 decimals of precision. Zero truncation is automatic.
Usage
echo formatNumber(0); //0
echo formatNumber(0.5); //0.5
echo formatNumber(0.894); //0.89
echo formatNumber(0.896); //0.9
echo formatNumber(1.896); //1.9
Method 2
Or if you 1.9 to display as 1.90, I suppose this would work:
function formatNumber($n) {
if ($n == 0)
return ''+$n;
$str = ''.round($n*100)/100;
$dotpos = strrpos('.', $str);
if (strlen(substr($str, $dotpos+1)) === 2)
$str .= '0';
return $str;
}
Usage:
echo formatNumber(0); //0
echo formatNumber(0.5); //0.50
echo formatNumber(0.894); //0.89
echo formatNumber(0.896); //0.90
echo formatNumber(1.896); //1.90
Edit: Accidentally posted broken version of method 2, should be fixed now.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have generate a 16 digit number and i want to extract one number from every 4 digits of that 16 digit number. For e.g: 1234567892345678. I want to extract 2 from 1234, 7 from 5678, 3 from 9034 & 7 from 5678. Then store it in another variable $a. the extraction will be in a random manner.
You can try this -
$d = '1234567892345678';
$s = str_split($d, 4); // split in 4 digits
$n = array_map(function($x) {
return substr($x, rand(0, 3), rand(1, 1)); // extract single digit random number
}, $s);
$n will hold the random numbers.
I might be late at answering this question but you can simply use strlen function along with for loop like as
$str = "1234567892345678";
for($i = 0; $i < strlen($str);$i += 4){
echo $str[$i+rand(0,3)];
}
Here you have a one-liner:
$s = $string[rand(0,3)].$string[rand(4,7)].$string[rand(8,11)].$string[rand(12,15)];
echo $s;
Another one-liner:
for($s='',$i=0;$i<10; $s.=$string[rand($i,$i+=3)]);
echo $s;