This question already has answers here:
Sort an array in Java
(19 answers)
Closed 9 years ago.
Im trying to organize random numbers in an array from least to greatest.
I came up with a loop which I thought should work but has a lot of logic errors.
for(int z=0; z<=999;z++){
for(w=1; w<=999;w++){
if(z<w){
if(numberArray[z]<numberArray[w])
temp=numberArray[w];
}
}
numberArray[z]=temp;
}
Can anyone tell me how to fix this or an algorithm of their own for doing this?
There are several ways you can sort an array in Java. Here I post but 3 of them : the core library, and 2 algorithms you can make on your own.
1 ) Core one: This is literally only one line of code. I would suggest using this - simple, and very efficient, compared to the below two solutions.
Arrays.sort(myArray);
2 ) Selection Sort : Find the lowest value in an array, move it to the first position, find the next lowest, move to 2nd position, etc.
public void selectionSort(Comparable[] a)
{
for(int index = 0; index < a.length; index++)
{
// find the smallest one in the array from index : end
int smallest = indexOfMin(a, index);
// swap the value at index and the value at the smallest one found
Comparable temp = a[smallest];
a[smallest] = a[index];
display.update();
a[index] = temp;
}
}
3 ) Insertion Sort : Inserts each element in the array into a growing sequence of sorted values and finishes at the end of the array.
public void insertionSort(Comparable[] a)
{
for(int i = 1; i < a.length; i++)
{
insert(a, i);
}
}
public void insert(Comparable[] a, int nextIndex)
{
int index = 0;
Comparable finalObject = a[nextIndex];
// Let us first find the first occurence of a comparable greater than our comparable
while(finalObject.compareTo(a[index]) > 0)
index++;
for(int i = (nextIndex-1); i >= index; i--)
a[i+1] = a[i];
a[index] = finalObject;
}
One liner:
Arrays.sort(numberArray);
Or greatest to least order:
Arrays.sort(numberArray, Collections.reverseOrder());
Or even better, use a Binary Search Tree that keeps its contents in sorted order, this is great for collections that are pretty dynamic, as the add operation is cheaper memory wise and time wise than a full in-place sort:
TreeSet<int> set = new TreeSet<int>();
set.add(10);
set.add(4);
set.add(11);
set.toString();
// prints 4, 10, 11
Arrays.sort() is a quick and easy way.
Also consider PriorityQueues if you need something a little more robust!
This link is another question on SO with a great answer.
Related
This question already has an answer here:
Finding all the number combos in array that add up to input number
(1 answer)
Closed 6 years ago.
I'm currently working on the following question from a interviewing book:
You are given a random array of 50 unique integers ranging from 1 to 100 inclusive. Write a method using Java that takes in a positive integer as a parameter and returns an array of all the number combinations that add up to that value.
For example, given an array of integers [3,6,1,9,2,5,12] and being passed the integer value 9, you would return [[3,6],[6,1,2],[9],[3,1,5]]. Order of returning the results in the array does not matter, though you should return unique sets (ie. [6,3] and [3,6] are the same and only one should be returned). Also, the individual results should be in the order they are found (ie [6,1,2] should be returned, not [1,2,6]).
I've made decent progress on it, but I fear I may solving this the wrong way.
import java.util.*;
public class findCombinations {
public static void main(String[] args) {
int number;
int[] list = new int[10];
Scanner reader = new Scanner(System.in);
//fill the array
for (int i = 0; i < list.length; i++) {
number = (int)(Math.random() * 10) + 1;
list[i] = number;
for (int j = 0; j < i; j++) { //remove duplicates
if (list[i] == list[j]) {
i--;
break;
}
}
}
Arrays.sort(list);
//test output
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
System.out.println("Enter a number: ");
int input = reader.nextInt();
ArrayList<Integer> trimmedList = new ArrayList<Integer>();
//cut out the numbers that are impossible to use
for (int i = 0; i < list.length; i++) {
if (list[i] <= input) {
trimmedList.add(list[i]);
}
}
//test output
printList(trimmedList);
ArrayList<Integer> comboList = new ArrayList<Integer>();
System.out.println("Finding combinations...");
for (int i = 0; i < trimmedList.size(); i++) {
int current = trimmedList.get(i);
if (current == input) { System.out.println(current); }
else if (current < input) {
comboList.add(current);
if (isCombo(comboList, input)) {
printList(comboList);
}
else { continue; }
}
else { continue; }
}
}
public static boolean isCombo(ArrayList<Integer> list, int input) {
ArrayList<Integer> combo = new ArrayList<Integer>();
int sum = 0;
for (int i : list)
sum += i;
if (sum == input) { return true; }
else { return false; }
}
public static void printList(ArrayList<Integer> list) {
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
}
}
I know this is incomplete but I wanted to ask if anyone had any suggestions or improvements I could make on this? I sorted my list and trimmed out all the integers that won't possibly be used, but now the hard part is finding all the combos.
There are many different approaches to solve this problem, each with their own merits, so I wouldn't worry too much about whether your answer is the 'right' one or not...so long as it actually solves the problem! Also, an interviewer will likely be more interested in your thought-process, and the strategies you use, rather than a 100% perfect solution written in the span of a few minutes on a whiteboard.
Here's a couple of things to consider:
As you noticed, you can immediately eliminate any integers larger than your target value.
You're essentially generating arbitrarily-sized subsets of your starting array—so Set is likely the most useful data type to work with. {2, 3} and {3, 2} should be seen as identical when you're generating your response set.
Integer partitioning is an NP-Complete problem. It's hard. I think you've taken the correct approach of starting with the array, rather than with the target value.
There are many algorithms for generating combinations of integers from a larger set. Check out this SO answer for a few of them. You can generate k sized combinations from your (already-filtered) starting set, for k from 1-50.
Actually...there are more direct ways to get the power set of your starting set. Consider the inherent structure of a power set (shown below). By enumerating a few examples, you'll notice a natural recurrence in your strategy for identifying the subsets.
As you're generating these combinations, discard any whose elements don't sum to your target value.
Image Source: https://en.wikipedia.org/wiki/Power_set
Since this is a learning exercise, you will benefit most if you can solve this for yourself. So ...
Hints:
Sorting the numbers first is on the right track
I would use recursion to iterate the solutions. Given a partial sum, only numbers less than a certain number are possible candidates to be added to the sum ...
Work out the algorithm in your head >before< you start coding it.
And I agree with what #nbrooks says on the topic of what the interviewers are looking for. You need to be able to think ... and explain your thinking to the interviewer ... at the algorithmic level. That is what will distinguish the excellent candidates from the ordinary ones.
I realize generating your array of random numbers is not part of the problem statement, but I think your difficulties begin here.
First of all, use a Set<Integer> type collection to collect your generated numbers; break when the set reaches the desired size. If generated order is important, use a LinkedHashSet.
Set<Integer> origSet = new HashSet<Integer>(); // fill with random numbers
At some point, you have a list of numbers for which the order matters. Maintain this list as a List<Integer>. The list preserves the order of your original list so that you can produce the number combinations in the right order (i.e., 6 precedes 1, 1 precedes 2).
List<Integer> origList = new ArrayList<Integer>(origSet); // use indexOf method to find index of a number
You create a second list that is sorted; this list is the one used by your recursion algorithm.
List<Integer> sortedList = new ArrayList<Integer>(origList); // sort this
You don't need to trim the list because a recursive algorithm will trim any branch with no feasible solution.
A recursive algorithm can generate the combos in fewer lines of code. Reordering takes a few more lines.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
list of integers with duplicates and integer N. Remove the duplicates from the list and find the N-th largest element in the modified list.
Implement at least two different solutions to find N-th largest element with O(N*log(N)) average time complexity in Big-O notation, where N is the number of elements in the list
The below is the solution i thought of is there any better way of implementing? Also, how do I implement two different solutions ?
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list= {5,3,8,2,5,7,6,7,3,7};
int n = 3;
System.out.println("Printing list before removing duplicates");
for (int i : list) {
System.out.println(i+" ");
}
for (int i = 0; i < list.length; i++) {
for (int j = i+1; j < list.length; j++) {
if (list[i] < list[j]) {
int swap = list[i];
list[i] = list[j];
list[j]=swap;
}
if (list[i] == list[j]) {
list[j] = 0;
}
}
}
System.out.println("Printing list after removing duplicates");
for (int i : list) {
System.out.println(i+" ");
}
System.out.println("the N-th largest element in the modified list is"+ list[n-1]);
}
For this sort of problem really you need to look at what language tools are provided to you and how to make use of them to do the hard work for you.
To remove duplicates just place them into a Set. To have them sorted use a TreeSet.
So you get:
Set<Integer> values = new TreeSet<Integer>();
That will sort them from smallest to largest, to reverse the order specify your own comparator for the TreeSet that just reverses the natural ordering.
Then iterate over the Set and the nth value returned from the iterator is your value.
Your current code looks mostly valid, it doesn't actually remove duplicates though - you need to actually remove things from the Array for that, which Arrays do not support without recreating them as they cannot be resized. Additionally it will get confused if you include 0s or negative numbers. For example the biggest number in (-3, -5, -6, -6) will come back as 0.
One line for each task if you start with a collection.
List<Integer> list = new ArrayList<Integer>(Arrays.asList(5,3,8,2,5,7,6,7,3,7));
To remove duplicates:
List<Integer> nodups = new ArrayList<Integer>(new HashSet<Integer>(list));
To find largest:
Integer largest = Collections.max(list);
Unless for some reason you're bound to using only primitives, Tim's answer solves the sorting problem. To implement multiple "solutions", just create two different functions which take the list of numbers and the value n as parameters:
public void firstSolution(int[] numbers, int n) {
// one implementation
}
public void secondSolution(int[] numbers, int n) {
// another implementation
}
Then simply make the appropriate function calls in main.
lets say i have this array
int [] array= new int[26];
it has 26 places because the position 0 is 'a' , position 1'b' ... position 25 is 'z'
so in each position i have an int number so
if in position array[0]=5 it means i have 5 'a'
if in position array[1]=6 it means i have 6'b'
if in position array[0]=0 it means that i do not have the 'a' letter
what i want is to find in each loop the 2 smallest frequencies and the letters of the two smallest frequencies
for(int i=0;i<array.length;i++)
if(array[i]==0)
continue;
else{
cmin1=(char)('a'+i);
posi=i;
min1=array[posi] ;
break;
}
for(int j=posi+1;j<array.length;j++){
if(array[j]==0)
continue;
else if(array[j]<=min1){
posj=posi;
posi=j;
cmin2=cmin1;
cmin1=(char)(j+'a');
min2=min1;
min1=array[j];
}
i have tried this which is wrong
Java is Object Oriented so...
Let's take a class, which name would be LetterFrequency
LetterFrequency has 2 attributes:
1) Char character
2) Integer occurrences
You need to sort the LetterFrequency objects by their "occurrences" atrribute. To do that, make LetterFrequancy implements Comparable and define method compareTo() accordingly.
Then put all your LetterFrequency objects in a List and use the method
Lists.sort(yourList)
Sort would work but it's not the best performing method.
How about a single loop which would be O(n)?
int min1 = Integer.MAX_INT;
int idx1 = -1;
int min2 = Integer.MAX_INT;
int idx2 = -1;
for(int i=0;i<array.length;i++) {
// skip empty items
if(array[i]==0)
continue;
if (array[i] < min1) {
min2 = min1;
idx2 = idx1;
min1 = array[i];
idx1 = i;
}
else if (array[i] < min2) {
min2 = array[i];
idx2 = i;
}
}
sort the array first...now apply the searching algorithm...and here you go
once you find the smallest element you can get the second smallest as the array is already sorted...i guess there would be no difficulty doing this...for sorting you can use quicksort with complexity(nlogn)...hope it helps you
I would create a class representing each frequency count. Then I would create a Comparator which orders the records by the frequency. Then I would use Arrays.sort() or Collections.sort() to sort the collection using the Comparator.
Alternatively, if you simply want to find the entries in the array but can't change your data type, then you need to define an algorithm for searching (not sorting) the array. To do this, and do it in one pass, I would define local variables for the positions and corresponding frequencies of the two least frequently occurring. Initialize the least to the first item in the array, then proceed by comparing the current one and if it is less then rotate the values of the variables which are keeping track. At the end you'll have the two least frequent.
If you just want to find the smallest element in an array, you can use the following code :
List<int> list = Arrays.asList(ArrayUtils.toObject(array));
// Print the smallest element of your array
System.out.println(Collections.min(list));
First of all, this array declaration will never work:
int [] array= new array[26];
You need:
int [] array= new int[26];
Heap - Sort Algorithm
The problem I am having is this, this algorithms n input is 2, this is designed so that the 1st position (int i) of the array and the 2nd position (int j) have their values compared.
The problem is that this ignores the 0 position of the given array list. I have tried reducing certain values, this will create infinite loops. The algorithm is an adaptation of pseudocode. It isn't designed to run arraylist from 0. I can't think of how to re-adapt this algorithm into a decent minimum heap sort.
public static void input( ArrayList<input> vertexList, int n )
{
int j=n;
int i=n/2;
input object = vertexList.get(n);
while ((i>0) && vertexList.get(i)> object){
vertexList.set(j, vertexList.get(i));
j = i;
i = i/2;
}
vertexList.set(j, object);
}
try to use vertexList.get(i-1) and vertexList.get(j-1) and vertexList.set(j-1, ...)
I wrote the following algorithm for finding all possible permutations of n unique alphabets.
Set<String> results = new HashSet<String>();
int size = 1;
//find the total permutations possible
for(int i=0;i<array.length;i++){
size*=(i+1);
}
// i is the number of items remaining to be shuffled.
while(results.size()<size){
for (int i = array.length; i > 1; i--) {
// Pick a random element to swap with the i-th element.
int j = rng.nextInt(i); // 0 <= j <= i-1 (0-based array)
// Swap array elements.
char tmp = array[j];
array[j] = array[i-1];
array[i-1] = tmp;
}
StringBuffer str = new StringBuffer();
for(int i=0;i<array.length;i++)
str.append(array[i]);
results.add(str.toString());
}
System.out.println(results);
1) Is there anything to be done to improve this algorithm?
2) What would be the time complexity of this algorithm?
PS: I apologize to the people who who reacted to my previous post. I'll try on my own before asking for help.
By utilizing a random shuffling, you're going to have a massive number of iterations that end up not actually putting a new item into the set - you should look for an approach that ensures that on each iteration a new item is placed into the set (by 'new' I simply mean a permutation that hasn't been seen previously).
I wouldn't like to guess at the time complexity of the algorithm supplied above - it's going to be big.
1) Is there anything to be done to improve this algorithm?
Yes. Just to give you some hints how you could generate the permutations deterministically:
imagine the lexicographic order of all permutations on N elements. Imagine, how could you generate the next permutation in that order given the previous
think about what would the set of permutations with a common prefix (eg. 435 126, 435 162 etc.) be and how could you use it in an algorithm.
The best way to generate permutations is to do so iteratively: finding a scheme to go from one permutation to the next until you've seen them all. Knuth has exposed such a scheme in one of the combinatorial fascicles of TAOCP, and without going into his assembly-like pseudo code, you might want to check these nifty C implementation of those algorithms. The algorithm you are looking for is the one that generates permutations.
The advantage of such an algorithm by opposition to (what I understand of) yours, is that it is deterministic and will generate a different permutation every single time.
Thank you for your inputs. I think I have got a better algorithm. Please provide comments
private static List<String> allPerms(char[] array) {
List<String> perms = new ArrayList<String>();
if(array.length<=1 )
perms.add(String.valueOf(array[0]));
else{
char[] newarray = Arrays.copyOf(array, array.length-1);
char lastChar = array[array.length-1];
List<String> soFar = allPerms(newarray);
for(int i=0; i<soFar.size(); i++) {
String curr = soFar.get(i);
for(int j=0;j<array.length;j++){
StringBuffer buff = new StringBuffer(curr);
perms.add(buff.insert(j, lastChar).toString());
}
}
}
return perms; }