Suppose there is a string s=abcd
I want the 5th string consisting of a,b,c,d, which is adbc.
But I also get all the answers beyond it which I don't need.
So how can I stop this method after its 5th execution?
import java.util.Arrays;
import java.util.Scanner;
class Test{
long times;
int n=1;
public static void main(String[] args) {
Test tm=new Test();
Scanner in=new Scanner(System.in);
int t=Integer.parseInt(in.nextLine());
while(t!=0){
String s=in.nextLine();
char ch[]=s.toCharArray();
Arrays.sort(ch);
String sort=String.valueOf(ch);
String ans;
long n=Long.parseLong(in.nextLine());
tm.times=n;
tm.permu("",sort);
t--;
}
}
private void permu(String prefix,String str) {
int len=str.length();
if(len==0){
if(n==times){
System.out.println(prefix);
}
else{
n++;
}
}
else{
for(int i=0;i<len;i++){
permu(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, len));
}
}
}
}
Secondly is there any site where I can read about permutation, combination and probability for calculating and finding the permutation, combination and probability... For coding thing not for mathematical thing..i.e I know how to solve mathematically but I can't code it.. Unable to write logic for it.
You don't change n after running the check and printing a result in your recursion. That's why you print everything after adbc.
If you use this code when checking:
if (n == times) {
System.out.println(prefix);
n = -1;
} else {
if (n > -1)
n++;
}
then you only get n == times to be true once, and that's when the prefix is adbc.
Example test for the solution:
If you want to stop a method that has no return value (has void in its return type in the method signature), then calling return; will exit the method... But it isn't needed here.
Related
Problem Statement is from hackerrank.
Name: Simple text Editor
Description: I has taken a stackNode.in stackNode i used three variables top is for previous operation performed operate is k and s for storing the string which was either deleted or appended in previous operation.
Link to the problem
: https://www.hackerrank.com/challenges/simple-text-editor/problem?isFullScreen=false
import java.io.*;
import java.util.*;
class StackNode
{
int top;
int operat;
String s;
}
public class Solution
{
static String S="";
static Stack<StackNode> stack=new Stack<>();
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-- >0)
{
int operation=sc.nextInt();
if(operation == 1)
{
String st=sc.next();
S=S+st;
StackNode node=new StackNode();
node.top=operation;
node.s=st;
stack.push(node);
}
else
if(operation == 2)
{
int k=sc.nextInt();
delete(k,operation);
}
else
if(operation == 3)
{
int k=sc.nextInt();
print(k);
}
else
if(operation == 4)
undo();
}
}
static void delete(int k,int operation)
{
StackNode node=new StackNode();
node.top=operation;
node.operat=k;
if(S.length() < k)
{
node.s=S;
S="";
return;
}
else
{
node.s=S.substring(S.length()-k);
S=S.substring(0,S.length()-k);
}
stack.push(node);
}
static void print(int k)
{
if(k<=S.length())
System.out.println(S.charAt(k-1));
}
static void undo()
{
if(stack.isEmpty())
return;
StackNode node=stack.pop();
if(node.top == 1)
{
S=S.substring(0,S.length()-node.s.length());
}
else
if(node.top == 2)
{
S=S+node.s;
}
}
}
Problem: Copying the entire editor content on each append and each delete operation takes a long time when the string is long. Solution: Instead of keeping the editor content in a String use a StringBuffer or StringBuilder.
The content of the editor may be up to a million chars. Each of the following code lines copies this content into a new String:
S=S+st;
S=S.substring(0,S.length()-k);
S=S.substring(0,S.length()-node.s.length());
S=S+node.s;
When instead you append to or delete from a StringBuffer or StringBuilder, the characters not involved in the operation can stay in place.
Other possible slight optimizations:
On the undo stack don’t store the appended string but only the length of it. The length suffices for undoing the append operation.
Use a switch statement for selecting the right operation rather than chained if-else.
is there any difference between switch and chained if-else in terms of
time complexity and space complexity
In most cases switch on an int value should be faster than chained if-else.
Documentation link: StringBuilder
I was asked to program a method that receives a scanner, and returns a sorted array of words which contain only letters, with no repetitions (and no bigger in length than 3000). Then, I was asked to program a method that checks whether a certain given string is contained in a given vocabulary. I used a simple binary search method.
This is what I've done:
public static String[] scanVocabulary(Scanner scanner){
String[] array= new String[3000];
int i=0;
String word;
while (scanner.hasNext() && i<3000) {
word=scanner.next();
if (word.matches("[a-zA-Z]+")){
array[i]=word.toLowerCase();
i++;
}
}int size=0;
while (size<3000 && array[size]!=null ) {
size++;
}
String[] words=Arrays.copyOf(array, size);
if (words.length==0 || words.length==1) {
return words;
}
else {
Arrays.sort(words);
int end= removeDuplicatesSortedArr(words);
return Arrays.copyOf(words, end);
}
}
private static int removeDuplicatesSortedArr(String[] array) { //must be a sorted array. returns size of the new array
int n= array.length;
int j=0;
for (int i=0; i<n-1; i++) {
if (!array[i].equals(array[i+1])) {
array[j++]=array[i];
}
}
array[j++]=array[n-1];
return j;
}
public static boolean isInVocabulary(String[] vocabulary, String word){
//binary search
int n=vocabulary.length;
int left= 0;
int right=n-1;
while (left<=right) {
int mid=(left+right)/2;
if (vocabulary[mid].equals(word)){
return true;
}
else if (vocabulary[mid].compareTo(word)>0) {
right=mid-1;
}else {
right=mid+1;
}
}
return false;
}
while trying the following code:
public static void main(String[] args) {
String vocabularyText = "I look at the floor and I see it needs sweeping while my guitar gently weeps";
Scanner vocabularyScanner = new Scanner(vocabularyText);
String[] vocabulary = scanVocabulary(vocabularyScanner);
System.out.println(Arrays.toString(vocabulary));
boolean t=isInVocabulary(vocabulary, "while");
System.out.println(t);
System.out.println("123");
}
I get nothing but-
[and, at, floor, gently, guitar, i, it, look, my, needs, see, sweeping, the, weeps, while]
nothing else is printed out nor returned. Both functions seem to be working fine separately, so I don't get what I'm doing wrong.
I would be very happy to hear your thoughts, thanks in advance :)
This has nothing to do with the console. Your isInVocabulary method is entering an infinite loop in this block:
if (!isInVocabulary(vocabulary, "while")) {
System.out.println("Error");
}
If you were to debug through isInVocabulary, you would see that after a few iterations of the while loop,
left = 0;
right = 2;
mid = 1;
if (vocabulary[mid].equals(word)){
// it doesn't
} else if (vocabulary[mid].compareTo("while") > 0) {
// it doesn't
} else {
right = mid + 1;
// this is the same as saying right = 1 + 1, i.e. 2
}
So you'll loop forever.
I am doing some java exercises and I am trying to make a method that counts to 100 and prints the number each time the for loop "loops". The exception is that it will print "Fizz" when the number is divisible by 3 and "Buzz" when the number is divisible by 5.
Now, I have three return types in my method that is gonna return a String. However, the error says I do not return a value. I am aware that I have to make it return a String outside the for loop but I am having some trouble figuring out how I should get to return the value that I want. I am also aware that I could use arrays or even arrayList to fix this problem but I think its possible without that and I would like to try doing so. Any help would be very appreciated! Here is the code:
package etcOvaningar;
public class ovning1 {
public static String fizz ="Fizz!";
public static String buzz ="Buzz!";
public static String countDown(){
for (int number = 0; number < 100; number++){
if (number%3 == 0){
return fizz;
}
else if (number%5 == 0){
return buzz;
}
else
return String.valueOf(number);
}
//I need to insert a return here I suppose, but I want the correct return from the if and else //statements
}
public static void main(String[] args){
}
}
Don't "return" in the loop, but rather print. When you return, the method exits, and the loop loops no more. If you simply print the necessary text, the for loop will continue to loop until it reaches its natural end condition.
public static void countDown(){
for (int number = 0; number < 100; number++){
if (number % (3*5) == 0) {
System.out.println("fizzbuzz");
} else
if (number % 3 == 0){
System.out.println("fizz");
} else
if (number % 5 == 0){
System.out.println("buzz");
}
}
}
Note as per Martin Dinov, this method should be declared to return void, nothing.
Your code won't compile because method countdown needs return value below the for loop.
However whatever you return value you put below the for loop won't matter because your countdown method will always return "Fizz!"
This is another way to do what you want to do. Perhaps, more of what you really should be doing.
private static String fizz ="Fizz!";
private static String buzz ="Buzz!";
public static void main(String[] args){
for (int number = 0; number < 100; number++){
String word = checkNumber(number);
System.out.println(word);
}
}
private static String checkNumber(int number){
String value = "";
if (number%3 == 0){
value += fizz;
}
if (number%5 == 0){
value += buzz;
}
if (value.isEmpty()) {
value = String.valueOf(number);
}
return value;
}
Points to note:
Start your methods and fields as private and upgrade their visibility as you further develop your program and your needs change. This helps keep the code clean and the exposure to the minimum.
Try not to have print statements in methods (unless they are specifically designed for printing messages). They should take an input, process the input and return an output. Nothing more, nothing less.
Understand the difference between if / else if / else and if / if / if. The number 15 is divisible by both 3 and 5.
I can't seem to get the "The numbers match" result if my input is a number that is in my array list in another class called SomeNumbers. If you run it, it will give you the result for it not being a number in the array at the speed of light though.
I am also having a hard time pin pointing where the actual problem is because I can use my debugging tools for whatever reason in jGrasp.
This is the main application that the user would input the number to see if there is a match.
import java.util.Scanner;
public class SomeNumbersClient {
public static void main(String[] args) {
SomeNumbers testNumbers = new SomeNumbers();
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Integer Value: ");
int input = userInput.nextInt();
testNumbers.setNumber(input);
if (testNumbers.getTest()) {
System.out.println("The numbers match");
} else {
System.out.println("The numbers don't match");
}
}
}
Now this is the class where I call on the getTest method to see if the boolean result is true or false. I then have the if statement in the client see if it's true then it will display that there is a match, if not, there is no match.
public class SomeNumbers {
private int[] numbers = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 120255, 1005231, 6545231, 3852082, 7576651,7881200, 4581002};
private int number;
private int index = 0;
private boolean test = true;
public void setNumber(int input) {
number = input;
}
public boolean getTest(){
while (index < numbers.length){
if (number != numbers[index]){
test = false;
index++;
} else {
test = true;
}
}
return test;
}
}
Sorry the code kind of got chopped up, any help is appreciated.
here is proper version of getTest function, your problem was because you find match (and set variable test to true), but then you continue search and next number converts "test" to false
public boolean getTest()
{
index = 0;
while (index < numbers.length)
if (number != numbers[index])
index++;
else
return true;
return false;
}
First of all this is not homework. Just me practicing.
I'm trying to recursively determine the number of times "hi" appears in the given string, but in every case it skips to the last else if statement and things the string is empty. Any ideas?
Basically,
if(string starts with "hi")
increment count by 1 and recurse with the string after the 2nd index to skip over the "hi" it just counted
else if(string does not start with "hi" and string is not empty)
recurse with the string after its 1st index to see if it starts with "hi" the next time around.
else if(string is empty)
Print("End of text reached")
return count;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
This is a good opportunity to practice debugging recursive functions calls -- actually quite difficult. Suggestions:
use strategically placed print-statements to ensure that the arguments are being changed correctly from one recursive invocation to the next
refactor the order of case-analysis in the if-statement to make it more clear. For example, 1) check if the string is empty (base case), 2) check if the string starts with "hi", 3) catch-all -- not empty and doesn't start with "hi"
As #Steve mentioned, you have to use the return value that recur returns.
See below for a modified version of your code, I also simplified your if/else statements:
public int recur(String str, int counter) {
if (str.startsWith("hi")) {
return recur(str.substring(2), counter+1);
} else if (!str.isEmpty()) {
return recur(str.substring(1), counter);
} else {
System.out.println("End of text reached");
return counter;
}
}
public static void main(String args[]) {
String str = "xxhixhixx";
Practice p = new Practice();
System.out.println(p.recur(str, 0));
}
You aren't using the value returned from recur.
public int countHi(String str) {
if (str.length() <= 1) {
return 0;
}
int count = 0;
if (str.substring(0, 2).equals("hi")) {
count = 1;
}
return count + countHi(str.substring(1)); //substring off
}
All this does is recursively count the number of the String "hi" inside a larger String. The rest of the implementations should be a piece of cake, happy Coding!
Your program printing 'End of text' is correct as finally as per the logic it will reach there, reason for count always coming as 0 is that in every iteration they change there own copy and finally when the termination condition is reached(String is empty) the result is popped out of the stack, hence final outcome that you receive is the pop of the first iteration where count was 0, so you have to return the value returned by recur at every step instead of returning count.
public static int recursive(String givenStr) {
int count =0 ;
Pattern pattern = Pattern.compile("hi");
Matcher match = pattern.matcher(givenStr);
while(match.find()){
System.out.println(match);
count++;
}
return count;
}
This Will return number of times "hi" has appeared into the String