473,763 Members | 7,541 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterate over array element combinations

I need to iterate over combinations of n array elements taken r at a
time. Because the value of r may vary quite a bit between program
invocations, I'd like to avoid simply hardcoding r loops. I assume the
best way to do this would be either using closures or creating some
sort of iterator class.

Any guidance on how to get started?
Thanks,
Jacob.

Oct 1 '06 #1
7 7422
VK
I need to iterate over combinations of n array elements taken r at a
time.
The algorithm description is not fully clear. If you are trying to
implement a sort of Shannon's clairvoyant, you may find interesting the
thread "Looping through variable number of arrays variable times?" at
<http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/65f35a3a759cd88 3>

If not then sorry for a wrong guess, more details could help.

Oct 1 '06 #2

VK wrote:
I need to iterate over combinations of n array elements taken r at a
time.

The algorithm description is not fully clear. If you are trying to
implement a sort of Shannon's clairvoyant, you may find interesting the
thread "Looping through variable number of arrays variable times?" at
<http://groups.google.c om/group/comp.lang.javas cript/browse_frm/thread/65f35a3a759cd88 3>

If not then sorry for a wrong guess, more details could help.
You're right. I really didn;t explain this very well at all.

I have an array of n floats. What I need to do is calculate a function
of the elements of every subset of n containing exactly r elements
(actually it's r or fewer, but for the sake of simplicity let's just
say exactly r) and then figure the sum of the functions

So for example given array = (a, b, c, d):

For r = 2 I'd be looking for:
f(a,b) + f(a,c) + f(a,d) + f(b,c) + f(b,d) + f(c,d)

and for r=3 I'd be looking for:
f(a,b,c) + f(a,b,d) + f(a,c,d) + f(b,c,d)
etc....

Oct 1 '06 #3
VK

Jacob JKW wrote:
I have an array of n floats. What I need to do is calculate a function
of the elements of every subset of n containing exactly r elements
(actually it's r or fewer, but for the sake of simplicity let's just
say exactly r) and then figure the sum of the functions

So for example given array = (a, b, c, d):

For r = 2 I'd be looking for:
f(a,b) + f(a,c) + f(a,d) + f(b,c) + f(b,d) + f(c,d)

and for r=3 I'd be looking for:
f(a,b,c) + f(a,b,d) + f(a,c,d) + f(b,c,d)

etc....
I see now... I guess the most helpful array method here would be
slice(lbound, ubound)

function iterator(r) {

var subset = new Array();
var len = myArray.length;
var lim = len - r;

for (var i=0; i<lim; i++) {
subset = myArray.slice(i , r-1);

for (var j=r; j<len; j++) {
methodCall(subs et.push(myArray[j]));
}

}

}

I did not check it for working, just some thoughts - I feel like I lost
some +/- 1 for indexes

Oct 1 '06 #4
JRS: In article <11************ **********@k70g 2000cwa.googleg roups.com>,
dated Sun, 1 Oct 2006 01:33:36 remote, seen in
news:comp.lang. javascript, Jacob JKW <ja******@yahoo .composted :
>I need to iterate over combinations of n array elements taken r at a
time. Because the value of r may vary quite a bit between program
invocations, I'd like to avoid simply hardcoding r loops. I assume the
best way to do this would be either using closures or creating some
sort of iterator class.

Any guidance on how to get started?
See <URL:http://www.merlyn.demo n.co.uk/js-misc0.htm#CP>.
Combinations are generated recursively, though AIUI any recursive
algorithm can be expressed iteratively.

function Comb(n, a, z, D) { // List combinations - D starts empty
if (n==0) { D[D.length] = z ; return }
for (var j=0 ; j < a.length ; j++)
Comb(n-1, a.slice(j+1), z+a[j], D)
return }

function TestComb() { var S = ["a","b","c" ,"d"], D, k
document.writel n("TestComb() :")
for (k=0 ; k <= S.length ; k++) {
D = [] ; Comb(k, S, "", D)
document.writel n("Comb(", k, ") = ", D) } }

document.writel n("<pre>")
TestComb()
document.writel n("<\/pre>")
gives:-

TestComb() :
Comb(0) =
Comb(1) = a,b,c,d
Comb(2) = ab,ac,ad,bc,bd, cd
Comb(3) = abc,abd,acd,bcd
Comb(4) = abcd
So :-
D = [] ; Comb(2, S = ["a","b","c" ,"d"], "", D) ;
gives D as ['ab', 'ac', 'ad', 'bc', 'bd', 'cd'] .
There should be a way of adapting that so that each element of array D
is not a string but an array of combinations of the elements of the
parameter array. Change f to take that array as a parameter, using
within it the array called arguments - and you might be more or less
there.

It's a good idea to read the newsgroup and its FAQ. See below.
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 1 '06 #5
Dr John Stockton wrote:
JRS: In article <11************ **********@k70g 2000cwa.googleg roups.com>,
dated Sun, 1 Oct 2006 01:33:36 remote, seen in
news:comp.lang. javascript, Jacob JKW <ja******@yahoo .composted :
I need to iterate over combinations of n array elements taken r at a
time. Because the value of r may vary quite a bit between program
invocations, I'd like to avoid simply hardcoding r loops. I assume the
best way to do this would be either using closures or creating some
sort of iterator class.

Any guidance on how to get started?

See <URL:http://www.merlyn.demo n.co.uk/js-misc0.htm#CP>.
Combinations are generated recursively, though AIUI any recursive
algorithm can be expressed iteratively.
<snip code sample from http://www.merlyn.demo n.co.uk/js-misc0.htm#CP>
This is perfect!. Thank you very much. :)

Jacob

Oct 2 '06 #6

VK wrote:
Jacob JKW wrote:
I have an array of n floats. What I need to do is calculate a function
of the elements of every subset of n containing exactly r elements
(actually it's r or fewer, but for the sake of simplicity let's just
say exactly r) and then figure the sum of the functions

So for example given array = (a, b, c, d):

For r = 2 I'd be looking for:
f(a,b) + f(a,c) + f(a,d) + f(b,c) + f(b,d) + f(c,d)

and for r=3 I'd be looking for:
f(a,b,c) + f(a,b,d) + f(a,c,d) + f(b,c,d)

etc....

I see now... I guess the most helpful array method here would be
slice(lbound, ubound)

function iterator(r) {

var subset = new Array();
var len = myArray.length;
var lim = len - r;

for (var i=0; i<lim; i++) {
subset = myArray.slice(i , r-1);

for (var j=r; j<len; j++) {
methodCall(subs et.push(myArray[j]));
}

}

}

I did not check it for working, just some thoughts - I feel like I lost
some +/- 1 for indexes
TYhis looks rather good as well.

For no real reason I decided to move forward with John's suggestion
above. But thanks anyway for your help on this. Highly appreciated. :)

Oct 2 '06 #7
JRS: In article <11************ *********@k70g2 000cwa.googlegr oups.com>,
dated Mon, 2 Oct 2006 07:25:51 remote, seen in
news:comp.lang. javascript, Jacob JKW <ja******@yahoo .composted :
>
<snip code sample from http://www.merlyn.demo n.co.uk/js-misc0.htm#CP>
This is perfect!. Thank you very much. :)
It was merely OK; I've improved it.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 3 '06 #8

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

Similar topics

6
3957
by: ChronoFish | last post by:
Hi there, I want to iterate through an array starting at a known index. However the indexes are not linear. For example I have an array of events keyed by timestamp. $eventList = array (1064263264 => "event1", 10642635555 => "event2", 1064266666 => "event3", 1064267782 => "event4", 1064268812 => "event5"); I basically want to do a "for" or "foreach" but I don't necessarily want to start at key 1064263264 (event1).
2
2212
by: deko | last post by:
I have a file that contains the output of time(). A different time is on each line of the file, and each line represents a visit to the website. I want to calculate the total visits per day, month and year. So, I dump the file into an array, and then iterate through the array testing each element and incrementing a counter for each respective time period. But what is the best way to iterate through the array? The foreach($av) does...
10
3205
by: BCC | last post by:
Ive been googling and reading through my books but I haven't figured out a solution (much less an elegant one) to create a multidimensional array with a runtime determined number of dimensions. I also checked out the boost::multi_array.hpp, and Giovanni Bavistrelli's Array code. Neither of these seem to allow dynamic array dimensions. For example, the user selects a 2 dimensional array, I want to create: MyObject** array = new...
15
3333
by: alanbe | last post by:
Greetings I am making a flashcard type application to help me in my TCP/IP protocols test. My instructor will test us periodically on how a device or networking function relates to the OSI layer. EG. bits-layer 1. Any way, I want the quiz to reorder the problems each time I take it. Here is part of the code i did so far for 62 components in the quiz.
9
2278
by: tony collier | last post by:
i have created a 7-dimensional array which has 19.5 million elements. when i try to create 8-dimensional array i get out of bounds system exception. does anyone know if this limitation is due to amount of memory in my pc or a limiation of c# language? thanks
2
1956
by: Rob | last post by:
I have a function exposed from a C DLL which takes a pointer to an array of strings as a param which then allocates that array of strings and returns. I'm using P/Invoke to call this function from C#, but I've been messing with it for too long now and haven't got it working exactly as I'd like. Here's the C function prototype, which will fill in its parameters: void GetStrings(LPTSTR **aStrings,int& iStrings);
4
2242
by: Norman Fritag | last post by:
Hi there, >>>__ 1020.83, 2305.22, 1176.86, 755.12, 123.41 __ 1976.1, 1325.99, 947, 718.03, 414.32 __ 1020.83, 1976.1, 352.5, 947, 718.03, 366.98 Their IDs were as ---------------------------------------------- __ 508671, 508789, 508850, 513108, 514552 __ 507960, 509289, 509149, 511454, 512759__ 508671, 507960, 510436, 509149, 511454, 513633 <<<
2
1785
by: Nico | last post by:
Dear all, I created the following php form. <FORM METHOD="POST" ACTION="prova.php"> <b>Combination</b><br><br> Element 1: <INPUT NAME="el1" TYPE="TEXT"> <BR> Element 2: <INPUT NAME="el2" TYPE="TEXT"> <br>
1
4507
by: Nico | last post by:
Hi all, I've created the following code: <?php session_start(); ?> <FORM METHOD="POST" ACTION="prova.php"> Add <b>Combination</b><br><br>
0
9386
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,...
1
9937
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9822
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
8821
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
6642
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();...
0
5270
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
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
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
3
2793
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.