Reputation: 1731
I am trying to develop an algorithm which takes in an input string S
and generate Strings by eliminating two characters at a time. Here's my code so far.
String[] strings = {"a", "b", "c", "d", "e", "f"};
int charsToBeRemoved = strings.length - 2;
for( int i = 0; i < strings.length; i++ )
{
int counter = 1;
StringJoiner p = new StringJoiner( "|" );
p.add( strings[i] );
for( int j = i + 1; j < strings.length; j++ )
{
p.add( strings[j] );
counter += 1;
if( counter == charsToBeRemoved )
{
counter = 1;
j = ( charsToBeRemoved - 2 ) > 0 ? j - ( charsToBeRemoved - 2 ) : j;
regexList.add( p.toString() );
p = new StringJoiner( "|" );
p.add( strings[i] );
}
}
}
This provides the output : [a|b|c|d, a|c|d|e, a|d|e|f, b|c|d|e, b|d|e|f, c|d|e|f]
. However, what I am trying to get is a rotating array based solution. Something like [a|b|c|d, a|c|d|e, a|d|e|f, b|c|d|e, b|d|e|f, b|e|f|a, c|d|e|f, c|e|f|a, c|f|a|b], d|e|f|a, d|f|a|b, d|a|b|c
. In my current code, these outputs b|e|f|a, c|e|f|a, c|f|a|b, d|e|f|a, d|f|a|b, d|a|b|c
are not formed because I need a way to access the previous elements of the array.
Can anyone suggest a way to do so, or how I should change my approach?
Upvotes: 0
Views: 53
Reputation: 5455
To "wrap around" to the beginning of the array you'd use the %
mod operator.
String[] strings = { "a", "b", "c", "d", "e", "f" };
int reduction = 2;
for(int i=0; i<strings.length; i++)
{
for(int j=0; j<=reduction; j++)
{
StringJoiner p = new StringJoiner("|");
p.add(strings[i]);
for(int k=1; k<strings.length-reduction; k++)
p.add(strings[(i + j + k) % strings.length]);
System.out.println(p);
}
}
Output:
a|b|c|d
a|c|d|e
a|d|e|f
b|c|d|e
b|d|e|f
b|e|f|a
c|d|e|f
c|e|f|a
c|f|a|b
d|e|f|a
d|f|a|b
d|a|b|c
e|f|a|b
e|a|b|c
e|b|c|d
f|a|b|c
f|b|c|d
f|c|d|e
Upvotes: 1