I am trying to generate permutations using list of strings taking one character one time.
Below is the code of input and output that I want.
Can we simply do it iteratively?. Also I am not finding exact method.
String[] lst = new String[]{"abc", "def", "ghi"}; //Given
String[] permutations = new String[]{ //To Generate
"adg", "adh", "adi",
"aeg", "aeh", "aei",
"afg", "afh", "afi",
"bdg", "bdh", "bdi",
"beg", "beh", "bei",
"bfg", "bfh", "bfi",
"cdg", "cdh", "cdi",
"ceg", "ceh", "cei",
"cfg", "cfh", "cfi",
};
Update: I am not looking just for the above example with list size=3. It can be of any size and each string may happen to be of different length.
For ex: list = [ "ab", "abc", "defghi", "x", "einsigl"]
In this answer I will walk through how I solved this problem to find an algorithm that works for an array of any length for words which can be any length and are not required to all be the same length.
I will first make a recursive solution, and then transorm it into an iterative one.
The easiest way to answer problems like this is to think of them recursively:
Generating all permutations of [] should return [""]
Generating all permutations of a non-empty list means, for each letter c in the first word in the list, return all permutations of the rest of the list with c prepended on the front.
This can be written in Java as follows:
public static List<String> generatePermutationsRecursiveSlow(String[] words) {
if (words.length == 0)
// base case
return Collections.singletonList("");
else {
// recursive case
// result list
ArrayList<String> permutations = new ArrayList<>();
// split array into item 0 and items [1..end]
String firstWord = words[0];
String[] otherWords = new String[words.length - 1];
System.arraycopy(words, 1, otherWords, 0, words.length - 1);
// recurse to find permutations for items [1..end]
List<String> otherWordsPermutations = generatePermutationsRecursiveSlow(otherWords);
// for each character in the first word
for (char c : firstWord.toCharArray()) {
// for each permutation from the recursive call's results
for (String otherWordsPermutation : otherWordsPermutations) {
// prepend this character onto the permutation and add it to the results
permutations.add(c + otherWordsPermutation);
}
}
return permutations;
}
}
Calling generatePermutationsRecursiveSlow(new String[0]) returns [""].
Calling generatePermutationsRecursiveSlow(new String[]{"cd"}) will cause the local c variable to be equal to 'c', and it will recurse with an empty array as the argument, making otherWordsPermutations equal to [""], so it will add 'c' + "" (which is "c") to the results, then it will do the same for 'd', adding "d" to the results.
Calling generatePermutationsRecursiveSlow(new String[]{"ab", "cd"}) will mean that when c is 'a', it will add to the results list 'a'+"c", then 'a'+"d", and whencis'b', it will add'b'+"c"and'b'+"d"`
A similar but better optimised version which works in the same way can be written like this:
public static List<String> generatePermutationsRecursive(String[] words) {
ArrayList<String> permutations = new ArrayList<>();
int wordLen = words.length;
generatePermutationsRecursive(words, permutations, new char[wordLen], 0);
return permutations;
}
public static void generatePermutationsRecursive(String[] words, ArrayList<String> permutations, char[] word, int i) {
if (i == word.length) {
// base case
permutations.add(new String(word));
} else {
for (int j = 0; j < words[i].length(); j++) {
// equivalent of prepending
word[i] = words[i].charAt(j);
// recurse
generatePermutationsRecursive(words, permutations, word, i + 1);
}
}
}
This is better optimised since it uses the word parameter to avoid the O(n) prepending to the string by instead modifying a character array. It also introduces the parameter i which is the effective start index of the array, making it possible to avoid copying parts of the input array.
This can be transformed into an iterative approach by tracking the variables that change between different recursive calls using a stack (in place of the call stack):
private static List<String> generatePermutationsIterative(String[] words) {
// in the recursive version, each recursive function call would have its own local copy of `i` and `j`
// simulate that here with 2 stacks
ArrayDeque<Integer> i_stack = new ArrayDeque<>(words.length);
ArrayDeque<Integer> j_stack = new ArrayDeque<>(words.length);
i_stack.add(0);
j_stack.add(0);
char[] word = new char[words.length];
ArrayList<String> permutations = new ArrayList<>();
while (!i_stack.isEmpty()) {
int i = i_stack.removeLast();
int j = j_stack.removeLast();
if (i == words.length) {
// base case
permutations.add(new String(word));
continue;
}
if (!(j < words[i].length())) {
// reached end of loop `for (int j = 0; j < words[i].length(); j++)`
continue;
}
// if not reached end of loop `for (int j = 0; j < words[i].length(); j++)` yet,
// then increment `j` and allow next iteration to happen
i_stack.add(i);
j_stack.add(j + 1);
word[i] = words[i].charAt(j);
// recurse
i_stack.add(i + 1);
j_stack.add(0);
}
return permutations;
}
Code here
As a sidenote, look how cool Haskell is with this 2-line solution to the problem here (admittedly its not iterative, but it should have tail-call optimisation, making it as fast as an iterative solution).
Here's one way to do it that should work for arbitrary number of words of arbitrary length (not including 0).
String[] lst = new String[] {
"abc",
"def",
"ghi"
};
int numWords = lst.length;
int wordlen = lst[0].length();
int numPerms = (int) Math.pow(wordlen, numWords);
char[][] perms = new char[numPerms][numWords];
char[][] chararr = Arrays.stream(lst)
.map(String::toCharArray)
.toArray(i -> new char[i][wordlen]);
for (int i = 0; i < numWords; i++) {
double permsLocal = Math.pow(wordlen, i + 1);
int numRepeats = (int) Math.ceil((numPerms / permsLocal));
int repeats = (int)(permsLocal / wordlen);
for (int x = 0; x < repeats; x++) {
char[] word = chararr[i];
for (int j = 0; j < wordlen; j++) {
char c = word[j];
for (int k = 0; k < numRepeats; k++) {
perms[(x * wordlen * numRepeats) + k + j * numRepeats][i] = c;
}
}
}
}
String[] permutations = Arrays.stream(perms)
.map(String::new)
.toArray(String[]::new);
Output:
[adg, adh, adi, aeg, aeh, aei, afg, afh, afi, bdg, bdh, bdi, beg, beh,
bei, bfg, bfh, bfi, cdg, cdh, cdi, ceg, ceh, cei, cfg, cfh, cfi]
Link to repl.it: https://repl.it/repls/BoilingExcitingAttributes
You can do it as follows:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] lst = new String[] { "abc", "def", "ghi" };
List<String> list = new ArrayList<>();
for (char a : lst[0].toCharArray()) {
for (char b : lst[1].toCharArray()) {
for (char c : lst[2].toCharArray()) {
list.add(new String(new char[] { a, b, c }));
}
}
}
// Convert to array
String[] permutations = list.toArray(new String[0]);
// Display
System.out.println(Arrays.toString(permutations));
}
}
Output:
[adg, adh, adi, aeg, aeh, aei, afg, afh, afi, bdg, bdh, bdi, beg, beh, bei, bfg, bfh, bfi, cdg, cdh, cdi, ceg, ceh, cei, cfg, cfh, cfi]
Related
I wanted to create an algorithm in java where I can pass a list of strings and it returns a new list with all possible combinations of the strings it has in the list.
Example:
String[] listWords = new String[] {
"windows",
"linux",
"mac",
"10",
"20"
};
I would like to call a method by passing the list that returns all possible combinations, in all orders.
combinations(listWords);
This is the result I wanted to have:
windows,linux,mac,10,20,windowslinux,linuxwindows,windowsmac,windows10,10windows,windows20,20windows,windowslinuxmac1020,windowsmaclinux20,mac10,mac20,20mac,20mac10,windowsmac,macwindows...
I tried this:
public String[][] combinations (String[] ports) {
List<String[]> combinationList = new ArrayList<String[]>();
for ( long i = 1; i < Math.pow(2, ports.length); i++ ) {
List<String> portList = new ArrayList<String>();
for ( int j = 0; j < ports.length; j++ ) {
if ( (i & (long) Math.pow(2, j)) > 0 ) {
portList.add(ports[j]);
}
}
combinationList.add(portList.toArray(new String[0]));
}
return combinationList.toArray(new String[0][0]);
}
But this returns:
This was not how I wanted it. The result had to be:
list: [windows, linux, windowslinux, linuxwindows, windows10, 10windowsmaclinux...]
Is it possible to do this in java? thank you who can help :)
If I've understood you correctly, the following will solve the problem.
You can build the result iteratively starting from the list of words that you have, and in each iteration you add longer and longer words. The first iteration gives you the original list. The second iteration adds one new word to each, giving you the permutations of 2 words. The third iteration adds one new word to each of those, giving you the permutations of 3 words, and so on.
List<String> getWordPermutations(List<String> words) {
List<String> result = new ArrayList<>(words);
List<String> oldPermutations = new ArrayList<>(words);
for (int i = 1; i < words.size(); i++) {
List<String> newPermutations = new ArrayList<>();
for (String previousList : oldPermutations) {
for (String word : words) {
if (previousList.contains(word)) {
continue;
}
newPermutations.add(previousList + word);
}
}
oldPermutations = newPermutations;
result.addAll(newPermutations);
}
return result;
}
import java.util.Scanner;
public class CountVowel{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Getting the size of the array:
System.out.println("Type how many words will be typed: ");
int input = scan.nextInt();
Filling array with string values
String[] ar1 = new String[input];
for(int i = 0; i < ar1.length; i++){
System.out.println("Type the elements of array with words: ");
ar1[i] = scan.next();
}
Output of the program :
System.out.println( input + " words are typed and " +
countVowels(ar1) +
" of them contain more than 3 vowels.");
}
The method that counts vowels:
public static int countVowels(String[] ar1){ // this method counts
int a = 0;
String[] ar2 = new String[]{"a", "e", "i", "u", "y", "o"};
for(int i = 0; i < ar1.length; i++){
for(String s : ar2){
if(ar1[i].toLowerCase().contains(s)){
a++;
}
}
}
return a;
}
}
The method above is to check the vowels, but i dont know how to make it check if
there are more than 3 vowels.
Another solution with replaceAll method.
The main idea is to substract from word.length() the same word length without vowels. And check the difference.
public static int countVowels(String[] ar1){
int a = 0;
for (String word : ar1) {
int i = word.length() - word.toLowerCase().replaceAll("[aeyiuo]", "").length();
if (i >= 3) {
a++;
}
}
return a;
}
Or you can use matches() as #pkgajulapalli suggested. It can be quite concise with stream api:
long count = Arrays.stream(words)
.filter(s -> s.toLowerCase().matches("(.*[aeyiuo].*){3,}"))
.count();
public static int countVowels(String[] ar1) { // this method counts
int vowelPerWord = 0;
int totalWordsWithThreeVowels = 0;
char[] ar2 = new char[] { 'a', 'e', 'i', 'u', 'y', 'o' };
for (int i = 0; i < ar1.length; i++) {
vowelPerWord = 0;
for (int j = 0; j < ar1[i].length(); j++) {
for (int k = 0; k < ar2.length; k++) {
if (ar2[k] == (ar1[i].charAt(j))) {
vowelPerWord++;
}
}
}
if (vowelPerWord >= 3) {
totalWordsWithThreeVowels++;
}
}
return totalWordsWithThreeVowels;
}
EDIT
alright now i fixed the error and edited the variablenames to make a bit more sense. although this is O(n*m) i believe (where n is the number of strings and m is the number of char the longest string has) (not so good complexity) it gets the job done ar1 in this case is your input of strings, ar2 are just the vowels that exist.
so you go through every string in ar1 and set "vowelPerWord" to 0, go through every single char in every string and check if it is a vowel increase the vowelPerWord by 1. at the end, after you went through every char of that string you check if there were 3 or more vowels, if so increase the totalWordsWithThreeVowels, which at the end is returned.
What you need is an additional loop and count. Something like this:
// This method counts how many words have at least 3 vowels
public static int countVowels(String[] wordsArray){
int atLeastThreeVowelsCount = 0;
for(String word : wordsArray){
int vowelCount = 0;
for(String vowel : new String[]{ "a", "e", "i", "u", "y", "o" }){
if(word.toLowerCase().contains(vowel)){
vowelCount++;
}
}
if(vowelCount >= 3){
atLeastThreeVowelsCount++;
}
}
return atLeastThreeVowelsCount;
}
Try it online.
Note that I've also given the variables some more useful names, instead of ar1, s, etc. so it's easier to read what's going on.
You can use regex matching to find if a string contains any set of characters. For example, if you want to find if a string contains any of vowels, you can use:
String str = "yydyrf";
boolean contains = str.toLowerCase().matches(".*[aeiou].*");
System.out.println(contains);
EDIT:
So your code would look like:
public static int countVowels(String[] ar1) {
int a = 0;
String[] ar2 = new String[] { "a", "e", "i", "u", "y", "o" };
String pattern = ".*[" + String.join("", ar2) + "].*";
for (int i = 0; i < ar1.length; i++) {
if (ar1[i].matches(pattern)) {
a++;
}
}
return a;
}
You can use this:
public static int countVowels(String[] words) {
char[] chars = {'a', 'e', 'i', 'u', 'y', 'o'};
int wordsWith3Vowels = 0;
for (String word : words) {
int countedVowels = 0;
for (char s : chars) {
if (word.toLowerCase().indexOf(s) != -1) {
countedVowels++;
}
}
if (countedVowels >= 3) {
wordsWith3Vowels++;
}
}
return wordsWith3Vowels;
}
Which uses chars instead of Strings which is a tad faster
public static int countVowels(String[] ar1){ // this method counts
//Create hash map key = array string && value = vowels count
Map<String,Integer> mapVowels=new HashMap<String,Integer>();
int a = 0;
String[] ar2 = new String[]{"a", "e", "i", "u", "y", "o"};
for(int i = 0; i < ar1.length; i++){
for(String s : ar2){
if(ar1[i].toLowerCase().contains(s)){
//Check map string already has vowel count then increase by one
if(mapVowels.get(s)!=null) {
mapVowels.put(s,mapVowels.get(s)+1);
//After add the vowels count get actual count and check is it more than 3
if(mapVowels.get(s)>3)
a++;
}
else {
//If the vowels string new for map then add vowel count as 1 for first time
mapVowels.put(s,1);
}
}
}
}
return a;
}
Since java-8 you can now use Streams.
String[] values = {"AA","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);
To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.
Example
int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
Suppose I have this array: [a,b,c,d] How would I go about finding every possible combination i.e ab,abc,abcd.....etc. This needs to include duplicates, so abcd is not the same as dcba
The purpose is to find all combinations and check if if can make the same combination from a different array. My initial attempt is:
for (int i = 0; i < values.length; i++) {
String cur = values[i];
for (int k = 0; k < values.length; k++) {
if (i != k) {
cur = cur.concat(values[k]);
System.out.println(cur);
}
}
}
Which give the output :
ab
abc
abcd
ba
bac
bacd
ca
cab
cabd
da
dab
dabc
which is obviously not correct
This is for a programming challenge I'm doing to try and improve so any suggestions of a faster solution would be helpful
Is this what you're looking for?
public static void main(String[] data) {
ArrayList<Character> chars = new ArrayList<>(4);
chars.add('a');
chars.add('b');
chars.add('c');
chars.add('d');
System.out.println(getPermutations("", chars));
}
private static ArrayList<String> getPermutations(String currentResult, ArrayList<Character> possibleChars) {
ArrayList<String> result = new ArrayList<>(possibleChars.size());
for (char append: possibleChars) {
String permutation = currentResult + append; //create a new string with an additional character
result.add(permutation); //add the permutation to the result
if (possibleChars.size() > 0) {
//make a new list with the appendable characters
ArrayList<Character> possibleCharsUpdated = (ArrayList)possibleChars.clone();
//from that list, exclude the character we just appended
possibleCharsUpdated.remove(new Character(append));
//merge the result of a recursive call of this method and the result we already had
result.addAll(getPermutations(permutation, possibleCharsUpdated));
}
}
return result;
}
test[0] = "one";
test[1] = "two";
test[2] = "one";
test[3] = "three";
I want to remove all the occurrences of "one" but can't use the classes Arrays, Collections, Set, or Map. Thats why I'm stuck, if it wasn't for the restriction I would be able to remove them.
You could have a method like so:
public static String[] removeFromArray(String[] inputArray, String removeString) {
int removeStringOccurences = 0;
for (String currString : inputArray) {
if (currString.equals(removeString)) {
removeStringOccurences++;
}
}
String[] result = new String[inputArray.length - removeStringOccurences];
int index = 0;
for (String currString : inputArray) {
if (!currString.equals(removeString)) {
result[index] = currString;
index++;
}
}
return result;
}
This first checks to see how many times the String we want to remove occurs and then creates a new String[] based on the length of the original String[] minus the times the undesired String occurs.
Running the following:
String[] test = new String[]{"one", "two", "one", "three"};
System.out.println("Before:");
System.out.println(Arrays.toString(test));
test = removeFromArray(test, "one"); //Call our method
System.out.println("\nAfter:");
System.out.println(Arrays.toString(test));
Results in:
Before:
[one, two, one, three]
After:
[two, three]
I think the most appropriate way of solving your issue is to take all of the elements after the element, you want to remove, and shift them one to the front. But this would leave a trail of one unused element.
You could also create a new array without the element to remove.
public void removeFromArrayShift(Object[] arr,int index) {
for(int i = 0;i< arr.length -1;i++){
if(i >= index)
arr[i]=arr[i+1];
}
arr[arr.length-1]=null;
}
public Object[] removeFromArrayNew(Object[] arr, int index) {
Object[] n = new Object[arr.length - 1];
for(int i = 0; i < n.length;i++)
if(i>= index)
n[i] = arr[i+1];
else
n[i] = arr[i];
return n
}
The later could be optimized with System.arrayCopy if you can access that. ;)
What kind of approch could be an easy way to find the given words on a puzzle like this? I'm using Java. Thanks for help.
Interesting question. I would solve this by first building a list of "possible word holders" (sequences of characters which can possibly hold one of the given words) by traversing the puzzle horizontally, vertically and diagonally (in both directions). I would then see if the given words (or their reverse) are present (using contains() method in Java) in each of the obtained "possible word holders". Here is the code I wrote in Java. I haven't tested it properly, but I guess it works!
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class WordPuzzle {
public Set<String> findWords(char[][] puzzle, Set<String> words) {
Set<String> foundWords = new HashSet<String>();
int minimumWordLength = findMinimumWordLength(words);
Set<String> possibleWords = findPossibleWords(puzzle, minimumWordLength);
for(String word : words) {
for(String possibleWord : possibleWords) {
if(possibleWord.contains(word) || possibleWord.contains(new StringBuffer(word).reverse())) {
foundWords.add(word);
break;
}
}
}
return foundWords;
}
private int findMinimumWordLength(Set<String> words) {
int minimumLength = Integer.MAX_VALUE;
for(String word : words) {
if(word.length() < minimumLength)
minimumLength = word.length();
}
return minimumLength;
}
private Set<String> findPossibleWords(char[][] puzzle, int minimumWordLength) {
Set<String> possibleWords = new LinkedHashSet<String>();
int dimension = puzzle.length; //Assuming puzzle is square
if(dimension >= minimumWordLength) {
/* Every row in the puzzle is added as a possible word holder */
for(int i = 0; i < dimension; i++) {
if(puzzle[i].length >= minimumWordLength) {
possibleWords.add(new String(puzzle[i]));
}
}
/* Every column in the puzzle is added as a possible word holder */
for(int i = 0; i < dimension; i++) {
StringBuffer temp = new StringBuffer();
for(int j = 0; j < dimension; j++) {
temp = temp.append(puzzle[j][i]);
}
possibleWords.add(new String(temp));
}
/* Adding principle diagonal word holders */
StringBuffer temp1 = new StringBuffer();
StringBuffer temp2 = new StringBuffer();
for(int i = 0; i < dimension; i++) {
temp1 = temp1.append(puzzle[i][i]);
temp2 = temp2.append(puzzle[i][dimension - i - 1]);
}
possibleWords.add(new String(temp1));
possibleWords.add(new String(temp2));
/* Adding non-principle diagonal word holders */
for(int i = 1; i < dimension - minimumWordLength; i++) {
temp1 = new StringBuffer();
temp2 = new StringBuffer();
StringBuffer temp3 = new StringBuffer();
StringBuffer temp4 = new StringBuffer();
for(int j = i, k = 0; j < dimension && k < dimension; j++, k++) {
temp1 = temp1.append(puzzle[j][k]);
temp2 = temp2.append(puzzle[k][j]);
temp3 = temp3.append(puzzle[dimension - j - 1][k]);
temp4 = temp4.append(puzzle[dimension - k - 1][j]);
}
possibleWords.add(new String(temp1));
possibleWords.add(new String(temp2));
possibleWords.add(new String(temp3));
possibleWords.add(new String(temp4));
}
}
return possibleWords;
}
public static void main(String args[]) {
WordPuzzle program = new WordPuzzle();
char[][] puzzle = {
{'F','Y','Y','H','N','R','D'},
{'R','L','J','C','I','N','U'},
{'A','A','W','A','A','H','R'},
{'N','T','K','L','P','N','E'},
{'C','I','L','F','S','A','P'},
{'E','O','G','O','T','P','N'},
{'H','P','O','L','A','N','D'}
};
Set<String> words = new HashSet<String>();
words.add("FRANCE");
words.add("POLAND");
words.add("INDIA");
words.add("JAPAN");
words.add("USA");
words.add("HOLLAND");
Set<String> wordsFound = program.findWords(puzzle, words);
for(String word : wordsFound) {
System.out.println(word);
}
}
}
In general, I say use the most naive approach unless your puzzles are going to be large. I wouldn't optimize anything that takes less than 0.1s, but thats just me.
foreach box
for all directions
grab the string of characters in that direction
lookup a dictionary
I think the smarts can be in how you design your dictionary. In this case, I would do a multi-level hash table where characters pick which hash table to look at the next level.
I would put the word list into a Trie, then do a search from all squares in all directions.
The easiest approach (conceptualy) is to simply enumerate all possible words in your array and check all of then in a dictionnary. A dictionnary behing a map, an array of string... or a real dictionnary downloaded from the internet.
As an exemple here is the code to find all possible word horizontally... Adding other direction is just more work :
import java.util.HashSet;
import java.util.Set;
public class WordFinder {
public static void main(String[] args) {
String[][] words = { { "F", "Y", "Y", "H", "N", "R", "D" },
{ "R", "L", "J", "C", "I", "N", "U" },
...};
Set<String> dictionnary = new HashSet<String>();
dictionnary.add(...);
Set<String> wordsFound = findWords(words, dictionnary);
...
}
/**
* Find all words in the specified array present in the dictionnary.
*
*/
private static Set<String> findWords(String[][] words, Set<String> dictionnary) {
Set<String> wordsFound = new HashSet<String>();
// Find all possible words horizontally :
int nbrRows = words.length;
int nbrCol = words[0].length; // We suppose we have at least one row and all row have same lengh
// Iterate through all rows
for (int currentRow = 0; currentRow < nbrRows; currentRow++) {
// Iterate through all possible starting position in the current row.
for (int beginWordIndex = 0; beginWordIndex < nbrCol; beginWordIndex++) {
// Iterate then through all possible ending positions in the current row, so to deal with word of any lengh.
for (int endWordIndex = beginWordIndex; endWordIndex < nbrCol; endWordIndex++) {
// Construct a word from the begin/end indexes :
String currentWord = getWordInRow(words, currentRow, beginWordIndex, endWordIndex);
// Check if the word candidate really exist, if yes, store it in the wordsFound variable.
if (dictionnary.contains(currentWord)) {
wordsFound.add(currentWord);
}
// The reverse
String reverseWord = reverseString(currentWord);
// Check if the reverse word really exist, if yes, store it in the wordsFound variable.
if (dictionnary.contains(reverseWord)) {
wordsFound.add(currentWord);
}
}
}
}
// Don't forget vertically and in diagonals too... Same principe.
return wordsFound;
}
/**
* Return a word "candidate" in the specified row, starting at beginIndex and finishing at endIndex.
*/
private static String getWordInRow(String[][] words, int row, int beginIndex, int endIndex) {
String currentWord = "";
int currentPosition = beginIndex;
while (currentPosition <= endIndex) {
currentWord += words[row][currentPosition];
}
return currentWord;
}
/**
* Return the reverse of a String
*/
private static String reverseString(String string) {
String result = "";
for (int i = string.length()-1; i >=0;i++) {
result+= string.charAt(i);
}
return result;
}
}
This is not the best, most effective solution. But it is conceptually simple.
EDIT :
reverse order: see edited code. Just write a function that can reverse a word. Because we already have all posible word in normal order, reversing them is enough to have words in reverse order.
Diagonals : I'am sure you can do it if you have understood the code I have already put. I will not do your homework or do your testing in place of you. Try to figure how you would do it with a paper and a pen. How would you do it if you had to do it by hand. Then from that, write your solution ;)