473,395 Members | 1,996 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,395 software developers and data experts.

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 1498
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.write("<BR>"+n+" permutations")'

perms = new Function (f)

perms()

document.write ('<PRE>'+perms.toString().replace(/</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.netcom.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.length;i++) {
acc.push(arr[i]); // push each other element on acc
arr[i] = tmp; // fill hole with elem from above
result = result.concat(perm(arr,acc)); // recurse
arr[i] = acc.pop(); // restore element
}
acc.push(tmp); // push picked element
result = result.concat(perm(arr,acc)); // recurse
arr.push(acc.pop()); // 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/rasterTriangleDOM.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
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...
40
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
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...
9
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
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
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. ...
4
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...
23
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...
3
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'...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...

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.