I need to remove duplicates from a table row.
to Combine the 3 numbers and generate all possible combinations, posted by .html form
(will be 6 if all numbers are different) Numbers must have 6 numbers each, like:
123, 234,etc.... Reduces the number of combinations if one number is the same of another,
like 112.
What i did, till now...
to isolate the numbers and store it in a row:
$cc=GetRow("SELECT numbers FROM table");
$n1=substr($cc, 0, 1);
$n2=substr($cc, 1, 1);
$n3=substr($cc, 2, 1);
//scrambling the numbers
$n1n2n3=$n1.$n2.$n3; //123 number stored
$n1n3n2=$n1.$n3.$n2; //132 number stored
$n2n1n3=$n2.$n1.$n3; //213 number stored
$n2n3n1=$n2.$n3.$n1; //231 number stored
$n3n1n2=$n3.$n1.$n2; //312 number stored
$n3n2n1=$n3.$n2.$n1; //321 number stored
$sql = sqlQuery("UPDATE table SET cc_concat = CONCAT_WS(',', '$n1n2n3', '$n1n3n2','$n2n1n3','$n2n3n1','$n3n1n2','$n3n2n1')");
But here´s the problem:
if the number is 112 will generate duplicates, only 3 are uniques:
$n1n2n3=$n1.$n2.$n3; //112 number stored
$n1n3n2=$n1.$n3.$n2; //121 number stored
$n2n1n3=$n2.$n1.$n3; //112 number stored
$n2n3n1=$n2.$n3.$n1; //121 number stored
$n3n1n2=$n3.$n1.$n2; //211 number stored
$n3n2n1=$n3.$n2.$n1; //211 number stored
Is there a way to update the table without the duplicates? or remove the duplicates
after update?
Thanks!
You could use an array to store the combinations and take advantage of the in_array() function to make sure you won't have duplicates:
$combinations = array();
if ( !in_array( $n1n2n3, $combinations ) ) $combinations[] = $n1n2n3;
if ( !in_array( $n1n3n2, $combinations ) ) $combinations[] = $n1n3n2;
// Do the same for the rest
// Then you could easily concatenate the result set from PHP.
$cc_concat = implode( ',', $combinations );
// Finally update the database.
$sql = sqlQuery("UPDATE table SET cc_concat = '{$cc_concat}' ");
Something like that should solve the problem.
Additionally you might prefer to use an algorithm to generate the combinations for you from an array of the three digits. For such algorithm you can check this thread out:
Get all permutations of a PHP array?
Related
I'm generating a unique 5 digit code using the following.
$randomUniqueNumber = rand(10000,99999);
I need to change this to an alphanumeric number with 5 digits and 2 letters.
The below gives me an alphanumeric number, but not restricted to just 2 letters.
$generated = substr(md5(rand()),0,5);
How would I generate a random string with 5 digits, and two letters?
There are probably a few ways to do it, but the following is verbose to get you going.
<?php
// define your set
$nums = range(0, 9);
$alphas = range('a', 'z');
// shuffle sets
shuffle($nums);
shuffle($alphas);
// pick out only what you need
$nums = array_slice($nums, 0, 5);
$alphas = array_slice($alphas, 0, 2);
// merge them together
$set = array_merge($nums, $alphas);
// shuffle
shuffle($set);
// create your result
echo implode($set); //86m709g
https://3v4l.org/CV7fS
Edit:
After reading I'm generating a unique 5 digit code using the following. I suggest, instead, create your string by changing the base from an incremented value, rather than random (or shuffled) as you will undoubtedly get duplicates, and to achieve no dupes you would need to pre-generate and store your entire set of codes and pick from them.
Instead look at something like hashids.
This question already has answers here:
PHP loop X amount of times
(10 answers)
Random Numbers without duplication using an array in PHP
(1 answer)
Closed 4 years ago.
How can I create a loop or limit for random number generation? I need 30 random numbers from (0,100).
I know I can use rand(0,100), for general generation of numbers. But I need to make this happen 30 times before I can sort out the data.
Repetition of numbers is NO issue, but I also need to sort the values into x<50 and x>50. Any idea how I can pull numbers from the array into 2 separate groups once generated?
Try this:
$lessFifty = array(); // Array to hold less than fifty numbers
$moreFifty = array(); // Array to hold more than fifty numbers
for ($i = 1; $i<=30; $i++) {
$number = rand(0, 100); // Variable $number holds random number
// Conditional statements
if ($number < 50 ) { // Check if value is less than fifty
$lessFifty[] = $number; // Add number to this array
} else { // Check if value is greater than fifty
$moreFifty[] = $number; // Add number to this array
}
}
// Display numbers in arrays
print_r($lessFifty);
print_r($moreFifty);
The for loop will will run the rand() function 30 times and insert each random number generated into the array $randomNum.
You can also use the while or do while loop to do the same action. It is up to you.
I've been searching for a way to count the amount of numbers in one row column spaced by ",". (But nothing found, I use MySQL and what to count with the use of PHP) This is going to be done for whole the database to find the total amount of numbers (by 100'reds). What I do is storing multiple numbers like the following.
100, 200, 300, 400
What I want is to get the amount of numbers in this column to be 4 and add this to the next row column number. Which could be
200
and therefore equal to 1 + 4 = 5.
To show it the database way see here
See database sample if it helps
The total number should then endup beeing 6.
I want to hear if it is possible in someway to do this?
Thanks in advance :)
You can write code as:-
<?php
$rows = array( '303, 117, 210, 211', '117', '444');
$count = 0;
foreach( $rows as $row ) {
$count += count(explode(',', $row));
}
echo "total : " . $count;
?>
To count the amount of numbers in this column you could use following:
$count_of_numbers = sizeof(explode(",",$row['yourColumn']));
Now add em up and you are done ;-)
I am working in php and I am trying to create 1000 tickets in a database. Each ticket needs it's own unique code that consists of letters and numbers about 6 characters long.
EXP.
Tbl_Tickets
ID code
1 3F2jk7
2 2HGUF1
3 9FJDNJ
4 MFJEY9
5 23988D
I was wondering is there a simple way of doing this with php, or excel, or any other way for that matter. I know that i can use a random number generator, but the check for the Unique would have a large BigO notation and the check would get messy.
Unique is not compatible with random, but the following might suit:
=CHOOSE(RANDBETWEEN(1,2),RANDBETWEEN(0,9),CHAR(RANDBETWEEN(65,90)))
copied across to populate six columns (say A to F) with, in G:
=A1&B1&C1&D1&E1&F1
and both copied down to say row 1100. Then select G, copy Paste Special Values, and Remove Duplicates on ColumnG and select first 1000 entries.
You could easily create an array of strings in php and write it to a database:
function generateRandomString($length = 6, $letters = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM'){
$s = '';
$lettersLength = strlen($letters)-1;
for($i = 0 ; $i < $length ; $i++){
$s .= $letters[rand(0,$lettersLength)];
}
return $s;
}
// Create an array with random strings
for ($i=0; $i<1000; $i++){
$ticket_numbers = array();
$ticket_number = generateRandomString();
while (in_array($ticket_number,$ticket_numbers))
$ticket_number = generateRandomString();
$ticket_numbers[] = $ticket_number;
}
// Write the array to a database
$con = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error");
foreach ($ticket_numbers as $number){
mysqli_query($con,"Your insert query using the value $number");
}
mysqli_close($con);
This should help you in the right direction though there are probably better ways to do this.
The function generateRandomString() was taken from How to generate random numbers/letters with PHP/Javascript
And another option. Encryption is guaranteed to be unique, so encrypting the numbers 0, 1, 2, ... will give you guaranteed unique random-seeming output. Six characters is 30 bits using Base32, or 36 bits using Base64. You will need a 30 (or 36 bit) cypher. Unless you have a library that includes Hasty Pudding cypher (unlikely) then just implement a simple four round Feistel cypher with the appropriate block size. It will not be completely secure, but it will be enough to defeat casual attacks.
This will produce random strings in column B with no repeats from B1 thru B1001
Sub Lottery()
Dim i As Long, j As Long, c As Collection
Set c = New Collection
v = Split("0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z", ",")
For i = 1 To 5000
can = ""
For j = 1 To 6
can = can & v(Application.RandBetween(0, 35))
Next j
On Error Resume Next
c.Add can, CStr(can)
On Error GoTo 0
If c.Count = 1000 Then Exit For
Next i
For i = 1 To 1000
Cells(i + 1, 2).Value = c(i)
Next i
End Sub
Is there is any way to avoid duplication in random number generation .
I want to create a random number for a special purpose. But it's should be a unique value. I don't know how to avoid duplicate random number
ie, First i got the random number like 1892990070. i have created a folder named that random number(1892990070). My purpose is I will never get that number in future. I it so i have duplicate random number in my folder.
A random series of number can always have repeated numbers. You have to keep a record of which numbers are already used so you can regenerate the number if it's already used. Like this:
$used = array(); //Initialize the record array. This should only be done once.
//Do like this to draw a number:
do {
$random = rand(0, 2000);
}while(in_array($random, $used));
$used[] = $random; //Save $random into to $used array
My example above will of course only work across a single page load. If it should be static across page loads you'll have to use either sessions (for a single user) or some sort of database (if it should be unique to all users), but the logic is the same.
You can write a wrapper for mt_rand which remembers all the random number generated before.
function my_rand() {
static $seen = array();
do{
$rand = mt_rand();
}while(isset($seen[$rand]));
$seen[$rand] = 1;
return $rand;
}
The ideas to remember previously generated numbers and create new ones is a useful general solution when duplicates are a problem.
But are you sure an eventual duplicate is really a problem? Consider rolling dice. Sometimes they repeat the same value, even in two sequential throws. No one considers that a problem.
If you have a controlled need for a choosing random number—say like shuffling a deck of cards—there are several approaches. (I see there are several recently posted answer to that.)
Another approach is to use the numbers 0, 1, 2, ..., n and modify them in some way, like a Gray Code encoding or exclusive ORing by a constant bit pattern.
For what purpose are you generating the random number? If you are doing something that generates random "picks" of a finite set, like shuffling a deck of cards using a random-number function, then it's easiest to put the set into an array:
$set = array('one', 'two', 'three');
$random_set = array();
while (count($set)) {
# generate a random index into $set
$picked_idx = random(0, count($set) - 1);
# copy the value out
$random_set []= $set[$picked_idx];
# remove the value from the original set
array_splice($set, $picked_idx, 1);
}
If you are generating unique keys for things, you may need to hash them:
# hold onto the random values we've picked
$already_picked = array();
do {
$new_pick = rand();
# loop until we know we don't have a value that's been picked before
} while (array_key_exists($new_pick, $already_picked));
$already_picked[$new_pick] = 1;
This will generate a string with one occurence of each digit:
$randomcharacters = '0123456789';
$length = 5;
$newcharacters = str_shuffle($randomcharacters);
$randomstring = substr($newcharacters, 0, $length);