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);
}
Related
I'm trying to find the maximum consecutive repeats of a substring in a given string. I'm using substring(), equals(), and length() methods from the String library. However, I don't get the correct result. Here's my code-
public static int maxRepeats(String dna) {
int max = 0;
int count = 0;
for (int i = 0; i < dna.length() - 3; i++) {
String s = dna.substring(i, i + 3);
if (s.equals("CAG")) {
count++;
i += 2;
}
if (!s.equals("CAG")) {
max = count;
count = 0;
}
}
return max;
}
Let for example dna= "CAGCAGCAGTTCAGCAGCAGCAGTTCAGCAGCAG"
Then, max consecutive repeats of substring "CAG" = 4 ---> expected output
But for this substring or any substring, this is the result I get-
max repeats = 0
Would be grateful if someone pointed out where am I wrong :-)
The problem with your code was you are not saving the max value properly . It was getting overridden to value 0 when ever the substring is not equal to "CAG". Instead you only need to set the value of count=0 in else condition and not max =0. Check this code. It should work for you
int max = 0;
int count = 0;
for (int i = 0; i < dna.length() - 3; i++) {
String s = dna.substring(i, i + 3);
if (s.equals("CAG")) {
count++;
i += 2;
} else {
count=0;
}
if (count>max) {
max = count;
}
}
The problem is you are comparing for not equal to CAG and it is not necessary, resulting in you not saving the max correctly. Also, it is not necessary to check for count on each iteration.
public static int maxRepeats(String dna) {
int max = 0;
int count = 0;
for (int i = 0; i <= dna.length() - 3; i++) {
String s = dna.substring(i, i + 3);
if (s.equals("CAG")) {
count++;
i += 2;
} else {
// only check max when CAG is not present.
if (count > max) {
max = count;
}
// but reset counter regardless.
count = 0;
}
}
return Math.max(max,count);
}
Another alternative is to use regular expressions.
public static int maxRepeats(String dna) {
// find the longest repeats of CAG
Matcher m = Pattern.compile("(CAG)*").matcher(dna);
int longest = 0;
while (m.find()) {
String f = m.group();
if (f.length() > longest) {
longest = f.length();
}
}
// the longest string must be divisible by 3 so...
return longest/3;
}
Method 1:
/**
* #param pattern string being searched
* #param text string being searched in
* #return max number of times pattern can be self-appended and remains a
* substring of text
*/
int maxRepeats(String pattern, String text) {
int max = 0;
int count = 0;
int i = 0;
while (i <= text.length() - pattern.length()) {
String s = text.substring(i, i + pattern.length());
if (s.equals(pattern)) {
count++;
i += pattern.length();
} else {
max = Math.max(max, count);
count = 0;
i++;
}
}
return Math.max(max, count);
}
Method 2:
int maxRepeats(String pattern, String text) {
String s = pattern;
int max = 0;
while (s.length() <= text.length()) {
if (text.contains(s)) {
max++;
s += pattern;
} else {
break;
}
}
return max;
}
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;
}
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.
I am trying to make an int method that converts a binary number into a base 10 number. I think my loop is structured correctly, but I cant figure out how to relate index position to an exponent. Basically if there is a '1' in the string, i want to return it as 2 to the power of whatever the index position of that char is. Also, this would require me to inverse the index (so that the 0 position is the rightmost char of the string. Here is what I have so far:
public static int BinaryToNumber(String numberInput)
{
int len = numberInput.length();
for(int i=len-1; i<len; i--)
{
if(i == '1');
{
return n;
}
}
return 0;
}
Thank you in advance!
I would prefer the Java built-in routines when possible - as I said in my comment Integer.parseInt(numberInput, 2);. By convention, Java method names begin with a lower case letter. Finally, you can fix your code (and I added a small test harness) with something like,
public static int binaryToNumber(String numberInput) {
if (numberInput == null) {
return 0;
}
int ret = 0;
char[] ni = numberInput.trim().toCharArray();
for (int i = 0; i < ni.length; i++) {
if (ni[i] == '1') {
// This is 2 ^ (n) where (n) is based on the position from the right.
ret += 1 << ni.length - i - 1;
}
}
return ret;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String t = Integer.toBinaryString(i);
System.out.printf("%s = %d%n", t, binaryToNumber(t));
}
}
this is my implementation for the problem
public static void main(String[] args) {
String str = "100101";
System.out.println(toDecimal(str));
}
private static int toDecimal(String binary) {
int result = 0;
for(int i = 0; i < binary.length(); i++) {
int a = (int) binary.charAt(i) - 48;
double secondPart = 1 << (binary.length()-1) - i;
result += a * secondPart;
}
return result;
}
I hope that helps
Salam
I'd appreciate any help on the following problem. I have n integers from 0 to n-1, and I'm trying to generate a list of all possible combinations of length k (i.e. k concatenated integers) such that every pair of consecutive integers are not equal. So, for example, (1)(2)(3)(2) would be valid with k = 4, but (1)(2)(3)(3) would not be valid. Any ideas on how to approach this most efficiently? (I don't care much about length/degree of complexity of the code, just efficiency)
It is the code:
void Generate(int[] source, List<int[]> result, int[] build, int k, int num) {
if (num == k) {
int[] a = (int[])build.clone();
result.add(a);
return;
}
for (int i = 0; i < source.length; i++)
if (num == 0 || source[i] != build[num - 1])
{
build[num] = source[i];
Generate(source, result, build, k, num + 1);
}
}
How to call:
int k = 2;
List<int[]> a = new ArrayList<int[]>();
Generate(new int[]{1,2,3}, a, new int[k], k, 0);
public class Generator {
final int k = 2;
final char[] n = new char[]{'0','1','2','3','4','5','6','7','8','9'};
final char[] text = new char[k];
public void gen(int i, int not_n) {
if(i == k) {
System.out.println(text);
return;
}
for(int j = 0; j < n.length; j++) {
if(j == not_n) continue;
text[i] = n[j];
gen(i+1, j);
}
}
public static void main(String[] args) {
new Generator().gen(0, -1);
}
}
public static void recursiveOutput(Integer n, int k, int limit, String prints){
k++;
if(k>limit)
return;
String statePrints = prints;
//cycle through all available numbers
for(Integer i = 1; i<=n; i++)
{
statePrints = prints;
//First cycle
if(k==1){
statePrints+= "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
//check if predecessor is not the same
if(i != Integer.parseInt(statePrints.substring(statePrints.length()-2,statePrints.length()-1))){
statePrints += "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
}
//Check if the length matches the combination length
if(statePrints.length() == 3 * limit)
System.out.println(statePrints);
}
call :recursiveOutput(3,0,4,"");