How do I sort randomly generated characters alphabetically? - java

this is what I have so far
public class RandomCharacter
{
public static char getRandomUpperCaseLetter()
{
int ascii = (int) (Math.random()*26) + (int) 'A';
return (char)ascii;
}
public static char getRandomDigitCharacter()
{
int digit = (int)(Math.random()*10) + (int) '0';
return (char)digit;
}
public static void main(String [] args)
{
for (int i = 1; i <= 100; i++)
{
System.out.print(getRandomUpperCaseLetter());
if(i%10 == 0)
System.out.print("\n");
}
}
}
I have no clue how to specifically order this alphabetically, I have tried for hours but could not find anything for this. Would someone be able to use my code to teach me how this works?

To sort the values, you must first store them in some data structure eg.an array list before sorting them. Then , if you have used a sortable collection such as the array list, you can use the .sort() method and the list will be sorted automatically.
eg/ref:
http://beginnersbook.com/2013/12/how-to-sort-arraylist-in-java/

For natural ordering you can just add the generated alphabets in string and call Collections.sort(listVariable) . This should answer your question.
Sample program
import java.util.*;
public class Details {
public static void main(String args[]){
ArrayList<String> listofcountries = new ArrayList<String>();
listofcountries.add("India");
listofcountries.add("US");
listofcountries.add("China");
listofcountries.add("Denmark");
/*Unsorted List*/
System.out.println("Before Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
/* Sort statement*/
Collections.sort(listofcountries);
/* Sorted List*/
System.out.println("After Sorting:");
for(String counter: listofcountries){
System.out.println(counter);
}
}
}

Related

I am working on an assignment about ordered list in java. We're not allowed to use sort so I made a solution but 2 numbers are outputted twice

here's the code for MyArrayList
public void addLast(int number){
if(!isFull())
doubleTheArray();
element[count++] = number;
}
and here's the code for MyOrderedList
public void add(int item){
for(int i = 0; i < count; i++){
for(int j = i+1; j < count; j++){
if(element[i] > element[j]){
item = element[i];
element[i] = element[j];
element[j] = item;
}
}
}
addLast(item);
}
This is the main method
public static void main(String [] args){
MyOrderedList oList = new MyOrderedList();
oList.add(3);
oList.add(5);
oList.add(2);
oList.add(4);
oList.add(7);
oList.add(8);
oList.add(10);
System.out.println("Ordered list of items: "+ oList);
}
Can anyone help me find out what's wrong? We're not allowed to use sort so I made a solution but 2 numbers are outputted twice in the main method for MyOrderedList. We have to add the elements at the right location. Or in ascending order for add(item). isFull() is boolean method that doubles (doubleTheArray()) the array size if it is true.

Difficulty reversing a linked list alphabetically

I'm having trouble reversing a LinkedList. In other words, I need them sorted in z-a order (in contrast to a-z). I've tried Collections.reverse but is not coming into effect? I have the following:
import java.io.*;
import java.util.*;
public class pa9Driver {
//create two list
//1st List is of type word class
//2nd list is of type Anagram_Family
public static List<Word> words = new LinkedList<Word>();
public static List<AnagramFamily> familyList = new LinkedList<AnagramFamily>();
//a main method for driver class
public static void main(String[] args) {
//call the generate method to read word from the file
generate_WordList();
//sort the word list
Collections.sort(words);
//generate the anagram family for the word
generate_FamilyList();
//sort the anagram family list
Collections.sort(familyList, new anagramFamilyComparator());
//reverse the anagram family list
Collections.reverse(familyList);
topFive();
}//main ends
public static void topFive() {
int i;
for(i = 0; i < 15; i++) {
System.out.print(familyList.get(i).getCanonicalForm1() + ", ");
System.out.print(familyList.get(i).getSize() + ": ");
System.out.println(familyList.get(i));
}
}
//method that read word
public static void generate_WordList() {
File inFile12=new File("words.txt");
Scanner fileRead1=null;
try {
fileRead1 = new Scanner(inFile12);
} catch (Exception exe) {
exe.printStackTrace();
System.exit(0);
}
//until the file has words read the words
while(fileRead1.hasNext()) {
words.add(new Word(fileRead1.next()));
}
}
//generate the anagram and add it to the current family
public static void generate_FamilyList() {
Iterator<Word> readWord1 = words.iterator();
Word previousWord1 = words.get(0);
familyList.add(new AnagramFamily());
int index1 = 0;
while(readWord1.hasNext()) {
Word currentWord1 = readWord1.next();
if(currentWord1.getCanonicalForm1().equals(previousWord1
.getCanonicalForm1())) {
familyList.get(index1).add(currentWord1);
} else {
index1++;
familyList.add(new AnagramFamily());
familyList.get(index1).add(currentWord1);
}
previousWord1 = currentWord1;
}
}
}
For convenience sake, I'll only show the first few lines of code that I have and that is expected.
Currently:
[apers, apres, asper, pares, parse, pears, prase, presa, rapes, reaps, spare, spear]
[alerts, alters, artels, estral, laster, ratels, salter, slater, staler, stelar, talers]
Expected:
[spear, spare, reaps, rapes, presa, prase, pears, parse, pares, asper, apres, apers]
[talers, stelar, staler, slater, salter, ratels, laster, estral, artels, alters, alerts]
Try:
Collections.sort(familyList, Comparator.reverseOrder());
Alternatively, you can do:
Collections.sort(familyList, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
//Print list in reverse order
for(String st : familyList){
System.out.println(st);
}
Seeing your code, it seems AnagramFamily is a kind of List, which you are not sorting.
You need to sort the AnagramFamily (List of String) with a StringComparator for getting your desired output.
I think you can use compareTo for this action no ? compareTo from Comparable

Implementation of Radix sort in Java using Nodes instead of integers

I have a final project for my Data Structures class that I can't figure out how to do. I need to implement Radix sort and I understand the concept for the most part. But all the implementations I found online so far are using it strictly with integers and I need to use it with the other Type that I have created called Note which is a string with ID parameter.
Here is what I have so far but unfortunately it does not pass any JUnit test.
package edu.drew.note;
public class RadixSort implements SortInterface {
public static void Radix(Note[] note){
// Largest place for a 32-bit int is the 1 billion's place
for(int place=1; place <= 1000000000; place *= 10){
// Use counting sort at each digit's place
note = countingSort(note, place);
}
//return note;
}
private static Note[] countingSort(Note[] note, long place){ //Where the sorting actually happens
Note[] output = new Note[note.length]; //Creating a new note that would be our output.
int[] count = new int[10]; //Creating a counter
for(int i=0; i < note.length; i++){ //For loop that calculates
int digit = getDigit(note[i].getID(), place);
count[digit] += 1;
}
for(int i=1; i < count.length; i++){
count[i] += count[i-1];
}
for(int i = note.length-1; i >= 0; i--){
int digit = getDigit((note[i].getID()), place);
output[count[digit]-1] = note[i];
count[digit]--;
}
return output;
}
private static int getDigit(long value, long digitPlace){ //Takes value of Note[i] and i. Returns digit.
return (int) ((value/digitPlace ) % 10);
}
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
//Main Method
public static void main(String[] args) {
// make an array of notes
Note q = new Note(" ", " ");
Note n = new Note("CSCI 230 Project Plan",
"Each person will number their top 5 choices.\n" +
"By next week, Dr. Hill will assign which piece\n" +
"everyone will work on.\n");
n.tag("CSCI 230");
n.tag("final project");
Note[] Note = {q,n};
//print out not id's
System.out.println(Note + " Worked");
//call radix
Radix(Note);
System.out.println(Note);
//print out note_id's
}
}
Instead of
public Note[] sort(Note[] s) { //
Radix(s);
return s;
}
I should have used
public Note[] sort(Note[] s) { //
s = Radix(s);
return s;
}
and change the variable type of Radix from void to Note[].

Swap array element in java in accending order

I'm trying to swap an array in ascending order but somewhere I'm going wrong. I'm taking input using
int n = Integer.parse.int(args[0]);
but it isn't working. Below is the full code.
package tech;
import java.util.*;
import java.io.*;
public class Techgig {
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Amount Mark has:");
int rs=50;//Integer.parseInt(args[0]);
//int a=0;
System.out.println(rs);
// for(int k=0;k<ta.length;k++)
//System.out.print("\t"+ ta);
int min,temp;
for(int i=0;i<ta.length;i++)
{
min=i;
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
for(int k=0;k<ta.length;k++)
{
System.out.print("\t"+ ta[k]);
}
}
}
You should replace variable i with j here:
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
Reason is you are comparing 'i'th index with itself which you assigned to min variable and hence it will never go in your if condition to swap.
You could resolve this as below by using i and j as index and checking between the two:
for(int i=0;i<ta.length;i++)
{
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[j]<ta[i])
{
temp=ta[j];
ta[j]=ta[i];
ta[i]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
Your logic of comparison is wrong.
Refer to the below code. Instead of applying so much logic. Why not just call upon sort method like below?
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
// print all the elements available in array
for (int number : ta) {
System.out.println("Number = " + number);
}
// sorting array
Arrays.sort(ta);
System.out.println("The sorted int array is:");
for (int number : ta) {
System.out.println("Number = " + number);
}

How to multiply the contents of my LinkedList using a while loop and an Iterator

Here is my code:
import java.util.*;
public class Multiply {
public static void main(String[] args) {
LinkedList<Integer>num = new LinkedList<Integer>();
num.add("1");
num.add("2");
num.add("3");
num.add("4");
num.add("5");
product( num );
}
public static void product(LinkedList<Integer> list) {
int index = 0;
Iterator<Integer>productw = list.iterator();
Integer next = productw.next()
while (productw.hasNext()) {
index++;
System.out.println("The product of the numbers is = " + num);
}
}
}
Initially have a multiplication identity ( i.e., 1 ) before your while loop. And keep multiplying to it the iterator values.
Psuedo - code :
public static void product(LinkedList<Integer> list)
{
Iterator<Integer>productw = list.iterator();
int result = 1;
for( int i=0; i<productw.size(); ++i ) {
result *= productw.get(i) ;
}
// result has the answer
}
Edit 1:
The above loop assumes that the list has at least 1 element. If list has no elements, then zero must be the answer which I assume you can easily program it.
You need to define an initial value for the product
And then change it in the loop
Also...Your loop will print the statement multiple times- you don't want that- right ?
HTH

Categories

Resources