I am having trouble comparing my dictionary file to the anagrams. I put a print statement at each and it is reading in the dictionary file correctly and it is also calculating all of the anagrams correctly But it won't calculate only the anagrams from the dictionary file. I'm pretty sure it's something very minor and if someone can fix it it would greatly be appreciated.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Anagram3
{
static int size;
static int count;
static char[] charArray;
static char[] words;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("Type the path of the dictionary to read from : ");
String fileName = sc.nextLine();
List<String> dictionary = new ArrayList<String>();
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(fileName));
String word;
while((word = br.readLine())!=null)
{
dictionary.add(word);
}
}
catch(IOException e)
{
e.printStackTrace();
}
String[] words = new String[dictionary.size()];
dictionary.toArray(words);
//for( int i = 0; i < words.length; i++ )
// System.out.println(words[i]);
System.out.println("\nEnter the phrase to scramble: ");
String input = sc.nextLine();
System.out.println();
size = input.length();
count = 0;
charArray = new char[size];
for (int j = 0; j < size; j++)
charArray[j] = input.charAt(j);
doAnagram(size);
}
public static void doAnagram(int newSize)
{
int limit;
if (newSize == 1) // if too small, return;
return;
// for each position,
for (int i = 0; i < newSize; i++) {
doAnagram(newSize - 1); // anagram remaining
if (newSize == 2) // if innermost,
printAnagrams();
rotate(newSize); // rotate word
}
}
public static void rotate(int newSize)
{
int i;
int position = size - newSize;
char temp = charArray[position];
for (i = position + 1; i < size; i++)
charArray[i - 1] = charArray[i];
charArray[i - 1] = temp;
}
public static void printAnagrams()
{
for (int i = 0; i < size; i++)
{
//System.out.print(charArray[i]);
if(charArray[i] == words[i])
{
System.out.print(charArray[i]);
}
}
System.out.println();
}
}
Your static variable words is not being used because you define a new String[] words before the assignment.
Use the equals method to compare Strings. 1
Another issue is that you're comparing the i'th anagram generated to the i'th element in your dictionary, when you actually (presumably) want to test if the i'th anagram is present in the dictionary at any position.
You can try using a HashSet h of strings, rather than the array, for the dictionary, and then check for validity of an anagram with h.contains(...).
Related
So basically I'm suppose to take the numbers from a file Ex.
And turn it into this Ex.
We're suppose to make a graph class and store a adjacency list representation of a graph. We're also suppose to do it with an array of arraylists. So I got some help making the graph class and I'm making it so that the users file is processed through the graph class but for some reason there's an error and the output isn't right. Can someone help with this?
Graph Class
import java.util.ArrayList;
public class Graph {
ArrayList<Integer> [] nodes;
int n_nodes;
public Graph(int numberNodes){
this.nodes = new ArrayList[numberNodes+1];
this.n_nodes = numberNodes;
for(int i = 0; i < n_nodes + 1; i++){
nodes[i] = new ArrayList<>();
}
}
public void addNeighbor(int node, int neighbor){
nodes[node].add(neighbor);
}
public String toString(){
StringBuilder myGraph = new StringBuilder();
for(int i = 1; i < nodes.length; i++){
myGraph.append(i);
ArrayList<Integer> neighbors = nodes[i];
int totalNeighbors = neighbors.size();
for(int j = 0; j < totalNeighbors; j++){
int myneighbor = neighbors.get(j);
myGraph.append(" -> " + myneighbor);
}
myGraph.append('\n');
}
return myGraph.toString();
}}
Main Class
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws IOException {
File file = null;
JFileChooser chooser = new JFileChooser();
Scanner ans = new Scanner(System.in);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "No File Selected");
System.exit(1);
}
Scanner input = new Scanner(file);
int y = input.nextInt();
int x = 0;
Graph graph = new Graph(y);
while (input.hasNextLine()) {
for (int i = 0; i < y; i++) {
x = input.nextInt();
graph.addNeighbor(i, x);
}
System.out.println(graph.toString());
}
}}
Also I'm new to the whole stackoverflow website so sorry if my wording isn't clear or my code isn't formatted good enough.
Edit
This is the error it's showing
As 3 as read by
int y = input.nextInt();
is on a different line then you need to read the CR-LF as well.
Personally I would use the following paradigm
str = input.nextLine ()
// convert to int
while (input.hasNextLine) {
str = input.nextLine ()
arr[] = str.split (" ");
// loop through length of arr - in your code `y` is not updated
add arr[x] to graph
so basically you want something like
Scanner input = new Scanner(file);
String line = input.nextLine();
int y = 0;
if (line != null) {
y = Integer.parseInt(line.trim());
}
Graph graph = new Graph(y);
while (input.hasNextLine() && y > 0) {
if (input.hasNextLine()) {
line = input.nextLine();
}
String nums[] = line.split(" ");
for (int i = 0; i < nums.length; i++) {
int x = Integer.parseInt(nums[i]);
graph.addNeighbor(i, x);
}
System.out.println(graph.toString());
}
I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String[] args) {
String s="aabcddkkbghff";
String[] cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String[] args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int[] count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String [] str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"\t"+count);
}
}
public static void main(String [] args) {
uniqueValue(input);
}
Step1: To find the unique characters in a string, I have first taken the string from user.
Step2: Converted the input string to charArray using built in function in java.
Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters.
Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times).
Step5 : Now set2 will have only unique characters. Hence, just print that set2.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
char arr[] = str.toCharArray();
HashSet<Character> set1=new HashSet<Character>();
HashSet<Character> set2=new HashSet<Character>();
for(char i:arr)
{
if(set1.contains(i))
{
set1.add(i);
set2.remove(i);
}
else
{
set1.add(i);
set2.add(i);
}
}
System.out.println(set2);
}
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char[] array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean[] uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
public class UniqueCharactersInString {
public static void main(String []args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int[] repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string. In the second line I am looking for characters repetitive once.
how about this :)
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
package extra;
public class TempClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
char[] myCharArray=abcString.toCharArray();
TempClass mClass=new TempClass();
mClass.countUnique(myCharArray);
mClass.countEach(myCharArray);
}
/**
* This is the program to find unique characters in array.
* #add This is nice.
* */
public void countUnique(char[] myCharArray) {
int arrayLength=myCharArray.length;
System.out.println("Array Length is: "+arrayLength);
char[] uniqueValues=new char[myCharArray.length];
int uniqueValueIndex=0;
int count=0;
for(int i=0;i<arrayLength;i++) {
for(int j=0;j<arrayLength;j++) {
if (myCharArray[i]==myCharArray[j] && i!=j) {
count=count+1;
}
}
if (count==0) {
uniqueValues[uniqueValueIndex]=myCharArray[i];
uniqueValueIndex=uniqueValueIndex+1;
count=0;
}
count=0;
}
for(char a:uniqueValues) {
System.out.println(a);
}
}
/**
* This is the program to find count each characters in array.
* #add This is nice.
* */
public void countEach(char[] myCharArray) {
}
}
Here str will be your string to find the unique characters.
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
for(let j= 0; j< str.length; j++) {
if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
uniqueChars += str[i];
}
}
}
return uniqueChars;
}
public static void main(String[] args) {
String s = "aaabcdd";
char a[] = s.toCharArray();
List duplicates = new ArrayList();
List uniqueElements = new ArrayList();
for (int i = 0; i < a.length; i++) {
uniqueElements.add(a[i]);
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
duplicates.add(a[i]);
break;
}
}
}
uniqueElements.removeAll(duplicates);
System.out.println(uniqueElements);
System.out.println("First Unique : "+uniqueElements.get(0));
}
Output :
[b, c]
First Unique : b
import java.util.*;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
for(int i=0;i<test.length();i++){
if(test.lastIndexOf(test.charAt(i))!=i)
test=test.replaceAll(String.valueOf(test.charAt(i)),"");
}
System.out.println(test);
}
}
public class Program02
{
public static void main(String[] args)
{
String inputString = "abhilasha";
for (int i = 0; i < inputString.length(); i++)
{
for (int j = i + 1; j < inputString.length(); j++)
{
if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
{
inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
}
}
}
System.out.println(inputString);
}
}
So I'm new to programming and we have to do this lab where we read from a text file that has only one line with numbers. We then have to put those integers into an array. I know how to read the numbers when they are in separate lines but not when they are in one line. I also know how to put numbers into an array, so I don't need help with that.
The only methods we are allowed to use are:
hasMoreTokens()
hasMoreLines()
readDouble()
readInt()
readLine()
readToken()
Is there a way to do such while using only these methods?
Here is the code:
import chn.util.FileInput;
import chn.util.FileOutput;
public class Compact {
public Compact (FileInput inFile, FileOutput outFile){
int[] compactArray = new int [21];
int numZeroes = 0;
int num;
int length = compactArray.length;
for (int i = 0; i < length; i++) { //making the array for the integers in the list
compactArray[i] = 0;
}
while (inFile.hasMoreLines()) {
num = 0;
num = inFile.readInt(); //reads the integers per line
compactArray[num]++;
}
for(int i = 0; i < length; i++) {
if(compactArray[i] == 0) {
length--;
for(int j = i; j < length; j++) {
compactArray[j] = compactArray[j+1];
}
i--; // Decrement i to check the value that was shifted
} else {
numZeroes++;
}
}
// now print the array without 0
for(int i = 0; i < numZeroes; i++) {
outFile.print(" " + compactArray[i]);
}
outFile.close();
}
For some reason it's simply returning a string of zeroes. I was thinking it may have to do with the way I read the code.
Input: numbers_line.txt which has one line:
1 8 3 43 4 56
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public class ReadIntFromFile {
public static void main(String []args){
String fileName = "numbers_line.txt";
List<String> numbersArrayList = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
numbersArrayList = Arrays.asList(line.split(" "));
}
} catch (IOException e) {
e.printStackTrace();
}
String[] numbersStringArray = new String[numbersArrayList.size()];
numbersStringArray = numbersArrayList.toArray(numbersStringArray);
int[] numbersIntArray = new int[numbersStringArray.length];
for(int i = 0;i < numbersStringArray.length;i++) {
numbersIntArray[i] = Integer.parseInt(numbersStringArray[i]);
}
for(int x : numbersIntArray)
System.out.println(x);
}
}
Output:
1
8
3
43
4
56
I am trying to create a dictionary out of a .txt file.The problem I think is in my addToDict method. I am trying to resize th array when its full because I am reading from a text file of unknown size but I can only use arrays. I get an out of bounds exception when I am printing the array. I have no idea whats wrong and I have been working on the project for days now. I am also having trouble with my else statement in my addToDict method. It is also and out of bounds exception
import java.io.*;
import java.util.Scanner;
import java.util.regex.*;
public class BuildDict {
static String dict[] = new String[20];
static int index = 0;
public static void main(String args[]) {
readIn();
}
public static void readIn() {
File inFile = new File("alice.txt");
try {
Scanner scan = new Scanner(inFile);
while (scan.hasNext()) {
String word = scan.next();
if (!Character.isUpperCase(word.charAt(0))) {
checkRegex(word);
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error");
}
}
public static void addToDict(String word) {
if (index == dict.length) {
String newAr[] = new String[index * 2];
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
dict = newAr;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
} else {
dict[index] = word;
index++;
}
}
public static void checkRegex(String word) {
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if (!regexMatcher.find()) {
addToDict(word);
}
}
}
You haven't assigned the new array to dict.
if (index == dict.length) {
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
// Assign dict to the new array.
dict = newAr;
} else {
dict[index] = word;
index++;
}
The value of index is 0 when the following statement is executed.
String newAr[] = new String[index*2];
Try revisiting your logic. index should be given a positive value before this method is called. That's why you are getting OutOfBounds.
EDIT: Did you mean to write index+2?
You have
static int index = 0;
You need to change the value of this variable, based on your file, otherwise you will always have an error in this line
String newAr[] = new String[index*2];
Instead of using a array use a arraylist for when you don't know the size of your array. It will save you a lot of trouble. I find they are much easier to work with in general then normal arrays.
ArrayList<String> dict = new ArrayList<>();
dict.add(word);
//displaying values
for( int i = 0; i < dict.size(); i++ ){
System.out.println(dict.get(i));
}
This is the text file:
1,2,8,4,5,6,7,7,
3,4,5,6,7,8,
5,6,7,8,9,9,
1,2,3,4,5,8,9,0
After ignoring the 1st column:
2,8,4,5,6,7,7,
4,5,6,7,8,
6,7,8,9,9,
2,3,4,5,8,9,0
I want to sort the array in descending order but I can't get it to work. This is the code that I have done so far:
Scanner scanner = new Scanner(new File("test.txt"));
int row = 0;
int col = 0;
while (scanner.hasNextLine())
{
String currentline = scanner.nextLine();
row++;
String[] items = currentline.split(",");
int[] intitems = new int[items.length];
for (int i = 1; i < items.length; i++)
{
intitems[i] = Integer.parseInt(items[i]);
System.out.print(intitems[i] + " ");
int temp = 0;
for (int j = 2; j < (items.length - i); j++)
{
temp = intitems[j - 1];
intitems[j - 1] = intitems[j];
intitems[j] = temp;
}
col = i;
}
col++;
System.out.println();
System.out.println("After sort: " + intitems);
System.out.println();
}
System.out.println("Row: " +row);
No need to complicate things:
for (int i = 1; i < items.length; i++) {
intitems[i - 1] = Integer.parseInt(items[i]);
}
Arrays.sort(intitems); // Ascending
Arrays.sort(intitems, Collections.reverseOrder()); // Descending
But if you really want to use a loop to sort the array (bubblesort) you need to compare the items you switch:
for (int i = 0; i < intitems.length - 1; i++) {
for(int j = i + 1; j < intitems.length; j++) {
if (intitems[i] > intitems[j]) {
int temp = intitems[j];
intitems[j] = intitems[i];
intitems[i] = temp;
}
}
}
If you want it sorted in descending order then just change the greater than (>) comparison to a lesser than (<) comparison:
if (intitems[i] < intitems[j]) {
private static void sortInDescending(int[] arrayObj)
{
int n = arrayObj.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arrayObj[j-1] < arrayObj[j])
{
temp = arrayObj[j-1];
arrayObj[j-1] = arrayObj[j];
arrayObj[j] = temp;
}
}
}
}
Call method
sortInDescending(arrayinput);
You can use the Arrays.sort() with a custom comparator to make it descending.
String[] items = currentLine.split(",");
Integer[] intItems = new Integer[items.length];
for(int i=0; i<intItems.length; ++i) {
intItems[i] = Integer.parseInt(items[i]);
}
Comparator<Integer> comparator = new Comparator<Integer>() {
#Override
public int compare(Integer left, Integer right) {
return -Integer.compare(left, right);
}
};
Arrays.sort(intItems, comparator);
System.out.println(Arrays.toString(intItems));
}
Or you can sort the array in ascending order and reverse the array.
Arrays.sort(intItems);
Integer[] descending = new Integer[intItems.length];
int length = descending.length;
for(int i=0; i<length; ++i) {
descending[i] = intItems[length - 1 - i];
}
System.out.println(Arrays.toString(descending));
Other answers contain the bubble sort algorithm, where one element is compared to its successor. If the sort condition matches, then they get swapped. A slightly faster solution is insertion sort: in essence, it finds the maximal (minimal) value of the array and puts it to the front. There the implementation could look like this:
static int[] array = {2,8,4,5,6,7,7,};
public static void insertionSort(final int[] array) {
for(int i = 0; i < array.length; i++){
int maxValueIndex = findMaxValue(array, i);
int temp = array[i];
array[i] = array[maxValueIndex];
array[maxValueIndex]=temp;
}
}
private static int findMaxValue(final int[] array, int index) {
int value = Integer.MIN_VALUE;
for (int i = index; i < array.length; i++) {
if (array[i] > value) {
value = array[i];
index = i;
}
}
return index;
}
public static void main(final String[] args){
insertionSort(array);
System.out.println(Arrays.toString(array));
}
There you go :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortTXT {
static File fout;
public static void main(String[] args) {
fout = new File("text.txt");
if (!fout.isFile())
{
System.out.println("text.txt - Parameter is not an existing file");
}
else
{
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(fout)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = null;
try {
while ((line = br.readLine()) != null) {
if (line.length()>2)
{
line.trim();
// crete an array from the line - seperate by ","
List<String> list = new ArrayList<String>(Arrays.asList(line.split(",")));
// remove the 1st number
list.remove(0);
//sorting the list
Collections.sort(list);
System.out.println();
System.out.println("After sort: ");
// print out the sorted array
for(String temp: list){
System.out.print("," + temp);
}
}
}
} catch (IOException e) {
}
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Hope This Helps :)
Dave.