Skip to content

Instantly share code, notes, and snippets.

@jpruiz114
Created May 23, 2022 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpruiz114/44bdbf4bf80e7334e3a8000034ef03aa to your computer and use it in GitHub Desktop.
Save jpruiz114/44bdbf4bf80e7334e3a8000034ef03aa to your computer and use it in GitHub Desktop.
Generate all the combinations of words from character in a matrix using Java
package com.derp;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static ArrayList<String> combineCharWithWords( String character,
ArrayList<String> words ) {
ArrayList<String> result = new ArrayList<>();
for ( String word : words ) {
String prefixed = character + word;
String suffixed = word + character;
result.add( prefixed );
result.add( suffixed );
}
return result;
}
public static void main( String[] args ) {
String[][] matrix = { { "C", "A" }, { "T", "O" } };
ArrayList<String> originalChars = new ArrayList<>();
for ( int i = 0; i < matrix.length; i++ ) {
for ( int j = 0; j < matrix[ 0 ].length; j++ ) {
originalChars.add( matrix[ i ][ j ] );
}
}
ArrayList<String> previousWords = new ArrayList<>();
previousWords.addAll( originalChars );
int numberRepeats = 4;
for ( int i = 0; i < numberRepeats; i++ ) {
System.out.println( "Iteration number " + i );
ArrayList<String> subFindings = new ArrayList<>();
for ( String currentChar : originalChars ) {
ArrayList<String> subResult = Main.combineCharWithWords( currentChar, previousWords );
for ( String currentWord : subResult ) {
if ( !subFindings.contains( currentWord ) ) {
subFindings.add( currentWord );
}
}
}
for ( String currentWord : subFindings ) {
if ( !previousWords.contains( currentWord ) ) {
previousWords.add( currentWord );
}
}
}
Collections.sort( previousWords );
System.out.println( "Previous words" );
System.out.println( previousWords );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment