How Code Is Getting All Permutations Of A String With Recursion
Aug 7, 2014
how the code is getting all the permutations of a string with recursion. The following code works correctly but I am having trouble grasping what it is doing.
public class Main {
private static void permutation(String prefix, String str){
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i+1));
}
}
public static void main(String[] args) {
permutation("", "ABCD");
}
}
I see that each character is being appended to prefix through each iteration. So I know it adds "A" then "B" etc etc. I can follow it up until the "D" is appended to the prefix string. After that I don't understand how the D moves back to the str string and then the C moves back to str followed by the D moving back to the prefix string. I have stepped through the code many times in my debugger but still don't see how it moves back to str and knows to send D to prefix and not to send C. I feel I don't understand how recursion behaves therefore I can't follow.
View Replies
ADVERTISEMENT
Mar 15, 2015
So I have to design a program that takes a word and reverses the order of it. The exact directions are:Write a recursive method void reverse() that reverses a sentence. For example:
[code = Java]
Sentence greeting = new Sentence("Hello!");
greeting.reverse();
System.out.println(greeting.getText());
[/code]
prints the string "!olleH".
Implement a recursive solution by removing the first character, reversing a sentence consisting of the remaining text, and combining the two. So basically my biggest issue is my method to actually reverse the word.
public class Sentance
{
private String Word;
public Sentance (String aWord)
{
Word = aWord;
[code]....
View Replies
View Related
Oct 2, 2014
I have 5 numbers between 0 to 13 in ascending order stored in an array. They may have repeats. I want to perform permutations and figure out the number of running pairs (minimum 3 numbers in a pair. Ex- 012, 345, 456, 1234, 78910) that I can make with these command line inputs that I get.
Lets say my user input was 01123. For this sequence I'll have the following pairs-
012
012
1234
1234
123
123
0123
0123
There are same repeated sequences because there are two 1's hence same pairs using different 1's.I have the input in an array so I'm wondering if there is any inbuilt class for arrays that would let me do this. If not, whether I can pass it into a collection and then find its permutations. Following which I traverse through the sequences and update a count for each running pair generated to pass onto an array in another variable to perform some other functionality. If this is viable how to implement this in code ? I'm new to java and am not familiar with the classes available.
View Replies
View Related
Apr 12, 2014
I have a set of 2D arrays, structured as so: int[][] cage = new int[someLength][4]. Each array has a set column length of 4; the first two columns are all that concern us with this problem. They are used to define the row and height respectively of a point (e.g. 2,4).
What I need is to generate all possible permutations of the points using both row and column coordinates from the 2D array. I found a working method to generate all permutations for 1D array of ints here: [URL] ..... , under update 2 of the first answer.
Here is an example of a possible input and corresponding output desired:
In: (1,0)
(1,1)
Out:(1,0),(1,1)
(1,1),(1,0)
Ideally the result will be stored in a 2D array of ints.
View Replies
View Related
Apr 12, 2014
I have a set of 2D arrays, structured as so: int[][] cage = new int[someLength][4]. Each array has a set column length of 4; the first two columns are all that concern us with this problem. They are used to define the row and height respectively of a point (e.g. 2,4).
What I need is to generate all possible permutations of the points using both row and column coordinates from the 2D array. I found a working method to generate all permutations for 1D array of ints here: My link, under update 2 of the first answer.
Here is an example of a possible input and corresponding output desired:
In: (1,0)
(1,1)
Out:(1,0),(1,1)
(1,1),(1,0)
the result will be stored in a 2D array of ints.
View Replies
View Related
Sep 18, 2014
I need to use print not println to declare stuff and I need to have string literals I think that's /n. Now when I compile it just shows row1, row2 ect. Why does it work like that?
public class art {
public static void main(String[] args) {
//local variables
String row1= "***********************";
String row2= "** *** *** **";
String row3= "** ***** ***** **";
[Code] ...
View Replies
View Related
Aug 25, 2014
I am trying to figure out how to convert a string of ASCII code into char.I know that you can use (char) to convert it, but the issue is you cannot really just it for Strings.
View Replies
View Related
May 8, 2015
I am trying to code using error handling and I am a bit confused on how to go about doing it correctly. My code converts a string that has all numbers into an integer and the error handling should recognize that if it isn't a proper number and ask the user to try again or enter 'q' to quit.Do I place a throw new exception in the try block and put conditionals like if charAt(i) is some letter or a symbol then throw new exception?
Java Code:
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
Integer finalValue = null;
boolean validValue = false;
Scanner scan = new Scanner(System.in);
int result = 0;
[code]....
View Replies
View Related
Apr 8, 2015
I want to extract a specific String from HTML, specifically, I want to extract a String from in between <...>
So far, I've got this
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class HTMLGrabber {
static String allOneString = "";
[code]....
The problem I have is when I change the last parameter in this line:
System.out.println("And the Keywords are:
" +allOneString.substring(allOneString.lastIndexOf("meta name="keywords" content=") + 30, allOneString.indexOf("Fictional History">")+17));
to
System.out.println("And the Keywords are:
" +allOneString.substring(allOneString.lastIndexOf("meta name="keywords" content=") + 30, allOneString.indexOf("">")));
i.e. the generic alternative, I get this error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -366
at java.lang.String.substring(Unknown Source)
at main.HTMLGrabber.main(HTMLGrabber.java:45)
Is there a better and simple way to extract a substring?
View Replies
View Related
Mar 7, 2015
import java.io.InputStreamReader;
import java.util.Scanner;
public class FinalCombinations {
public static void main(String[] args){
//Read number of values
System.out.println("Enter the no of values");
[Code] .....
I am getting output like this
Enter the no of values
4
Enter the values
1
2
3
4
Enter the number for combination
2
C(4,2)=6
1
1
2
1
1
3
1
1
4
2
2
3
2
2
4
3
3
4
where as I want output like this..wit one array
1
2
1
3
1
4
2
3
2
4
3
4
View Replies
View Related
Nov 7, 2014
i need to run a piece of code which is inside a string object..is it possible?if so how?
View Replies
View Related
Sep 3, 2014
I am not sure how to go about doing this, An ItemEvent.Selected constant is the hint given to me but i dont know how to start it.
My Array is : private ArrayList billItems = new ArrayList();
My method is : private void beverageJComboBoxItemStateChanged( ItemEvent event )
View Replies
View Related
Apr 29, 2014
I am trying to make a game, for some reason i have begun to get a java.lang.StackOverflowError.
I am not exactly sure how i can fix it. only removing line 14 from infopannel1 (and everything that used that class.) seems to work. im not sure what else i can do to fix it. or why its resulting in stack overflow for that matter.
I am putting in a link for the files i wrote this using bluej (several classes have no relevance, errorv2, demonstration, folderreadertest, ReadWithScanner, saveloadtest, menutest,rannum, and menutestTester. are all irrelivent to my problem.)
[URL] .....
View Replies
View Related
Dec 13, 2014
how does recursion works, I don't understand why it prints al numbers going up again?This is the code
void print2(int n){
if (n<0){
out.printf(" %d",-1);
return;
}
out.printf(" %d", n);
print2(n-1)
out.printf(" %d", n);
}
this should be the output if n is 6: 6 5 4 3 2 1 0 -1 0 1 2 3 4 5 6.
View Replies
View Related
Mar 25, 2015
How to add the sum of an array with a recursion, but I don't understand how to use recursion. I just understand that it calls back the method. I am nearly done with the code.
import java.util.Scanner;
class Question1{
public static void main(String[]args){
Scanner s = new Scanner(System.in);
int size, sum;
System.out.println("Please input how many numbers will be used");
size=s.nextInt();
[Code] .....
View Replies
View Related
Aug 6, 2014
public void myFunc(MyNode n, ArrayList<MyNode> path) {
boolean hasChildren = false;
path.add(n);
int index = path.indexOf(n);
ArrayList<MyNode> statefulPath = new ArrayList<MyNode>();
[Code] ....
I have similar code that I stepped through in a debugger. After running the code I found that it built the desired tree, in this case a root node H with left child L and right child P. I want list of lists to contain all paths from root to leaf. I expected [H, L] and [H, P]. I discovered that statefulPath is not stateful; after a recursive stack frame pops, statefulPath still contains n! But that stack frame just popped! I expected to see statefulPath be [H] in the debugger and it was [H, L]! So I later have a list [H,L,P] which I don't want. How do I make the statefulPath list I want for my algorithm?
View Replies
View Related
Mar 22, 2015
I have a question related to the code below, that I do not understand. The aim is to count all files and subdirectories in an ArrayList full of files and subdirectories. So I have to count every file and every subdirectory.
The code concerning counting files is clear to me - every time d is of the type file I have to increment n by one. However I thought that I have to do the same thing in case d is a directory, so I would have written the same code for directories.
So what does "n += ((Directory) d).countAllFiles();" mean? In my understanding the method countAllFiles() is applied again on the object Directory ( as Directory is the class that contains this method), but how is n incremented by this? I thought n should be incremented by one as we did with files.
public int countAllFiles() {
int n = 0;
for(SystemFile d : content) {
if(d instanceof File) {
n++;
[Code] ....
View Replies
View Related
Jun 5, 2014
How the recursion works. I tried to figure out writing down low, mid, high at each recursive call. But I seem to be making a mistake somehow. I don't understand where the values are returned to in
if(leftmax>rightmax){
return leftmax;}
else
return rightmax;
Here's the code:
public class Maximum{
public static int max(int[] a,int low,int high){
int mid,leftmax,rightmax;
if(low==high)
return a[low];
[Code] ....
firstly leftmax=max(a,0,4)
Then what is the next line executed?Is it rightmax=max(a,5,8).
After this is it leftmax=max(a,5,6)
rightmax=max(a,7,8)
I tried to understand what these recursion calls by writing them down.But I somehow make a mistake.
View Replies
View Related
Oct 20, 2014
I just started studying recursion and I wanted to know how to create a palindrome number going up from 1 to n then back to 1 like this: "12345...n...54321".
I've done one going downwards and then upwards like this: "n...4321234...n".
Here's my code:
Java Code: import java.util.*;
public class PalindromeTest
{
public static void downPalindrome(int n)
[Code].....
View Replies
View Related
Jul 16, 2014
The program I'm working on is supposed to read input from a file and using recursion, print the pattern of asterisks for each value until the value is either < 0 or > 25.For example, if the value was 4, the pattern would look like this
*
* *
* * *
* * * *
* * *
* *
*
The values are stored in a file entitled prog3.dat which looks like this
4
3
15
26
0
I've never used recursion before and haven't been able to find anything showing how it would work with this particular type of problem.Here is what I've been able to come up with so far, but I'm having problems still which I will show following the code.
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
[code]...
It appears to be reading the file correctly, but is only printing the top half of the pattern. Also, like I said, I'm not very familiar with recursion, so am not sure if this is actually recursion?
View Replies
View Related
Jul 16, 2014
The program I'm working on is supposed to read input from a file and using recursion, print the pattern of asterisks for each value until the value is either < 0 or > 25. For example, if the value was 4, the pattern would look like this
*
* *
* * *
* * * *
* * *
* *
*
The values are stored in a file entitled prog3.dat which looks like this
4
3
15
26
0
I've never used recursion before and haven't been able to find anything showing how it would work with this particular type of problem. Here is what I've been able to come up with so far, but I'm having problems still which I will show following the code.
import java.util.Scanner;
import java.io.*;
public class Program3 {
public static void main(String[] args) throws Exception {
int num = 0;
java.io.File file = new java.io.File("../instr/prog3.dat");
Scanner fin = new Scanner(file);
[Code] ....
Output:
Please enter an integer
*
* *
* * *
* * * *
Please enter an integer
*
* *
* * *
Please enter an integer
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
Please enter an integer
Please enter an integer
As you can see, I don't know how to make it print the pattern like in the example and am honestly not even sure if this is recursion since I've never actually worked with recursion before.
View Replies
View Related
Apr 26, 2015
I was asked to create a word pyramid program using recursion. I understand the concept of recursion (i.e. a method calling itself with the problem it is solving getting simpler and simpler each time) but I am having issues writing the program. Here is my code:
public static void main(String[] args) {
//This program will create a word pyramid by using a recursive algorithm.
//For example, the output of "DOGGY" should be:
//DOGGY
//OGG
//G
//This program will also use a recursive algorithm to accomplish this.
String userWord = JOptionPane.showInputDialog(null, "Hello and welcome to the Word Pyramid program."
[Code] .....
So, if I input HORSE the output should be:
HORSE
ORS
R
View Replies
View Related
Nov 6, 2014
We are supposed to create a MergeSort method without the using recursion. Most of the code is already completed, the only thing that I believe I need are two for loops (an inner and an outter) that will make calls to the merge method. I need implementing the sort method of the merge sort algorithm without recursion, where the length of the array is a power of 2. Keep merging adjacent regions whose size is a power of 2. For ex: lengths will be 1, 2, 4, 8, 16,.
public class MergeSorter {
public static void sort(int[] a) {
//for(int i = 1; i <= a.length; i++) the parameters for the for loop are wrong.
{
merge(0,0,1,a);
merge(1,1,2,a);
merge(2,2,3,a);
[Code]...
View Replies
View Related
Nov 26, 2014
Here is what I have so far:
/**
* This class encapsulates a simple dice game. The number of dice and number of sides on those dice are given by instance variables. The outcomes ArrayList holds a list of all possible outcomes of throwing that number of dice with that number of sides.
*
* If there were 2 dice, each with 6 sides, then possible outcomes would include 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 2 1, 2 2, 2 3, and so on.
*
* Your task is to complete the methods that calculate the possible outcomes. One method calculates outcomes allowing for repeated numbers. One method calculates the outcomes of a fictional dice game where repeated numbers cannot occur.
*
* You must use recursion. This is a variation on the permutations problem from the book.
*/
public class Dice
{
private static int numberOfSides;
private static int numberOfDice;
public ArrayList<String> outcomes;
[code]...
I manage to calculate the numberOfOutcomes correctly, but then get a nullPointerException. Also, is there a way that I can use getNumberOf Outcomes without making it static? The testing code that the teacher provided is using it in another class and if I make it static, then it doesn't work in that file.
View Replies
View Related
Feb 26, 2014
I have this method
Java Code:
public static int[] oddNums(int n){
} mh_sh_highlight_all('java');
When a number is passed in, this method returns an array of odd numbers the amount of the number passed in.
So
Ex: Class.oddNums(5) would return [ 1, 3, 5, 7, 9 ]
Class.oddNums(2) would return [ 1, 3]
View Replies
View Related
Apr 12, 2014
From a two-dimensional grid 5x5 that looks like this:
(0,0)(0,1)(0,2)(0,3)(0,4)
(1,0)(1,1)(1,2)(1,3)(1,4)
(2,0)(2,1)(2,2)(2,3)(2,4)
(3,0)(3,1)(3,2)(3,3)(3,4)
(4,0)(4,1)(4,2)(4,3)(4,4)
We have Starting point that is (3,0) and an ending point is (1,3). We can only move up and right to get to the ending point by using recursion. We have to list all possible paths from (3,0) to (1,3)
Example: paths:(3,0)(2,0)(1,0)(1,1)(1,2)(1,3)
(3,0)(2,0)(2,1)(1,1)(1,2)(1,3)
etc...
I was able to get from (3,0) to (1,3) but how to list the other paths. This is my code so far
public class Program7 {
public static void main(String[] args){
int size = 5;
int x1 = 3;
int y1 = 0;
int x2 = 1;
int y2 = 3;
System.out.println(x1+" "+y1);
System.out.println(x2+" "+y2);
int [][] path = new int[size][size];
grid(path,x1,y1,x2,y2);
[code].....
View Replies
View Related