Java backtraking problem - java

Hey guys. I've been strugling with a backtraking problem for hours. Can anyone lend me a hand? Here is the problem:
n camels numbered from 1 to n are the arranged order. I want to rearrange so that each camel has a diferent camel in front.
This is what I have so far:
import java.util.*;
public class NCamile{
static int size;
static int count;
static char[] arrN= new char[100];
public static void main(String[] args){
System.out.print("Enter word: ");
String numar = getInt();
size = numar.length();
count=0;
for(int i=0; i < size ; i++){
arrN[i] = numar.charAt(i);
}
backtraking(size);
}
public static void backtraking(int newsize){
if (newsize == 1){
return;
}
for(int i=0 ; i < newsize; i++){
backtraking(newsize - 1);
if(newsize == 2 ){
display();
}
rotate(newsize);
}
}
public static void rotate(int newsize){
int position = size - newsize;
for(int i = position + 1; i < newsize; i++){
char gigi;
gigi = arrN[i - 1];
arrN[i - 1] = arrN [i];
arrN[i] = gigi;
}
}
public static void display(){
if (count < 9){
System.out.print(" ");
}
System.out.print(++count+ ")" + " ");
for(int i = 0 ; i < size ; i++)
System.out.print(arrN[i]);
System.out.print(" ");
if(count % 10 == 0){
System.out.println(" ");
}
}
public static String getInt(){
Scanner scan = new Scanner(System.in);
String s = scan.next();
return s;
}
}
With this, the algorithems show me every posible solution to rearrange a string, but it dosen't respect the last condition of the problem. I've tried ading this:
for(int j = 0 ; j < size ; j++){
if (array[j] !=[array[j + 1] )
display()
}
But after I added it I got about 10 times more displayed words then it should have shown me
Can anyone give me an idea on what should I do?

If you're only asked to insure that
i) a single new arrangement is produced, and
ii)that new arrangement must satisfy the condition that each camel follows a camel different from the one it followed in the original arrangement,
then you can easily satisfy this just by reversing the list of camels.

Surely this is not optimized solution, but for simply gettin result I would consider checking all of the permutations. Method producing every permutation wouldn't be hard to write (see e.g. String permutation) and checking if some camel has the same backtraced won't be any effort at all.
--- edit
So... Few things mended, few not:
I worked on String, not char array. Char array is completely misunderstand in this problem. It's better to use String object (cause in fact, String is char array) or int array (this have been hard to me, cause I haven't found any permutation method to be applied with such parameter). So the main method looks now:
private static String word;
public static void main(String[] args)
{
System.out.print("Enter word: ");
Scanner scan = new Scanner(System.in);
word = scan.next();
permutation(word);
}
I deleted your class variables (length, count, etc...) cause they are unnecessary right now. Writing out String is quite simple and if you would like to change output format - use String.length property instead.
Permutation method is copied from mentioned source, and little modified. It looks following:
public static void permutation(String s)
{
permutation("", s);
}
private static void permutation(String prefix, String s)
{
int n = s.length();
if (n == 0)
{
if (camelFit(prefix))
System.out.println(prefix);
}
else
{
for (int i = 0; i < n; i++)
permutation(prefix + s.charAt(i),
s.substring(0, i) + s.substring(i + 1, n));
}
}
if you would uncomment line checking if (camelFit (prefix)) it would display every permutation of input String. But! We would like to print only these camel chains, which fits problem conditions. How do we check if given chain is so? Simple method:
private static boolean camelFit(String prefix)
{
for (int i = 0; i < word.length() - 1; i++)
{
char camel = word.charAt(i);
char camelFollow = word.charAt(i+1);
for (int j = 0; j < prefix.length() - 1; j++)
{
if (prefix.charAt(j)==camel && prefix.charAt(j+1)==camelFollow)
{
return false;
}
}
}
return true;
}
Maybe not so simple, because we have to check every pair of input chain (every follower and followed) with every pair of output chain. If there isn't any match between any two pairs - given chain is fine.
Please notice, that this solution is absolutely non-optimized. Finding permutations is O(n!) complexity and checking pairs is O(n^2) complexity. Final complexity is O(n^2)*O(n!) so very, very high.

Related

Vowel counter Java application: stuck in for loops? Doesn't seem to be an infinite loop

I made a java program to count the number of vowels in a string, and I need to use a, or multiple, for loop(s) to do it for a project. The problem is that it does not do anything, or just takes too long, after inputting the string:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a string to count the vowels>> ");
String x = s.nextLine();
int numVowels = countVowels(x, "aeiou");
System.out.println(numVowels);
}
static int countVowels(String x, String vowels)
{
int count = 0;
String z = x.toLowerCase();
for (int i = 0; i <= vowels.length() - 1; i++)
{
if (i == vowels.length() - 1)
{
for (int n = z.indexOf(vowels.substring(i)); n != -1; count++)
{
z.replace(vowels.substring(i), "");
}
}
else if (z.indexOf(vowels.substring(i, i + 1)) != -1)
{
for (int n = z.indexOf(vowels.substring(i, i + 1)); n != -1; count++)
{
z.replace(vowels.substring(i, i + 1), "");
}
}
}
return count;
}
}
I have reduced the number of loops, because the original was very confusing. I think the problem is with the nested loops, but I have not yet tried running this on a local compiler, only online IDEs. I've heard that it makes a world of difference for compile times.
It's an infinite loop: you're not doing anything with z if you use only z.replace. Since strings are immutable in Java, you can't change it by only calling a method, you must assign it again:
z = z.replace(...)
I took the liberty of using while-loop instead of for-loop since the idea is to keep looping till find, count and replace all the vowels one by one.
static int countVowels(String x, String vowels) {
int count = 0;
String z = x.toLowerCase();
for (int i = 0; i < vowels.length(); i++) {
String vowel = Character.toString(vowels.charAt(i));
while (z.indexOf(vowel) != -1) {
count++;
z = z.replaceFirst(vowel, "");
}
}
return count;
}

Adding gradually decreasing spaces in java with nested for loops in this java program, beginner question

currently trying to write this in java, but i cant seem to get the spaces and the colons correct with for loops.
|"""""""""|
\:::::::/
\:::::/
\:::/
\:/
/:\
/:::\
/:::::\
/:::::::\
|"""""""""|
^ the thing im trying to write
my code currently :
public class nested4loops {
public static void main(String[] args) {
timething();
}
public static void timething() {
System.out.println("|\"\"\"\"\"\"\"\"\"|");
for (int i = 0; i < 5; i++) {
for (int s = 0; s < i; s++) {
System.out.print(" ");
}
System.out.print("\\");
for (int b = 7; b > i; b--) {
System.out.print(":");
}
System.out.println();
}
}
}
Currently however, this code prints:
|"""""""""|
\:::::::
\::::::
\:::::
\::::
\:::
One way to do this, is to have 2 loops, one for the top part and one for the bottom part.
However, that means that the body of those loops are repeated, which violates the DRY principle (Don't Repeat Yourself).
That can of course be handled by moving the common logic to methods, e.g. like this:
public static void printHourGlass(int size) {
printEndRow(size);
for (int row = 1; row < size; row++)
printGlassRow(row, size, '\\', '/');
for (int row = size - 1; row > 0; row--)
printGlassRow(row, size, '/', '\\');
printEndRow(size);
}
private static void printEndRow(int size) {
System.out.println("|" + repeat('"', size * 2 - 1) + "|");
}
private static void printGlassRow(int row, int size, char left, char right) {
System.out.println(repeat(' ', row) + left + repeat(':', (size - row) * 2 - 1) + right);
}
private static String repeat(char ch, int count) {
char[] buf = new char[count];
Arrays.fill(buf, ch);
return new String(buf);
}
Tests
printHourGlass(3);
printHourGlass(5);
printHourGlass(9);
Outputs
|"""""|
\:::/
\:/
/:\
/:::\
|"""""|
|"""""""""|
\:::::::/
\:::::/
\:::/
\:/
/:\
/:::\
/:::::\
/:::::::\
|"""""""""|
|"""""""""""""""""|
\:::::::::::::::/
\:::::::::::::/
\:::::::::::/
\:::::::::/
\:::::::/
\:::::/
\:::/
\:/
/:\
/:::\
/:::::\
/:::::::\
/:::::::::\
/:::::::::::\
/:::::::::::::\
/:::::::::::::::\
|"""""""""""""""""|

One method policy in Java

I need some help. My professor give us an assignment that we need to "extract" these codes into ONE METHOD ONLY. Is there a way to do it? It's a heap code sorting algorithm. I'm currently do have a little knowledge about programming so bear with me guys. Can you help me?
import java.util.Arrays;
import java.util.Scanner;
class HeapSort {
private static Scanner sc;
public static void main(String args[]) {
sc = new Scanner(System.in);
System.out.println("Enter no of terms");
int n = sc.nextInt();
System.out.println("Enter the terms");
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println("The unsorted array is:");
System.out.println(Arrays.toString(arr));
heap(arr);
System.out.println("The sorted array is:");
System.out.println(Arrays.toString(arr));
}
static void heapify(int a[], int n, int i) {
int max, child;
child = 2 * i + 1;
max = i;
if (child < n)
if (a[child] > a[max])
max = child;
if (child + 1 < n)
if (a[child + 1] > a[max])
max = child + 1;
if (max != i) {
int temp = a[i];
a[i] = a[max];
a[max] = temp;
heapify(a, n, max);
}
}
static void buildheap(int a[]) {
for (int i = a.length / 2 - 1; i >= 0; i--)
heapify(a, a.length, i);
}
static void heap(int a[]) {
buildheap(a);
for (int i = a.length - 1; i >= 1; i--) {
int temp = a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
}
You get there by simply replacing each method invocation with the actual body of the method. Of course, that will quickly lead to all kinds of confusion, given the poor naming of method parameters.
But the real challenge here (and probably your actual homework) is that you have to rework that heapify() method to not use recursion. In other words: you have to do the heap sort without using recursion. You can find some guidance here for example.
And of course: this code is already hard to read. Forcing all code into a single method will make it unreadable and not human comprehensive. It is like the exact opposite of good practices!
One thing you can do is replace all the code in each method to where the method is being called.
For example, instead of calling heap(arr) you can move all the code up to the place where heap(arr) is being called and continue to do so with the rest of the code.

Algo: Find anagram of given string at a given index in lexicographically sorted order

Need to write an Algo to find Anagram of given string at a given index in lexicographically sorted order. For example:
Consider a String: ABC then all anagrams are in sorted order: ABC ACB
BAC BCA CAB CBA. So, for index 5 value is: CAB. Also, consider the case of duplicates like for AADFS anagram would be DFASA at index 32
To do this I have written Algo but I think there should be something less complex than this.
import java.util.*;
public class Anagram {
static class Word {
Character c;
int count;
Word(Character c, int count) {
this.c = c;
this.count = count;
}
}
public static void main(String[] args) {
System.out.println(findAnagram("aadfs", 32));
}
private static String findAnagram(String word, int index) {
// starting with 0 that's y.
index--;
char[] array = word.toCharArray();
List<Character> chars = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
chars.add(array[i]);
}
// Sort List
Collections.sort(chars);
// To maintain duplicates
List<Word> words = new ArrayList<>();
Character temp = chars.get(0);
int count = 1;
int total = chars.size();
for (int i = 1; i < chars.size(); i++) {
if (temp == chars.get(i)) {
count++;
} else {
words.add(new Word(temp, count));
count = 1;
temp = chars.get(i);
}
}
words.add(new Word(temp, count));
String anagram = "";
while (index > 0) {
Word selectedWord = null;
// find best index
int value = 0;
for (int i = 0; i < words.size(); i++) {
int com = combination(words, i, total);
if (index < value + com) {
index -= value;
if (words.get(i).count == 1) {
selectedWord = words.remove(i);
} else {
words.get(i).count--;
selectedWord = words.get(i);
}
break;
}
value += com;
}
anagram += selectedWord.c;
total--;
}
// put remaining in series
for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < words.get(i).count; j++) {
anagram += words.get(i).c;
}
}
return anagram;
}
private static int combination(List<Word> words, int index, int total) {
int value = permutation(total - 1);
for (int i = 0; i < words.size(); i++) {
if (i == index) {
int v = words.get(i).count - 1;
if (v > 0) {
value /= permutation(v);
}
} else {
value /= permutation(words.get(i).count);
}
}
return value;
}
private static int permutation(int i) {
if (i == 1) {
return 1;
}
return i * permutation(i - 1);
}
}
Can someone help me with less complex logic.
I write the following code to solve your problem.
I assume that the given String is sorted.
The permutations(String prefix, char[] word, ArrayList permutations_list) function generates all possible permutations of the given string without duplicates and store them in a list named permutations_list. Thus, the word: permutations_list.get(index -1) is the desired output.
For example, assume that someone gives us the word "aab".
We have to solve this problem recursively:
Problem 1: permutations("","aab").
That means that we have to solve the problem:
Problem 2: permutations("a","ab").
String "ab" has only two letters, therefore the possible permutations are "ab" and "ba". Hence, we store in permutations_list the words "aab" and "aba".
Problem 2 has been solved. Now we go back to problem 1.
We swap the first "a" and the second "a" and we realize that these letters are the same. So we skip this case(we avoid duplicates).
Next, we swap the first "a" and "b". Now, the problem 1 has changed and we want to solve the new one:
Problem 3: permutations("","baa").
The next step is to solve the following problem:
Problem 4: permutations("b","aa").
String "aa" has only two same letters, therefore there is one possible permutation "aa". Hence, we store in permutations_list the word "baa"
Problem 4 has been solved. Finally, we go back to problem 3 and problem 3 has been solved. The final permutations_list contains "aab", "aba" and "baa".
Hence, findAnagram("aab", 2) returns the word "aba".
import java.util.ArrayList;
import java.util.Arrays;
public class AnagramProblem {
public static void main(String args[]) {
System.out.println(findAnagram("aadfs",32));
}
public static String findAnagram(String word, int index) {
ArrayList<String> permutations_list = new ArrayList<String>();
permutations("",word.toCharArray(), permutations_list);
return permutations_list.get(index - 1);
}
public static void permutations(String prefix, char[] word, ArrayList<String> permutations_list) {
boolean duplicate = false;
if (word.length==2 && word[0]!=word[1]) {
String permutation1 = prefix + String.valueOf(word[0]) + String.valueOf(word[1]);
permutations_list.add(permutation1);
String permutation2 = prefix + String.valueOf(word[1]) + String.valueOf(word[0]);
permutations_list.add(permutation2);
return;
}
else if (word.length==2 && word[0]==word[1]) {
String permutation = prefix + String.valueOf(word[0]) + String.valueOf(word[1]);
permutations_list.add(permutation);
return;
}
for (int i=0; i < word.length; i++) {
if (!duplicate) {
permutations(prefix + word[0], new String(word).substring(1,word.length).toCharArray(), permutations_list);
}
if (i < word.length - 1) {
char temp = word[0];
word[0] = word[i+1];
word[i+1] = temp;
}
if (i < word.length - 1 && word[0]==word[i+1]) duplicate = true;
else duplicate = false;
}
}
}
I think your problem will become a lot simpler if you considerate generating the anagrams in alphabetical order, so you don't have to sort them afterwards.
The following code (from Generating all permutations of a given string) generates all permutations of a String. The order of these permutations are given by the initial order of the input String. If you sort the String beforehand, the anagrams will thus be added in sorted order.
to prevent duplicates, you can simply maintain a Set of Strings you have already added. If this Set does not contain the anagram you're about to add, then you can safely add it to the list of anagrams.
Here is the code for the solution i described. I hope you find it to be simpler than your solution.
public class Anagrams {
private List<String> sortedAnagrams;
private Set<String> handledStrings;
public static void main(String args[]) {
Anagrams anagrams = new Anagrams();
List<String> list = anagrams.permutations(sort("AASDF"));
System.out.println(list.get(31));
}
public List<String> permutations(String str) {
handledStrings = new HashSet<String>();
sortedAnagrams = new ArrayList<String>();
permutation("", str);
return sortedAnagrams;
}
private void permutation(String prefix, String str) {
int n = str.length();
if (n == 0){
if(! handledStrings.contains(prefix)){
//System.out.println(prefix);
sortedAnagrams.add(prefix);
handledStrings.add(prefix);
}
}
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
}
}
public static String sort(String str) {
char[] arr = str.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
}
If you create a "next permutation" method which alters an array to its next lexicographical permutation, then your base logic could be to just invoke that method n-1 times in a loop.
There's a nice description with code that can be found here. Here's both the basic pseudocode and an example in Java adapted from that page.
/*
1. Find largest index i such that array[i − 1] < array[i].
(If no such i exists, then this is already the last permutation.)
2. Find largest index j such that j ≥ i and array[j] > array[i − 1].
3. Swap array[j] and array[i − 1].
4. Reverse the suffix starting at array[i].
*/
boolean nextPermutation(char[] array) {
int i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i]) i--;
if (i <= 0) return false;
int j = array.length - 1;
while (array[j] <= array[i - 1]) j--;
char temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
return true;
}

Using Shellsort to sort a list of countries by population (Java)

In my program, I have a class Sorting, that inputs a file called CountryUnsortedFormat that contains a random list of countries and their populations. The class is supposed to use shellsort to sort the countries by population and display them on the screen.
Here is my code:
package assignment3;
import java.io.PrintWriter;
import java.io.File;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) throws Exception{
//Array for handling list of countries
String[] line = new String[238];
//read list of countries into array
readInArray(line);
//unsort the array
unSort(line);
}
static void readInArray(String[] line) throws Exception{
Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountrySortedFormat.txt"));
//Read in countries from sorted file into an array
int k=0;
while (stdIn.hasNextLine()){
line[k]=stdIn.nextLine();
k++;
}
}
static void unSort(String[] line) throws Exception{
PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");
//Pick a random int from 1 to 238 called where
//Write where into Unsorted Country Format file
//Make where null
//Repeat until all 238 countries are written in random order
int j = line.length-1;
Random r = new Random();
while (j > 0){
int where = r.nextInt(j)+1;
out.println(line[where]);
line = pop(where, line);
j--;
}
out.close();
}
static String[] pop(int index, String[] line){
String[] newLine = new String[line.length-1];
int offset = 0;
for (int i = 0; i<line.length; i++){
if(i == index){
offset = 1;
continue;
}
newLine[i - offset] = line[i];
}
return newLine;
}
}
class Sorting {
public static void main(String[] args) throws Exception{
//Array for handling list of countries
String[] line = new String[238];
readInArray(line);
shellsort(line);
System.out.println(Arrays.toString(line));
}
static void readInArray(String[] line) throws Exception{
Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt"));
//Read in countries from unsorted file into an array
int k=0;
while (stdIn.hasNextLine()){
line[k]=stdIn.nextLine();
k++;
}
}
static void shellsort(String[] line){
int j;
for(int gap = line.length-1/2; gap > 0; gap /= 2){
for(int i = gap; i < line.length-1; i++){
String tmp = line[i];
for (j = i; j >= gap && getPopulation(line, j-gap) > getPopulation(line, i); j -= gap){
line[j] = line[j -gap];
}
line[j] = tmp;
}
}
}
static int getPopulation(String[] line, int index){
String populationString = line[index].substring(50,65).trim().replaceAll(",","");
int population = Integer.parseInt(populationString);
return population;
}
}
My classes work separately but when put together my program doesn't print to the screen. All it shows is "BUILD SUCCESSFUL (total time: 0 seconds)"
What am I doing wrong?
This is pretty obviously a homework assignment, and it'd be wrong to help you further. I would first organize your code into a more readable format. Eg:
public class Country{
private int population;
public Country(String line){
// parse and set population
}
public int getPopulation(){
return population;
}
}
then implement the sort
# Sort an array countires[0...n-1].
# Start with the largest gap and work down to a gap of 1
int j;
for(int gap = countries.length/2; gap > 0; gap /= 2){
# Do a gapped insertion sort for this gap size.
# The first gap elements countries[0..gap-1] are already in gapped order
# keep adding one more element until the entire array is gap sorted
for(int i = gap; i < line.length; i++){
# add countries[i] to the elements that have been gap sorted
# save countries[i] in temp and make a hole at position i
int temp = countries[i].getPopulation();
# shift earlier gap-sorted elements up until the correct location for countries[i] is found
for (j = i; j >= gap && a[j - gap].getPopulation() > temp; j -= gap){
countries[j] = countries[j - gap]
}
# put temp (the original countries[i]) in its correct location
countries[j] = temp
}
}
Which is more or less ripped directly from Wikipedia, and what you have....
This looks like a case of needing better debugging. Drop some breakpoints or some printlns in populating line. There's a chance Netbeans isn't printing anything, because there is nothing to print out. Or you could simply be messing up your parsing. You have hard-coded values in there for your substrings and chances are that's where it's breaking. Using a regex or scanner could solve this problem, simply by not being an an unholy cluster of functions. I don't know what your input looks like so I couldn't tell you. However, I know your sort works because I copy and pasted with some random values and ran it myself:
class Sorting {
public static void main(String[] args) throws Exception{
int[] line = new int[]{97,95,66,91,33,91,73,63,67,84,40,34,85,43,73,8,45,14,86,23,74,22,50,33,4,75,12,28,44,43,20,69,95,28,8,44,5,21,50,53,83,53,93,4,62,45,24,57,41,30,32,21,44,76,42,85,35,36,20,96,95,35,5,49,21,43,29,97,69,15,40,15,82,73,24,30,53,50,73,2,86,25,35,50,83,15,66,80,36,22,46,34,89,18,15,59,99,85,12,65};
int j;
for(int gap = line.length/2; gap > 0; gap /= 2){
for(int i = gap; i < line.length; i++){
int population = line[i];
for (j = i; j >= gap && line[j - gap] > population; j -= gap){
line[j] = line[j -gap];
}
line[j] = population;
}
}
for (int l : line) {
System.out.println(l);
}
}
}
The lack of error log sounds like an environmental issue, or might comes down to what you unsorted file looks like, which is most likely wrong since I attempted to answer your previous question which you have since deleted
Traversing Through Array Using A Random Int and Unsorting a File
So the difficulty with your code as is that you will not end up with a shuffled array. Instead you will have probably duplicates. Let's run through this with an array of 4 lines = ["Argentina","Barbados","Canada","Dominica"]
Iteration 1. j = 4, let's have where = 2 and therefore out = "Canada"
Iteration 2. j = 3, there's nothing to stop where = 2 again as such, out = "Canada, Canada"
To properly scramble your array, I would recommend popping the chosen value To prevent duplicates. Given you are using a plain old array and not an ArrayList you should have a function pop (although I would suggest using an ArrayList):
// pop(2,["Argentina","Barbados","Canada","Dominica"]) == ["Argentina","Barbados","Dominica"]
function String[] pop(int index, String[] list){
newList = new String[list.length - 1]
int offset = 0;
for(int i; i < list.length; i++){
if(i == index){
offset = 1; // Start skipping
continue;
}
newList[i - offset] = list[i];
}
return newList;
}
Your new unSort should like:
public static void unSort(String[] line) throws Exception{
Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt"));
PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");
int j = line.length; // Opposed to hardcoding 238
Random r = new Random(); // Let's put random out so we don't have to continuously initialize
while (j > 0){
int where = r.nextInt(j);
out.println(line[where]);
line = pop(where, line); // get rid of what we just printed
j--;
}
out.close();
}
Of course there are other shuffles, for instance: you could perform a Fisher-Yates on line and then print it out after. I don't fully understand what you're directly asking for, but I imagine it's something like this:
public static void unSort(String[] line) throws Exception{
Scanner stdIn = new Scanner(new File("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt"));
PrintWriter out = new PrintWriter("C:/Users/Vicki/Desktop/CountryUnsortedFormat.txt");
int j = line.length; // Opposed to hardcoding 238
Random r = new Random(); // Let's put random out so we don't have to continuously initialize
while (j > 0){
int where = r.nextInt(line.length);
if(line[where] != null){
out.println(line[where]);
j--;
line[where] = null;
}
}
out.close();
}
Where this guarantees no duplicates. However this has a best case run time of O(n) and a worst case of being an infinite loop.

Categories

Resources