To print strings in which consecutive characters are different. For example, ABAA into ABA.To do this, it is allowed to delete the characters in the string. Task is to find the minimum number of required deletions. My code computes desired output for less value of T. But when T(=10) or string length become large it is Terminated due to timeout...can anyone give solution?
Input Format
The first line contains an integer T i.e. the number of test cases.
Next T lines contain a string each.
Output Format
Print minimum number of required steps for each test case.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.ArrayList;
public class AlternatingCharacters{
static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int no_of_testcase=s.nextInt();
String values="";
int removechars;
ArrayList<String> arrlist = new ArrayList<String>(no_of_testcase);
for(int i=0;i<no_of_testcase;i++)
{
values=s.next();
arrlist.add(values);
}
for(int i=0;i<arrlist.size();i++)
{
removechars=0;
for(int k=0;k<arrlist.get(i).length()-1;k++)
{
if(arrlist.get(i).charAt(k)==arrlist.get(i).charAt(k+1))
{
removeCharAt(arrlist.get(i),k+1);
removechars++;
}
}
System.out.println(removechars);
}
}
}
s.substring(0, pos) + s.substring(pos + 1);
There is your problem.
You should try using char arrays instead of Strings. String concatenation is extremely slow. Put everything in a char array than change your algorithm to use that.
Related
I am trying to create an algorithm that solves word problems
'' import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.lang.*;
public abstract class test {
static Scanner s = new Scanner(System.in);
public static void check() throws IOException {
String q = s.nextLine();
boolean add[] = {q.contains("together"), q.contains("sum"), q.contains("more"),q.contains("plus"), q.contains("altogether")};
if (add[0] == true || add[1] == true || add[3] == true || add[4] == true|| add[2] == true) {
String[] split = {"and",",",".","more"};
String[] parsedLine[] = {q.split(split[0]),q.split(split[1]),q.split(split[2]),q.split(split[3])};
String[] num1 = {parsedLine[0][0],parsedLine[0][1],parsedLine[0][2],parsedLine[0][3]};
String[] num2 = {parsedLine[1][0],parsedLine[1][1],parsedLine[1][2],parsedLine[1][3]};
int numget1[] = {Integer.parseInt(num1[0].replaceAll("[\\D]", "")),Integer.parseInt(num1[1].replaceAll("[\\D]", "")),Integer.parseInt(num1[2].replaceAll("[\\D]", "")),Integer.parseInt(num1[3].replaceAll("[\\D]", ""))};
int numget2[] = {Integer.parseInt(num2[0].replaceAll("[\\D]", "")),Integer.parseInt(num2[1].replaceAll("[\\D]", "")),Integer.parseInt(num2[2].replaceAll("[\\D]", "")),Integer.parseInt(num2[3].replaceAll("[\\D]", ""))};
int res[] = {numget1[0] + numget2[0],numget1[1] + numget2[1],numget1[2] + numget2[2],numget1[3] + numget2[3]};
}
}
public static void main(String[] args) throws IOException {
String question = "if ben has 3 apples and bee has 4 apples how many apples do they have all together";
check();
}}
I want this algorithm solve this simple world problem "if ben has 3 apples and bee has 4 apples how many apples do they have all together?"
basically it checks if its addition if it is it splits it removes the string turns it into int then adds the int simple but I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at mathproblemsolving.test.check(test.java:34)
at mathproblemsolving.test.main(test.java:61)
String#split takes a regular expression as argument. The "." is the regular expression for "any character", so that "Some.String".split(".") will return an empty array.
You need to escape the ".", that is "Some.String".split("\\.") will return the desired result.
You can view more information regarding split() here: java.lang.String
More information on Regex Expression here: W3 java_regex
When I run this program, it does not return anything yet no errors occur. I'm trying to create a method that will return the number of words I previously entered into the array once I enter "".
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayCounter {
public static int CountItems(ArrayList<String> list ) {
int i = list.size();
return i;
}
public static void main (String args[]) {
ArrayList<String> Names = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("Hey gimme a word");
String word = input.nextLine();
if (word.equals("")) {
System.out.println("The number of values entered were:");
break;
} else {
Names.add(word);
}
}
CountItems(Names);
input.close();
}
}
You're ignoring the result returned from CountItems.
The println should be:
System.out.println("The number of values entered were: " + CountItems(Names));
As an aside, methods names in Java should start with a lowercase, so CountItems should instead be countItems.
Your CountItems method returns the item count, but you are ignoring the result. You need some kind of System.out.println(CountItems(Names)) to print the result to the console.
Also, please consider renaming CountItems to countItems and Names to names to follow the naming conventions for Java.
I have a file with many lines.
Ex :
toto = 0x0020 tata 0x2000 0x0003
tata = 0x0001
tututtt = 0x0021
=> 0x3200
I just want to have these hexadecimal values in a byte array.
I've tried to use a BufferReader and split lines with the " " but I need to find a way to keep exclusively hexadecimal values.
Thanks in advance for your help.
I'd go with java.util.Scanner which can read tokens and patterns, here is the code that can read the file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ReadOnlyHex {
private static Pattern pattern = Pattern.compile("0x\\d{4}");
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("c:/temp/input.txt"));
while(in.hasNextLine()) {
String token = in.findInLine(pattern);
if (token == null) {
in.nextLine();
continue;
}
System.out.println(token.getBytes());
}
in.close();
}
}
I can only assume you are looking for the bytes array of the string, which can be achieved with String.getBytes()
Otherwise, the value represents an int that can be later changed to Integer.toBinaryString
You can use a regex pattern to filter. Loop over the line and use filter function in if you are using Java8.
So first define your pattern
final Pattern p= Pattern.compile("0x[0-9A-F]+$");
Then you can filter your each line array as
String[] splitLineArray=line.split(" ");
String[] hexNumbers=Arrays.stream(splitLineArray).filter((s)-> p.matcher(s).matches()).toArray();
This will return a new array with only hex numbers.
Hello I have a bit of a problem with calculating numbers from a file.
My input is the following rawData.txt:
19.95
5
The output however is this:
49.0 57
My code looks like this:
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite
{
public static void main(String args[])
throws FileNotFoundException {
Scanner diskScanner = null;
diskScanner = new Scanner(new FileReader("rawData.txt"));
PrintStream diskWriter = new PrintStream("cookedData.txt");
double total;
double unitPrice = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(unitPrice);
int quantity = diskScanner.findWithinHorizon(".", 0).charAt(0);
System.out.println(quantity);
total = unitPrice * quantity;
diskWriter.println(total);
diskScanner.close();
}
}
Eventually the cookedData.txt file contains the number 2793.0
Please help
You are fetching only the first character of each line - because of the charAt(0), then cast it to a double (casting char to double!!)
I can't understand what you are trying to do, but converting char to double using casting is almost always NOT what you should do.
Try using Double.parseDouble instead. see it here: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
diskScanner.findWithinHorizon(".",0).charAt(0);
means that you are getting any character, because the first parameter of findWithinHorizon is a regular expression, and "." means one character. From that string you take the first char, i.e. 1. The ascii value of 1 is... 49.
Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversion.
I was wondering if there's an input conversion method akin to C's scanf in Java?
Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.
Following code is taken from cited website:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
System.out.println("Enter something here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
--
import java.util.Scanner;
public class ReadConsoleScanner {
public static void main(String[] args) {
System.out.println("Enter something here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
}
Regards.
There is not a pure scanf replacement in standard Java, but you could use a java.util.Scanner for the same problems you would use scanf to solve.
Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:
71 5796 2489
88 1136 5298
42 420 842
Here's the code using findAll:
new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
.forEach(result -> {
int fst = Integer.parseInt(result.group(1));
int snd = Integer.parseInt(result.group(2));
int third = Integer.parseInt(result.group(3));
int sum = fst + snd + third;
System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
});
If one really wanted to they could make there own version of scanf() like so:
import java.util.ArrayList;
import java.util.Scanner;
public class Testies {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> strings = new ArrayList<String>();
// get input
System.out.println("Give me input:");
scanf(strings, nums);
System.out.println("Ints gathered:");
// print numbers scanned in
for(Integer num : nums){
System.out.print(num + " ");
}
System.out.println("\nStrings gathered:");
// print strings scanned in
for(String str : strings){
System.out.print(str + " ");
}
System.out.println("\nData:");
for(int i=0; i<strings.size(); i++){
System.out.println(nums.get(i) + " " + strings.get(i));
}
}
// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> nums){
Scanner getLine = new Scanner(System.in);
Scanner input = new Scanner(getLine.nextLine());
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
// pass it a string for input
public static void scanf(String in, ArrayList<String> strings, ArrayList<Integer> nums){
Scanner input = (new Scanner(in));
while(input.hasNext()){
// get integers
if(input.hasNextInt()){
nums.add(input.nextInt());
}
// get strings
else if(input.hasNext()){
strings.add(input.next());
}
}
}
}
Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.
Output:
Give me input:
apples 8 9 pears oranges 5
Ints gathered:
8 9 5
Strings gathered:
apples pears oranges
Data:
8 apples
9 pears
5 oranges
Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext<datatypehere>() methods; and then storing the input.
C/C++ has a notion of variable references, which makes creating something like scanf much easier. However, in Java, everything is passed by value. In the case of objects, their references are passed by value.
So, it's essentially impossible to have a concise equivalent to scanf. However, you can use java.util.Scanner, which does things similar to scanf.
So this C/C++:
int a;
float b;
scanf("%d %f", &a, &b);
is (roughly) equivalent to this Java:
int a;
float b;
try (Scanner sc = new Scanner(System.in)) {
a = sc.nextInt();
b = sc.nextFloat();
}
Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.
Use Integer.parseInt() to convert your string into Interger.
To print any string you can use System.out.println()
Example :
int a;
a = Integer.parseInt(args[0]);
and for Standard Input you can use codes like
StdIn.readInt();
StdIn.readString();
THERE'S an even simpler answer
import java.io.BufferedReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String myBeautifulScanf = new Scanner(System.in).nextLine();
System.out.println( myBeautifulScanf );
}
}