I have to sort strings in an array for a school project. Our teacher won't allow us to use array,sort().
i have to use 2 sort methods but they aren't working too well.
The first one returns double of each value. ie John, jack, adam, tom will return adam,adam,jack,jack,john,john,tom,tom.
public static void sort() {
inputFileNames();//inputs list of names from a file.
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (stArr[i].compareTo(stArr[j])>0) {
temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
}
}
}
display("The names are: ");// method to display array
System.out.println("");
}
the second sort doesn' run:
public static void bubbleSort() {
inputFileNames();
for (int i = size - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (stArr[j].compareTo(stArr[j+1])>0) {
temp = stArr[j];
stArr[j] = stArr[j + 1];
stArr[j + 1] = temp;
}
}
}
display("The names are: ");
System.out.println("");
}
input and display:
static void display(String heading) {
System.out.println(heading + "\n");
for (int i = 0; i < size; i++) {
System.out.println(stArr[i]);
}
}
static void inputFileNames() {
try {
Scanner scFile = new Scanner(new File("Names.txt"));
while (scFile.hasNext()) {
stArr[size] = scFile.nextLine();
size++;
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
}
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{ Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
String[] stArr = new String[n];
for(i=0;i<n;i++)
{
stArr[i]=sc.next();
// System.out.println(stArr[i]);
}
//inputs list of names from a file.
for (i = 0; i < n ; i++) {
for (j = i+1 ; j < n; j++) {
if (stArr[i].compareTo(stArr[j])>0)
{
String temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
// System.out.println(stArr[i]);
// System.out.println(stArr[j]);
}
}
}
for(i=0;i<n;i++)
{
System.out.println(stArr[i]);
}
// your code goes here
}
}
This Is the answer for first code. I am not good in file handling so you have to use your input method. I know Scanner thats why i have used here.
In Your Second Example Your j loop is wrong it should be for ( j = 0; j <= i-1; j++). And Please Mark It as answer if your problem is solved
Related
So i am currently workin on my homework and cant seem to get the .csv file into a 2D-array. The thing is that we have to use the Scanner and the .split() method, no workarounds. currently it seems to only load second to last line into the whole array.
The .csv file looks like this:
8;2;0;1;4;5;7;6;9
9;0;4;2;6;7;3;0;8
7;6;0;3;8;9;4;5;2
1;0;0;7;9;0;5;4;0
5;0;6;4;2;0;0;3;7
0;0;9;5;3;6;8;2;1
3;9;7;6;1;4;0;8;0
0;0;8;9;5;2;0;7;3
2;0;5;0;0;3;6;0;4
so the problem would be in the while-loop in "readArrayFromFile", everything else has been predetermined.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class array2D{
private static int[][] readArrayFromFile(String filename) {
int[][] array = new int[9][9];
try {
Scanner myFileReader = new Scanner(new File(filename));
while (myFileReader.hasNextLine()) {
String line = myFileReader.nextLine();
String[] tokens = line.split(";");
for (int i = 0; i < tokens.length; i++) {
for (int j = 0; j < tokens.length; j++) {
if (myFileReader.hasNext()) {
array[i][j] = Integer.parseInt(tokens[j]);
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
return array;
}
private static void printArray(int[][] inputArray) {
for (int y = 0; y < inputArray.length; y++) {
for (int x = 0; x < inputArray[y].length; x++) {
System.out.print(inputArray[y][x] + "\t");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
String filename = "./src/sudoku1.csv";
int[][] sudokuField = readArrayFromFile(filename);
printArray(sudokuField);
}
}
You don't need 2 loops in while loop, here is the solution.
public class array2D
{
private static int[][] readArrayFromFile(String filename)
{
int[][] array = new int[9][9];
try
{
Scanner myFileReader = new Scanner(new File(filename));
int i = 0;
while (myFileReader.hasNextLine())
{
String line = myFileReader.nextLine();
String[] tokens = line.split(";");
for (int j = 0; j < tokens.length; j++)
{
array[i][j] = Integer.parseInt(tokens[j]);
}
i++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
return array;
}
private static void printArray(int[][] inputArray)
{
for (int y = 0; y < inputArray.length; y++)
{
for (int x = 0; x < inputArray[y].length; x++)
{
System.out.print(inputArray[y][x] + "\t");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args)
{
String filename = "./src/test.csv";
int[][] sudokuField = readArrayFromFile(filename);
printArray(sudokuField);
}
}
From my understanding, your problem is with the nested for loops. Your current code is going to fill the whole 2d array with the last line. My fix would be to place a counter inside the while loop, get rid of one of the for loops, and then it should work. I hope that makes sense
Don't be afraid of using more than one Scanner at once:
private static int[][] readArrayFromFile(String filename) {
int[][] array = new int[9][9];
int rowNum = 0;
try (Scanner myFileReader = new Scanner(new File(filename))) {
while (myFileReader.hasNextLine()) {
String line = myFileReader.nextLine();
Scanner sRow = new Scanner(line);
sRow.useDelimiter(";");
int colNum = 0;
while (sRow.hasNextInt()) {
array[rowNum][colNum++] = sRow.nextInt();
}
rowNum++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return array;
}
i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}
Link to this problem:
https://www.hackerrank.com/contests/takneek/challenges/maximum-length-substring/problem
The code passes the initial test case but then times out when I go to submit on hacker rank for much larger strings. I have a feeling it's the algorithm I'm using for the unique substrings, how do I cut down this time into something efficient?
My code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<Integer> kList = new LinkedList<Integer>();
LinkedList<String> setout = new LinkedList<String>();
LinkedList<String> setLex = new LinkedList<String>();
//Get the original text
String text = in.nextLine();
//Get n from the file
int n = in.nextInt();
//Get the next needed items for comparison and order
for (int i = 0; i < n; i++) {
kList.add(in.nextInt());
}
setout = getAllUniqueSubset(text);
setLex = sortLexographically(setout);
int findMax = findMaximumSub(setLex, kList, 0);
// System.out.println(setLex);
System.out.println(findMax);
}
//Get the unique subset to begin with and return it
public static LinkedList<String> getAllUniqueSubset(String text) {
LinkedList<String> set = new LinkedList<String>();
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < text.length() - i; j++) {
String elem =text.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
public static LinkedList<String> sortLexographically(LinkedList<String> setout){
for(int i = 0; i < setout.size()-1; ++i) {
for (int j = i + 1; j < setout.size(); ++j) {
if (setout.get(i).compareTo(setout.get(j)) > 0) {
String testLex = setout.get(i);
setout.set(i, setout.get(j));
setout.set(j, testLex);
}
}
}
return setout;
}
public static int findMaximumSub(LinkedList<String> setLex, LinkedList<Integer> kList, int maxCheck){
for (int i = 0; i < kList.size()-1; i++) {
if (maxCheck < setLex.get(kList.get(i)).length()) {
maxCheck = setLex.get(kList.get(i)).length();
}
}
return maxCheck;
}
}
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.
I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}