If the input is a1bc2def3 output should be abcbcdefdef - arrays

If the given input is a1bc2def3 then output should be abcbcdefdefdef
Whenever the number comes then we should repeat previous substring that many number of times.
Please provide the algorithm or code to accomplish this.

Here's another approach that doesn't rely on regex.
public String splitRepeat(String str)
{
StringBuilder out = new StringBuilder();
boolean number = false;
for(int i=0,j=0,k=0; i<=str.length(); i++)
{
if(i==str.length() || Character.isDigit(str.charAt(i)) != number)
{
if(number)
{
for(int r = Integer.parseInt(str.substring(j, i)); r>0; r--)
{
out.append(str.substring(k, j));
}
}
else
{
k=j;
}
j=i;
number = !number;
}
}
return out.toString();
}

My suggestion would be:
Try using regex so you can get an array of numbers and characters,
then convert the number Parsable elements of the array into an integer,
after that loop with the index of the arrays to append n-times the characters of the array
then print the final result
Example:
public static void main(String[] args) {
String stringToProcess = "a1bc2def3";
String[] regexSplitted = stringToProcess.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
String appender = "";
for (int i = 0; i < regexSplitted.length; i++) {
try {
int kilo = Integer.parseInt(regexSplitted[i]);
for (int j = 0; j < kilo; j++) {
sb.append(appender).append(regexSplitted[i - 1]);
appender = "-";
}
} catch (NumberFormatException e) {
}
}
System.out.println(sb.toString());
}
this will print
a-bc-bc-def-def-def
that is pretty much what you are looking for.

Related

SplitTokens issue in Processing

Here is a short code below to count words and more, but I face a strange problem:
when I run it some words of the original string don’t appear on the screen!? How come?
Did I forgot something using splitTokens ?! Thanks a lot for your help in advance.
All the best,
L
IntDict counts;
String[] tokens;
void setup() {
size(1000, 1000);
background(0);
counts = new IntDict();
String[] lines = {
"If only you were paying a bit attention to me sometimes.",
"I am not just a care giver I also need soemone to hug me tenderly."
};
String alltext = join(lines, " ");
tokens = splitTokens(alltext, "\n\";.?!'():\n ");
for (int i = 0; i < tokens.length; i++) {
String word = tokens[i].toLowerCase();
if (counts.hasKey(word)) {
counts.increment(word);
} else {
counts.set(word, 1);
}
println(word);
}
String[] keys = counts.keyArray();
for (int i = 0; i < keys.length; i++) {
textSize(20);
float x = 50;
float y = 50 + 15 * i;
text(keys[i], x, y);
}
}
void draw() {}
What you're rendering on the screen is not the split tokens, it's only the unique words(counts' keys).
If you call printArray(tokens); you'll see in console that each word appears, including duplicates:
IntDict counts;
String [] tokens;
void setup() {
size(1000, 1000);
background(0);
counts = new IntDict();
String [] lines = {"If only you were paying a bit attention to me sometimes.",
"I am not just a care giver I also need soemone to hug me tenderly."};
String alltext = join(lines, " ");
tokens = splitTokens(alltext, "\n\";.?!'():\n ");
println("with duplicates");
printArray(tokens);
for (int i =0; i<tokens.length; i++) {
String word = tokens[i].toLowerCase();
if (counts.hasKey(word)) {
counts.increment(word);
println("\tfound duplicate", word);
} else {
counts.set(word, 1);
}
//println(word);
}
String []keys = counts.keyArray();
println("without duplicates");
printArray(keys);
for (int i=0; i<keys.length; i++) {
textSize(20);
float x = 50;
float y= 50+15*i;
text(keys[i], x, y);
}
}
void draw() {
}
If you want to render all the words simply iterate (and access) tokens instead of keys in the second for loop where you call text()

Permutation of a string so that the patterns match

The question is to count how many permutations of a string B have an equivalent pattern into a bigger string A. For example, if A="aabbccd" and B="xx", then it should print 3, since "aa", "bb", "cc" are all substrings of A which share the same pattern as B.
I have tried to pass the substrings as numbers, such as xx becomes "11" and do the same for string A, but I still can't get it to work. Any ideas? Length can be up to 10^7.
Here's the code for changing pattern:
void transform(int* dest, char* original, int len) {
int j=1;
Al[original[0]-'a']=j;
dest[0]=j;
j++;
for (int i=1;i<len;i++) {
if (Al[original[i]-'a']==0)
Al[original[i]-'a']=j++;
dest[i]=Al[original[i]-'a'];
}
}
Concept: Use Regular Expressions
You would need the following regular expression (\\w)\\1{(REPETITIONS-1)}
I don't know about C but Java provides a library to compile RegEx patterns. Here's a class that implements just what you want:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPatternPermutation {
public static void main(String[] args) {
int REPETITIONS = 3;
String REGEX = "(\\w)\\1{" + (REPETITIONS-1) + "}";
String INPUT = "abbbbbbccddeffff";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
int count = 0;
while(m.find()){
String match = m.group();
System.out.println(match);
count++;
}
System.out.println(count);
}
}
Here's a test of the code above: https://ideone.com/5nztaa
Here's a useful website to test any RegEx: https://regexr.com/
Without Regular Expressions
public class StringPatternPermutation {
public static void main(String[] args) {
String a = "abjjjiixsssppw";
String b = "qwwwee";
String patternA = detectPattern(a);
String patternB = detectPattern(b);
System.out.println("-String A: " + a);
System.out.println("-Pattern A: " + patternA);
System.out.println("-String B: " + b);
System.out.println("-Pattern B: " + patternB);
System.out.println("-A contains B? " + patternA.contains(patternB));
int count = 0;
int index = 0;
while((index = patternA.indexOf(patternB)) != -1){
count++;
patternA = patternA.substring(index+1, patternA.length());
}
System.out.println("-Number of occurances: " + count);
}
private static String detectPattern(String a){
StringBuilder sb = new StringBuilder();
char prev = a.charAt(0);
int count = 1;
for(int i = 1; i < a.length(); i++){
char curr = a.charAt(i);
if(curr == prev)
count++;
else {
sb.append(count + ", ");
prev = curr;
count = 1;
}
if(i == a.length() - 1){
sb.append(count);
}
}
return sb.toString();
}
}
Test it on ideOne: https://ideone.com/w422Du

Storing each digit from double to an array

I am a newbie at this and I am not sure on how to go about to store the digits of a double to an array. I have this double value: 0120.1098
I want it to be stored as something like this:
value[1] = 0
value[2] = 1
value[3] = 2
value[4] = 0
value[5] = 1
`
and so on...
How do I do it?
I'm not sure if you really need to extract them, but as I don't know much more about your context, here you go.
You could turn it into a String, split it on . and iterate. This way you get two int arrays. One for the digits before the decimal and on for the digits after de decimal.
public static void main(String[] args) {
double d = 12323.213432;
String asString = String.valueOf(d);
String[] splitOnDecimal = asString.split("\\.");
int[] upperBound = getIntArray(splitOnDecimal[0]);
int[] lowerBound = getIntArray(splitOnDecimal[1]);
System.out.println(Arrays.toString(upperBound));
System.out.println(Arrays.toString(lowerBound));
}
private static int[] getIntArray(String numberString) {
int[] tmpArray = new int[numberString.length()];
for (int i = 0; i < numberString.length(); i++) {
tmpArray[i] = Integer.parseInt(numberString.substring(i, i + 1));
}
return tmpArray;
}
Try this, it will even show your zeroes:
String dbl = "0012300.00109800";
int dblArraylength = dbl.length();
char[] c = dbl.toCharArray();
int dotId= dbl.indexOf(".");
int a[] = new int[dblArraylength-1];
for(int i=0; i<dotId; i++){
a[i]=Integer.parseInt(Character.toString ((char)c[i]));
}
for(int i=dotId; i<a.length; i++){
a[i]=Integer.parseInt(Character.toString ((char)c[i+1]));
}
for(int i=0; i<a.length; i++){
System.out.println("a[" +i+ "] = " + a[i]);
}

sorting strings in an array alphabetically

I came up with this code to try and sort out an array of strings (I don't want to use ints or imports as I'm trying to understand iteration loops), but it only rearranges the first two strings. Can anyone point out my mistakes?
public class Alpha8 {
public static void main(String[] args) {
String[] Names = {"O","B","K","S","D","M","N","A"};
String temp = null;
for(int i=0;i<Names.length;i++){
for(int j = i+1;j<Names.length;j++) {
if(Names[j].compareTo(Names[i])<0)
temp = Names[i];
Names[i] = Names[j];
Names[j] = temp;
for( i = 0;i<Names.length;i++){
System.out.println(Names[i]);
}
}
}
}
}
You have made two mistakes:
You are printing the array inside your 'swap' code. You should only print the array once the sorting is complete.
You only iterate through the array once. For a bubble sort (which is what you are implementing) you need to keep iterating through until no swaps occur.
The method should look something like:
boolean hasSwapped;
do {
hasSwapped = false;
for (int i = 1; i < names.size(); i++) {
if (names[i-1].compareTo(names[i]) > 0) {
swap(names[i-1], names[i]);
hasSwapped = true;
}
}
} while (hasSwapped);

compare two int array in j2me?

In my app I have 2 images with same dimensions,that I would to give their RGB data and compare them.In j2me we can not use java.util.Arrays and so Arrays.equals(array1, array2) method. One way to compare them is using for loop and compare each element of two int array,but i'm looking for better way.When I search in web I found ArrayUtils class,here,that has some equals() methods,but it's method compare two arrays of objects and before compare int arrays convert them to Enumeration by arrayToEnumeration(Object array) that creates an enumeration from given object.
Finally this is my question:
Is there a better way to compare two int arrays in j2me?
Try something like this.. From the Util class
public static boolean equals(byte[] a, byte[] a2) {
if (a==a2)
return true;
if (a==null || a2==null)
return false;
int length = a.length;
if (a2.length != length)
return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i])
return false;
return true;
}
private int compareArray(String[] _array1, String[] _array2){
Vector m_length1 = new Vector();
Vector m_length2 = new Vector();
if(_array1 && _array2!=null)
{
for(int i=0; i<_array1.length; i++){
if(m_length1[i]!=null){
m_length1.add(_array1[i]);
}
}
for(int j=0; j<_array2.length; j++){
if(m_length2[j]!=null){
m_length2.add(_array2[j]);
}
}
}
if(m_length1.size()==m_length2.size()){
return 0; /*matching*/
}else{
return -1; /*no matching*/
}
}
You can modify it as int array or you can compare byte of each value.
For instance;
byte sample[] = {0,0,0,0};
sample= yourValue.getBytes();
Convert byte array to String:
public boolean equals(byte[] b1, byte[] b2){
String strB1 = new String(b1);
String strB2 = new String(b2);
if(strB1.equals(strB2)){
return true;
}
else{
return false;
}
}

Resources