473,788 Members | 2,807 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find longest matching key

Hello,

I have two arrays like this:

$aSearch = array( 'A', 'B', 'C.D', 'E', 'F' );
$aSubject = array( 'A' =0, 'A.B' =1, 'X' =2, 'C.D.E' =3, 'A.B.C' =>
4 );

Now I want to search $aSubject for the longest key that consists of the
first x elements of $aSearch concatenated by "." (where x = 1...count(
$aSearch ) ). In other words, he algorithm involved should check for the
existence of the following keys in $aSubject:

A
A.B
A.B.C.D
A.B.C.D.E
A.B.C.D.E.F

and return the longest match - in the example 'A.B'. Now I could first
create an array of all keys to search for and then loop through them to find
a match in $aSubject, but I wonder if there is a more efficient, more
elegant solution. There doesn't seem to be any PHP function that could help
with this specific problem.

Greetings,
Thomas

--
C'est pas parce qu'ils sont nombreux ŕ avoir tort qu'ils ont raison!
(Coluche)
Nov 17 '07 #1
4 3055
Thomas Mlynarczyk wrote:
I have two arrays like this:

$aSearch = array( 'A', 'B', 'C.D', 'E', 'F' );
$aSubject = array( 'A' =0, 'A.B' =1, 'X' =2, 'C.D.E' =3, 'A.B.C' =>
4 );

Now I want to search $aSubject for the longest key that consists of the
first x elements of $aSearch concatenated by "." (where x = 1...count(
$aSearch ) ). In other words, he algorithm involved should check for the
existence of the following keys in $aSubject:

A
A.B
A.B.C.D
A.B.C.D.E
A.B.C.D.E.F

and return the longest match - in the example 'A.B'.
foreach ($aSearch as $a)
{
$key = $a;
while (strlen($key) && !isset($aSubjec t[$key]))
$key = preg_replace('/\.?[^\.]*$/', '', $key);

if (strlen($key))
printf("Searche d for '%s'. Closest match was '%s', value %s.\n",
$a,
$key,
$aSubject[$key]);
else
printf("Searche d for '%s'. No matching key found.\n", $a);
}

A bit cleaner to use a function:

function array_component _search ($needle, &$haystack, &$value=NULL )
{
$key = $needle;
while (strlen($key) && !isset($haystac k[$key]))
$key = preg_replace('/\.?[^\.]*$/', '', $key);

$value = strlen($key) ? $haystack[$key] : NULL;

return strlen($key) ? $key : FALSE;
}
foreach ($aSearch as $a)
{
$key = array_component _search($a, $aSubject, $value);

if ($key!==FALSE)
printf("Searche d for '%s'. Closest match was '%s', value %s.\n",
$a,
$key,
$value);
else
printf("Searche d for '%s'. No matching key found.\n", $a);
}

Note that array_component _search takes two required arguments:

$needle = Key you're searching for a close match for.
$haystack = Lookup array.

The closest matching key is returned by the function, and as a side-effect,
the value for that key may be placed in a variable passed to the function
as a third argument.

Helpful?

--
Toby A Inkster BSc (Hons) ARCS
[Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
[OS: Linux 2.6.12-12mdksmp, up 11 days, 1:11.]
[Now Playing: ./stereophonics/handbags_and_gl adrags.ogg.]

Belgium
http://tobyinkster.co.uk/blog/2007/11/17/belgium/
Nov 17 '07 #2
Also sprach Toby A Inkster:
foreach ($aSearch as $a)
{
$key = $a;
while (strlen($key) && !isset($aSubjec t[$key]))
$key = preg_replace('/\.?[^\.]*$/', '', $key);

if (strlen($key))
printf("Searche d for '%s'. Closest match was '%s', value %s.\n",
$a,
$key,
$aSubject[$key]);
else
printf("Searche d for '%s'. No matching key found.\n", $a);
}
This finds $aSubject['A'], but should find $aSubject['A.B'].
If I remove the foreach and put an
$a = implode( '.', $aSearch )
at the beginning, it will find $aSubject['A.B.C']. (Because, in the imploded
form, the information that 'C.D' is "indivisibl e" gets lost.)

Maybe I was not clear enough describing my problem. The algorithm should be
something equivalent to

$aSearch = array( 'A', 'B', 'C.D', 'E', 'F' );
$aSubject = array( 'A' =0, 'A.B' =1, 'X' =2, 'C.D.E' =3, 'A.B.C' =>
4 );
1)
Convert $aSearch somehow to
$aSearch =array(
'A.B.C.D.E.F',
'A.B.C.D.E',
'A.B.C.D',
'A.B', // Note: no 'A.B.C', as 'C.D' is "indivisibl e"
'A'
)

2)
foreach ( $aSearch as $sKey )
{
if ( array_key_exist s( $sKey, $aSubject ) ) { echo "Found
$aSubject[$sKey]"; break; }
}

Meanwhile I've come up with this:

for ( $tmp = array(), $i = 0; $i < count( $aSearch ); $i++ )
{
$tmp[$i] = $i ? $tmp[ $i - 1 ] . '.' . $aSearch[$i] : $aSearch[$i];
}

foreach ( array_reverse( $tmp, true ) as $sKey )
{
if ( array_key_exist s( $sKey, $aSubject ) ) { echo "Found
$aSubject[$sKey]"; break; }
}

But it does not look elegant/efficient enough to me.

Greetings,
Thomas
--
C'est pas parce qu'ils sont nombreux ŕ avoir tort qu'ils ont raison!
(Coluche)
Nov 17 '07 #3
On Nov 17, 6:13 pm, "Thomas Mlynarczyk" <tho...@mlynarc zyk-
webdesign.dewro te:
$aSearch = array( 'A', 'B', 'C.D', 'E', 'F' );
$aSubject = array( 'A' =0, 'A.B' =1, 'X' =2,
'C.D.E' =3, 'A.B.C' =4 );

Now I want to search $aSubject for the longest key that consists of the
first x elements of $aSearch concatenated by "."
....
and return the longest match - in the example 'A.B'. Now I could first
....
function longestMatching Key ($aSrch, $aSubj) {
if (array_key_exis ts($k=implode(" .", $aSrch), $aSubj)) return $k;
for ($i=sizeof($aSr ch);$k=substr($ k,0,-strlen($aSrch[--$i])-1);)
if (array_key_exis ts($k, $aSubj)) break;
return $k; }
(5 lines total, one loop, no reversing, watch for wrapping) Though
perhaps not overly different from what you suggested...
Csaba Gabor from Vienna
Nov 17 '07 #4
Also sprach Csaba Gabor:
function longestMatching Key ($aSrch, $aSubj) {
if (array_key_exis ts($k=implode(" .", $aSrch), $aSubj)) return $k;
for ($i=sizeof($aSr ch);$k=substr($ k,0,-strlen($aSrch[--$i])-1);)
if (array_key_exis ts($k, $aSubj)) break;
return $k; }
(5 lines total, one loop, no reversing, watch for wrapping) Though
perhaps not overly different from what you suggested...
Maybe not overly different, but certainly much more efficient and elegant!
Thanks a lot! :-)

Greetings,
Thomas

--
C'est pas parce qu'ils sont nombreux ŕ avoir tort qu'ils ont raison!
(Coluche)
Nov 18 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2121
by: Mudge | last post by:
This thread is hereby dubbed PHP Purpose, or PHPP. It has the following purposes: 1. To bring together PHPers and programmers around the world to become organized. 2. To dicuss purposes of programmers as relates to motives for programming. 3. To dicuss purposes of PHP itself and related technologies.
12
2972
by: Joerg Schuster | last post by:
Hello, The program given below returns the lines: a ab Is there a way to use python regular expressions such that the program would return the following lines?
26
13328
by: rkleiner | last post by:
Is there a regular expression to find the first unmatched right bracket in a string, if there is one? For example, "(1*(2+3))))".search(/regexp/) == 9 Thanks in advance.
2
2582
by: Keith Chadwick | last post by:
XML <data> <option>this is test 1</option> <option>this is test 11</option> <option>this is test 111</option> <option>this is test 1111</option> <option>this is test 11111</option> </data>
1
1297
by: Keith Chadwick | last post by:
XML <data> <option>this is test 1</option> <option>this is test 11</option> <option>this is test 111</option> <option>this is test 1111</option> <option>this is test 11111</option> </data>
32
14708
by: Licheng Fang | last post by:
Basically, the problem is this: 'do' Python's NFA regexp engine trys only the first option, and happily rests on that. There's another example: 'oneself' The Python regular expression engine doesn't exaust all the
1
4002
by: iElf | last post by:
can someone point out my error? cus this is printing out garbage and not the longest word... Program ( I underlined the loop Im trying to make to read and find the longest word) everything else works perfectly: #include <stdio.h> #include <string.h>
2
1349
by: longhorn | last post by:
Hello, I'm looking for a macro that will return the longest range of ones in an unsigned integer, along with starting and ending position. For example I have an unsigned int data that looks like: bit pos: 31 30 29 28 27 26 25 24 23 22 21 20 19 18 .... 00 data 0 1 1 1 1 0 1 1 0 1 0 1 1 0 ... 0
9
3005
by: C#_Help_needed | last post by:
I need help with the following question. THANKS :) Write a program in c# that takes in a directory as a command line parameter, and returns the longest repeated phrase in ALL text files in that directory. Assume that all contents of all the files may be held in memory at the same time. Do not use unsafe code blocks and/ or pointers.
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10373
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10177
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5403
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2897
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.