How do I compare 2 numbers which can have the values 202.10.200 and 202.101.30 in java. I understand the above 2 cannot be "numbers". We need to compare this keeping in mind 202.101.30 should be greater than 202.10.200.
Scanner keyboard = new Scanner(System.in);
String inputLine = keyboard.nextLine();
String[] inputArray = inputLine.split(".");
int[] numArray = null;
for(int i = 0; i < inputArray<length; i++)
{ numArray[i] = Integer.parseInt(inputArray[i]);
}
Then you just need to write another loop to compare another two input arrays with different numbers.
If you are sure that strings are syntattically identical and have the same number of elements separated by ".", you can split them into arrays, convert arrays elements into int and then compare them onw by one:
String s1 = "202.10.200";
String s2 = "202.101.30";
String sGreater = s1;
String[] strArr1 = s1.split("\\.");
String[] strArr2 = s2.split("\\.");
for (int i=0; i<strArr1.length; i++)
{
int x1 = Integer.parseInt(strArr1[i]);
int x2 = Integer.parseInt(strArr2[i]);
if (x2>x1)
{
sGreater = s2;
break;
}
}
This method can be used as an implementation of a Comparator:
public static int compareTo(String s1, String s2) {
String[] a1 = s1.split("\\.");
String[] a2 = s2.split("\\.");
for (int i = 0; i < 3; i++) {
if (!a1[i].equals(a2[i]))
return Integer.parseInt(a1[i]) - Integer.parseInt(a2[i]);
}
return 0;
}
This one works with any (but equal) number of integer groups separated by dots.
private static int compareDotNums(String str1, String str2) {
if (str1 != null && str2 != null) {
String[] split1 = str1.split("\\.");
String[] split2 = str2.split("\\.");
if (split1.length != split2.length)
throw new IllegalArgumentException("Input length mismatch.");
int result = 0;
for (int i = 0; i < split1.length; i++) {
try {
result = Integer.valueOf(split1[i]).
compareTo(Integer.valueOf(split2[i]));
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"Illegal input. Not a number.");
}
if (result != 0)
break;
}
return result;
} else
throw new IllegalArgumentException("Non-null input required.");
}
Sample Output:
System.out.println(compareDotNums("202.10.200", "202.201.30")); // -1
System.out.println(compareDotNums("202.210.200", "202.201.30")); // 0
System.out.println(compareDotNums("202.201.30", "202.201.30")); // 1
System.out.println(compareDotNums("202.201.30.110", "202.201.30.128")); // -1
System.out.println(compareDotNums("202.201.30.128", "202.201.30.128")); // 0
System.out.println(compareDotNums("202.201.30.210", "202.201.30.128")); // 1
Related
I'm doing a hackerrank medium challenge for a password cracker. I want to be able to check if a given string, attempt, contains all the words in pass. pass is an array of passwords and attempt is a concatenation of random entries in pass. If attempt contains ONLY words that are found as entries in pass, then it is deemed a good password and the words from the input of attempt, limited with spaces, is printed.
Sample Input
3 //3 attempts
6 //6 words for attempt 1
because can do must we what //pass[]
wedowhatwemustbecausewecan //attempt
2 //...
hello planet
helloworld
3
ab abcd cd
abcd
Expected Output
we do what we must because we can
WRONG PASSWORD //Because planet is not in pass[]
ab cd
Code
public class Solution {
static String passwordCracker(String[] pass, String attempt) {
int arrayLength=pass.length;
int accuracy=0;
String trips_array[] = new String[pass.length];
String [] newWord = new String[20];
for (int i=0; i<pass.length;i++)
{
// int j=0;
String[] arr = pass[i].split(" ");
//-------------------------------
if (attempt.contains(pass[i]))
{
accuracy++;
newWord[i] = pass[i];
trips_array[i] = attempt.split(" ");
}
//------------------------------
}
StringBuilder sb = new StringBuilder();
for (String words : trips_array) {
sb.append(words);
}
for (int i=0; i<pass.length;i++)
{
if (accuracy==pass.length)
return sb.toString() + " ";
else
return "WRONG PASSWORD";
}
return "test";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
String[] pass = new String[n];
for(int pass_i = 0; pass_i < n; pass_i++){
pass[pass_i] = in.next();
}
String attempt = in.next();
String result = passwordCracker(pass, attempt);
System.out.println(result);
}
in.close();
}
}
The part in focus is the part in the //----------------- comment section. Basically, my goal is to see if the attempt contains the correct entries in pass, and if so, save that substring of the attempt (or similarly, the entry in pass) to a new array which can be printed in the correct order. If you check the expected output above, you'll see that the output is the same as attempt except with spaces.
Essentially, I would need to find the breaks in the words of attempt and print that if it fulfills the above requirements (first paragraph).
See this for more details
https://www.hackerrank.com/challenges/password-cracker/problem
If it helps you
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int testNumb = Integer.parseInt(reader.readLine());
List<String> passList = new ArrayList<>();
List<String> attList = new ArrayList<>();
for (int i = 0; i < testNumb; i++) {
reader.readLine();
passList.add(reader.readLine());
attList.add(reader.readLine());
}
reader.close();
for (int i = 0; i < testNumb; i++) {
String s1 = passList.get(i);
String s2 = attList.get(i);
StringBuilder sb = new StringBuilder();
String[] s1Arr = s1.split(" ");
while (s2.length() > 0) {
int s2Lenght = s2.length();
for (String s : s1Arr) {
if (s2.startsWith(s)) {
sb.append(s + " ");
s2 = s2.substring(s.length());
}
}
if (s2.length() == s2Lenght) {
sb = new StringBuilder("wrong pass");
break;
}
}
System.out.println(sb.toString());
}
Your for loop looks too complicated, here is how I would approach that part.
boolean isAllWords = true;
int checksum = 0;
for (int j = 0; j < pass.length; j++) {
if (!attempt.contains(pass[j]) {
isAllWords = true;
break;
}
checksum += pass[j].length;
}
if (isAllWords && checksum == attempt.length) {
//This means attempt contains all words in pass array and nothing more
//... handle successful attempt
} else {
//... handle bad attempt
}
It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn
So, I want to compare from string to array of strings
String [] string = new String [10];
string [1] = "pencil";
string [2] = "pen";
string [3] = "eraser";
how do i compare string to the array of strings from above?
A quicker way is to use this code
if(Arrays.asList(string).contains(search_string))
If I understand you correctly, Write a loop, where iterate multiple string(example array) and equals with src string.
String [] string = new String [10];
...
String src = ..;//src string
for(String string : string){
if(src.equals(string)){
//Equal
}
}
Try using this:
for (int i = 0; i < string.length; i++) {
if (ch.equals(string[i])) { // ch is the string to compare
System.out.println("equal");//or whatever your action is
}
}
EDIT:
If what you are seeking to do is to verify if the searched string appears in the string[i] you can try:
string[0] = "pentagon";
string[1] = "pencil";
string[2] = "pen";
string[3] = "eraser";
string[4] = "penny";
string[5] = "pen";
string[6] = "penguin";
string[7] = "charp";
string[8] = "charpen";
string[9] = "";
String ch = "pen";
Then test if the arrays elements contain the searched string:
for (int i = 0; i < string.length; i++) {
if (string[i].indexOf(ch) != -1) {
System.out.println(string[i]+" contains "+ch);
} else
System.out.println(string[i]+" doesn't contain "+ch);
}
EDIT 2:
int i=0;
Boolean found=false;
while(i < string.length && !found) {
if (string[i].indexOf(ch) != -1) {
found=true;
}
i++;
}
if(found){
system.out.println(ch+" is found");
}
I am working on a simple Java program where we have sorted string array named arr
I am trying to compare two adjacent string and calculate frequency for each string present in that array
for(j1=0;j1<arr.length;j1++){
if(j1+1 < arr.length){ // To prevent arrayOutofBoundsException
if(arr[j1].equals(arr[j1+1])){
counter++;
}
else {
System.out.println(arr[j1]+" "+counter);
counter=1;
}
But it's not working right , what's wrong ?
edit:problem is not in comparing , it's not calculating frequency as desired
OK, besides the equals fix, you want to keep the original order of words:
String orig = "hellow hello hello how how he ho" ;
//String orig = "how are you how do you do";
String[] arr = orig.split(" ");
//Arrays.sort(arr);
for(int j1 = 0; j1 < arr.length; j1++){
if (arr[j1] != null) {
int counter = 1;
for(int j2 = j1+1; j2 < arr.length; j2++) {
if(arr[j2] != null && arr[j1].equals(arr[j2])){
counter++;
arr[j2] = null;
}
}
System.out.println(arr[j1]+" "+counter);
}
}
The trick is that I run through the array, count all occurrences, null the occurrences, so they don't count again, and print the count. No need to sort the array.
== compares object identity in terms of memory address - to compare objects in terms of equality, use the equals-method.
This should work:
public static void main(String[] args)
{
String text = "how are you how do you do";
String[] keys = {"how", "are", "you", "how", "do", "you", "do"};
Arrays.sort(keys);
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("Count of ["+key+"] is : "+count);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
Output:
how are you how do you do
Count of [how] is : 2
Count of [are] is : 1
Count of [you] is : 2
Count of [do] is : 2
Are you looking some sort of this
public static void main(String[] args){
String[] arr = new String[5];
arr[0] = "One";
arr[1] = "Two";
arr[2] = "One";
arr[3] = "Three";
arr[4] = "Two";
List<String> lstString = Arrays.asList(arr);
Collections.sort(lstString);
for(String eachString : arr){
System.out.println("Frequency of " + eachString + " is " + getFrequency(eachString,lstString));
}
}
private static int getFrequency(String word, List lstOfString){
int frequency = 1;
if(lstOfString != null && lstOfString.size() > 0){
int firstIndex = lstOfString.indexOf(word);
int lastIndex = lstOfString.lastIndexOf(word);
frequency += lastIndex - firstIndex;
}
return frequency;
}
Result :
Frequency of One is 2
Frequency of One is 2
Frequency of Three is 1
Frequency of Two is 2
Frequency of Two is 2
I tried to search online to solve this question but I didn't found anything.
I wrote the following abstract code to explain what I'm asking:
String text = "how are you?";
String[] textArray= text.splitByNumber(4); //this method is what I'm asking
textArray[0]; //it contains "how "
textArray[1]; //it contains "are "
textArray[2]; //it contains "you?"
The method splitByNumber splits the string "text" every 4 characters. How I can create this method??
Many Thanks
I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:
List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
strings.add(text.substring(index, Math.min(index + 4,text.length())));
index += 4;
}
Using Guava:
Iterable<String> result = Splitter.fixedLength(4).split("how are you?");
String[] parts = Iterables.toArray(result, String.class);
What about a regexp?
public static String[] splitByNumber(String str, int size) {
return (size<1 || str==null) ? null : str.split("(?<=\\G.{"+size+"})");
}
See Split string to equal length substrings in Java
Try this
String text = "how are you?";
String array[] = text.split(" ");
Or you can use it below
List<String> list= new ArrayList<String>();
int index = 0;
while (index<text.length()) {
list.add(text.substring(index, Math.min(index+4,text.length()));
index=index+4;
}
Quick Hack
private String[] splitByNumber(String s, int size) {
if(s == null || size <= 0)
return null;
int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
String[] arr = new String[chunks];
for(int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
arr[j] = s.substring(i, Math.min(l, i + size));
return arr;
}
Using simple java primitives and loops.
private static String[] splitByNumber(String text, int number) {
int inLength = text.length();
int arLength = inLength / number;
int left=inLength%number;
if(left>0){++arLength;}
String ar[] = new String[arLength];
String tempText=text;
for (int x = 0; x < arLength; ++x) {
if(tempText.length()>number){
ar[x]=tempText.substring(0, number);
tempText=tempText.substring(number);
}else{
ar[x]=tempText;
}
}
return ar;
}
Usage : String ar[]=splitByNumber("nalaka", 2);
I don't think there's an out-of-the-box solution, but I'd do something like this:
private String[] splitByNumber(String s, int chunkSize){
int chunkCount = (s.length() / chunkSize) + (s.length() % chunkSize == 0 ? 0 : 1);
String[] returnVal = new String[chunkCount];
for(int i=0;i<chunkCount;i++){
returnVal[i] = s.substring(i*chunkSize, Math.min((i+1)*chunkSize-1, s.length());
}
return returnVal;
}
Usage would be:
String[] textArray = splitByNumber(text, 4);
EDIT: the substring actually shouldn't surpass the string length.
This is the simplest solution i could think off.. try this
public static String[] splitString(String str) {
if(str == null) return null;
List<String> list = new ArrayList<String>();
for(int i=0;i < str.length();i=i+4){
int endindex = Math.min(i+4,str.length());
list.add(str.substring(i, endindex));
}
return list.toArray(new String[list.size()]);
}
Here's a succinct implementation using Java8 streams:
String text = "how are you?";
final AtomicInteger counter = new AtomicInteger(0);
Collection<String> strings = text.chars()
.mapToObj(i -> String.valueOf((char)i) )
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 4
,Collectors.joining()))
.values();
Output:
[how , are , you?]
Try this solution,
public static String[]chunkStringByLength(String inputString, int numOfChar) {
if (inputString == null || numOfChar <= 0)
return null;
else if (inputString.length() == numOfChar)
return new String[]{
inputString
};
int chunkLen = (int)Math.ceil(inputString.length() / numOfChar);
String[]chunks = new String[chunkLen + 1];
for (int i = 0; i <= chunkLen; i++) {
int endLen = numOfChar;
if (i == chunkLen) {
endLen = inputString.length() % numOfChar;
}
chunks[i] = new String(inputString.getBytes(), i * numOfChar, endLen);
}
return chunks;
}
My application uses text to speech!
Here is my algorithm, to split by "dot" and conconate string if string length less then limit
String[] text = sentence.split("\\.");
ArrayList<String> realText = sentenceSplitterWithCount(text);
Function sentenceSplitterWithCount: (I concanate string lf less than 100 chars lenght, It depends on you)
private ArrayList<String> sentenceSplitterWithCount(String[] splittedWithDot){
ArrayList<String> newArticleArray = new ArrayList<>();
String item = "";
for(String sentence : splittedWithDot){
item += DataManager.setFirstCharCapitalize(sentence)+".";
if(item.length() > 100){
newArticleArray.add(item);
item = "";
}
}
for (String a : newArticleArray){
Log.d("tts", a);
}
return newArticleArray;
}
function setFirstCharCapitalize just capitalize First letter: I think, you dont need it, anyway
public static String setFirstCharCapitalize(String input) {
if(input.length()>2) {
String k = checkStringStartWithSpace(input);
input = k.substring(0, 1).toUpperCase() + k.substring(1).toLowerCase();
}
return input;
}