473,406 Members | 2,710 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Generating unknown depth of nested for loops?

xaxis
15
Context: I'm working on a function that generates domain names. For instance, if I want to generate every possible domain name with 3 alpha characters, I've been doing something like this:

Expand|Select|Wrap|Line Numbers
  1. $alpha = array('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');
  2. $numeric = array('0','1','2','3','4','5','6','7','8','9');
  3. $condition = 'alpha';
  4. $hyphen = FALSE;
  5.  
  6. switch ($condition) {
  7.     case 'alpha' : $arr = (!$hyphen) ? $alpha : array_push($alpha, '-'); break;
  8.     case 'numeric' : $arr = (!$hyphen) ? $numeric : array_push($numeric, '-'); break;
  9.     case 'alphnum' : $arr = (!$hyphen) ? array_merge($alpha, $numeric) : array_push(array_merge($alpha, $numeric), '-'); break;
  10. }
  11.  
  12. generateDomains($arr, 'com');
  13.  
  14. function generateDomains($arr, $tld)
  15. {
  16.     for ($i=0; $i<count($arr); $i++){    
  17.         for ($q=0; $q<count($arr); $q++){
  18.             for ($p=0; $p<count($arr); $p++){
  19.                 @$domains .= $arr[$i].$arr[$q].$arr[$p].'.'.$tld.' ';                                            
  20.             }    
  21.         }
  22.     }
  23.     echo $domains;
  24. }
  25.  
Now when the time comes that I want to generate all possible domains with say 10 alpha chars, I don't want to have to manually nest that many for loops to achieve the result.

So does anyone have any thoughts on how this might be achieved with the above context in mind. I played with recursion a bit: a function with a single for loop that called itself to a specified $depth, however I could not figure out how to recombine the end $domain parts to get my desired result.

Any help would be most appreciated.
Feb 11 '09 #1
9 3712
TheServant
1,168 Expert 1GB
Not sure, but 10 characters will be a possible combination of over 3.6x10^15 (3,600,000,000,000,000... Not advised. Unfortunately for loops is all I can think of, but I will keep the juices flowing and come back if I think of anything.
Feb 11 '09 #2
xaxis
15
@TheServant
You're absolutely right... I realized that I'm going to need to add a bit more intelligence when it comes to the generation of domains, such as dictionary list scrambles, common domain pre- and -post fixes, none the less I still have not been able to devise a way in which a recursive function can produce the same type of linear output that the plain old nested for loops do.... It's driving me semi-mad.

My end purpose for this entire project is rather trivial/silly... I want to make a crawler that does no more than sample hex colors from as many websites as possible so I can have a little statistical fun and determine the "color of the web"...

Thanks for the pick me up.
Feb 12 '09 #3
TheServant
1,168 Expert 1GB
Interesting idea. I still cannot think of any other way besides systematically looping through each possible combination. I hope you have a dedicated server because running something like that could definitely get you banned from a shared one!
Feb 12 '09 #4
xaxis
15
You are most correct, a dedicated server is paramount. However I fully intend to make a "polite" crawler bot. Also, I to have not had any luck with such an algorithm, but it's okay because I realized I only need to produce a vast list of domains one time, and after that it will just be referenced in a database... So anyhow, thank you for your thoughts.
Feb 13 '09 #5
TheServant
1,168 Expert 1GB
No worries. Sorry I couldn't have been of any assistance.
Feb 13 '09 #6
Atli
5,058 Expert 4TB
@xaxis
I was playing around with this a bit. Ended up with this:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $chars = "abc"; // etc...
  3. $end = ".com"; // To be appended to each line
  4.  
  5. function Generate($depth, &$output, $prefix="")
  6. {
  7.     global $chars;
  8.     global $end;
  9.  
  10.     for($i = 0; $i < strlen($chars); $i++) 
  11.     {
  12.         $currentPrefix = $prefix . $chars[$i];
  13.         if($depth > 1) {
  14.             Generate($depth - 1, $output, $currentPrefix);
  15.         }
  16.         else {
  17.             $output .= $currentPrefix . $end . PHP_EOL;
  18.         }
  19.     }
  20. }
  21.  
  22. Generate(2, $out);
  23. echo $out;
  24. ?>
  25.  
It should give you all possible combinations of the characters in the $chars string using the depth you specify.

The idea is that every level of recursion, until the bottom level, loops through all the characters and passes each one to the next level, passing along the characters of it's parent loop, and the bottom loop prints the entire string.
Thus, printing every possible combination of the chars as deep as you specify.

Seeing as this uses a single string to store all the output, this script eats up a lot of resources. I would recommend outputting it to a file or a database if you intend to run anything like this at any real depth.
Feb 13 '09 #7
xaxis
15
Bravo! \(^_^)/

Using the $chars string of desired characters as the depth level specifier in and of itself is quite ingenious!

Thank you very much this will save me from copying and pasting many different for loops.
Feb 13 '09 #8
TheServant
1,168 Expert 1GB
Very impressed Atli! Nice work.
Feb 14 '09 #9
Markus
6,050 Expert 4TB
That's cool - I was unaware you could access a string like an array.

:)
Feb 14 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Oleg Leschov | last post by:
Could there be means of exiting nested loops in python? something similar to labelled loops in perl.. I consider it irrating to have to make a flag for sole purpose of checking it after loop if...
0
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return...
46
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
17
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html Why is C# 500% slower than C++ on Nested Loops ??? Will this problem be solved in...
10
by: Roshawn | last post by:
Hi, I am experimenting with nested For...Next loops. My code looks like this: Dim i as Byte Dim itm as Byte For i = 0 to 9 For itm = 0 to 9 'code omitted
77
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop....
3
by: tzuriel | last post by:
Hello all, I think nested loops will do what I want, but I can't seem to get them right. I have two tables, members and casts. I run a query as follows: $sql_query="SELECT DISTINCT...
4
by: toddlahman | last post by:
I am using two while loops that are nested. The first loop (post name) returns the full column of results, but the second (post modified) only returns the first row of the column. Is there another...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.