Sorting characters inside String - java

I'm trying to sort the characters alphabetically in a String and when I run my code with the following example: hello, then I get: heeeeeeeeeheeeelheeellhee instead of ehllo. Could smb suggest me what I should fix in my code? Thanks in advance!
public static void main(String[] args)
{
String result = "";
Scanner kbd = new Scanner(System.in);
String input = kbd.nextLine();
char[] myArray = input.toCharArray();
for(int i = 0; i < myArray.length; i++)
for(int j = 0; j < myArray.length; j++)
{
if(myArray[i] > myArray[j])
{
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
result += myArray[i];
}
else
result += myArray[i];
}
System.out.println(result);
}

Why so complicated?
public String sortByChar(String s)
{
char[] cs = s.toCharArray();
Arrays.sort(cs);
return new String(cs);
}

On each iteration of your loop, you appending the character at i within the array to result, but the array is not sorted yet
The loop will perform n * (n - 1) loops, so, for a String of 5 characters, that's going to be 5 * (5 - 1) (or 20) iterations.
Instead, sort the array and then create a new String based on it's content...
String input = "hello";
char[] myArray = input.toCharArray();
for (int i = 0; i < myArray.length; i++) {
for (int j = 1; j < myArray.length; j++) {
if (myArray[i] > myArray[j]) {
char temp = myArray[j];
myArray[j] = myArray[i];
myArray[i] = temp;
}
}
}
System.out.println(new String(myArray));
Also note, for (int j = 0; j < myArray.length; j++) { is wrong and should be for (int j = 1; j < myArray.length; j++) {, otherwise you'll be comparing the same character at the same position, which isn't what you want to do...
A more "accurate" bubble sort might look something like...
for (int i = 0; i < (myArray.length - 1); i++) {
for (int j = 0; j < myArray.length - i - 1; j++) {
if (myArray[j] > myArray[j + 1]) {
char swap = myArray[j];
myArray[j] = myArray[j + 1];
myArray[j + 1] = swap;
}
}
}

You keep modifying result as you go. This is wrong: result collects a record of characters as you modify them, which is not what you want.
You should remove result += ... from your code, and use this after the loop:
String result = new String(myArray);

Related

Bubble Sort: How to prevent it from comparing to itself in the first iteration

As you can see the code below compares to itself in the first iteration and is a waste of process. But the solution I'm thinking of would most likely go ArrayIndexOutOfBoundsException, I would need some help solving this.
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < words.length; j++) {
int result = words[i].compareTo(words[j]);
if (result < 0) {
String temp;
temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
I suggest int j = i + 1, also i < words.length - 1 like
for (int i = 0; i < words.length - 1; i++) {
for (int j = i + 1; j < words.length; j++) {
// Nothing changed below this line...
int result = words[i].compareTo(words[j]);
if (result > 0) {
T temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}

Sort Array with two loops Implementation

I am new with Java.
I try to do one of my assignment, but i can not figure out why my result still can not sort.
I have a prompt value(argument) 20 10 30 60 55, and i want to sort it.
I wrote two loops, and converted prompt value (which is string) to Integer.
Result: ( It is not sorted)
20
10
30
60
55
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at question2.SortedArray.main(SortedArray.java:29)
This is the code i wrote:
int temp = 0;
int array[] = null;
int array2[];
for(int i=0; i<args.length; i++){
int a = Integer.parseInt(args[i]);
array = new int[a];
for(int j=0; j<args.length; j++){
int b = Integer.parseInt(args[i]);
array2 = new int[b];
if(array[i]>array2[j])
temp = array2[j];
array2[j] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < array.length; i++)
{
System.out.println(args[i].toString());
}
I could understand this code i fould online below
int tempVar;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j])
{
tempVar = numbers [j ];
numbers [j]= numbers [i];
numbers [i] = tempVar;
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
}
First, convert the String array of args into an int array of values. Then sort and display values. You've been sorting arrays (sized by your array int value), then printing the arguments (which you didn't sort). So, something like
int[] values = new int[args.length];
for (int i = 0; i < args.length; i++) {
values[i] = Integer.parseInt(args[i]);
}
int temp = 0;
for (int i = 0; i < values.length - 1; i++) {
for (int j = i + 1; j < values.length; j++) {
if (values[i] > values[j]) {
temp = values[j];
values[j] = values[i];
values[i] = temp;
}
}
}
System.out.println(Arrays.toString(values));
You need to initialize your array to hold your prompt values
int [] yourArray = {2,3,4 5,};
You don't need a second array to sort the values just a temporary int to hold the value that is being moved.
The statements below if needs to be enclose with { } otherwise all it will do is run to the first semicolon and then get out of the if.
Basically what the code you pasted in the second part is checking if element at the value i is greater than the value at element j. If the value is greater it swaps j with i.
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j]) //if element at i is greater than element a j
{
tempVar = numbers [j ]; //store the number at element j in temp
numbers [j]= numbers [i];// set the number at element i to element j
numbers [i] = tempVar;// set the number at temp to element
}
} // does this for each element until no element i greater than j
}
Get the integers to an array at first.
int[] yourArray = { 20, 10, 30, 60, 55 };
for (int i = 0; i < yourArray.length; i++) {
for (int j = 0; j < yourArray.length - 1; j++) {
// swap
if (yourArray[i] < yourArray[j]) {
int temp = yourArray[i];
yourArray[i] = yourArray[j];
yourArray[j] = temp;
}
}
}
for (int i : yourArray)
System.out.println(i);
Output
10
20
30
55
60

Getting All Possibilities - Schoolwork

What I need to do is take a String array with each element having an exact length of 2, and find all possible combinations of the the elements, using each character within each String. By that I mean the String array {"Ss", "Ff"} returns "SF", "Sf", "sF", "sf". I have already tried a loop method that counts the iteration and then chooses a letter based on that, but it only works for arrays with a single element:
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
String [] r = new String [s.length * 2];
for(int i = 0; i < r.length; i++)
{
r[i] = getPossibility(i, s);
}
return r;
}
private String getPossibility(int iteration, String [] source)
{
int [] choose = new int [source.length];
for(int i = 0; i < choose.length; i++)
{
choose[i] = 0;
}
for(int i = choose.length - 1; i >= 0; i--)
{
if(iteration < 1)
break;
choose[i] = 1;
iteration--;
}
String result = "";
for(int i = 0; i < source.length; i++)
result += source[i].substring(choose[i], choose[i] + 1);
return result;
}
Solved Thanks Sven!
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
ArrayList<String> ra = new ArrayList<String>();
for(int i = s.length - 1; i >= 0; i--)
{
for(int j = 0; j < s[i].length(); j++)
{
String c = s[i].substring(j, j + 1);
if(ra.size() < 2)
{
ra.add(c);
}
else
{
for(int k = 0; k < ra.size(); k++)
{
String s1 = ra.get(k);
if(s1.substring(0, 1).equalsIgnoreCase(c))
continue;
else
{
s1 = c + s1;
ra.add(s1);
}
}
}
}
for(int j = 0; j < ra.size(); j++)
{
if(ra.get(j).length() != s.length - i)
{
ra.remove(j);
j--;
}
}
}
String [] r = new String [ra.size()];
for(int i = 0; i < r.length; i++)
{
r[i] = ra.get(i);
}
return r;
}
I would iterate the array of character tuples from last element to first. In each step you append to each current character the possibilities of the last iteration. You therefore double the elements in each step.
So for your example in the first iteration you have {Ff} and this would result to the two strings "F" and "f". In the next step you take each character of {Ss} and append each string of the last step to it getting "SF", "Sf", "sF" and "sf". You could then continue with further character tuples.

Getting each letter in a String only once

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.

sum digits a number in Java

I have a bunch of numbers.Each digit of those numbers is concatenated n times and then summed. I have to write function which is returns 1 if sum equals number else returns 0.
public static int checkConcatenatedSum(int n, int catlen) {
char[] charArray = String.valueOf(n).toCharArray();
int[] test = new int[charArray.length];
String[] digit = new String[charArray.length];
int sum = 0;
for (int j = 0; j < charArray.length; j++){
for(int i = 0; i < catlen; i++){
digit[j] += charArray[j];
}
test[j] = Integer.parseInt(digit[j]);
sum += test[j];
}
if(sum == n){
return 1;
}
else return 1;
}
digit[j] begins with null every time.
When you initialize a new array of objects (String[] strs = ...) all elements in the array will be initialized to null, but you can then iterate over the array and set them all to some value (like "")
When you create an array (of String in this case), its elements are null at first.
You need to initialize the elements:
String[] digit = new String[charArray.length];
for (int i = 0; i < digit.length) {
digit[i] = new String();
}
for (int j = 0; j < charArray.length; j++){
digit[j] = new String();
for(int i = 0; i < catlen; i++){
digit[j] += charArray[j];
}
test[j] = Integer.parseInt(digit[j]);
sum += test[j];
}
Other answers are right, but just a quick addition to your existing loop that achieves it without making a new loop.
Another way is to test if array[?] is 'null' avoiding to create a temporary object String for Garbage Collector
for (int j = 0; j < charArray.length; j++){
for(int i = 0; i < catlen; i++){
digit[i] = digit[i] == null ? charArray[j] : digit[i] + charArray[j];
}
test[j] = Integer.parseInt(digit[j]);
sum += test[j];
}
EDIT
Your second return is erroneous (0 attempted);

Categories

Resources