HomeWork #5: Práce s poli
Nacházíte se: / Programování / Java / Školní rok 2008/2009
Zadání:
Napište funkci, která pro zadané pole celých čísel zjistí, který prvek je nejčastější a kolikrát se v daném poli opakuje.
Nedodržel jsem přímo zadání, protože čísla generuju, ale kdo je šikovnej, tak si to upraví, aby to vyhovovalo přesně zadání. :)
Vypracování:
package homework5;
public class Main {
public static void main(String[] args) {
/* Pocet cisel, ve kterych se bude hledat se upravuje pomoci velikosti
* tohoto pole
*/
int[] SourceData = new int[100];
int[][] ResultData = new int[SourceData.length][1];
GenerujCisla( SourceData );
ResultData = CetnostCisel( SourceData );
System.out.println("Nejvice opakovane cislo je: " + ResultData[0][0] + ", ktere je tam " + ResultData[0][1] + "x." );
/*for ( int i = 0 ; i < ResultData.length ; i ++ )
System.out.println( ResultData[i][0] + " ma " + ResultData[i][1] );*/
}
public static void GenerujCisla( int[] Data ) {
for (int i = 0; i < Data.length; i++)
Data[i] = (int)(Math.random() * 100 );
}
public static int NajdiMax( int[] Data ) {
int Max = Integer.MIN_VALUE;
for( int i = 0 ; i < Data.length ; i ++ )
if ( Max < Data[i] )
Max = Data[i];
return Max;
}
public static int[][] CetnostCisel( int[] SourceData ) {
int MaxArraySize = NajdiMax( SourceData ) + 1;
int[][] Result = new int[MaxArraySize][2];
int[] Tmp = new int[MaxArraySize];
for ( int i = 0 ; i < SourceData.length ; i ++ )
Tmp[SourceData[i]] ++ ;
boolean[] CheckedKeys = new boolean[Tmp.length];
for ( int Rows = 0 ; Rows < Tmp.length ; Rows ++ )
{
int MaxKeyIndex = 0 , MaxValue = Integer.MIN_VALUE;
for ( int i = 0 ; i < Tmp.length ; i ++ ) {
if ( Tmp[i] > MaxValue && CheckedKeys[i] != true ) {
MaxKeyIndex = i;
MaxValue = Tmp[i];
}
}
CheckedKeys[MaxKeyIndex] = true;
Result[Rows][0] = MaxKeyIndex;
Result[Rows][1] = MaxValue;
}
return Result;
}
}