I have this recursive code for counting the number of permutations a string can have
public class Permutation {
static int counter = 0;
public static int perms(String s, int level,int length) {
if(level == length-1) {
counter++;
}
else {
for (int i = 0; i < s.length(); i++) {
String newString = s.substring(0, i) + s.substring(i + 1);
perms(newString,level + 1, length);
}
}
return counter;
}
public static void main(String[] args) {
System.out.println(perms("plot", 0, 4));
}
}
I was wondering how I can rewrite it so that it doesn't use static int counter = 0? Thanks!
NOTE: Yes, I know I can just use the permutation formula for this haha
Without the need for a static counter or passing a counter value to each method call. Note that your implementation counts all permutations and not unique permutations (String "aab" returns 6, not 3).
public static int permsRedone(String s, int level,int length){
int count = 0;
if(level == length-1){
return 1;
}
else {
for (int i = 0; i < s.length(); i++) {
String newString = s.substring(0,i)+s.substring(i+1);
count += permsRedone(newString,level+1,length);
}
}
return count;
}
You can pass the counter as the fourth argument (using 0 as the initial value). Return it from perms and set it to the value returned from the inner call.
public static int perms2(String s, int level,int length, int count){
if(level == length-1){
count++;
}
else {
for (int i = 0; i < s.length(); i++) {
String newString = s.substring(0,i)+s.substring(i+1);
count = perms2(newString,level+1,length, count);
}
}
return count;
}
Related
So, I have this block of code that takes something like printAllPossibilities("1234", 2) and prints all combinations of the string of length 2.
I want it to be able to find all possible combinations (for another part I'll be adding later) AND count the total number of combinations found. I tried adding a counter in the for loop, but it doesn't seem to be working in the way I applied it. Any thoughts are appreciated!
static void printAllPossibilities(String charSet, int length) {
printAllPossibilities_(charSet, length, "");
}
static void printAllPossibilities_(String charSet, int length, String temp) {
if (length == 0) {
System.out.println(temp);
return;
}
for (int i = 0; i < charSet.length(); i++)
printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}
If I understand your code correctly, you can do the following:
static void printAllPossibilities(String charSet, int length) {
printAllPossibilities_(charSet, length, "");
}
// declare counter
static int counter = 0;
static void printAllPossibilities_(String charSet, int length, String temp) {
if (length == 0) {
System.out.println(temp);
// increment counter
counter += 1;
return;
}
for (int i = 0; i < charSet.length(); i++)
printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}
Then output counter when you see fit.
You can count number of combinations this way
static void printAllPossibilities(String charSet, int length) {
int cnt = printAllPossibilities_(charSet, length, "");
System.out.println(cnt);
}
static int printAllPossibilities_(String charSet, int length, String temp) {
if (length == 0) {
System.out.println(temp);
return 1;
}
int res = 0;
for (int i = 0; i < charSet.length(); i++) {
res += printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}
return res;
}
Also you could use Permutations with Repetition formula
static void printAllPossibilities(String charSet, int length) {
printAllPossibilities_(charSet, length, "");
int cnt = (int) Math.pow(charSet.length(), length);
System.out.println();
System.out.println(cnt);
}
So given this.
//Fibonacci Series using Recursion
class fibonacci
{
static int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
public static void main (String args[])
{
int n = 10;
System.out.println(fib(n));
}
}
How could I transform it so it takes an index as a parameter and returns the given Fibonacci number at that index? So say I put in index = 5 and it should return 8.
static int fib(int index)
{
int counter = 0;
int current = 0;
int previous = 0;
int temp = 0;
while(counter < index)
{
temp = previous;
previous = current;
current += temp;
counter++;
}
return current;
}
If it does not have to be recursive, then I think this might work. Haven't tested it but tried to answer your question
int main(){
int index, temp1 = 0, temp2 = 1, value_at_index = 0;
printf("Enter index: ");
scanf("%d",&index);
if(index==1){
printf("Fib value at index 1 = 1");
}
else{
for (int i = 2; i <= index; ++i){
value_at_index = temp1 + temp2;
temp1 = temp2;
temp2 = value_at_index;
}
printf("Fib value at index %d = ", index);
printf("%d\n", value_at_index);
return 0;
}
}
It is printing out a few permutations but the rest are null and I'm not sure why. I need to but all the permutations into String[] and I can't import any other package except for util.Arrays. Please help!
import java.util.Arrays;
public class DIE
{
public static String[] printPermutations(String s)
{
int l = s.length();
int f = factorial(l);
int count = 0;
String[] array = new String[f];
permute("", s, array, 0);
Arrays.sort(array);
return array;
}
private static String[] permute(String x, String s, String [] array, int count)
{
int l = s.length();
if (l == 0)
{
array[count] = (x + s);
}
for (int i = 0; i < l; i++)
{
permute(x + s.charAt(i), s.substring(0, i) +
s.substring(i +1, s.length()), array, count);
count++;
}
return array;
}
public static int factorial(int l)
{
if (l == 1)
{
return 1;
}
else
{
int result = l * factorial(l - 1);
return result;
}
}
/*
Do not edit anything below this comment.
*/
public static void main(String[] args)
{
String[] permutations = printPermutations(args[0]);
for(String p : permutations)
{
System.out.println(p);
}
}
}
Your count variable is wrong. Within the outermost call to permute("", "abc", ...) it is incremented only by one, even though the call to the next level permute("a", "bc", ...) creates two permutations!
There are two possible solutions:
Instead of a String[] to collect your result use a List<String>. Then you don't need to manually count the number of permutations.
let permute return the new count (instead of the result array, that one is never used anyway)
For permute to return the new count the method would look like this:
private static int permute(String x, String s, String [] array, int count)
{
int l = s.length();
if (l == 0)
{
array[count++] = x;
}
for (int i = 0; i < l; i++)
{
count = permute(x + s.charAt(i), s.substring(0, i) +
s.substring(i +1, s.length()), array, count);
}
return count;
}
Using a List<String> would need some more changes, but the permute function would be smaller:
public static List<String> printPermutations(String s)
{
int l = s.length();
int f = factorial(l);
List<String> result = new ArrayList<>(f);
permute("", s, result);
Collections.sort(result);
return result;
}
private static void permute(String x, String s, List<String> result)
{
int l = s.length();
if (l == 0)
{
result.add(x);
}
for (int i = 0; i < l; i++)
{
permute(x + s.charAt(i), s.substring(0, i) +
s.substring(i +1, s.length()), result);
}
}
And some small changes in the main method due to the changed result of printPermutations (IMHO a very bad named method: it prints out nothing, it creates the permutations together with a helper method)
Here is my code ,
Find me the way to finish this off .
I had this question in paper this is the code at that time I could do.
In following example it should return 3.(starting point of "d")
public class HelloWorld {
public static void main(String []args){
int result = getMax("haaddddddddccf");
System.out.println(result);
}
public static int getMax(String input){
int length = input.length();
int count = 0;
int max = 0;
int tempCount = 0;
for(int i=0;i<length-1;i++) {
if(input.charAt(i) == input.charAt(i+1)) {
count ++ ;
}
tempCount = count;
count = 0;
if(max > tempCount) {
max = tempCount;
return i;
}
tempCount = 0;
}
return 0;
}
}
How about something like this:
public class HelloWorld {
public static void main(String []args){
int result = getMax("haaddddddddccf");
System.out.println(result);
}
public static int getMax(String input){
int length = input.length();
int maxIndex = 0;
int max = 0;
int count = 1;
char current = input.charAt(0);
int index = 0;
for(int i=1; i<length-1; i++) {
if(input.charAt(i) == current) {
count ++ ;
if(count > max) {
max = count;
maxIndex = index;
}
}
else {
count = 1;
current = input.charAt(i);
index = i;
}
}
return maxIndex;
}
}
This goes over the entire string and counting consecutive occurrences of characters. If the count goes over the observed maximum, the start index of that series of consecutive characters is saved as well as the number of characters. If the character changes, the current values reset and counting starts over. After going over the entire list, the index of the longest series of consecutive characters is in maxIndex.
Hi I have to create a method that takes the word message, and counts how many times the character e appears this is what I have but I always get 0. any suggestions?
public class run
{
public static void main(String[] args)
{
String message ="message";
int count=0;
for(int i=0; i>=message.length()-1;i++)
{
char ch = message.charAt(i);
char e='e';
if( ch == e)
{
count = count +1;
}
}
System.out.println(count);
}
}
for(int i=0; i>=message.length()-1;i++)
This will never enter the loop (except for some short-message edge cases where it will then stay in the loop for quite a while) since you have the comparison sense around the wrong way. You need:
for (int i = 0; i < message.length(); i++)
And you don't really need those extra variables, this will do fine:
int count = 0;
for (int i = 0; i < message.length(); i++)
if (message.charAt(i) == 'e')
count++;
Here is another recursive method:
public int countE(String str) {
int count = 0;
if (str.charAt(0) == 'e')
count++;
if (str.length() > 1) {
count += countE (str.substring(1));
}
return count;
}
Heres a recursive solution:
public static int countChar (String message, char e)
{
int charOccurences = 0;
for (int i = 0 ; i < message.length () ; i++)
{
if (message.charAt (i) == e)
{
charOccurences++;
message = message.substring (0, i) + message.substring (i + 1);
return charOccurences + countChar (message, e);
}
}
return charOccurences;
}