


PHP Core Technology and Best Practices Hash Algorithm_PHP Tutorial
PHP Core Technology and Best Practices Hash Algorithm
PHP Core Technology and Best Practices Hash Algorithm
Hash table, also known as hash table, accesses records by mapping the keyword Key to a position in the array to speed up search. This mapping function is called a Hash function, and the array storing records is called a Hash table.
1. Hash function
The function is to convert an input of any length into a fixed-length output through the Hash algorithm, and the output is the Hash value. This conversion is a compression mapping, that is, the hash value space is usually much smaller than the input space. If no input is made, the hashing may result in the same output, and it is impossible to uniquely determine the input value from the hash value.
A good hash function should meet the following conditions: each keyword can be evenly distributed to any position in the Hash table, and does not conflict with other keywords that have been hashed into the Hash table. This is the most difficult thing to implement for the Hash function.
2. Hash algorithm
1) Direct remainder method
The direct remainder method is relatively simple. Just divide the keyword k by the size m of the Hash table to get the remainder. The algorithm is as follows:
H(k) = k mod m
For example: the size of the Hash table is m=12, and the given keyword is k=100, then h(k) = 4. This algorithm is a remainder operation and is relatively fast.
2) Product rounding method
The product rounding method first uses the keyword k times a constant A (0
H(k) = floor (m*(kA mod 1))
Among them, kA mod1 represents the decimal part of kA, and floor is the rounding operation.
When the keyword is a string, the above Hash algorithm cannot be used. Because a string is composed of characters, you can add up the ASCII codes of all the characters in the string to get an integer, and then calculate it according to the Hash algorithm above.
The algorithm is as follows:
Function hash($key,$m){
$strlen= strlen($key);
$hashval= 0;
For($i=0;$i< $strlen;$i ){
$hashval =ord($key{$I});
}
Return $hashval % $m;
}
3) Classic Hash algorithm Times33
Unsigned int DJBHash(char *str){
Unsignedint hash = 5381;
While(*str){
Hash =(hash <<5) (*str );
}
Return (hash &0x7FFFFFFF)
}
The algorithm idea is to continuously multiply by 33. Its efficiency and randomness are very good, and it is widely used in many open source projects, such as Apache, Perl and PHP.
3. Hash table
The time complexity of the Hash table is O(1), and the Hash table structure can be represented by a diagram:
To construct a Hash table, you must create an array large enough to store data, and you also need a Hash function to map the keyword Key to a certain position in the array.
Hash table implementation steps:
1) Create a fixed-size array to store data.
2) Design Hash function.
3) Map the keyword to a certain position in the array through the Hash function, and perform data access at this position.
4. Use PHP to implement Hash table
First create a HashTable class with two attributes $buckets and $size. $buckets is an array used to store data, and $size is used to record the size of the $buckets array. Then allocate memory for the $buckets array in the constructor. The code is as follows:
ClassHashTable{
Private$buckets;
Private$size =10;
Publicfunction __construct(){
$this-> buckets =new SplFixedArray($this->size);
}
}
?>
In the constructor, an array of size 10 is allocated for the $buckets array. The SPL extended SplFixedArray array is used here, not an ordinary array
This is because the SplFixedArray array is closer to the C language array and more efficient. An initial size needs to be provided when creating its array.
Note: To use the SplFixedArray array, the SPl extension must be enabled. If it is not enabled, you can use a normal array instead.
Then specify a Hash function for the Hash table. For the sake of simplicity, the simplest Hash algorithm is used here. That is, as mentioned above, add all the characters of the string and take the remainder. The code is as follows:
Public Function hashfunc($key){
$strlen= strlen($key);
$hashval= 0;
For($i=0;$i< $strlen;$i ){
$hashval =ord($key{$I});
}
Return $hashval % $this->size;
}
With the Hash function, you can implement the insertion and search methods. When inserting data, first calculate the location of the keyword in the Hash table through the Hash function, and then save the data to this location. The code is as follows:
Public function insert($key,$val){
$index= $this -> hashfunc($key);
$this-> buckets[$index] = $val;
}
The method of finding data is similar to the method of inserting data. First, calculate the position of the keyword in the Hash table through the Hash function, and then return the data at this position. The code is as follows:
Public function find($key){
$index= $this -> hashfunc($key);
Return$this ->buckets[$index];
}
At this point, a simple Hash table has been written. Let’s test this Hash table. The code list is as follows:
$ht= new HashTable();
$ht->insert(‘key1’,’value1’);
$ht->insert(‘key2’,’value2’);
Echo$ht ->find(‘key1’);
Echo$ht ->find(‘key2’);
?>
Full code: #hash.php
<!--?PHP Class HashTable{ Private$buckets; Private $size=10; Public function__construct(){ $this---> buckets =new SplFixedArray($this->size); } PublicFunction hashfunc($key){ $strlen= strlen($key); $hashval= 0; For($i=0;$i< $strlen;$i++){ $hashval+=ord($key{$i}); } return$hashval % $this->size; } Publicfunction insert($key,$val){ $index= $this -> hashfunc($key); $this-> buckets[$index] = $val; } Publicfunction find($key){ $index= $this -> hashfunc($key); Return$this ->buckets[$index]; } } $ht = newHashTable(); $ht->insert('key1','value1'); $ht->insert('key2','value2'); Echo $ht->find('key1'); Echo $ht->find('key2'); ?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











StableDiffusion3’s paper is finally here! This model was released two weeks ago and uses the same DiT (DiffusionTransformer) architecture as Sora. It caused quite a stir once it was released. Compared with the previous version, the quality of the images generated by StableDiffusion3 has been significantly improved. It now supports multi-theme prompts, and the text writing effect has also been improved, and garbled characters no longer appear. StabilityAI pointed out that StableDiffusion3 is a series of models with parameter sizes ranging from 800M to 8B. This parameter range means that the model can be run directly on many portable devices, significantly reducing the use of AI

This paper explores the problem of accurately detecting objects from different viewing angles (such as perspective and bird's-eye view) in autonomous driving, especially how to effectively transform features from perspective (PV) to bird's-eye view (BEV) space. Transformation is implemented via the Visual Transformation (VT) module. Existing methods are broadly divided into two strategies: 2D to 3D and 3D to 2D conversion. 2D-to-3D methods improve dense 2D features by predicting depth probabilities, but the inherent uncertainty of depth predictions, especially in distant regions, may introduce inaccuracies. While 3D to 2D methods usually use 3D queries to sample 2D features and learn the attention weights of the correspondence between 3D and 2D features through a Transformer, which increases the computational and deployment time.

Written above & the author’s personal understanding: At present, in the entire autonomous driving system, the perception module plays a vital role. The autonomous vehicle driving on the road can only obtain accurate perception results through the perception module. The downstream regulation and control module in the autonomous driving system makes timely and correct judgments and behavioral decisions. Currently, cars with autonomous driving functions are usually equipped with a variety of data information sensors including surround-view camera sensors, lidar sensors, and millimeter-wave radar sensors to collect information in different modalities to achieve accurate perception tasks. The BEV perception algorithm based on pure vision is favored by the industry because of its low hardware cost and easy deployment, and its output results can be easily applied to various downstream tasks.

Trajectory prediction plays an important role in autonomous driving. Autonomous driving trajectory prediction refers to predicting the future driving trajectory of the vehicle by analyzing various data during the vehicle's driving process. As the core module of autonomous driving, the quality of trajectory prediction is crucial to downstream planning control. The trajectory prediction task has a rich technology stack and requires familiarity with autonomous driving dynamic/static perception, high-precision maps, lane lines, neural network architecture (CNN&GNN&Transformer) skills, etc. It is very difficult to get started! Many fans hope to get started with trajectory prediction as soon as possible and avoid pitfalls. Today I will take stock of some common problems and introductory learning methods for trajectory prediction! Introductory related knowledge 1. Are the preview papers in order? A: Look at the survey first, p

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

The convergence of artificial intelligence (AI) and law enforcement opens up new possibilities for crime prevention and detection. The predictive capabilities of artificial intelligence are widely used in systems such as CrimeGPT (Crime Prediction Technology) to predict criminal activities. This article explores the potential of artificial intelligence in crime prediction, its current applications, the challenges it faces, and the possible ethical implications of the technology. Artificial Intelligence and Crime Prediction: The Basics CrimeGPT uses machine learning algorithms to analyze large data sets, identifying patterns that can predict where and when crimes are likely to occur. These data sets include historical crime statistics, demographic information, economic indicators, weather patterns, and more. By identifying trends that human analysts might miss, artificial intelligence can empower law enforcement agencies

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images
