Checking a number range with regular expressions - java

I'm using a regular expression to validate a certain format in a string. This string will become a rule for a game.
Example: "DX 3" is OK according to the rule, but "DX 14" could be OK too... I know how to look at the string and find one or more "numbers", so the problem is that the regex will match 34 too, and this number is out of "range" for the rule...
Am I missing something about the regex to do this? Or is this not possible at all?

Unfortunately there's no easy way to define ranges in regex. If you are to use the range 1-23 you'll end up with a regex like this:
([1-9]|1[0-9]|2[0-3])
Explanation:
Either the value is 1-9
or the value starts with 1 and is followed with a 0-9
or the value starts with 2 and is followed with a 0-3

It is not that short, and not flexible.
If you search for 1 to 19, you can search for "DX 1?[0-9]", for example, but if it doesn't end at a number boundary, it get's ugly pretty soon, and changing the rules is not flexible.
Splitting the String at the blank, and then using x > 0 and x < 24 is better to understand and more flexible.

You can use following format for writing a regular expression solving your problem.
Suppose your range is 0-15.
"^DX [0-9]|1[0-5]$"
You can even make it dynamic depending on your range by appending strings.

package dev.dump;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Collections;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA. User: User Date: 28.09.2007 Time: 9:46:47 To change this template use
* File | Settings | File Templates.
*/
class NumberDiapasone2RegExp {
private static final String invalidArgumentEmpty="Invalid argument \"{0}\" was found! {1}";
private static final Pattern pattern=Pattern.compile("^(\\d+)-(\\d+)?$");
private String src;
private String result="";
private Long left;
private Long right;
private boolean transform09ToD;
public NumberDiapasone2RegExp(final String src) {
this(src, false);
}
public NumberDiapasone2RegExp(final String src, final boolean transform09ToD) {
this.transform09ToD=transform09ToD;
if (src==null || src.trim().length()==0)
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It cannot be empty."));
if (src.indexOf("-")<0)
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It is supposed to have \"-\"."));
if (src.indexOf("-")!=src.lastIndexOf("-"))
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It is supposed to have only one \"-\"."));
Matcher syntaxChecker=pattern.matcher(src);
if (!syntaxChecker.find()){
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It is supposed to be in format \"##-##\"."));
}
this.src=src;
parseAndCheck();
String theSameDigits="";
//the same digit goes towards result
if (left.toString().length()==right.toString().length()){
for (int i=0; i<left.toString().length(); i++){
if (i<right.toString().length() &&
left.toString().charAt(i)==right.toString().charAt(i)){
theSameDigits+=left.toString().charAt(i);
}
}
if (theSameDigits.length()>0){
this.src=this.src.replaceFirst(Pattern.quote(theSameDigits),"");
this.src=this.src.replaceFirst(Pattern.quote("-"+theSameDigits),"-");
parseAndCheck();
}
}
result=glueParts(compact(transform09ToD, toParts()));
Matcher m=secondCompact.matcher(result);
while (m.find()){
result=m.group(1).replace("(","").replace(")","")+"["+m.group(2).replaceAll("[\\[\\]]","")+m.group(3).replaceAll("[\\[\\]]","")+"][0-9]";
m.reset(result);
}
//compact squares again
StringBuffer sb=new StringBuffer();
Pattern squresP=Pattern.compile("(\\[(\\d|-)+\\])");
m=squresP.matcher(result);
while (m.find()) {
m.appendReplacement(sb, Matcher.quoteReplacement(compactSquares(m.group(1))));
}
m.appendTail(sb);
result=sb.toString();
result=result.replaceAll("\\[(\\d)-\\1\\]","$1");
result=result.replaceAll("\\[(\\d)\\]","$1");
result=result.replace("{1}","").replace("{0,1}","?");
if (result.indexOf("|")>=0) result=theSameDigits+"("+result+")";
else result=theSameDigits+result;
if (result.startsWith("(") && result.endsWith(")")) result=result.substring(1, result.length()-1);
}
private static Pattern secondCompact=Pattern.compile("(.*)(\\[\\d-?\\d\\]|\\d)\\[0-9\\]\\|(\\[\\d-?\\d\\]|\\d)\\[0-9\\]");
static List<String> compact(boolean transform09ToD, String... parts) {
Set<String> unique=new HashSet<String>();
List<String> result=new ArrayList<String>();
for (String part : parts){
if (part==null || part.length()==0) continue;
part=compactSquares(part);
part=part.replaceAll("\\[(\\d)\\]","$1");
if (part.indexOf("[0-9]")>=0){
if (transform09ToD) part=part.replace("[0-9]","\\d");
}
//[0-3][0-9]|4[0-9]=>[0-34][0-9]
//[023][0-9]|4[0-9]=>[0234][0-9]
//[02345789]=>[02-57-9]
Matcher m=secondCompact.matcher(part);
if (m.find()){
part=m.group(1).replace("(","").replace(")","")+"["+m.group(2).replaceAll("[\\[\\]]","")+m.group(3).replaceAll("[\\[\\]]","")+"][0-9]";
}
part=part.replaceAll("\\[(\\d)-\\1\\]","$1");
if (unique.add(part)) result.add(part);
}
return result;
}
static String compactSquares(String src){
boolean inSquares=false;
if (src.startsWith("[") && src.endsWith("]")){
inSquares=true;
src=src.substring(1,src.length()-1);
}
StringBuffer sb=new StringBuffer();
if (!src.contains("-")) {
List<Integer> digits=new ArrayList<Integer>();
for (int i=0; i<src.length();i++){
digits.add(Integer.parseInt(""+src.charAt(i)));
}
Collections.sort(digits);
for (Integer s : digits){
sb.append(s);
}
src=sb.toString();
sb.setLength(0);
}
int firstChar = -2;
int lastChar = -2;
int currentChar;
for (int i=0; i<src.length(); i++) {
currentChar=src.charAt(i);
if (currentChar == lastChar + 1) {
lastChar = currentChar;
continue;
}
if (currentChar == '-' && i+1 < src.length()) {
lastChar = src.charAt(i + 1) - 1;
continue;
}
flush(sb, firstChar, lastChar);
firstChar = currentChar;
lastChar = currentChar;
}
flush(sb, firstChar, lastChar);
return (inSquares?"[":"")+sb.toString()+(inSquares?"]":"");
}
private static void flush(StringBuffer sb, int firstChar, int lastChar) {
if (lastChar<=0) return;
if (firstChar==lastChar) {
sb.append((char)firstChar);
return;
}
if (firstChar+1==lastChar){
sb.append((char)firstChar);
sb.append((char)lastChar);
return;
}
sb.append((char)firstChar);
sb.append('-');
sb.append((char)lastChar);
}
static String glueParts(List<String> parts) {
if (parts==null || parts.isEmpty()) return "";
if (parts.size()==1) return parts.get(0);
StringBuilder result=new StringBuilder(128);
for (String part : parts){
result.append(part);
result.append("|");
}
result.deleteCharAt(result.length()-1);
return result.toString();
}
private String[] toParts() {
List<String> result=new ArrayList<String>();
if (getNumberOfDigits(left)>2 || getNumberOfDigits(right)>2) {
result.add(startPart(left));
}
long leftPart=left;
long rightPart=right;
if (!String.valueOf(left).matches("10*")) leftPart=toPower(left);
if (!String.valueOf(right).matches("10*")) rightPart=toPower(right)/10;
if (rightPart/leftPart>=10) {
result.add(speedUpPart(left, right));
}
//for 1-2 digit process
if (getNumberOfDigits(left)==1 && getNumberOfDigits(right)==1){
result.add("["+left+"-"+right+"]");
}
else if (getNumberOfDigits(left)==1 && getNumberOfDigits(right)==2){
if (0==Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (1==Integer.parseInt(getMajorDigit(right))) {
result.add("["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (2<=Integer.parseInt(getMajorDigit(right))) {
result.add("["+
getMajorDigit(left)+
"-9]");
result.add("[1-"+
(Integer.parseInt(getMajorDigit(right))-1)+
"][0-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else throw new IllegalStateException();
}
else if (getNumberOfDigits(left)==2 && getNumberOfDigits(right)==2){
if (Integer.parseInt(getMajorDigit(left))==Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (Integer.parseInt(getMajorDigit(left))+1==Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (Integer.parseInt(getMajorDigit(left))+2<=Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-9]");
result.add("["+(Integer.parseInt(getMajorDigit(left))+1)+
"-"+(Integer.parseInt(getMajorDigit(right))-1)+
"][0-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else throw new IllegalStateException();
}
else result.add(staticPart(right));
result.add(breakPart(right));
return result.toArray(new String[0]);
}
static String breakPart(final Long number) {
if (getNumberOfDigits(number)<=2) {
return "";
}
StringBuilder result=new StringBuilder(256);
StringBuilder staticSection=new StringBuilder(32);
staticSection.append(getMajorDigit(number));
for (int i=1; i<getNumberOfDigits(number)-1; i++){
if (i!=1) result.append("|");
result.append(staticSection.toString());
staticSection.append(String.valueOf(number).charAt(i));
final long nextDigit=Long.parseLong(""+String.valueOf(number).charAt(i))-1;
if (nextDigit<0) {
result.setLength(0);
result.append("|");
continue;
}
if (nextDigit==0) result.append("0");
else if (nextDigit==1) result.append("[01]");
else result.append("[0-"+(nextDigit)+"]");
final int numberOfRepeats=(getNumberOfDigits(number)-i-1);
if (numberOfRepeats==1) result.append("[0-9]");
else result.append("[0-9]{"+numberOfRepeats+"}");
}
//остаток - 2 последние цифры числа
if (result.length()>0) {
result.append("|");
result.append(staticSection.toString());
//последнюю цифру от 0 до нее
result.append("[0-"+Long.parseLong(number.toString().replaceFirst("\\d+(\\d)","$1"))+"]");
}
if (result.length()>0) return result.toString().replace("||","|").replaceAll("^\\|","");
return "";
}
static String staticPart(final Long number) {
final long majorDigitMinus1=(Long.parseLong(getMajorDigit(number))-1);
if (majorDigitMinus1<=0) return "";
if (majorDigitMinus1==2) return "[1"+majorDigitMinus1+"][0-9]{"+(getNumberOfDigits(number)-1)+"}";
else if (majorDigitMinus1==1) return "1[0-9]{"+(getNumberOfDigits(number)-1)+"}";
return "[1-"+majorDigitMinus1+"][0-9]{"+(getNumberOfDigits(number)-1)+"}";
}
/**
* [1-9][0-9]{<X-1>,<Y-1>}, where X-number of digits of less number, Y-number of digits of greater number
*/
static String speedUpPart(Long left, Long right) {
//найти ближайшее до 0 то есть для 23 найти 100 для 777 найти 1000
//округленные до ближайшего 0
if (!String.valueOf(left).matches("10*")) left=toPower(left);
if (!String.valueOf(right).matches("10*")) right=toPower(right)/10;
final int leftPartRepeat=getNumberOfDigits(left)+(String.valueOf(left).matches("10*")?0:1)-1;
final int rightPartRepeat=getNumberOfDigits(right)+(String.valueOf(right).matches("10*")?0:1)-2;
if (getNumberOfDigits(left)==1 && getNumberOfDigits(right)==2)
return "[1-9]";
else if (leftPartRepeat>=rightPartRepeat)
return "[1-9][0-9]{"+rightPartRepeat+"}";
else
return "[1-9][0-9]{"+leftPartRepeat+","+rightPartRepeat+"}";
}
private static long toPower(final Long number) {
final double dValue=Math.pow(10, getNumberOfDigits(number));
final String value=String.format(Locale.US,"%24.0f",dValue);
return Long.parseLong(value.replaceFirst("\\s*(\\d+)(\\D\\d+)?","$1"));
}
private static int getNumberOfDigits(long number){
return (String.valueOf(number).length());
}
private static String getMajorDigit(long number){
return (String.valueOf(number).substring(0,1));
}
private static long getNumberWithoutMajorDigit(long number){
return Long.parseLong(String.valueOf(number).replaceFirst("\\d(\\d+)","$1"));
}
/**
* f(<n>>2)=<major digit>(f(<n-1>)|[<major digit+1>-9][0-9]{<n-1>})
*/
static String startPart(long number) {
int i=getNumberOfDigits(number);
if (i==1) {
if (number==9) return "9";
else if (number==8) return "[89]";
return "["+number+"-9]";
}
final long majorPlusOne=Long.parseLong(getMajorDigit(number))+1;
final int numberOfDigitsMinusOne=getNumberOfDigits(number)-1;
String result = (majorPlusOne < 10 ? "(" : "");
result+=getMajorDigit(number);
result+=startPart(getNumberWithoutMajorDigit(number));
result+=result.indexOf("|")<0 && majorPlusOne<10 && majorPlusOne!=numberOfDigitsMinusOne && numberOfDigitsMinusOne>1?"{"+numberOfDigitsMinusOne+"}":"";
result+=(majorPlusOne < 10
? "|[" + majorPlusOne + "-9][0-9]"+(numberOfDigitsMinusOne > 1 ? "{" + numberOfDigitsMinusOne + "}" : "")
: "");
result+=(majorPlusOne < 10 ? ")" : "");
return result;
}
private void parseAndCheck() {
Matcher matcher=pattern.matcher(src);
matcher.find();
try{
left=Long.parseLong(matcher.group(1));
right=Long.parseLong(matcher.group(2));
}
catch(Exception ex){
left=right+1;
}
if (left>right){
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"Left part must be less than right one."));
}
}
public String getPattern() {
return result;
}
public static void main(String[] args) {
System.err.println(new NumberDiapasone2RegExp(args[0]).getPattern());
}
}

I was also trying to find a range of valid range for minutes
[0-60] worked for me.
I am using jdk 1.8 though

Related

Check whether a given String is palindrome or not without using any library without loop

I was asked in an interview to write code to check if a given string is a palindrome or can be a palindrome by altering some character without using a library function. Here is my Approach
import java.util.Scanner;
public class Palindrom {
static int temp=0;
static char[] cArr;
static boolean chackPotentialPalindrom(char[] cAr){
cArr=cAr;
if(cArr!=null){
char current=cArr[0];
for(int i=1;i<cArr.length;i++){
if(current==cArr[i]){
cArr=removeElement(i);
chackPotentialPalindrom(cArr);
break;
}
}
if(cAr.length==2){
if(cAr[0]==cAr[1]){
cArr=null;
}}
if(temp==0 && cArr!=null){
temp=1;
cArr=removeFirstElement(cArr);
chackPotentialPalindrom(cArr);
}
}
if(cArr==null){
return true;
}else{
return false;
}
}
static char[] removeFirstElement(char[] cAr){
cArr=cAr;
if(cArr!=null){
if(cArr.length >1){
char[] cArrnew=new char[cArr.length-1];
for(int j=1,k=0;j<cArr.length;j++,k++){
cArrnew[k]=cArr[j];
}
return cArrnew;
} else {
return null;
}
} else {
return null;
}
}
static char[] removeElement(int i){
if(cArr.length>2){
char[] cArrnew=new char[cArr.length-2];
for(int j=1,k=0;j<cArr.length;j++,k++){
if(i!=j){
cArrnew[k]=cArr[j];
}else{
k-=1;
}
}
return cArrnew;}
else{
return null;
}
}
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
while(true){
temp=0;
String s=scn.next();
char[] arr=s.toCharArray();
System.out.println(chackPotentialPalindrom(arr));
}
}
}
Any tips to optimize this code?I could not write this in an interview as they have given a pen and paper to code.It took 3 hrs for me to write this. Can I be a developer?
Title says "without loop" but you need to check all symbol pairs, so using recursion, as you have tried, looks reasonable. But you don't check and use results of recursive calls.
Pseudocode might look like (note we don't need to change source data or extract substring):
Edit to provide possibility to alter one char
boolean checkPotentialPalindrom(char[] cAr, start, end, altcnt){
if (end <= start)
return true
if (cAr[start] != cAr[end])
altcnt = altcnt + 1
if (altcnt > 1)
return false
return checkPotentialPalindrom(cAr, start + 1, end - 1, altcnt)
}
and make the first call with arguments 0, len(cAr-1), 0
Answering to your first question..You have to use recursion to solve this problem. Here is my approach.
public boolean isPalindrom(char[] str, int start, int end) {
if (end <= start)
return true;
if (str[start] != str[end] || arraySize(str) <= 1)
return false;
return isPalindrom(str, start + 1, end - 1);
}
public int arraySize(char[] str) {
int count = 0;
for (char i : str) {
count++;
}
return count;
}
You have tried to implement this algorithm using loops and you can simplify it like this
public boolean isPalindroms(char[] str) {
int diffCount = 0;
int left = 0;
int right = arraySize(str) - 1;
while (right > left) {
if (str[right--] != str[left++]) {
diffCount++;
}
}
return (diffCount < 2);
}
public int arraySize(char[] str) {
int count = 0;
for (char i : str) {
count++;
}
return count;
}
The answer for the second question that you have ask is definitely you can be a good developer. Computer programming is a Craft. Not Some Kind of Rocket Science. You have to master it by crafting it.
using recursive function
calling with left=0 and right = arr.length-1
public static boolean isPalindrom(char[] arr, int left, int right){
if(arr[left++] != arr[right--])
return false;
if(left < right)
isPalindromss(arr, left++, right--);
return true;
}
if you have to use while loop, you can simplify it like following
public boolean isPalindrom(char[] arr){
int left=0;
int right = arr.length-1;
while(left < right){
if(arr[left++] == arr[right--])
continue;
return false;
}
return true;
}
Using StringBuilder, We can do it
public static boolean isPalindrom(String str, int len){
StringBuilder sb= new StringBuilder(str);
if((len > 1) & !(sb.substring(0,len/2 + 1).equals(sb.reverse().substring(0,len/2 + 1))))
return false;
return true;
}
function palin(input, leftIdx = 0, rightIdx = input.length - 1) {
if (leftIdx >= rightIdx) return true;
if (input[leftIdx] != input[rightIdx]) return false;
return palin(input, leftIdx + 1, rightIdx - 1);
}
const testCases = {
air: false,
airia: true,
caria: false,
a: true,
bb: true,
bcdb: false,
zzaaaaz: false,
};
Object.keys(testCases).forEach(test =>
console.log("Test: ", test, " is palindrome: ", palin(test), testCases[test])
);

Converting multiple strings into one

I'm trying to convert multiple strings into one simple dialogue from a NPC. Basically what I'm trying to do is make a list of all the skills a player has 200M experience in and output it into a NPC dialogue.
OLD
if (componentId == OPTION_4) {
sendNPCDialogue(npcId, 9827, "You can prestige: "+maxedSkills()+"");
}
private String maxedSkills() {
return ""+attackMax()+""+strengthMax()+""+defenceMax()+"";
}
public String attackMax() {
if (player.getSkills().getXp(Skills.ATTACK) == 200000000)
return "Attack, ";
else
return "";
}
public String strengthMax() {
if (player.getSkills().getXp(Skills.STRENGTH) == 200000000)
return "Strength, ";
else
return "";
}
public String defenceMax() {
if (player.getSkills().getXp(Skills.DEFENCE) == 200000000)
return "Defence, ";
else
return "";
}
With that code I have it working, but that is a lot of code to add due to there being 25 different skills. How would I create a way to make all of the skills be referenced into one? Here are all of the skill names:
public static final String[] SKILL_NAME = { "Attack", "Defence", "Strength", "Constitution", "Ranged", "Prayer",
"Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining",
"Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "Construction",
"Summoning", "Dungeoneering" };
New and working (for attack/strength/defence):
public static final int[] SKILL_TYPE = {Skills.ATTACK, Skills.STRENGTH, Skills.DEFENCE};
public String maxedSkills() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < SKILL_TYPE.length; i++) {
if (player.getSkills().getXp(i) == 200000000) {
if(sb.length()>0) sb.append(", ");
sb.append(Skills.SKILL_NAME[i]);
}
}
if(sb.length()>0) sb.append(".");
return sb.toString();
}
Simplest way would be to have a parameteried method that takes the Skill type as input. Here is how it would look like:
public String skillMax(Skills skill) {
if (player.getSkills().getXp(skill) == 200000000)
return skill.getName() + ", ";
else
return "";
}
The next thing to do is to provide a name to the skill in Skills enum. Something like this should work:
public enum Skills {
DEFENSE("Defense"), ...;
private String name;
Skills(String name) { this.name = name; }
String getName() { return this.name; }
}
Use a StringBuffer (thread safe) or a StringBuilder and do something like this.
....
public static final Skills[] SKILL_TYPE = {Skills.Attack, Skills.Defence, ...};
public String getBigString() {
StringBuffer sb = new StringBuffer();
int nSkills = 0, lSkill = 0;
for( int i = 0; i < SKILL_TYPE.length; i++ )
{
if( player.getSkills().getXp(SKILL_TYPE[i]) == K_SOMELEVEL ) {
if(nSkills > 0) sb.append(", ");
lSkill = sb.length(); // track position of last skill in string
nSkills += 1;
sb.append(SKILL_NAME[i]);
}
}
if( nSkills > 0 )
{
if( nSkills > 1 ) sb.insert( lSkill, "and ");
sb.append(".");
}
return sb.toString();
}

NZEC error for ACODE spoj

I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.

getting a multi decimal number from a string [duplicate]

This question already has answers here:
Comparing version number strings (major, minor, revision, beta)
(3 answers)
Closed 7 years ago.
For one of my projects i would like to get a version from a string which has multiple decimals, is it possible to convert it into a multi decimal point double or is it not possible. I would like to use this to see if it is more than the previous one, which would also have multiple decimals.
What I am using at the moment is
if (!vers.equalsIgnoreCase(plugin.getDescription().getVersion())) { // Do stuff
But I would like to make it so I can do
if (vers > plugin.getDescription().getVersion()) { // do stuff
vers is equal to 1.0.1, and the plugin.getDescription().getVersion() is equal to 1.0.2
thanks!
You could implement this way, if you assume all the portions are numbers.
public static int compareVersions(String vers1, String vers2) {
String[] v1 = vers1.split("\\.");
String[] v2 = vers2.split("\\.");
for (int i = 0; i < v1.length && i < v2.length; i++) {
int i1 = Integer.parseInt(v1[i]);
int i2 = Integer.parseInt(v2[i]);
int cmp = Integer.compare(i1, i2);
if (cmp != 0)
return cmp;
}
return Integer.compare(v1.length, v2.length);
}
and
System.out.println(compareVersions("1.0.1", "1.0.2"));
System.out.println(compareVersions("1.0.1", "1.0"));
System.out.println(compareVersions("1.0.2", "1.0.10"));
prints
-1
1
-1
A more complex version supports letters inside versions
public static int compareVersions(String vers1, String vers2) {
String[] v1 = vers1.split("\\.");
String[] v2 = vers2.split("\\.");
for (int i = 0; i < v1.length && i < v2.length; i++) {
String [] w1 = v1[i].split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
String [] w2 = v2[i].split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for(int j=0;j<w1.length&&j<w2.length;j++) {
try {
int i1 = Integer.parseInt(w1[j]);
int i2 = 0;
try {
i2 = Integer.parseInt(w2[j]);
} catch (NumberFormatException e) {
return -1;
}
int cmp = Integer.compare(i1, i2);
if (cmp != 0)
return cmp;
} catch (NumberFormatException e) {
try {
Integer.parseInt(w2[j]);
return +1;
} catch (NumberFormatException e1) {
int cmp = w1[j].compareTo(w2[j]);
if (cmp != 0)
return cmp;
}
}
}
int cmp = Integer.compare(w1.length, w2.length);
if (cmp != 0)
return cmp;
}
return Integer.compare(v1.length, v2.length);
}
and
System.out.println(compareVersions("1.0.2", "1.0.2a"));
System.out.println(compareVersions("1.0.2b", "1.0.2a"));
System.out.println(compareVersions("1.8.0_66", "1.8.0_65"));
System.out.println(compareVersions("1.7.0_79", "1.8.0_65"));
prints
-1
1
1
-1
It seems that you would like to compare versions. Or to take decisions based on some string represented version. If the plugin.getDescription().getVersion() is a String, then you should be able to use a simple String comparison to establish the order between versions. Something like this should work:
String pluginVersion=plugin.getDescription().getVersion();
if (ensureValidVersion(pluginVersion)
&& compareVersions(vers,pluginVersion)>0) {
// do staff is vers is greater then plugin version
}
ensureValidVersion method will validate if you have a valid version number representation. And compareVersions will do a comparison for each version subcomponent.
Assuming you have a version number of the following form: x.y.z
You can use a similiar approach as suggested by Viacheslav Vedenin:
String versionNumber = "1.3.45";
String[] singleParts = versionNumbers.split(".");
int[] versionParts = new int[singleParts.length];
for(int i=0; i<singleParts.length; i++) {
versionParts[i] = Integer.parseInt(singleParts[i]);
}
Now you have an array of the single parts of your version number. To compare it to a previous one you could do as follow:
public static boolean isGreater(int[] firstVersion, int[] secondVersion) {
if(secondVersion.length > firstVersion.length) {
return false;
}else {
if(firstVersion.length > secondVersion.length) {
return true;
}else {
for(int k=0; k< firstVersion.length; k++) {
int v1 = firstVersion[k];
int v2 = secondVersion[k];
if(v1 < v2) {
return true;
}
}
return false;
}
}
}
If you want to compare versions using the equality/inequality operators (==, <, >, <=, and >=), you have two options.
Use a language like C++ that supports operator overloading
Set a limit on the length for each string in major.minor.build and convert each version to an integer before comparing them. For example, if the limit on each of them is 3 (i.e. the longest version you can have is abc.def.ghi), then you can just use build + minor * 10^3 + major * 10^6.
Alternatively, you can just implement Comparable<Version> and have a nice OOP solution.
public class Example {
static class Version implements Comparable<Version> {
private int major;
private int minor;
private int build;
public Version(String s) {
final String[] split = s.split("\\.");
major = Integer.parseInt(split[0]);
minor = Integer.parseInt(split[1]);
build = Integer.parseInt(split[2]);
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getBuild() {
return build;
}
#Override
public int compareTo(Version v) {
if (getMajor() < v.getMajor()) {
return -1;
} else if (getMajor() > v.getMajor()) {
return 1;
} else {
if (getMinor() < v.getMinor()) {
return -1;
} else if (getMinor() > v.getMinor()) {
return 1;
} else {
if (getBuild() < v.getBuild()) {
return -1;
} else if (getBuild() > v.getBuild()) {
return 1;
} else {
return 0;
}
}
}
}
}
public static void main(String[] args) {
String s1 = "1.0.1";
String s2 = "1.0.2";
compare(s1, s2);
compare(s1, s1);
compare(s2, s2);
compare(s2, s1);
}
private static void compare(String s1, String s2) {
Version v1 = new Version(s1);
Version v2 = new Version(s2);
final int compareTo = v1.compareTo(v2);
if (compareTo == -1) {
System.out.println(s1 + " was released before " + s2);
} else if (compareTo == 0) {
System.out.println(s1 + " is the same as " + s2);
} else {
System.out.println(s1 + " was released after " + s2);
}
}
}
Output:
1.0.1 was released before 1.0.2
1.0.1 is the same as 1.0.1
1.0.2 is the same as 1.0.2
1.0.2 was released after 1.0.1
String[] numbers = version.split(".");
String[] numbers2 = version2.split(".");
int index = numbers.length-1;
while(numbers[index] != "."){
index--;
}
String lastnumber = version.substring(index+1, numbers.length];
index = numbers2.length-1;
while(numbers2[index] != "."){
index--;
}
String lastnumber2 = version.substring(index+1, numbers2.length];
if(lastnumber > lastnumber2){
//later version
}else{
//use the same thing to check the other numbers
}

Print to file from within a method

I am taking an input file with various infix expressions, calculating them, and printing them back to another output file with each line formatted as:
THE MODULO 10 VALUE OF %%%%% IS %
The output text and modulo 10 answer are both correct; however, I cannot get the program to reprint the entire expression in between "OF" and "IS."
I tried putting output.write(token) in the getToken() method, but I got a "cannot find symbol" error. So I understand that I can't access the BufferedWriter from another method since it is declared in main, but how can I get around that?
import java.io.*;
public class Lab1
{
public static char token;
public static String expr;
public static int k = 0;
public static void main (String[] args)
{
int exprValue;
String line;
try
{
BufferedReader input = new BufferedReader(new FileReader("inputfile.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("outputfile.txt"));
while ((line = input.readLine()) != null)
{
output.write("THE MODULO 10 VALUE OF ");
expr = line;
getToken();
output.write(token);
exprValue = expression();
output.write(" IS " + exprValue);
output.newLine();
output.newLine();
k = 0;
}
input.close();
output.close();
}
catch (IOException ex)
{
System.err.println("Exception:" + ex);
}
}
public static void getToken()
{
k++;
int count = k-1;
if(count < expr.length())
{
token = expr.charAt(count);
}
}
public static int expression()
{
int termValue;
int exprValue;
exprValue = term();
while(token == '+')
{
getToken();
termValue = term();
exprValue = (exprValue + termValue)%10;
}
return exprValue;
}
public static int factor()
{
int factorValue = token;
if(Character.isDigit(token))
{
factorValue = Character.getNumericValue(token);
getToken();
}
else if(token == '(')
{
getToken();
factorValue = expression();
if(token == ')')
{
getToken();
}
}
return factorValue;
}
public static int term()
{
int factorValue;
int termValue;
termValue = factor();
while(token == '*')
{
getToken();
factorValue = factor();
termValue = (termValue * factorValue)%10;
}
return termValue;
}
}
Currently my input is:
(3*6+4)*(4+5*7)
3*((4+5*(1+6)+2))
My output is:
THE MODULO 10 VALUE OF ( IS 8
THE MODULO 10 VALUE OF 3 IS 3
Solved the problem. In the while loop in the main method, replace output.write(token) with output.write(expr)

Categories