473,602 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function writing function

Can a function write another function that has a specific number of
nested loops and then run it?

i.e.
function maker (N) {
// does stuff that creates function doer()
// invoke doer
doer()
}

For a specific value of N, doer might have this construction:

function doer() {
for (i0=0;i0<x;i0++ {
for (i1=0;i1<x;i1++ {
...
for (i#N#=0;i#N#<x; i#N#++ {

// stuff

}...}} // N closing braces
}

i#N# simply means replace #N# with what ever value of N is.

So for N=4, I would want 4 nested loops, for N=5 I would want 5 nested
loops, etc...
Thanks,
Richard
Jul 23 '05 #1
3 1513
Richard A. DeVenezia wrote:
Can a function write another function that has a specific
number of nested loops and then run it?
The - Function - constructor can be invoked with a string holding the
text of source code as its final argument and will create a function
object using that code as the function body (except possibly on systems
implementing the ECMAScript compact profile (ECMA 327) and taking
advantage of the option not to facilitate the use of the Function
constructor).

In any real problem situation the use of the - Function - constructor is
unlikely to be necessary or optimal. Javascript is so dynamic in its
nature that creating functions from strings would usually be avoidable
and the overhead in string manipulation would be difficult to justify
unless the resulting function was destined for repeated use.
i.e.
function maker (N) {
// does stuff that creates function doer()
// invoke doer
doer()
}

For a specific value of N, doer might have this construction:

function doer() {
for (i0=0;i0<x;i0++ {
for (i1=0;i1<x;i1++ {
...
for (i#N#=0;i#N#<x; i#N#++ {

// stuff

}...}} // N closing braces
}

i#N# simply means replace #N# with what ever value of N is.

So for N=4, I would want 4 nested loops, for N=5 I would want
5 nested loops, etc...


Identifying a better alternative hangs of the unspecified "stuff" that
if to happen within the innermost loop. How is it going to take
advantage of loop counter i#N#, and if it doesn't why are the nested
loops needed?

Richard.
Jul 23 '05 #2
Richard Cornford wrote:
Identifying a better alternative hangs of the unspecified "stuff" that
if to happen within the innermost loop. How is it going to take
advantage of loop counter i#N#, and if it doesn't why are the nested
loops needed?


This function writes a function that enumerates permutations of n things by
iterations.
Yes, the dense interaction of abstract and specific is a difficult brew to
understand and maintain.
Yes, there are recursive techniques that can do the same thing (I haven't
done any benchmarking to see if lots of loops with lots of ifs is faster
than lots of loops of recursive function calls)

<html>
<head>
<title>Perms</title>
<script type="text/javascript">
function Perms (n) {

var f = '// Permutations of ' + n + ' things';
f += '\nvar n=0'

for (var i=0;i<n;i++) {
f += '\nfor (i'+i+'=0;i'+i+ '<'+n+';i'+i+'+ +) {'

for (var j=0;j<i;j++) {
f += '\nif (i'+i+'==i'+j+' ) continue'
}
}

f += '\nn++'
f += '\n/**/ document.write ("<BR>"+n+": "'

for (var i=0;i<n;i++) {
if (i) f += '+","'
f += '+i'+i
}

f += ') /**/'

f += '\n'

for (var i=0;i<n;i++) {
f += '}'
}

f += '\ndocument.wri te("<BR>"+n+" permutations")'

perms = new Function (f)

perms()

document.write ('<PRE>'+perms. toString().repl ace(/</g,"&lt;")+'</PRE>')
}
</script>
</head>
<body>
<script type="text/javascript">
Perms(4)
</script>
</body>
</html>

--
Richard A. DeVenezia
Jul 23 '05 #3
"Richard A. DeVenezia" <ra******@ix.ne tcom.com> writes:
This function writes a function that enumerates permutations of n things by
iterations.
Yes, the dense interaction of abstract and specific is a difficult brew to
understand and maintain. Yes, there are recursive techniques that can do the same thing (I haven't
done any benchmarking to see if lots of loops with lots of ifs is faster
than lots of loops of recursive function calls)


My guess is that the recursive version will be simpler and therefore
faster.

The way you generate ifs, the inner loop (which will run n times) will
start with n-1 if statements that will continue the loop in all but
one case. There will be approx. (1/2)*n^2 if statements, which will all
have been tested for each permutation you generate, as well as all the
tests that fail and continue a loop. I believe the time complexity
is quite bad for this approach.

Here is a recursive function for comparison :)
---
function perm(arr,acc) { // arr(ay): elements yet to permute
// acc(umulator): elements placed so far
if (!acc) {acc=[];}
if (arr.length == 0) {
return [acc.slice(0)]; // return copy of accumulator
}
var result = [];
var tmp = arr.pop(); // pick element to fill hole with
for(var i=0;i<arr.lengt h;i++) {
acc.push(arr[i]); // push each other element on acc
arr[i] = tmp; // fill hole with elem from above
result = result.concat(p erm(arr,acc)); // recurse
arr[i] = acc.pop(); // restore element
}
acc.push(tmp); // push picked element
result = result.concat(p erm(arr,acc)); // recurse
arr.push(acc.po p()); // restore arr and acc

return result;
}

alert(perm([0,1,2,3]).join("\n"));
---

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4

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

Similar topics

9
4945
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
40
2953
by: Xah Lee | last post by:
is it possible in Python to create a function that maintains a variable value? something like this: globe=0; def myFun(): globe=globe+1 return globe
58
10097
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
9
2995
by: drhowarddrfinedrhoward | last post by:
I see a number of pages with functions like MM_somefunction(). Where does the MM_ come from? I don't see it in any books I'm studying.
17
2414
by: strout | last post by:
function F(e) { return function(){P(e)} } Can anybody tell me what the code is doing? If return another function all in a function I would do function F(e)
39
6510
by: Randell D. | last post by:
Folks, I'm sure this can be done legally, and not thru tricks of the trade - I hope someone can help. I'm writing a 'tool' (a function) which can be used generically in any of my projects. When it completes, it can call a success, or a failure function. The names of these success, or failure functions will differ, and I'd like to know how I can pass the name of a function to my tool, and how my tool can call the function, using that...
4
7704
by: Mark Kamoski | last post by:
Hi Everyone. What is the real difference between writing a Sub versus writing a Function with no return value? It seems to me that both of these would need to compile to the same IL, so it seems they are identical. Please advise.
23
7794
by: bluejack | last post by:
Ahoy... before I go off scouring particular platforms for specialized answers, I thought I would see if there is a portable C answer to this question: I want a function pointer that, when called, can be a genuine no-op. Consider: typedef int(*polymorphic_func)(int param);
3
3639
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
2
1968
by: petermichaux | last post by:
Hi, It seems like determining element position in a web page is a difficult task. In the position reporting source code I've looked at there are special fixes for at least some versions of Safari and Opera. I am doing a lot of dragdrop experimentation and in some situations need a position reporting function. The function doesn't need to report the positions of exotic elements like images in button elements; however, I would like a...
0
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7920
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
8401
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
8404
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
8268
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...
0
6730
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2418
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1254
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.