All possible Strings of 1 and 0
if i wanted to create all possible strings of n 1's and n 0's where there are never more 0's than 1's using 2 for loops and recursion how would i go about this? (the first for loop controlls how many 1's are in the string the second how many 0's up to the number of 1's) What would the recursive alogrithim have to look like inorder for me to create every possible string of n 1's and n 0's where there are never more 0's than 1's ?
void spew(int c0, int c1, int bal, String soFar){
if(c0 == 0 && c1 == 0)System.out.println soFar;
if(c0 > 0 && bal >= 0) spew(c0 - 1, c1, bal - 1, soFar+"0");
if(c1 > 0) spew(c0, c1 - 1, bal + 1, soFar+"1");
void spew(int n){spew(n,n,0,"");}And for those of you that are interested, the ones and zeros were not really ones and zeros, they were open and close parenthesis. The reason for not allowing the zeros to ever outnumber the ones was so avoid a mis-balanced set of parenthesis in the initial portion of the string, and the reason to have the same number of ones and zeros was so that final string would have a balanced set of parenthesis.
Once you cast the problem in it's proper form, you can see that the real question was how to emit Strings with exactly n balanced pairs of parens. The total number of strings of this form are known as the Catalan numbers and you can look them up in Sloan's list of integer sequences. And of course the Catalan numbers are also the way that you count the distinct number of binary trees that you can create with exactly n nodes.
Of course, I don't know any of that, I am just guessing the intent from the otherwise peculiar clarification of the problem and from the other posts by the OP asking about binary trees. It is a pity that the OP felt a need to obscure the original problem, making it both harder to solve and less likely that anyone googling for similar help would ever find it here.
Similar Messages
-
Creating all binary strings with n 1's and n 0's
if i wanted to create all possible strings of n 1's and n 0's where there are never more 0's than 1's using 2 for loops and recursion how would i go about this? (the first for loop controlls how many 1's are in the string the second how many 0's up to the number of 1's) What would the recursive alogrithim have to look like inorder for me to create every possible string of n 1's and n 0's where there are never more 0's than 1's ?
{color:#ff0000}Cross posted{color}
{color:#000080}Including this post --{color}{color:#0000ff}
http://forum.java.sun.com/thread.jspa?threadID=5223773
http://forum.java.sun.com/thread.jspa?threadID=5223679
http://forum.java.sun.com/thread.jspa?threadID=5223774{color}{color:000080}
Cross posting is rude.
{color} -
Fill Array with all possible combinations of 0/1
Hi,
i'm looking for a fast way to fill an array, respectively an int[8], with all possible combinations of 0 and 1 (or -1 and 1, shouldn't make a difference).
I kind of know how to do it using multiple loops but I assume there is a more elegant or at leaster "better" practice.
Thanks,
nikolaus
static int cnt = 0;
public static void main(String[] args) {
int[] element = new int[]{1,1,1,1,1,1,1,1};
Integer[] x = new Integer[2];
x[0] = 1;
x[1] = -1;
for(int i7:x){
element[7] = i7;
for(int i6:x){
element[6] = i6;
for(int i5:x){
element[5] = i5;
for(int i4:x){
element[4] = i4;
for(int i3:x){
element[3] = i3;
for(int i2:x){
element[2] = i2;
for(int i1:x){
element[1] = i1;
for(int i0:x){
element[0] = i0;
cnt++;
}Edited by: NikolausO on Oct 30, 2008 4:21 AM
Edited by: NikolausO on Oct 30, 2008 4:22 AMpm_kirkham wrote:
No I replied to message number 5. as the ' (In reply to #5 )' above my post indicates, which was in reply to (a reply) to Sabre150's post which wasn't using enhanced loops, nor has any obvious place where you could use that approach to fill the array.
Though you could pass in an array of the values to fill the array with, and loop over those, instead of using 0 or 1, at which point Sabre's approach becomes the same as your OP, but without the manual unrolling:
import java.util.Arrays;
public class NaryCombinations {
public interface CombinationHandler {
void apply (int[] combination) ;
public static void main(String[] args) {
calculateCombinations(new int[]{-1, 0, 1}, 4, new CombinationHandler () {
public void apply (int[] combination) {
System.out.println(Arrays.toString(combination));
public static void calculateCombinations (int[] values, int depth, CombinationHandler handler) {
recursivelyCalculateCombinations(values, 0, depth, handler, new int[depth]);
private static void recursivelyCalculateCombinations (int[] values, int index, int depth,
CombinationHandler handler, int[] combination) {
if (index == depth) {
handler.apply(combination);
} else {
for (int value : values) {
combination[index] = value;
recursivelyCalculateCombinations(values, index + 1, depth, handler, combination);
Which looks to use the same basic approach to the generalization I created shortly after posting the original.
public class Scratch1
* A 'callback' to be invoked with every combination
* of the result.
public interface Callback
* Invoked for each combination.
* <br>
* Each call is passed an new instance of the array.
* @param array the array containing a combination.
void processArray(int[] array);
public Scratch1(final int[] array, final Callback callback, final int... values)
if (callback == null)
throw new IllegalArgumentException("The 'callback' cannot be 'null'");
if (array.length < 1)
throw new IllegalArgumentException("The array length must be >= 1");
if ((values == null) || (values.length < 1))
throw new IllegalArgumentException("The 'values' must have be at least of length 2");
callback_ = callback;
values_ = values.clone();
array_ = array;
public Scratch1(final int order, final Callback callback, final int... values)
this(new int[order], callback, values);
* Generates every possible value and invokes the callback for each one.
public void process()
process(0);
* Internal method with no logical external use.
private void process(int n)
if (n == array_.length)
callback_.processArray(array_.clone());
else
for (int v : values_)
array_[n] = v;
process(n + 1);
private final Callback callback_;
private final int[] values_;
private final int[] array_;
public static void main(String[] args) throws Exception
final Callback callback = new Callback()
public void processArray(int[] array)
System.out.println(java.util.Arrays.toString(array));
new Scratch1(6, callback, 2, 1, 0).process(); -
I just have just downloaded Mountain lion and I wanted to listen to music on my computer screen with my HDMI cable plug into my back of my screen and I wanted to talk to dictation on my regular standard iPhone headphone and I was wondering if it's all possible change your settings Mac Mini to set it so you can listen to those both like your headphones and use the mic in your headphones and there's no settings that would change in the Mac Mini so do there is a flaw in this system or I am just really really really really dumb.
You computer is probably perfectly repairable, but if you want a new one anyway, it is perfectly possible to transfer the data from the faulty one.
But it would be a mistake to simply put the old HD in the new computer.
These are the steps:
Remove Hard drive from faulty computer. (very easy on Unibody MBPs, do-able but not so easy on older MBPs)
Put it in a cheap enclosure
Connect it the new computer
Boot up new computer.
If the new computer has never been run before the Setup Assistant will ask if you want to import your apps, data, settings etc from either another mac, another HD connected to the Mac or a Time Machine back up.
Obviously chose the second option (another HD connected to this Mac) and follow prompts.
If the new computer has already been run (so Setup Assistant doesn't run when you boot it up), you will need to use Migration Assistant...or run the installer again so that Setup Assistant runs again.
Message was edited by: Mike Boreham...added sec on line -
Please a simple problem but I don't know how to solve it. After installing 16 gb of ram all is good but when I turn on the computer it is a window signaling that all is correct. How is possible to delete once and for all that window? Thank you
Well then maybe you could take a screenshot because the appearance of such a window is news to me.
Also post your OS X version and what model Mac you have. The more detail, the better. Thanks.
To take a screenshot hold ⌘ Shift 4 to create a selection crosshair. Click and hold while you drag the crosshair over the area you wish to capture and then release the mouse or trackpad. You will hear a "camera shutter" sound. This will deposit a screenshot on your Desktop.
If you can't find it on your Desktop look in your Documents or Downloads folder.
When you post your response, click the "camera" icon above the text field:
This will display a dialog box which enables you to choose the screenshot file (remember it's on your Desktop) and click the Insert Image button.
⌘ Shift 4 and then pressing the space bar captures the frontmost window.
⌘ Shift 3 captures the entire screen.
Drag the screenshot to the Trash after you post your reply. -
Is it possible to search for strings containing spaces and special characters?
In our RoboHelp project, there are figures with text labels such as Figure 1, Figure 3-2, etc.
When I search for "Figure 3" I get all pages containing "Figure" and "3", even if I surround it in quotes. Similarly, searching for "3-2" treats the '-' character as a space and searches for all pages containing '3' or '2'.
Is there a way to search for strings containing spaces and special characters?In that case I think the answer is no if you are using the standard search engine. However I believe that Zoom Search does allow this type of searching. Check out this link for further information.
http://www.grainge.org/pages/authoring/zoomsearch/zoomsearch.htm
The RoboColum(n)
@robocolumn
Colum McAndrew -
sold my ipad today. the concern is how to access all info stored in cloud and if possible eventualy merge data into new andriod tablet. Thanks all of you who respond.
>
<IfModule mod_weblogic.c>
WebLogicCluster 127.0.0.1:7005,127.0.0.1:7007,127.0.0.1:7003,127.0.0.1:7103,127.0.0.1:7104
MatchExpression /app1
</IfModule>
<Location /weblogic>
SetHandler weblogic-handler
WebLogicCluster 127.0.0.1:7003,127.0.0.1:7005,127.0.0.1:7007,127.0.0.1:7103,127.0.0.1:7104
DebugConfigInfo ON
PathTrim /weblogic
</Location>
<IfModule mod_weblogic.c>
WebLogicCluster 127.0.0.1:7003,127.0.0.1:7005,127.0.0.1:7007
MatchExpression /app2
</IfModule>
<Location /weblogic>
SetHandler weblogic-handler
WebLogicCluster 127.0.0.1:7003,127.0.0.1:7005,127.0.0.1:7007
DebugConfigInfo ON
PathTrim /weblogic
</Location>
>
This configuration is weird little bit. There is MatchExpression /app1 and MatchExpression /app2 and at the same time two <Location /weblogic> sections. Are you sure you understand what that configuration stands for?
Try something like this ...
<Location /app1>
SetHandler weblogic-handler
WebLogicCluster 127.0.0.1:7003,127.0.0.1:7005,127.0.0.1:7007,127.0.0.1:7103,127.0.0.1:7104
DebugConfigInfo ON
</Location>
<Location /app2>
SetHandler weblogic-handler
WebLogicCluster 127.0.0.1:7003,127.0.0.1:7005,127.0.0.1:7007
DebugConfigInfo ON
</Location>
where /app1 and /app2 are contexts of your weblogic applications.
http://download.oracle.com/docs/cd/E11035_01/wls100/plugins/apache.html
http://httpd.apache.org/docs/2.0/mod/core.html#location -
I have an HP Photosmart c4780 all in one printer. I know it doesnt have eprint so I installed the HP home and biz app. Im stuck and cannot figure out how to print from my IPAD. Is this at all possible? I just want to print "pages" documents from my IPAD to my HP PHotosmart c4780. How do I do this?
Hi rorybird,
The HP ePrint Home & Biz app, which is a free download from the App Store, supports many "legacy" printers, so it should work for you.
If I have solved your issue, please feel free to provide kudos and make sure you mark this thread as solution provided.
Although I work for HP, my posts and replies are my own opinion and not those of HP. -
Hi there! today i wanted to buy some gems so i charged my acc with 10 dolars and try out to buy gems. problem is i m getting "your purchase could not be completed" error...
I have tried all possible solutions i found on internet...my restrinctions are disabled...tried reinstaling, relogging, restarting phone.. nothing seems to help...
normally i would contact custommer support but i m using US account and i m not from US. anyway my US account is charged with money and it workes perfectly for all my other friends using this method ( we got some free US vouchers so we needed US accounts)
Any advice?
thanks in advanceiTunes Store Support
http://www.apple.com/emea/support/itunes/contact.html -
Is there a app that will tell all apps that are running and possibly how much battery power they use?
You don't need an app to do this. Here's how you get the battery info. Go to Settings>More>Battery. This will show you all the active apps and their individual battery usage.
-
I need a function that will go through and encrypt all the strings
I want to use one way enryption and need a function that will
go through and encrypt all the strings in my password column in sql
server 2003.
I also need a function that compares a test password string
is equal to the hash value in the database. Can anyone give me some
advice in this?Apparently it's not as simple as I thought. My first instinct
was
update yourtable set password = '#hash(password)#'
but that will crash
This is inefficient, but you only have to do it once.
query1
select id, password thepassword
from yourtable
cfloop query="query1"
update yourtable
set password = '#hash(thepassword)#'
where id = #id# -
All possible alarms from Cisco VG 202, 204 and ISR G2 2900 Series Routers
Hello,
I am working on a project that involves integrating Cisco Voice Gateways and ISR G2 routers to our NetCool NMS. The project team wanted a list of all possible alarms that could be generated by these Voice Gateways and ISR 2900 series routers.
Does anyone know somewhere I can get a list of these alarms?This issue is now resolved. Removing the codec entries under DSPFarm and replacing them fixed things. I'd done this in the past so I'm not sure why it worked this time around. Anyway, here's the final config section that is allowing video sessions to operate (loudest speaker mode) between three or more video phones:
saccavgw01#sh run | s dsp
voice-service dsp-reservation 0
dspfarm
dsp services dspfarm
dspfarm profile 1 conference video homogeneous
codec g729ar8
codec g722-64
codec g711ulaw
codec h264 cif frame-rate 30 bitrate 320kbps
maximum conference-participants 8
maximum sessions 8
associate application SCCP -
I am shooting aerial video with a GoPro H3+ at 1080p 30fps and would like to edit videos and give them to my clients to use in as much media as possible for their advertising and marketing needs. I would like to give it to them at the highest quality allowed. What form should I save it in 'Publish and Share'? I have Premier Elements 12.
KM
Can we assume that your 1080p30 is an AVCHD.mp4 file or other?
You manually or the project automatically should set the project preset to
NTSC
DSLR
1080p
DSLR 1080p30 @29.97
(If your frame rate is really 30 instead of 29.97, then go with DSLR 1080p30 instead of DLSR 1080p30 @29.97)
See the following link for setting the project preset manually
http://www.atr935.blogspot.com/2013/04/pe11-accuracy-of-automatic-project.html
For your export
Publish+Share
Computer
AVCHD
with Presets = MP4 - H.264 1920 x 1080p30
Please let us know if you have further questions on this or need clarification on anything written.
Thank you.
ATR -
Printing all possible combinations of a given word.
Well I'm supposed to print all possible combinations of a given word(I'm writing this for the benefit of those who might not have guessed this from the subject). I've got some code but its horribly wrong. Could anyone point out any mistakes.
public class Try
public void display(String s)
char ch[]=s.toCharArray();
for(int i=0;i<ch.length;i++)
String word="";
word+=ch;
char c[]=new char[s.length()];
for(int j=0;j<ch.length;j++)
if(ch[j]!=ch[i])
c[j]=ch[j];
for(int j=0;j<ch.length;j++)
for(int k=0;k<ch.length;k++)
if(c[j]!=c[k])
word+=c[k];
word+=c[j];
System.out.println(word);Me and Lucifer have been workin on this program for ages.... we cant quite understand your pseudo code.. could you elaborate a bit more on how it works ??
Meanwhile this is the dysfunctional program weve managed to come up with so far:
public class SHAM
public void display(String s)
char c[]=s.toCharArray();
for(int i=0;i<c.length;i++)
String word="";
char c1[]=new char[c.length-1];
int a=0;
for(int l=0;l<c.length;l++)
if(i!=l)
c1[a++]=c[l];
for(int j=0;j<c.length-1;j++)
char c2[]=c1;
word=c[i]+word;
if(j+1!=c.length)
char t=c2[j];
c2[j]=c2[c2.length-1];
c2[c2.length-1]=t;
for(int k=0;k<c2.length;k++)
word+=c2[k];
System.out.println(word);
}And this is my coding of your pseudo code:
public class WordCombo2
public void combo(String s)
getCombos(s.toCharArray(), s.length());
private void getCombos(char[] c,int n)
if (n==1)
print(c);
System.out.println();
else
for (int i=0;i<c.length;i++)
if (i==0 && i<n)
c=c[n-1];
n--;
getCombos(c,n);
c[i]=c[n-1];
private void print(char c[])
for (int i=0;i<c.length;i++)
System.out.print(c[i]+" ");
I really dont understand how this is supposed to work so i dont know whats wrong :( Im sorry this program is just totally baffling me, and on top of that recursion kind of confuses me. -
Creating a tree of all possible combinations of {a,b,c,d}
I am an MSc conversion student who is struggling with the initial stages of coding his Association Rule Mining dissertation project.
I have a TreeNode class, which is in the process of being written.
The class is designed to create a tree that stores all possible combinations of a Vector alphabet of strings {a,b,c,d}
Please could somebody explain what my TreeNode class is doing so far?
I have had a lot of help with this and I can't understand why there are so many vectors and what they all do.
A few pointers (no sarcastic comments please) would be much appreciated.
The code so far:
package treenode;
import java.io.*;
import java.util.*;
public class TreeNode
public static final String INFO_TEXT ="A program to store a vector of string items a,b,c,d in all their possible combinations into a TreeNode class";
private Vector alphabet;
private Vector data; // this IS TreeRootData
private Vector children;
public TreeNode(Vector inputAlphabet, Vector inputData)
// the alphabet and data have already been parsed in.
this.alphabet = inputAlphabet;
this.data = inputData;
System.out.println("Tree node constructed with data "+displayVectorOfStrings(this.data));
children = new Vector(); // we now construct the Vector of children
//createChildren();
public void createChildren()
if data.length =
// first check to see whether the current data length is the same
// as the length of the alphabet
// if it is then stop here (return;)
// we loop through the alphabet we have...
// for each candidate in the alphabet, attempt to create a new child TreeNode
// with a data Vector that is the same as the data in this TreeNode plus
// the candidate we are looking at in the alphabet. i.e. add available LHS
// NB: Do NOT add if the candidate is already in the data. {a,b,a} is wrong!
// NB: We will check to see whether data is already in the tree at a later stage
// NB: The new Child TreeNode MUST BE ADDED to the children VECTOR -
// or it will be lost
public static String displayVectorOfStrings(Vector vector) //Printing the Vector of Strings
String vectorText = "{";
for (int i=0; i<vector.size(); i++)
vectorText += (String)vector.elementAt(i)+",";
if (vector.size() > 0) vectorText = vectorText.substring(0, vectorText.length()-1);
// now we chop off the last element, replacing it with a closing bracket,
// provided that the Vector is not empty.
vectorText += "}";
return vectorText;
public static void main(String[] args) //main method WITH THE ARGUMENTS PASSED IN.
// This main class can be thought of as OUTSIDE the TreeNode class. Although
// it is in the file called TreeNode.java it is only here for convenience.
// This is the top level of the program where everything starts. It is here -
// that the alphabet is hardcoded in and that the Tree root is constructed.
displayHeading();
Vector alphabet = new Vector(); // constructing an initial alphabet,
alphabet.addElement("a"); // which will eventually come from the database
alphabet.addElement("b");
alphabet.addElement("c");
alphabet.addElement("d");
System.out.println("Alphabet set to be "+TreeNode.displayVectorOfStrings(alphabet));
// the root's initial data is now made into an empty Vector...
Vector initialData = new Vector();
// the root can now be constructed
TreeNode treeRoot = new TreeNode(alphabet, initialData); // the treeRoot constructor
public static void displayHeading()
System.out.println();
System.out.println(INFO_TEXT);I don't remember from which site I took this material.
You read this to find all possible combination of a set {a,b,c,d}
Consider three elements A, B, and C. It turns out that for n distinct elements there are n! permutations possible. For these three elements all of the possible permutations are listed below:
ABC, ACB, BAC, BCA, CAB, CBA
Since there are 3 elements there are 3! = 6 permutations possible.
Suppose instead of A, B, and C you have a deck of 52 playing cards. There are 52! permutations possible (i.e., the number of different ways the cards could be shuffled). Since 52! = 8x10^67, you will need to play a lot of cards before you have seen every permutation of the deck! Since shuffling the deck is a random process (or it should be), each of these 52! permutations is equally likely to occur.
Developing a non-recursive algorithm to generate all permutations of n elements is a non-trivial task. However, developing a recursive algorithm to do this requires only modest effort and this is what we will do next.
1. Let E = {e1, e2, ..., en } denote the set of n elements whose permutations we are to generate.
2. Let Ei be the set obtained by removing element i from E.
3. Let perm(X) denoted the permutations of the elements in the set X.
4. Let ei.perm(X) denote the permutation list obtained by prefixing each permutation in perm(X) with element ei.
Consider the following example, which is provided to clarify the definitions given above:
If E = {a, b, c}, then E1 = {b, c} since the element in position 1 has been removed from E to create E1. Perm(E1) = (bc, cb) since these are the only two possible permutations of the two elements which appear in E1. Finally, e1.perm(E1) = (abc, acb) which should be apparent from the value of e1 and perm(E1) since the element a is simply used as a prefix to each permutation in perm(E1).
Given these definitions, we set the recursion base case when n = 1. Since only one permutation is possible for one element, perm(E) = (e) where e is the lone element in E. When n > 1, perm(E) is the list e1.perm(E1) followed by e2.perm(E2) followed by e3.perm(E3) � followed by en.perm(En). This recursive definition of perm(E) defines perm(E) in terms of n perm(X)s, each of which involves an X with n � 1 elements. Thus both the base component and the recursive component (of a recursive algorithm) have been established and we thus have a complete recursive technique to generate the permutations.
The following Java method is an implementation of this recursive definition of perm(E). This method will output all permutations whose prefix is list[0:k-1] and whose suffixes are the permutations of list[k:m]. By invoking the method with Perm(list, 0, n-1) all n! permutations of list[0: n-1] will be produced. [This is because this invocation will set k = 0 and m = n � 1, so the prefix of the generated permutations is null and their suffixes are the permutations of list[0: n-1]. When k = m, there is only one suffix which is list[m] and list[0: m] defines a permutation that is to be produced. When k < m, the else clause is executed.
In the algorithm, let E denote the elements in list[k: m] and let Ei be the set obtained by removing ei = list[i] from E. The first swapping sequence in the for-loop has the effect of setting list[k] = ei and list[k+1: m] = Ei. Therefore, next statement which is the call to perm computes ei.perm(Ei). The final swapping sequence restores list[k: m] to its state prior to the first swapping sequence (the state is was in before the recursive call occurred).
public static void perm(Object [] list, int k, int m)
{ //generate all permutations of list[k:m]
int i; Object temp;
if (k == m) //list has one permutation � so output it
{ for (i = 0; i <= m; i++)
System.out.print(list);
System.out.println;
else //list has more than one permutation � so generate them recursively
for (i = k; i <= m; i++)
{ temp = list[k]; //these next three lines are a simple swap function
list[k] = list[i];
list[i] = temp;
perm(list, k+1, m); //the recursive call
temp = list[k]; //reset the order in the list
list[k] = list[i];
list[i] = temp;
}//end for-loop
} //end method perm
See the program pasted below that prints all possible combination of a set {a,b,c,d}
public class Perm
public Perm()
public static void main(String[] args)
String s = "abcd";
char [] chars = s.toCharArray();
perm(chars, 0);
public static void perm(char [] list, final int k)
int i;
char temp;
if (k == list.length-1) //list has one permutation, so output it
for (i = 0; i <= list.length-1; i++)
System.out.print(list[i]);
System.out.println();
else { //list has more than one permutation, so generate them recursively
for (i = k; i <= list.length-1; i++)
temp = list[k]; //these next three lines are a simple swap function
list[k] = list[i];
list[i] = temp;
perm(list, k+1); //the recursive call
temp = list[k]; //reset the order in the list
list[k] = list[i];
list[i] = temp;
}//end for-loop
Maybe you are looking for
-
In previous versions, setting browser.newtab.url to about:blank disabled the newtab grid. Now that I've updated to Firefox 18, Firefox doesn't remember the setting. When I restart Firefox, it changes the browser.newtab.url that I had set to about:bla
-
How do I uninstall a program that is running in the background but does not show in Force Quit?
-
Multiple Linux JComboBox drops in the same position
Following program create two similar JComboBox dropdown, and in Linux, when it runs, it works weirdly. If I first click first dropdown (s1), then later when I click second one (s2), dropdown part still appears under the first component. import java.a
-
Vendor wise TDS Amount Exmptions
Hi, I have Refer the other old threads but i have not found any suitable answer. How we can maintain vendor wise maximum amounts for TDS deduction. steps: Go to Define withholding tax type, under Accumulation Type, select radio button Per Year, Star
-
FICA and AUDDIS Integration steps
Hi Guru's We are planning to Implement AUDDIS and we are using the FICA. I tryed to attached external format AUDDIS standard version to see the output, but it is giving dump and reason is below. Can anyone help me please. Thank you Termination occurr