-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordHelper.java
110 lines (109 loc) · 2.44 KB
/
WordHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* Written by Noah Shaw
*/
public class WordHelper {
//Sort by least number of vowels to greatest number of vowels
public static String[] sortByVowels(String[] aString)
{
String[] copy = copyArray(aString);
boolean hasSwapped = true;
while(hasSwapped)
{
hasSwapped = false;
for(int i = 0; i < copy.length - 1; i++)
{
if(countVowels(copy[i]) > countVowels(copy[i+1]))
{
//Swap
String temp = copy[i];
copy[i] = copy[i+1];
copy[i+1] = temp;
hasSwapped = true;
}
}
}
return copy;
}
//Sort by least number of consonants to greatest number of consonants
public static String[] sortByConsonants(String[] aString)
{
String[] copy = copyArray(aString);
boolean hasSwapped = true;
while(hasSwapped)
{
hasSwapped = false;
for(int i = 0; i < copy.length - 1; i++)
{
if(countConsonants(copy[i]) > countConsonants(copy[i+1]))
{
//Swap
String temp = copy[i];
copy[i] = copy[i+1];
copy[i+1] = temp;
hasSwapped = true;
}
}
}
return copy;
}
//Sort by smallest length to greatest length
public static String[] sortByLength(String[] aString)
{
String[] copy = copyArray(aString);
boolean hasSwapped = true;
while(hasSwapped)
{
hasSwapped = false;
for(int i = 0; i < copy.length - 1; i++)
{
if(copy[i].length() > copy[i+1].length())
{
//Swap
String temp = copy[i];
copy[i] = copy[i+1];
copy[i+1] = temp;
hasSwapped = true;
}
}
}
return copy;
}
//Count the number of vowels in each word
public static int countVowels(String aString)
{
int count = 0;
for(int i = 0; i < aString.length(); i++)
{
char c = aString.charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y')
{
count++;
}
}
return count;
}
//Count the number of consonants in each word
public static int countConsonants(String aString)
{
int count = 0;
for(int i = 0; i < aString.length(); i++)
{
char c = aString.charAt(i);
if(c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' && c != 'y')
{
count++;
}
}
return count;
}
//Create a copy of the initial array
public static String[] copyArray(String[] aString)
{
String[] copy = new String[aString.length];
for(int i = 0; i < aString.length; i++)
{
copy[i] = aString[i];
}
return copy;
}
}