Java - Uncommon sort a multidimensional array - java

I need help with this exercise
Consider you have 2d array
String[][]myArray={
{"0.0","0.1","0.2","0.3","0.4"},
{"1.0","1.1","1.2","1.3"},
{"2.0","2.1","2.2","2.3","2.4","2.5"}
};
and you wish to print:
0.0|1.0|2.0|
0.1|1.1|2.1|
0.2|1.2|2.1|
0.3|1.3|2.3|
0.4|2.4|
2.5|
I have tried to use Comparator
Here is code :
public static void main(String[] args) {
String[][]Array={
{"0.0","0.1","0.2","0.3","0.4"},
{"1.0","1.1","1.2","1.3"},
{"2.0","2.1","2.2","2.3","2.4","2.5"}
};
Arrays.sort(Array, new PorKolumn(2));
for (int i = 0; i < Array.length; i++) {
String [] kol = Array[i];
for(int j=0; j<kol.length; j++) {
System.out.print(kol[j] + " | ");
}
System.out.println();
}
}
}
class PorKolumn implements Comparator{
int Kolumny;
public PorKolumn(int Kolumny) {
this.Kolumny = Kolumny;
}
public int compare (Object o1, Object o2 ){
String [] kol1 = (String []) o1;
String [] kol2 = (String []) o2;
return kol1[Kolumny].compareTo(kol2[Kolumny]);
}'
Thx for any help.

public static void print( String[][] a ){
int iRow = 0;
while(true){
boolean done = false;
for( int iCol = 0; iCol < a.length; iCol++ ){
if( iRow < a[iCol].length ){
System.out.print( a[iCol][iRow] + "|" );
done = true;
}
}
if( ! done ) break;
System.out.println();
iRow++;
}
}
Prints as requested:
0.0|1.0|2.0|
0.1|1.1|2.1|
0.2|1.2|2.2|
0.3|1.3|2.3|
0.4|2.4|
2.5|

As #Teepeemm stated there is no sorting:
String[][]myArray={
{"0.0","0.1","0.2","0.3","0.4"},
{"1.0","1.1","1.2","1.3"},
{"2.0","2.1","2.2","2.3","2.4","2.5"}
};
int maxLength = 0;
for(int i = 0; i < myArray.length; i++)
if(maxLength < myArray[i].length)
maxLength = myArray[i].length;
for(int j = 0; j < maxLength; j++) {
for(int i = 0; i < myArray.length; i++)
if(j < myArray[i].length)
System.out.print(myArray[i][j] + "|");
System.out.print("\n");
}
}
Output:
0.0|1.0|2.0|
0.1|1.1|2.1|
0.2|1.2|2.2|
0.3|1.3|2.3|
0.4|2.4|
2.5|

You could try something like this:
(This is untested code, because i have written it directly here)
int i = 0;
boolean ongoing = true;
while(ongoing){
for(int j = 0; j < myArray.length; j++){
if(myArray[j][i] == null){
System.out.print("\t|");
ongoing = false;
continiue;
}
ongoing = true;
System.out.print(myArray[j][i]+"\t|");
}
System.out.print("\n");
i++;
}
it should give out the right format.

Related

printing a symmetrical 2d array

I want to randomly generate a symmetrical 10x10 table with "*" symbols but It all basically prints in two long rows. I know I'm doing something wrong but I'm looking at it too hard and cant see the issue.
public class Main {
public static void main(String[]args) {
int n = 10;
char[][] array = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i++) {
for(int j = 0; j < i; j++) {
char value;
if (Math.random()> .5) {
value = '*';
}
else {
value = ' ';
}
array[i][j] = value;
array[j][i] = value;
System.out.print(array[i][j]);
System.out.println();
System.out.print(array[j][i]);
}
}
}
}```
I don't see your context here. But you can try this
public class Main {
public static void main(String[] args) {
int n = 10;
char[][] array = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
char value;
if (Math.random() > .5) {
value = '*';
} else {
value = ' ';
}
array[i][j] = value;
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
you're not printing row by row, also missing the diagonal element. Fixing those and some other minor changes
int n = 10;
char[][] matrix = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
char value = rd.nextBoolean() ? '*':' ';
matrix[i][j] = value;
matrix[j][i] = value;
}
}
for(char[] row : matrix) {
System.out.println(row);
}

Java Insertion Sort doesnt sort

I have written a java sorting algorithm by insertion, the code compiles but doesnt sort:(. If anyone could point out any flaws, Id be very thankful, Java doesnt...
public class Sort {
public static int[] sort(int[] x) {
int[] y = new int[x.length];
for(int i = 0; i < x.length; ++i) {
int j = 0;
while (y[j] < x[i] && j < i) ++j;
for (int k = i-1; k >= j; --k) y[k+1] = y[k];
y[j]=x[i];
}
return y;
}
public static void main(String[] args) {
int[] size = new int[10];
for(int k=0; k<size.length; ++k ) {
size[k]=(int)(Math.random()*20);
System.out.println(size[k]);
}
System.out.println(sort(size));
}}
[I#39ed3c8d is returned by invoking toString() on an int array, which you then print with System.out.println.
You presumably want System.out.println(Arrays.toString(sort(size))); instead.
You are printing the reference of size i.e., [I#39ed3c8d .
This should help you to understand:
public class Sort {
public static int[] sort(int[] x) {
int[] y = new int[x.length];
for(int i = 0; i < x.length; ++i) {
int j = 0;
while (y[j] < x[i] && j < i) ++j;
for (int k = i-1; k >= j; --k) y[k+1] = y[k];
y[j]=x[i];
}
return y;
}
public static void main(String[] args) {
int[] size = new int[10];
System.out.println("Befor sorting");
for(int k=0; k<size.length; ++k ) {
size[k]=(int)(Math.random()*20);
System.out.print(size[k]);
System.out.print(" ");
}
size = sort(size);
System.out.println("\nAfter sorting");
for(int i = 0; i<size.length; i++){
System.out.print(size[i]);
System.out.print(" ");
}
}}
That random is result of:
System.out.println(sort(size));
Do this instead:
size = sort(size);
for(int k=0; k<size.length; ++k ) {
System.out.print(size[k] + " " );
}

Can anyone tell me why my calculateCoin function doesnt show up?

Can anyone help me why the calculateCoin function doesn't show up? Basically what it does is, it calculates the coin, that was generated randomly in the drawMap function within 20% chance.
What I did and not sure doing right is, I called the calculateCoin function IN the drawMap function, and then I call the drawMap in the main.
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.drawMap());
}
public int[][] drawMap(){
int[][] map = new int[5][5];
char coin = 'o';
for(int i =0; i<map.length; i++){
for(int j =0; j<map[i].length; j++){
map[i][j] = (int)(Math.random()*10);
if(map[i][j]<2){
System.out.print(coin+ " ");
}
else
System.out.print("*"+ " ");
}
System.out.println("");
}
calculateCoin(map, coin);
System.out.println("");
return map;
}
public int calculateCoin(int[][] map, char coin){
int result = 0;
for(int i = 0; i<map.length; i++){
for(int j = 0; j<map[i].length; j++){
if(map[i][j] == coin){
result++;
}
}
}
return result;
}
The function is actually being called but the value that you return from it is not stored in any variable. If you want something to happen after printing the map, store the result of the call in a variable and then print it.
int calculatedCoin = calculateCoin(map, coin);
System.out.println("Calculated coin: " + calculatedCoin)
try this , but basically you declare a type of a class not a method.
public class dave {
public static void main(String[] args) {
dave main = new dave();
System.out.println(dave.drawMap());
}
public static int[][] drawMap() {
int[][] map = new int[5][5];
char coin = 'o';
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
map[i][j] = (int) (Math.random() * 10);
if (map[i][j] < 2) {
System.out.print(coin + " ");
} else
System.out.print("*" + " ");
}
System.out.println("");
}
calculateCoin(map, coin);
System.out.println("");
return map;
}
public static int calculateCoin(int[][] map, char coin) {
int result = 0;
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[i][j] == coin) {
result++;
}
}
}
return result;
}
}

Can't return an array from method in main

I'm very beginner in Java. This is my univercity work of creating a KMeans algorithm. A person writes digits in SAMPLES and number of centers in NUM_CLUSTERS. Algorithm gives cluster center Points
I need to return an array from this method but I can't:
public static int[][] getCentroid_arr(int SAMPLES[],int NUM_CLUSTERS,int centroid_arr[][]).
What exactly array? - It's shown in Console:
Points
1, 2, 7, 22, 44,
It's necessary to return an array because I want to use it for checking in JUnit test.
Instead of return centroid_arr must be this one sorted array:
printArray(arr_sort_asc(sorted_distTocentroid_arr))
After spending about 3 days with this issue I still have no idea how to resolve a problem. I can only get it in print.
I'd be thankfull for any help.
package kmeans;
import java.util.*;
import java.util.Map.Entry;
public class KM_don_touch {
private static final int NUM_CLUSTERS = 5; // Total clusters.
private static final int SAMPLES[] = new int[]{1, 2, 3, 6, 7, 9, 11, 22, 44, 50};
public static void main(String[] args) {
System.out.println("data size is: " + SAMPLES.length);
System.out.println("number of clusters is: " + NUM_CLUSTERS);
System.out.print("dataset is: ");
printArray(SAMPLES);
System.out.println();
int maxDiffData_arr[]=new int[NUM_CLUSTERS];
Kmeans_test3 get_prepare_data = new Kmeans_test3();
maxDiffData_arr=get_prepare_data.prepare_data(SAMPLES);
int centroid_arr[][]=new int[2][NUM_CLUSTERS];
for (int i=0; i<NUM_CLUSTERS; i++) {
centroid_arr[0][i] = 0;
centroid_arr[1][i] = SAMPLES[maxDiffData_arr[i]];
}
System.out.println();
System.out.print("centroid_arr 0 is: ");
printArray(centroid_arr[0]);
System.out.println();
System.out.print("centroid_arr 1 is: ");
printArray(centroid_arr[1]);
System.out.println();
getCentroid_arr(SAMPLES, NUM_CLUSTERS, centroid_arr);
}
public static void firstDiffSort(int[] difference){
int tmp[]=new int[difference.length];
tmp = arr_sort_desc(difference);
for (int i=0; i<difference.length; i++){
}
}
public static int[] arr_sort_desc(int[] arr) {
int tmp;
for (int k = 0; k < arr.length; k++) {
for (int j = k + 1; j < arr.length; j++) {
if (arr[k] < arr[j]) {
tmp = arr[k];
arr[k] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
public static int[] arr_sort_asc(int[] arr) {
int tmp;
for (int k = 0; k < arr.length; k++) {
for (int j = k + 1; j < arr.length; j++) {
if (arr[k] > arr[j]) {
tmp = arr[k];
arr[k] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
public static int getMinValue(int[] numbers){
int minValue = numbers[0];
for(int i=1; i<numbers.length; i++){
if(numbers[i] < minValue){
minValue = numbers[i];
}
}
return minValue;
}
public static int FindSmallest (int [] arr1){
int index = 0;
int min = arr1[index];
for (int i=1; i<arr1.length; i++){
if (arr1[i] < min ){
min = arr1[i];
index = i;
}
}
return index;
}
public static int[][] getCentroid_arr(int SAMPLES[],int NUM_CLUSTERS,int centroid_arr[][]){
int distance[][]=new int[NUM_CLUSTERS][SAMPLES.length];
int cluster[]=new int[SAMPLES.length];
int clusternodecount[]=new int[NUM_CLUSTERS];
int storedData[][]=new int[1][NUM_CLUSTERS];
int clusterelements[][]=new int[NUM_CLUSTERS][SAMPLES.length];
centroid_arr[0] = centroid_arr[1];
centroid_arr[1]=new int[NUM_CLUSTERS];
for (int i=0; i<NUM_CLUSTERS; i++) {
centroid_arr[1][i] = 0;
}
System.out.println("========== Starting to get new centroid_arr =========");
//сложность алгоритма С2
for(int i=0;i<NUM_CLUSTERS;i++){
for(int j=0;j<SAMPLES.length;j++){
distance[i][j]=Math.abs(SAMPLES[j]-centroid_arr[0][i]);
System.out.print(distance[i][j]+" ,");
}
System.out.println();
}
System.out.println("========== Just ranspose =========");
int smallerDistance=0;
int[][] numbers = new int[SAMPLES.length][NUM_CLUSTERS];
for(int i=0;i<SAMPLES.length;i++){
for(int j=0; j<NUM_CLUSTERS; j++){
numbers[i][j]=distance[j][i];
System.out.print(numbers[i][j]+", ");
}
System.out.println();
smallerDistance = FindSmallest(numbers[i]);
centroid_arr[1][smallerDistance] = centroid_arr[1][smallerDistance]+SAMPLES[i];
clusternodecount[smallerDistance]=clusternodecount[smallerDistance]+1;
cluster[i]=smallerDistance;
}
System.out.println("New clusters are ");
for (int i = 0; i < NUM_CLUSTERS; i++) {
System.out.print("C" + (i + 1) + ": ");
for (int j = 0; j < SAMPLES.length; j++) {
if (cluster[j] == i)
System.out.print(SAMPLES[j] + ", ");
}
System.out.println();
}
System.out.println("======================================== ");
System.out.println("New centroid_arr is ");
for (int k = 0; k < NUM_CLUSTERS; k++) {
centroid_arr[1][k] = centroid_arr[1][k] / clusternodecount[k];
System.out.print(centroid_arr[1][k] + ", ");
}
System.out.println();
boolean isAchived = true;
for (int j = 0; j < NUM_CLUSTERS; j++) {
if (isAchived && centroid_arr[0][j] == centroid_arr[1][j]) {
isAchived = true;
continue;
}
isAchived = false;
}
if (!isAchived) {
getCentroid_arr(SAMPLES, NUM_CLUSTERS, centroid_arr);
}
if (isAchived) {
System.out.println("======================================== ");
System.out.println(" Final Cluster is ");
for (int i = 0; i < NUM_CLUSTERS; i++) {
System.out.print("C" + (i + 1) + ": ");
for (int j = 0; j < SAMPLES.length; j++) {
if (cluster[j] == i)
System.out.print(SAMPLES[j] + ", ");
}
System.out.println();
}
for (int i=0; i<SAMPLES.length; i++){
for (int j=0; j<NUM_CLUSTERS; j++){
if (j==cluster[i])
clusterelements[j][i]=SAMPLES[i];
}
}
int distTocentroid_arr[][]=new int[NUM_CLUSTERS][SAMPLES.length];
for (int i=0; i<NUM_CLUSTERS; i++){
for (int j=0; j<SAMPLES.length; j++){
distTocentroid_arr[i][j]=Math.abs(centroid_arr[1][i]-clusterelements[i][j]);
}
}
System.out.println("Points:");
int sorted_distTocentroid_arr[] = new int[NUM_CLUSTERS];
for (int i=0; i<NUM_CLUSTERS; i++){
smallerDistance = FindSmallest(distTocentroid_arr[i]);
sorted_distTocentroid_arr[i]=clusterelements[i][smallerDistance];
}
printArray(arr_sort_asc(sorted_distTocentroid_arr));
}
return centroid_arr;
}
public int[] prepare_data(int[] arr) {
int sorted_arr[] = arr_sort_desc(SAMPLES);
int maxDiff_arr[] = new int[SAMPLES.length];
int sorted_diff[] = new int[SAMPLES.length];
maxDiff_arr[0] = Math.abs(sorted_arr[0] - sorted_arr[1]);
for (int i = 1; i < SAMPLES.length; i++) {
maxDiff_arr[i] = Math.abs(sorted_arr[i] - sorted_arr[i - 1]);
}
Map<Integer, Integer> m1= new HashMap<Integer, Integer>();
int k=0;
for(int i:maxDiff_arr){
m1.put(k++, i);
}
m1= sortByValues(m1);
int i=0;
for (int key: m1.keySet()){
sorted_diff[i++]=key;
}
return sorted_diff;
}
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
#Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entry: entries){
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
}
public static void printArray2(int[][] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[1][i] + ", ");
}
}
}
Console output

extract different number in two array in java

Here i come with to extract different number in two array in java .different number are to be store in third list of array i am new to java could some one guide me in right Direction
which i tried upto now??
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int [] list2 =null;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list1.length; j++)
{
if(list[i]!=list1[j])
{
System.out.println(list2[]);
}
}
}
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int [10] list2 =null;
boolean flag=false;
int k=0;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list1.length; j++)
{
if(list[i]!=list1[j])
{
flag=false;
}
else
{
flag=true;
}
if(flag==true)
{
list2[k]=list[i];
k++;
}
}
}
Now I am pretty sure about answer.
Well the problem is that in java you need to specify the size of the array.
What you can do :
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int size = list1.length;
boolean found = false;
int[] list2=new int[size];
for (int i = 0; i < list1.length; i++)
{
for (int i = 0; i < list1.length; i++){
if(list[i]==list1[i])
{
found = true;
}
}
if(found)
found = false;
else
list2[i]=list1[i];
}
System.print.out("List2={");
for(int k = 0; k < list2.length; k++){
if(list2[k] != 0)
System.print.out(list2[k] + ", ");
}
System.print.out("}");
(c.f. : JavaDoc)

Categories

Resources