Can someone please help me how to solve it?
Create a new class named blabla in the bla package. An instance of the class should
be able to store a two-dimensional array of type double. The size of the array is not
bound. The class should have a no-parameter procedure-like method named sortRows. The
method should sort rows of the array in the following manner: the values of the last
column must be in a descending order (greatest first, smallest last).
So i tried to do myself, please help me if there is a mistake.
double temp = 0;
double[][] number;
boolean fixed=false;
while(fixed==false){
fixed=true;
}
number = new double[5][5];
for(int i=0; i<number.length-1; i++){
if(number[i][i] > number[i+1][i+1])
temp = number[i+1][i+1];
number[i+1][i+1] = number[i][i];
number[i][i]=temp;
fixed=false;
}
for(int i=0; i<number.length; i++){
System.out.println(number[i][i]);
}
Well, I'm not gonna do your homework!
You should be able to create a class in a package yourself,
For creating dynamic arrays, check this topic: Variable length (Dynamic) Arrays in Java
For sorting arrays, check this topic: char multidimensional array sorting in java
This should get you going, I hope ;)
Related
I am currently starting to learn java for school and for myself and I am stuck on a question I can't answer...
The problem contains two arrays including different ints with different length.
Both arrays should have the same order of numbers when they are included in the array.
For Examples {3,8,2,6} and {3,2,6}
How can I make sure that the arrays are sorted in the same way?
I don't want a sort method form lowest to highest, just the same order?
The algorithm should be based on normale if/ while/ for methods.
Appreciate the help!
I think a code like below should solve your need. Finally, c will have elements of b ordered same as a. Hope this helps you. Still I don't understand the use of this.
Regards, Srikanth Kondaveti
int a[] = { 3,8,2,6};
int b[] = {6,3,2};
int c[] = new int[b.length];
int index = 0;
for(int k=0; k<a.length; k++) {
for(int l=0; l<b.length; l++) {
if(a[k]==b[l]) {
c[index++]=b[l];
break;
}
}
}
I just recently started learning java and today I learned how I can do the so called selection sort. I have been trying for the last 3 hours to do a bucket sort, but there are some parts which I don't know how to code. Important : I am learning java completely by myself with a book. I am not a student and I am doing this as a hobby. I already googled everything I could think of and I didn't find a solution. I don't have a teacher or anybody who I can ask, so yea, any help would be appreciated!
Code:
private int[] bucketSort() {
int[]bucket=new int[maxSize+1];
int[]sortedElements = new int[elementaros.length];
for(int i=0; i<elementaros.length;i++) {
bucket[elementaros[i]]++; //it says that I can't convert from Car to int. How can I add the elements of array elemenators to bucket?
}
int outPos = 0;
for (int j = 0; j < bucket.length; j++){
for (int k = 0; k < bucket[i]; k++){
sortedElements[outPos++] = i;
}
}
return bucket;
}
The idea of the code :
I have an array elements of type Car(Car is another class of my program). It looks like this - Car[] elementaros. int maxSize shows the maximum number of administrable Car objects. What I want to do is the following - I want to sort the elements in the elementaros array alphabetically. I would really really appreciate it if somebody has the time to show me how this would function with an example code or would just give me some tips. As I said - I have nobody who I can ask.
A selection sort is a combination of searching and sorting.
The principle is quite simple but I always prefer a diagram than huge explanations.
Start a pointer at the beginning of your unsorted array. Then, for each value of the array, search for the minimum value (or search for the alphabeticaly ordered car) in your array and switch the position of the founded Car with the pointer (which is a Car too)
Then you can advance the pointer to the next element of the array.
Here is a basic implementation to do this
public static Car[] doSelectionSort(Car[] elementaros) {
for (int i = 0; i < elementaros.length - 1; i++) {
int index = i;
for (int j = i + 1; j < elementaros.length; j++) {
if (elementaros[j].getName().compareTo(elementaros[index].getName()) < 0) {
index = j;
}
}
Car nextOrderedCar = elementaros[index];
elementaros[index] = elementaros[i];
elementaros[i] = nextOrderedCar;
}
return elementaros;
}
Just for example sake, I imagine your object of type Car has a name that we could use for the comparison.
UPDATE 1:
I have read your initial question too quickly and it leds me to answer a total different sorting algorithm. My bad.
I found an implementation here that does the trick:
williamfiset bucket sort
explanation of bucket sort plus different implementation
Hope this helps.
So for this extra credit problem in my calculus class, my other nerdy classmates and I decided that we would build a program to brute force a solution. One of these steps involves permutations. Through this algorithm, I managed to get it to work (I think):
public void genPermutations(int[] list, int k){
System.out.println("List: " + Arrays.toString(list));
System.out.println("----------------------");
if(k > list.length){
System.out.println("Not enough elements!");
return;
}
int[] counts = new int[list.length];
for(int i = 0; i < counts.length; i++){
counts[i] = 1;
}
int[] data = new int[k];
permutationHelper(list, counts, data, 0, k);
}
public void permutationHelper(int[] list, int[] counts, int[] data, int index, int k){
if(index == k){
//System.out.println(Arrays.toString(data));
permutations.add(data);
}else{
for(int i = 0; i < list.length; i++){
if(counts[i] == 0){
continue;
}
data[index] = list[i];
counts[i]--;
permutationHelper(list, counts, data, index + 1, k);
counts[i]++;
}
}
}
I have an ArrayList that stores all of the possible permutations (as integer arrays) that can be made from k elements of the list that I pass into the function. The problem is that if I print all of these permutations outside of the function, say after I call the genPermutations function, every permutation now is the same. But, when I print out the data where the comment is in the permutationHelper function, it correctly lists every possible permutation; I'm just unable to access them within the program later. My question is why are the values changing when I exit the function? Any help would be greatly appreciated.
Here are some pictures:
What is printed where the comment is.
What is printed later in the program.
The code used to print everything outside of the function is:
for(int i = 0; i < permutations.size(); i++){
System.out.println(Arrays.toString(permutations.get(i)));
}
I don't really know if that's necessary to know, but I just thought I'd include it just in case. Thanks in advance.
You're constantly modifying the same array object. Instead of adding different arrays to your list, you're in fact adding a reference to the same array over and over again.
To fix, instead of adding the data array to your list, you would have to add a copy of it, e.g. using Arrays.copyOf():
permutations.add(Arrays.copyOf(data, data.length));
Here the problem is that you are modifying the array after adding it to the list, you are modifying the same object again and again in different iterations. You were getting [3,2,1] in the list is because that was the outcome from last iteration. So as a fix you can use the following code. What it does is it will create a copy of data array and add that to the list.
int[] temp = Arrays.copyOf(data, data.length);
permutations.add(temp);
OR you can use clone() from array as follows.
int[] temp = data.clone();
permutations.add(temp);
I'm taking a Java class in College. My instructor is actually a teacher for languages derived from C, so she can't figure out what's going on with this piece of code. I read on this page http://docs.oracle.com/javase/6/docs/api/java/util/List.html that I could use the syntax "list[].add(int index, element)" to add specific objects or calculations into specific indexes, which reduced the amount of coding needed. The program I'm looking to create is a random stat generator for D&D, for practice. The method giving the error is below:
//StatGenrator is used with ActionListener
private String StatGenerator ()
{
int finalStat;
String returnStat;
//Creates an empty list.
int[] nums={};
//Adds a random number from 1-6 to each list element.
for (int i; i > 4; i++)
nums[].add(i, dice.random(6)+1); //Marks 'add' with "error: class expected"
//Sorts the list by decending order, then drops the
//lowest number by adding the three highest numbers
//in the list.
Arrays.sort(nums);
finalStat = nums[1] + nums[2] + nums[3];
//Converts the integer into a string to set into a
//texbox.
returnStat = finalStat.toString();
return returnStat;
}
My end goal is to use some kind of sorted list or method of removing the lowest value in a set. The point of this method is to generate 4 random numbers from 1-6, then drop the lowest and add the three highest together. The final number is going to be the text of a textbox, so it is converted to a string and returned. The remainder of the code works correctly, I am only having trouble with this method.
If anyone has any ideas, I'm all ears. I've researched a bit and found something about using ArrayList to make a new List object, but I'm not sure on the syntax for it. As a final note, I tried looking for this syntax in another question, but I couldn't find it anywhere on stackoverflow. Apologies if I missed something, somewhere.
'int nums[]' is not a List, it's an array.
List<Integer> intList = new ArrayList<>();
creates a new ArrayList for example.
You can access Elements in the list directly with the following Syntax :
intList.get(0); // Get the first Element
You can sort Lists with the Collections class :
Collections.sort(intList);
Here are some informations about Collections in Java : http://docs.oracle.com/javase/tutorial/collections/
Arrays are fixed size, so you need to allocate space for all the slots at the start. Then to put numbers into the array assign to nums[i]. No add() method needed.
int[] nums = new int[4];
for (int i = 0; i < 4; i++)
nums[i] = dice.random(6) + 1;
Arrays.sort(nums);
finalStat = nums[1] + nums[2] + nums[3];
Alternatively, if you really want a dynamically-sized array, use an ArrayList. An ArrayList can grow and shrink.
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < 4; i++)
nums.add(dice.random(6) + 1);
Collections.sort(nums);
finalStat = nums.get(1) + nums.get(2) + nums.get(3);
Notice how different the syntax is due to ArrayList being a class rather than a built-in type.
nums[].add(i, dice.random(6)+1); //Marks 'add' with "error: class
expected"
You are trying to use add on an array. List is a dynamic array, but that doesn't mean that array == List. you should use List instead.
List<Integer> nums=new ArrayList<Integer>();
//Adds a random number from 1-6 to each list element.
for (int i; i > 4; i++)
nums.add(i, dice.random(6)+1);
You're mixing arrays and lists.
Have a look at the tutorial:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://docs.oracle.com/javase/tutorial/collections/index.html
I'm trying to write a simple game where an enemy chases the player on a grid. I'm using the simple algorithm for pathfinding from the Wikipedia page on pathfinding. This involves creating two lists with each list item containing 3 integers. Here's test code I'm trying out to build and display such a list.
When I run the following code, it prints out the same numbers for each array in the ArrayList. Why does it do this?
public class ListTest {
public static void main(String[] args) {
ArrayList<Integer[]> list = new ArrayList<Integer[]>();
Integer[] point = new Integer[3];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
point[j] = (int)(Math.random() * 10);
}
//Doesn't this line add filled Integer[] point to the
//end of ArrayList list?
list.add(point);
//Added this line to confirm that Integer[] point is actually
//being filled with 3 random ints.
System.out.println(point[0] + "," + point[1] + "," + point[2]);
}
System.out.println();
//My current understanding is that this section should step through
//ArrayList list and retrieve each Integer[] point added above. It runs, but only
//the values of the last Integer[] point from above are displayed 10 times.
Iterator it = list.iterator();
while (it.hasNext()) {
point = (Integer[])it.next();
for (int i = 0; i < 3; i++) {
System.out.print(point[i] + ",");
}
System.out.println();
}
}
}
First of all, several of the other answers are misleading and/or incorrect. Note that an array is an object. So you can use them as elements in a list, no matter whether the arrays themselves contain primitive types or object references.
Next, declaring a variable as List<int[]> list is preferred over declaring it as ArrayList<int[]>. This allows you to easily change the List to a LinkedList or some other implementation without breaking the rest of your code because it is guaranteed to use only methods available in the List interface. For more information, you should research "programming to the interface."
Now to answer your real question, which was only added as a comment. Let's look at a few lines of your code:
Integer[] point = new Integer[3];
This line creates an array of Integers, obviously.
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
point[j] = (int)(Math.random() * 10);
}
//Doesn't this line add filled Integer[] point to the
//end of ArrayList list?
list.add(point);
//...
}
Here you assign values to the elements of the array and then add a reference to the array to your List. Each time the loop iterates, you assign new values to the same array and add another reference to the same array to the List. This means that the List has 10 references to the same array which has been repeatedly written over.
Iterator it = list.iterator();
while (it.hasNext()) {
point = (Integer[])it.next();
for (int i = 0; i < 3; i++) {
System.out.print(point[i] + ",");
}
System.out.println();
}
}
Now this loop prints out the same array 10 times. The values in the array are the last ones set at the end of the previous loop.
To fix the problem, you simply need to be sure to create 10 different arrays.
One last issue: If you declare it as Iterator<Integer[]> it (or Iterator<int[]> it), you do not need to cast the return value of it.next(). In fact this is preferred because it is type-safe.
Finally, I want to ask what the ints in each array represent? You might want to revisit your program design and create a class that holds these three ints, either as an array or as three member variables.
I would highly recommend to enclose the integer array of 3 numbers into a meaningful class, that would hold, display and control an array of 3 integers.
Then in your main, you can have an growing ArrayList of objects of that class.
You have an extra ) here:
element = (int[])it.next()); //with the extra parenthesis the code will not compile
should be:
element = (int[])it.next();
Besides the problem in the other answer, you cal it.next() two times, that cause the iterator move forward two times, obviously that's not what you want. The code like this:
element = (int[])it.next());
String el = (String)element;
But actually, I don't see you used el. Although it's legal, it seems meaningless.