Java 2-D selection sort - java

I am preparing for an exam, and we are likely to be tasked with sorting a two dimensional array of ints. Sorted meaning the first row, first column is the lowest and the last row, last column is the highest.
I approached the task by creating a 1-D array, and then populating it with all the values in the 2d array. Then, I passed it through a sorting method. Finally, I wrote each value of the sorted array back into the 2d array and returned it.
This sort of worked, as you can see from the output below. I am confused as to where my process is breaking down, I would appreciate any input.
Input:
int[][] nums = {{1,5,9},{8,9,3},{0,7,6}};
output:
0 0 0
0 0 0
0 0 1
public int[][] sort2D(int[][]nums){
int[] temp = new int[((nums.length+1)*(nums.length+1))];//make one long array
for(int i =0; i<nums.length; i++){ //populate
int counter = 0; //indices for long array
for(int j = 0; j<nums[i].length; j++){
System.out.println(temp[counter]);
temp[counter] = (int)nums[i][j];
counter++;
}
}
temp = sort(temp); //sort it (verified code)
for(int i = 0; i<nums.length; i++){ //reverse the above process
int counter = 0;
for(int j = 0; j<nums.length; j++){
nums[i][j] = temp[counter];
counter++;
}
}
return nums;
}

The first thing I think you're doing wrong is this:
int[] temp = new int[((nums.length+1)*(nums.length+1))];//make one long array
nums.length +1 = 4 in your case. you are copying your 3*3 array into a 4*4 array.
This has the funny effect of adding 5 0's to your result. (temp[9] till temp[15] will be 0 filled)
After you sort, these 0's will show up
the place where your code breaks down is:
for(int i =0; i<nums.length; i++){ //populate
>> int counter = 0; //indices for long array
for(int j = 0; j<nums[i].length; j++){
System.out.println(temp[counter]);
temp[counter] = (int)nums[i][j];
counter++;
}
}
You initialize the counter to 0 every time you go through one of your outer arrays.
this means that on the 3rd pass (last array) you overwrite temp[0], temp1 and temp[2] with nums[2][0], nums2, nums[2][2]
I assume in your actual code, you do
int counter = 0; //indices for long array
for(int i =0; i<nums.length; i++){ //populate
for(int j = 0; j<nums[i].length; j++){
System.out.println(temp[counter]);
temp[counter++] = (int)nums[i][j];
}
}
You could also use System.arrayCopy, especially if you know the length and suchlike.

Related

Insert value to 2d array

I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me

Separating an array into three

I currently have a 2d array, could anyone explain how i would extract the following:
the 0th to the 4th row the whole way down the array
then the 5th-10th row the whole way down the array
then the 11th-16th row the whole way down the array
I then want to hold these in 3 seperate arrays.
and then once I have carried out calculations on each individual array how do i sum them all back to one array?
This is the calculations I will carry out on the full array, that I would like to carry out on each individual array.
double[][] newjagssw = jaggedarr;
for(int i=0; i<jaggedarr.length; i++){
for(int j = 0; j<jaggedarr[i].length; j++){
newjagssw[i][j] = jaggedarr[i][j] - average[i];
double hold = newjagssw[i][j];
newjagssw[i][j] = Math.pow(hold, 2);
}
}
sst = new double[record];
for(int i = 0; i < sst.length; i++){
double hold = 0;
for(int j= 0; j < newjagssw[i].length; j++){
hold = hold + newjagssw[i][j];
}
sst[i] = hold;
System.out.println(probename[i] + ": " + ssw[i]);
}return ssw;
is there anyway of adapting it?
Thanks.

Element Modification in Multi-Dimensional Arrays in Java

I have created a 2-D array in Java and I wish to change the value of each element.
Here is what I am trying to accomplish
-number each student from 1-10
-give each student 5 random marks from 40-100
int[][] students = new int[10][5];
Random numGen = new Random();
for (int i=0; i < students.length; i++){
students[i] = i; //Problem here..
for (int j=0; j<5; j++){
students[i][j] = numGen.nextInt(40)+61
}
}
I am having issues assigning each student a number from 1-10.
Where I wrote '//Problem here', is where the compiler keeps giving me trouble.
What is the appropriate method for modifying a single element in multi-dimension arrays?
Just use the index into the students (and return id as index+1 when you need to).
int[][] students = new int[10][5];
Random numGen = new Random();
for (int i=0; i < students.length; i++){
for (int j=0; j<5; j++){
students[i][j] = numGen.nextInt(40)+61
}
}
Array indices in java starts from 0. Which means 1st row is represented as 0. To edit an element in a 2D array you need to specify the both indices.
For example to edit an element at 5th row and 4th column you should use myArray[4][3]. Because you start counting from 0. myArray[0][0] is first element of the first row.
int[][] students = new int[10][5];
Random numGen = new Random();
for (int i=0; i < students.length; i++){
students[i][0] = i; //Change student[i] = i to student[i] = i+i
// because i starts from 0 but student number starts from 1.
for (int j=0; j<5; j++){
students[i][j] = numGen.nextInt(40)+61
}
}

Is there something wrong with my nested for-loop? counting and incrementing values of arrays

So, I generate a 100 numbers between the range of 0 and 9. I store these 100 numbers in an array called 'array'. Then I have the array called 'count'. It has 10 elements, and I wanted to check the following: for each element in 'array' if it equals to 0-9 then count[0-9] increments by 1, count[0] = how many times number 0 appears and so on count[1] = 1, count[2] = 2... . I just keep getting the output of around 20k numbers and i suppose? the sum of each element?, no idea why. I was wondering if there is something major wrong with my for loop?
import java.util.*;
class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}
System.out.println("0 appears " + count[0] + " times.");
}
}
Your Login is Perfect only mistake which i found u made is with the brackets........!
Generate the numbers using first loop and then count the number of occurrence using different for loop.
Here is your code's modified version which generates 10 numbers and counts the individual number occurrence count.....
public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}
for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}
}
System.out.println("3 appears " + count[3] + " times.");
}
}
There's a simpler way to do this without nested loops, so forgive me for suggesting this as a fix rather than finding the issue in the loop.
for(int i=0; i<size; i++){
int num = generator.nextInt(max);
array[i] = num;
count[num]++;
}
One loop, incrementing the count for each number as it appears. You may need to ensure all the entries in count start at 0, but even then an additional loop through 10 entries is MUCH faster.
To increment your counter, you don't need to have two nested for loops. Instead, you can use the value of array[x] as your counter.
for (int i = 0; i < size; i++) {
count[array[i]]++
}
You've nested your counting loop inside of your random number generating loop. Move the counting part outside.
Edit: The reason you're getting like 20k or whatever instances of zero is because when you set array[0] with a random value, you also check how many instances of 0 are in array[1] to array[99].
You probably shouldn't do your count until you have finished assigning your numbers, but here is how you could. Note that you want the value at array[i] to be your index to count.
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates random numbers
count[array[i]]++;
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(count));

why selected part used in code for finding sum of positive element of an array?

I have this code :
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
int sum = 0;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}
}
This java code tries to find out the sum of positive elements of an array. I understood the way it is implemented but am not clear about this part,
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++)
ia[i] = i;
}
Why is this part used here?
the for part is used to initialise ia array with 0 to 100 values.
by default every ia[i] element will be 0.
becuase of this loop you array gets values
ia[0] =0
ia[1] =1
ia[2] =2
ia[3] =3
and so on...
This part populates the array. The element at index 0 has the value 0, the element at index 1 has the value 1, etc. until the index 100 (included). Without this part, all the elements would have the value 0.
//This creates an array of ints of size 101
int[] ia = new int[101];
//This is a for-loop (that will continue for as long as i<ia.length) that fills
//the array with the value of i. i will increase +1 in value every time it loops
for (int i = 0; i < ia.length; i++)
ia[i] = i;
for (int i = 0; i < ia.length; i++)
ia[i] = i;
this part initializing the array with values from 0 to 100.
Then adding this values in next part. Probably the task is to
add numbers from 0 to 100.

Categories