On my quest learning Java I come across one doubt.
For sorting a unidimensional array we can use Arrays.sort() but if I want to sort a bidimensional array based on three columns? Is there any option to d that or do I have to code it for my self (something like three nested loops)?
Here is an example input:
13 2 28 36
1 4 56 17
4 2 5 40
2 4 41 55
9 5 48 12
19 2 25 12
20 5 13 8
15 3 51 30
12 5 39 59
17 3 56 40
3 1 56 46
7 3 28 51
8 5 14 58
5 3 34 15
14 4 53 2
18 4 38 57
6 2 16 25
16 3 17 13
10 5 41 33
11 1 13 57
Columns are int and this is stored in an array of ints.
I wanna sort by column 2, if equal numbers are found, then sort by column 3 and finally, if equals found, sort by column 3.
The output should be this:
11 1 13 57
3 1 56 46
4 2 5 40
6 2 16 25
19 2 25 12
13 2 28 36
16 3 17 13
7 3 28 51
5 3 34 15
15 3 51 30
17 3 56 40
18 4 38 57
2 4 41 55
14 4 53 2
1 4 56 17
20 5 13 8
8 5 14 58
12 5 39 59
10 5 41 33
9 5 48 12
Is there a simple way for doing this?
Remember that I'm new at Java.
regards,
Favolas
Simple use Comparator and use Arrays.sort(arr, comparator);
It depends on how you get the data.
In general, you could give your own Comparator to Collections.sort.
Use the comparator below
class MyArrayComparator implements Comparator<Integer[]> {
#Override
public int compare(Integer[] o1, Integer[] o2) {
if (o1[1] == o2[1]) {
if (o1[2] == o2[2]) {
return o1[3].compareTo(o2[3]);
}
else {
return o1[2].compareTo(o2[2]);
}
}
return o1[1].compareTo(o2[1]);
}
}
Use the following sort method
Collections.sort(yourListOfArry, new MyArrayComparator());
Implementing an Comparator on arrays of arrays seems kind of dangerous to me because you have to ensure manually, that all arrays in the second dimension are of the same length and the semantics of the components of the array must be the same at all times - for these kind of constraints objects should be used.
If the second dimension in the array has some meaning (i.e. it is always four becouse three are coordinates and the fourth is the value), you should consider not to model it as an array of arrays but an array of objects with four member variables (e.g. xCoord, yCoord, zCoord and value). You can then make this class implement the Comparable interface and implement the compareTo method. Then the Arrays.sort() method will sort according to the given compareTo method.
Related
I have declared a list of fruits like:
def fruits = ["apple", "orange", "pineapple"]
and I use the list like
for (fruit in fruits){
if(fruit=="orange"){
println("A delicious ${fruit}")
}
if(fruit=="pineapple"){
println("Another delicious ${fruit}")
}
if(fruit=="apple"){
println("More delicious ${fruit}"})
}
}
This works. But I'm just curious to see if there is a better to achieve the same result.
Thanks for your help.
Usually, for such problems, you'd have two ways to go about it. I'm using Python here as an example to explain the difference in syntax and the results it might generate for you.
for i in range(len(fruits)):
or the one which you've used
for fruit in fruits:
Analysing the bytecode
[Alternate Solution]
12 0 SETUP_LOOP 40 (to 43)
3 LOAD_GLOBAL 0 (range)
6 LOAD_GLOBAL 1 (len)
9 LOAD_FAST 0 (fruits)
12 CALL_FUNCTION 1
15 CALL_FUNCTION 1
18 GET_ITER
>> 19 FOR_ITER 20 (to 42)
22 STORE_FAST 1 (i)
13 25 LOAD_GLOBAL 2 (print)
28 LOAD_FAST 0 (fruits)
31 LOAD_FAST 1 (i)
34 BINARY_SUBSCR
35 CALL_FUNCTION 1
38 POP_TOP
39 JUMP_ABSOLUTE 19
>> 42 POP_BLOCK
>> 43 LOAD_CONST 0 (None)
46 RETURN_VALUE
[Your Solution]
17 0 SETUP_LOOP 24 (to 27)
3 LOAD_FAST 0 (fruits)
6 GET_ITER
>> 7 FOR_ITER 16 (to 26)
10 STORE_FAST 1 (fruit)
18 13 LOAD_GLOBAL 0 (print)
16 LOAD_FAST 1 (fruit)
19 CALL_FUNCTION 1
22 POP_TOP
23 JUMP_ABSOLUTE 7
>> 26 POP_BLOCK
>> 27 LOAD_CONST 0 (None)
30 RETURN_VALUE
This makes it very clear that your solution is far more optimized when it comes to the loop itself. However, this problem with your block is that you're using if statements everywhere, this means that each and every statement will be evaluated and checked even tho the loop has already found the value you were looking for.
A much better way would be to use if-else instead to further make it more optimized. However instead of using nested if statements a better faster and cleaner would be to replace them completely with a switch statement as long as the number of cases are good.
Think that with every if-statement the complexity of a program increases, better avoid them as much as possible and also avoid switch-statements which are even worse.
Your code is efficient but ugly, because it cannot scale well. If you modify the list, then you need to modify the loop as well. With a modern language as groovy, you can write this (as already suggested):
def fruits = [
apple : { "A delicious $it" },
orange : { "Another delicious $it" },
pineapple : { "More delicious $it" }
]
fruits.each { fruit, action ->
println action(fruit)
}
This can be inefficient comparing with your code, because it involves a map, but if I would care about the speed I would go for another programming language.
Generally in table cells go row wise but I want to render it column wise.
Data is stored in an array list.
----------- means page break
Expectation is:
1 6
2 7
3 8
4 9
5 10
-------------
11 16
12 17
13 18
But generally it comes like this
1 2
3 4
5 6
7 8
9 10
-------------
11 12
13 14
15 16
17 18
I have been asked to implement a hash map using an array. I need to insert the following keys:
15, 7, 26, 39, 11, 9, 27, 5, 18, 2, 54, 22, 4
into an array of size 19 using the hash function:
(3x + 7) % 19
Using linear probing, I would expect to get the following array (correct me if I'm wrong):
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Key: 4 11 5 18 7 26 39 27 2 15 9 22 54
where 26 had a collision with 7 at index 9, and so was inserted at index 10, and 39 then had a collision with 26 at index 10 and so was inserted at index 11.
I am now attempting to insert the same elements in an array implementation of a HashMap, using double hashing instead of linear probing. The 2nd hash function I am given is:
11 - (x % 11)
I have two questions:
Does this mean that my array will be of size 11 or still 19?
Do I initially use the original hash function and if the given index is free, insert the element there, otherwise if there is a collision, use the 2nd hash function and insert the element there?
According to Wikipedia the secondary hash function is used indirectly in the probing function:
h(0, x) = (3x + 7) % 19
h(j, x) = ((3x + 7) + j(11 - (x % 11))) % 19
Where j is the collision counter.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a csv file with this format, where in the first column I have the number of repetitions, in the second the number of days and in the third the time of execution.
Here's the representation:
1 7 131
2 7 71
3 7 114
[.....]
9 7 338
10 7 394
11 7 437
12 7 496
1 31 171
[.....]
12 31 1894
1 91 437
[.....]
10 91 4394
[.....]
I want to process this file to transform it in this way, I can use Java or Excel Macros
7 31 91 183 366
1 131 171 437 866 1906
2 71 305 867 173 3460
3 114 493 136 261 5356
4 159 596 182 356 6916
5 210 800 249 468 8762
6 223 919 378 605 11296
7 270 107 354 644 12898
8 270 123 401 746 14265
9 338 145 398 903 15487
10 394 164 439 934 16971
11 437 174 507 104 18941
12 496 189 527 110 21378
Where the first column of the Csv file remain the first column of the file, but not repeated. Then the period [7,31,...,366] must be placed as the first row.
Inside this matrix there will be placed all elements?
How can i do with Java or directly with macro inside Excel?
Thanks
What about a Map <Integer, Map <Integer, Integer>> being the first key the column and the inner key the number of days? The inner value would be the time of execution.
After being filled, you could print it doing something like:
print map.get(1).getKeys()
for (Entry entry : map.getKeys()
print entry.key()
for (Integer innerValue : map.get(entry.key())
print innerValue
The maps should be ordered for this to work...
I had a question on a test - I got it wrong, but I don't know why?
Question: An array of integers is to be sorted from biggest to smallest using an insertion sort. Assume the array originally contains the following elements:
5 9 17 12 2 14
What will it look like after the third pass through the for loop?
17 9 5 12 2 14
17 12 9 5 2 14 - Correct answer
17 12 9 5 14 2
17 14 12 9 5 2
9 5 17 12 2 14
In an insertion sort, I thought the source array is untouched; I felt, at the third pass, the destination array would be incomplete.
How did the test arrive at this answer?
Basically, after n passes of insertion sort, the first n+1 elements are sorted in the correct order and the rest are untouched. As you can see in the alternatives, the correct answer is the only one that fulfills that. Every step is only inserting relative to the already sorted numbers, so each step one extra number is correctly sorted.
Step 0 (Original, 5 assumed sorted)
5 9 17 12 2 14
Step 1, takes the 9 and puts it in the correct place before 5 (result, 9 5 sorted)
9 5 17 12 2 14
Step 2, takes the 17 and puts it in the correct place before 9 (result 17 9 5 sorted)
17 9 5 12 2 14
Step 3, takes the 12 and puts it in the correct place after 17 and before 9 (result 17 12 9 5sorted)
17 12 9 5 2 14
Insertion sort is typically done in-place. After k iterations the first k + 1 elements are sorted, hence the answer you've shown above.