How can I find all available combinations of some digits. For example I have 0, 1, 2. In the output I should receive something like this:
0
01
02
012
021
1
10
12
102
120
2
20
21
201
210
The problem is in algorithm. I think here should be recursion, but how to to write it?
I have one done the same with strings. However, I just swapped random digits until I get all combinations(which is the factorial of the length of the string). I then print out the non-recurring ones.
Here is how I did it, just change the String you input to the allpos() method and it will work for any number.
import java.util.Random;
import java.util.Scanner;
public class shift {
public static void main(String[] args) {
//Change "012" to anything, even a String.
allpos("012");
}
public static int unbin(String s){
int ans=0;
for(int x=0;x<s.length();x++){
char c=s.charAt(x);
if(c=='1'){
ans+=Math.pow(2, s.length()-1-x);
}
}
return ans;
}
public static String bin(int n){
int[] ans=new int[32];
int a=n;
for(int x=31;x>=0;x--){
if(Math.pow(2, x)<=a){
a-=Math.pow(2, x);
ans[x]=1;
}
}
String s="";boolean zero=false;
for(int x=ans.length-1;x>=0;x--){
if(ans[x]==1){
s+="1";
zero=true;
continue;
}else if(zero){
s+="0";
}
}
return s;
}
public static boolean ispresent(String[] words,String s){
for(int x=0;x<words.length;x++){
if(words[x]==null){return false;}
if(words[x].equals(s)){return true;}
}
return false;
}
public static void allpos(String s){
int fac=1;
for(int x=1;x<=s.length();x++){
fac*=x;
}
int len=s.length();
String[] values=new String[fac];
values[0]=s;
System.out.println(s+" (1)");
int id1=0,id2=0;
Random r=new Random();
for(int x=1;x<fac;){
s=inchange(s,r.nextInt(len),r.nextInt(len));
if(ispresent(values,s)==false){
values[x]=s;
x++;
System.out.println(s+" ("+x+")");
}
}
}
public static String inchange(String s,int id1,int id2){
char[] chars=new char[s.length()];
for(int x=0;x<s.length();x++){
chars[x]=s.charAt(x);
}
char temp=chars[id1];
chars[id1]=chars[id2];
chars[id2]=temp;
String ans="";
for(int x=0;x<s.length();x++){
ans+=chars[x];
}
return ans;
}
}
I know that it is inefficient but it gets the job done for smaller numbers. I hope this helped.
Related
I'm trying to find the rank of given strings using recursion, but can't seem to to come out of the recursion the way I want to. Where am I going wrong?
class Solution {
public static int flag=0;
public static int ans=0;
public static int findRank(String A) {
/* write your solution here */
char[] carr=A.toCharArray();
Arrays.sort(carr);
String suffix=new String(carr);
ArrayList<String> list=new ArrayList<String>();
int rank=0;
rank=generate(rank,"",suffix,list,A);
for(int i=0;i<list.size();i++)
System.out.print(list.get(i)+" ");
return rank;
}
public static int generate(int rank,String prefix,String suffix, ArrayList<String> list,String A){
if(suffix.length()==0){
list.add(prefix);
rank++;
if(prefix.equals(A)){
return rank;
}
}
for(int i=0;i<suffix.length();i++) {
// System.out.println(rank);
return generate(rank,prefix+suffix.charAt(i),suffix.substring(0,i)+suffix.substring(i+1),list, A);
}
return rank;
}
}
This is the question:
Given a string, find the rank of the string amongst its permutations sorted lexicographically.
Assume that no characters are repeated.
Example :
Input : 'acb'
Output : 2
The order permutations with letters ‘a’, ‘c’, and ‘b’ :
abc
acb
bac
bca
cab
cba
I tried putting it in a visualizer, here's the code for that:
import java.util.*;
public class Solution {
public static int flag=0;
public static int ans=0;
public static void main(String args[]) {
/* write your solution here */
String A="dbca";
char[] carr=A.toCharArray();
Arrays.sort(carr);
String suffix=new String(carr);
ArrayList<String> list=new ArrayList<String>();
int rank=0;
rank=generate(rank,"",suffix,list,A);
for(int i=0;i<list.size();i++)
System.out.print(list.get(i)+" ");
System.out.println(rank);
}
public static int generate(int rank,String prefix,String suffix, ArrayList<String> list,String A){
if(suffix.length()==0){
list.add(prefix);
rank++;
if(prefix.equals(A)){
return rank;
}
}
for(int i=0;i<suffix.length();i++){
// System.out.println(rank);
return generate(rank,prefix+suffix.charAt(i),suffix.substring(0,i)+suffix.substring(i+1),list, A);
}
return rank;
}
}
https://cscircles.cemc.uwaterloo.ca/java_visualize/#mode=edit
Your for loop causes you to end the recursion after you find the first permutation, which is why you always return 1.
What you should be doing is to end the recursion once you find the permutation you are looking for. You can do that, for example, if your recursive method would return a boolean flag instead of an int.
Once the recursive method returns, the length of your list will be the rank you are looking for:
public static int findRank(String A)
{
char[] carr=A.toCharArray();
Arrays.sort(carr);
String suffix=new String(carr);
ArrayList<String> list=new ArrayList<String>();
generate("",suffix,list,A);
for(int i=0;i<list.size();i++)
System.out.print(list.get(i)+" ");
return list.size();
}
public static boolean generate(String prefix,String suffix, ArrayList<String> list,String A)
{
if(suffix.length()==0){
list.add(prefix);
return (prefix.equals(A));
}
for(int i=0;i<suffix.length();i++) {
if (generate(prefix+suffix.charAt(i),suffix.substring(0,i)+suffix.substring(i+1),list, A)) {
return true;
}
}
return false;
}
Below is the problem statement from hackerrank
Mark and Jane are very happy after having their first child. Their son loves toys, so Mark wants to buy some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of toys Mark can buy? For example, if prices = [1,2,3,4] and Mark has k=7 to spend, he can buy items [1,2,3] for 6, or [3,4] for 7 units of currency. He would choose the first group of 3 items.
Below is code I wrote for this problem which involves backtracking technique
import java.util.ArrayList;
import java.util.Collections;
public class MarkAndToys {
static ArrayList<Integer> possibleSolutions = new ArrayList<>();
static boolean findSolution(int[] prices,int amount,int left,int length,int items){
// Base case: if whole array was iterated and amount is >=0 then we got a solution
if(left >= length){
if(amount>=0){
possibleSolutions.add(items);
return true;
}
return false;
}
// Key idea: prices[left] is chosen or it is not.
// Deal with prices[left], letting recursion
// deal with all the rest of the array.
// Recursive call trying the case that prices[left] is chosen --
// subtract it from amount in the call.
if (findSolution(prices,amount-prices[left],left+1,length,items+1)) return true;
// Recursive call trying the case that prices[left] is not chosen.
if (findSolution(prices,amount,left+1,length,items)) return true;
// If neither of the above worked, it's not possible.
return false;
}
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
if(findSolution(prices,k,0,prices.length,0)){
//if solutions are found then return maximum of them
return Collections.max(possibleSolutions);
}
return 0;
}
public static void main(String[] args) {
System.out.println(maximumToys(new int[]{1,12,5,111,200,1000,10}, 50));
}
}
This seems to be working fine:
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
Arrays.sort(prices);
int sum = 0;
int index = 0;
for(int i = 0; i < prices.length; i++) {
sum+=prices[i];
index = i;
if(sum > k) {
break;
}
}
return index;
}
package Scanarios;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Toys {
public static void main(String[] args) {
Toys t=new Toys();
int[] a = {3,6,2,1,4,5};
int q=1;
int n=6;
ArrayList<Integer> queries[]=new ArrayList[n];
ArrayList<Integer> result=new ArrayList();
for (int i = 0; i < n; i++) {
queries[i] = new ArrayList<Integer>();
}
queries[0].add(10);
queries[0].add(2);
queries[0].add(2);
queries[0].add(5);
result=t.maximumToys(n,a,q,queries);
System.out.println(result);
}
public ArrayList<Integer> maximumToys(int n, int a[], int q, ArrayList<Integer> queries[]) {
ArrayList<Integer> arrlist=new ArrayList();
for(int z=0;z<q;z++) {
int[] arr=queries[z].stream().mapToInt(i -> i).toArray();
int cost=arr[0];
int k=arr[1];
int count=0;
int[] proxyarr=new int[n-1];
proxyarr =removeBrokenPrice(a,arr,k);
Arrays.sort(proxyarr);
for(int i=0;i< proxyarr.length;i++) {
cost -=proxyarr[i];
if(cost > 0) {
count++; }else {
break;
}
}
arrlist.add(count);
}
return arrlist;
}
int[] removeBrokenPrice (int a[],int b[],int k){
int count=0;
for(int i=k;i <= b.length-1;i++) {
for(int j=0;j<a.length;j++) {
if(j==b[i]-1) {
a[j]=-1;
count++;
}
}
}
int[] proxyarr=new int[a.length-count];
for(int i=0,j=0;i< a.length;i++)
{
if(a[i]==-1) {
continue;
}else {
proxyarr[j++]=a[i];
}
}
return proxyarr;
}
}
My teacher gave me some java code and asked me to rewrite it in python. I'm not asking for help with rewriting it, but when I entered the code into my Java compiler I got this error:
Exception in thread "main" java.lang.StackOverflowError
at
java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.<init>(StringBuilder.java:113)
at Permutations.perm1(Permutations.java:12)
at Permutations.perm1(Permutations.java:4)
Any help is greatly appreciated, here is the code:
public class Permutations {
public static void perm1(String s) {
perm1("", s);
}
private static void perm1(String prefix, String s){
int N=s.length();
if(N==0){
System.out.println(prefix);
}else{
for(int i=0; i<N; i++){
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,
N));
}
}
}
public static void perm2(String s){
int N=s.length();
char[] a = new char[N];
for(int i=0;i<N;i++){
a[i]=s.charAt(i);
perm2(a,N);
}
}
private static void perm2(char[] a, int n){
if(n==1){
System.out.println(a);
return;
}
for(int i=0; i<n;i++){
swap(a,i,n-1);
perm2(a,n-1);
swap(a,i,n-1);
}
}
private static void swap(char[] a, int i, int j) {
char c;
c=a[i];
a[i]=a[j];
a[j]=c;
}
public static void main(String[] args) {
int N=5;
String alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0,N);
perm1(elements);
System.out.println();
perm2(elements);
}
}
There is an error in this line:
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,
N));
Should look like this:
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, N));
Compere with this code:
http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html
Stepping through the code with a debugger shows that you get a stack overflow error because of this section:
for(int i=0; i<N; i++){
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N));
}
perm1 is called repeatedly, but the input doesn't change - it's always passed "abcde" with no prefix, and the result of prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N) is still "abcde". Since the call is recursive, and the input doesn't change with each iteration, it just repeats and takes up increasingly more space on the stack until it overflows and throws an exception.
My problem is my program doesn't find the 10001st prime. So it never stops and I still don't know the 10001st prime. I will be happy to solve the problem with my implementation. Thank you :)
public class problem7 {
public static boolean sonuc=true;
public static void asalmi(int j)
{
int counter=0;
int asayac=0;
for(int k=1;k<=j;k++)
{
if(j%k==0)
{
counter++;
}
}
if(counter==2)
{
// Only factors are 1 and j, so j is prime
System.out.println(j);
asayac++;
counter=0;
if(asayac==10001)
{
System.out.println(j);
sonuc=false;
}
}
}
public static void main(String[] args)
{
int i=1;
while(sonuc)
{
asalmi(i);
i++;
}
}
}
Every time you call asalmi, you set a local variable asayac to 0. This should be a static variable, not a local one.
c program to find the 10001st prime number
#include<stdio.h>
isPrime(int x){
int i;
for(i=2;i<=x/2;i++){
if(x%i==0) return 0;
}
return 1;
}
int main(){
int n=3;
int counter=1;
while(counter!=10001){
if(isPrime(n)==1) counter++;
n=n+2; // possibility of next prime is by adding 2 to current
}
printf("counter=%d\n",counter);
printf("number is:%d\n",n-2); //-2 due to unwanted increment in loop
}
I am having a String , i am creating a BIT of String based on the frequency of the element present
String:
abcdbcaab
Code:
class Test{
static int[][] dp;
public static void update(int i , int val ,int[] dpp){
while(i<=100000){
dpp[i]+=val;
i+= (i&-i);
}
}
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i);
}
return ans;
}
public static void main(String args[] ) throws IOException {
Scanner in = new Scanner(new InputStreamReader(System.in));
dp = new int[27][1000001];
String s = in.next();
for(int i=0;i<s.length();i++){
update(i+1,1,dp[s.charAt(i)-'a']);
}
System.out.println(dp[0][7]); // Should show 2 as the frequency of 'a' at 7 position is 2
}
}
Where i am doing wrong . i could not get it but dp[0][8] is showing me 3Please Help i could not figure it out where i have commit mistake
Negativity should be avoided in life !!! but i think a little more negativity can improve you'r code:
value function you are doing wrong decrement of value of i
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i); // Should be (i&-i);
}
return ans;
}