I need help understanding how to sort numbers.
Below is what I have I came up with so far and it didn't work. Can you please point out the mistake and tell me what to do?
I saw some of you guys using java.util.Arrays . Can you describe to me its functions?
import static java.lang.System.*;
import java.util.*;
public class Lab07v2_Task10{
public static void main (String[] args){
Scanner orcho = new Scanner (in);
int quantity = 5;
int[] myArray = new int [quantity];
out.println("Please enter 5 numbers");
for(int count = 0; count<myArray.length; count++){
myArray[count] = orcho.nextInt();
}
int maxSoFar = myArray[0];
for(int count = myArray.length-1; count>=0; count--){
if(myArray[count] > maxSoFar){
maxSoFar = myArray[count];
}
out.println(maxSoFar);
}
}
}
No solution.
The idea is to take several steps, do a for-loop. And assume that you are in the middle. The first part already is sorted, the rest is to-be-done.
Then tackle the current element with respect to what already is sorted.
int maxSoFar = myArray[0];
for (int i = 1; i < myArray.length; i++) {
// The array 0, ..., i-1 is sorted
if (myArray[i] >= maxSoFar) {
// Still sorted
maxSoFar = myArray[i];
} else {
// myArray[i] must be shifted left
...
}
// Now the array 0, ..., i is sorted
}
This is a general trick: assume part is already done, tackle one small step, and let continue.
The java.util.Arrays.sort(int[]) method sorts the specified array of int into ascending numerical order.
try this out..
// sorting array
java.util.Arrays.sort(myArray);
// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : myArray) {
System.out.println("Number = " + number);
}
}
Arrays.sort is a method which is a utility method available in java.util package.
Where Arrays is a system defined Utility class which contains the mehtod sort(int[]) takes int[] (array) as an argument and after sorting this array, It re-assign Array.
For more deep Info Here or Official Java Docs
The way your program runs right now: it will print 5 numbers and the number that it prints is the highest number it finds at that iteration.
The way that you want it to work: sort 5 numbers from lowest to highest. Then print these 5 numbers. This is an implementation of bubble sort in your program:
for(int i = 0; i< myArray.length; i++){
for(int j = 0; j < myArray.length-1; j++){
if(myArray[j] > myArray[j+1]){ //if the current number is less than the one next to it
int temp = myArray[j]; //save the current number
myArray[j] = myArray[j+1]; //put the one next to it in its spot
myArray[j+1] = temp; //put the current number in the next spot
}
}
}
it is probably the easiest sort to understand. Basically, for as many times as the length of your array, comb over the numbers and bring the next highest number as far up as it can go.
When it's done sorting you can then print the numbers.
Related
How can I make the values of an array the index of another array? I am trying to count the different integers that were entered. When I run the code, I am getting an index out of bounds message. Any thoughts?
import java.util.Scanner;
public class MatchineNums{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] arr = new int[4];
System.out.print("Enter 4 numbers: ");
for(int i = 0; i < arr.length; i++){
arr[i] = input.nextInt();
}
int[] count = new int[arr.length];
for(int i = count.length; i > -1; i--){
int value = arr[i];
count[value]++; //I think my problem is here but can't figure out why.
}
}
}
You're getting index out of bounds exception because you're out-of-bound.
You need to start your loop from count.length - 1, not from count.length.
for (int i = count.length - 1; i > -1; i--) {...}
How can I make the values of an array the index of another array?
You cannot make indices. You can create an array big enough to have all the indices you need. Just keep the maximum value of your inputs and then create an array this size. Then you have an array with all these indices.
A better way to handle this problem is to use a hashmap. The keys will be the inputs and the values will be the counter of each of them. This way is better than an array because you have a map entry for each different input and that's it. Using an array you'll end up having a really sparse array with many "holes".
I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.
Yes, this is homework, but I need some help with it. I have been able to make it sort through the highest number, but none of the numbers are correct after that. List of numbers: http://pastebin.com/Ss1WFGv1
Right now, we are learning arrays, so is this simply trying to shoot a fly with a cannonball?
package hw2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class HW2 {
public static ArrayList<Integer> nums1 = new ArrayList<Integer>();
public static int size = 0;
public static void main(String[] args) throws Exception {
ArrayList<Integer> sortedNums = new ArrayList<Integer>();
readFile();
System.out.println("Name: Jay Bhagat" + "\n" + "Email: xxxxxx");
size = nums1.size();
for(int l = 0; l<=10;l++){
nums1.set(sortThis(nums1, l), 90009);
System.out.println("\n\n");
}
// for (int k = 0; k <= size - 1; k++) {
// System.out.println("Number " + (k + 1) + sortedNums.get(k));
//
// }
}
public static void readFile() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("L:\\numbers.txt"));
while (reader.readLine() != null) {
nums1.add(Integer.parseInt((reader.readLine())));
}
reader.close();
}
public static int sortThis(ArrayList<Integer> current, int offset) {
int j = 0;
int tempNum = 0;
int curNum = 0;
int finalIndex = 0;
int prevIndex = 0;
int curIndex = 0;
for (j = 0; j < size-offset; j++) {
curIndex = j;
nums1.trimToSize();
curNum = current.get(j);
//Thread.sleep(1000);
if(curNum!=90009){
if (curNum > tempNum) {
tempNum = curNum;
System.out.println(tempNum);
prevIndex = j;
finalIndex = prevIndex;
}
if (curNum < tempNum) {
finalIndex = prevIndex;
}
}
}
return finalIndex;
}
}
An approach that lets you make just one pass through the list and doesn't require sorting:
Declare an array of 5 integers: int[] largest = new int[5];
Put the first 5 elements in the ArrayList into largest.
Starting with the 6th element, look at each element N in the ArrayList, and if N is larger than any element in largest, throw out the smallest number currently in largest and replace it with N.
If you need to exclude duplicates, the algorithm can be modified easily (just skip over any ArrayList element that's already in largest).
Why not use Collections.sort(List list) or Arrays.Sort(arr). This will save much of effort. Or is it part of your task?
Assuming your collection is sorted, and you want the last 5 elements, try this out:
for (int i = sortedNums.size() - 5; i < sortedNums.size(); ++i) {
System.err.println(sortedNums.get(i));
}
How I would go about doing this:
Create a temporary ArrayList, as a copy of the initial one.
After each largest element is found, remove it from the temporary ArrayList and add it to your 5 largest numbers
Repeat until complete
edit* This does not require your elements to be sorted, and has a fairly poor efficiency as a result
I assume you do not have the liberty to use sort and suchlike, considering this is a homework. So here is outline of an algorithm that you can try to implement
create an array of five integers (we will keep this sorted)
for each element in the list
find the index of the element in the array that it is greater than
if no such element exists in the array (i.e. it is smaller than all elements in the array)
continue on to the next element in the list
else
push all elements in the array to one index below, letting them fall off the
edge if need be (e.g. if the number in list is 42 and the array has
45 and 40 at index 3 and 2 respectively then
move arr[1] to arr[0], and arr[2] (40) to arr[1] and set arr[2] = 42)
end if
end for
At the end the array will have the five elements
I will leave one question for you to answer (it is important): what should you set the array to initially?
You only need two lines of code:
Collections.sort(nums1);
List<Integer> high5 = nums1.subList(nums1.size() - 5, nums1.size());
If you must "do it yourself", the simplest way to sort is a bubble sort:
iterate over the list
swap adjacent numbers if they are in the wrong order
repeat n times
Not efficient but very easy to code.
I need to get a minimum number that I cant get by adding different numbers of an array. Basically if I have these numbers:1,1,1,5; I can get 1,2,3,5,6... but I cant get 4 so that is the number I am looking for. Now this is my code:
import java.util.Scanner;
public class Broj_6 {
public static void main(String[] args) {
Scanner unos = new Scanner(System.in);
int k;
int n = unos.nextInt();
int niz []= new int [n];
for(int i = 0;i<n;i++){
niz[i]=unos.nextInt();
}
BubbleSort(niz);
for(int i = 0;i<n;i++){
System.out.print(niz[i] + " ");
}
for(int br = 1;br<=10000;br++){
for(k = 1;k<n;k++){
if(niz[k]>br){
break;
}
}
int podniz [] = new int [k];
for(int i=0;i<podniz.length;i++){
niz[i] = podniz[i];
}
//This is where I will need my logic to go
}
}
static void BubbleSort (int [] niz){
int pom;
for(int i = 0;i<niz.length-1;i++){
for(int j = 0;j<niz.length-1-i;j++){
if(niz[j]>niz[j+1]){
pom = niz[j];
niz[j] = niz[j+1];
niz[j+1] = pom;
}
}
}
}
}
So the code goes by testing each number individually from 1 to 100000 and makes a subarray of all numbers given that are less than the number itself. Now here is the problem,I dont know how to mix and match the numbers in the subarray so it can get(or not get) the desired number. When every combination is tested and there is no desired number,I will break; the loop and print i. Just to clarify,I can only use addition,and each number can only go in once
You can achieve this as below:
Use two nested loops, like below to calculate the sum of different numbers:
List<Integer> additionList = new ArrayList<Integer>();
int []inputNumbers = .... // Logic to read inputs
for(int _firstIndex = 0; _firstIndex < totalInputs; _firstIndex++){
for(int _secondIndex = _firstIndex + 1; _secondIndex < totalInputs; _secondIndex++){
additionList.add(inputNumbers[_firstIndex]); // only because you have 1 in the sample output
additionList.add(inputNumbers[_firstIndex] + inputNumbers[_secondIndex ]);
}
}
Then sort additionList and look for any missing entry. The first missing entry will be your answer,
Sorting the whole array and then finding sum of all subarrays does solve the problem, but is costly: O(2n^2) ~ O(n^2).
More efficient way to solve this will be Kadane's Algorithm: http://en.wikipedia.org/wiki/Maximum_subarray_problem
What the algo does:
Start from first element and increase the array size (sub array) till you reach the sum you're desiring.
my_num = 1;
while(true){
if(sum_subarray) > my_num){
current position = new subarray;
}
and this subarray concept is calculated through Kadane's approach:
def sum_subarray(A):
sum_ending_here = sum_so_far = 0
for x in A:
sum_ending_here = max(0, max_ending_here + x)
sum_so_far = max(sum_so_far, sum_ending_here)
return sum_so_far
I couldn't solve the problem completely. 'my_num' mentioned here needs to be incremented from 1, and break when my_num > max_sum. I hope someone can add to it and make it compilable.
Note:
This will also take care if negative elements are present in array.
In line 24, I am getting an error which is commented out. What is causing this and how to I get it fixed?
Any help is much appreciated. Thanks ahead of time. :)
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//initialize array
double[] numbers = new double [10];
//Create Scanner object
System.out.print("Enter " + numbers.length + " values: ");
//initialize array
for ( int i = 0; i < numbers.length; i++){
numbers[i] = input.nextDouble() ;
java.util.Arrays.sort(numbers[i]); //getting an error here, thay says [The method sort(int[]) in the type Arrays is not applicable for the arguments (double)]
//Display array numbers
System.out.print(" " + numbers);
}
//Close input
input.close();
}
}
You need to sort the complete array rather than a single element:
Arrays.sort(numbers);
Better to move it outside of the for-loop. You could use Arrays.toString to display the contents of the array itself:
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextDouble();
}
Arrays.sort(numbers);
System.out.print(Arrays.toString(numbers));
Note: Class names start with an uppercase letter, e.g. MyMain.
Put this after the for loop:
java.util.Arrays.sort(numbers);
notice numbers not numbers[i] and the print needs to come out of that loop too.
The mistake you're making is that you are trying to sort a single number. The error message points out that the sort method expects an array.
Your algorithm should first read in all the numbers, before sorting. So change your code to something like this:
...
// first read in numbers
for ( int i = 0; i < numbers.length; i++){
numbers[i] = input.nextDouble() ;
}
// then apply sort
java.util.Arrays.sort(numbers); // numbers is an array, so it's a valid argument.
// finally, after sorting you may now output the sorted array
for(int number : numbers){
System.out.println(number);
}
...