تحديات برمجيةالتحدي الثالث - حل التمرين الثاني بلغة جافا
المطلوب
قم بتعريف دالة إسمها CountOccurrence
, مهمتها البحث في مصفوفة أحادية ( تتألف من أعداد صحيحة ) و طباعة كم مرة تكررت كل قيمة موجودة فيها.
بعدها قم بتجربة هذه الدالة في البرنامج.
الحل بلغة جافا
public class Main {
// هنا قمنا بتعريف الدالة
public static void countOccurrence(int[] arr)
{
int counter = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
counter++;
}
}
if (counter > 0)
{
System.out.println("[0] is repeated " + counter + " time(s)");
}
for (int i = 0; i < arr.length; i++)
{
counter = 1;
if (arr[i] != 0)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] == arr[j])
{
counter++;
arr[j] = 0;
}
}
System.out.println("["+ arr[i] +"] is repeated " + counter + " time(s)");
}
}
}
public static void main(String[] args)
{
// هنا قمنا بتجهيز القيم التي سنمررها للدالة
int[] array = {0, 4, 2, 3, 2, 4, 3, 5, 2, 0, 1, 4, 2};
// هنا قمنا بتجربة الدالة
countOccurrence(array);
}
}
public class Main {
// هنا قمنا بتعريف الدالة
public static void countOccurrence(int[] arr)
{
int counter = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
counter++;
}
}
if (counter > 0)
{
System.out.println("[0] is repeated " + counter + " time(s)");
}
for (int i = 0; i < arr.length; i++)
{
counter = 1;
if (arr[i] != 0)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i] == arr[j])
{
counter++;
arr[j] = 0;
}
}
System.out.println("["+ arr[i] +"] is repeated " + counter + " time(s)");
}
}
}
public static void main(String[] args)
{
// هنا قمنا بتجهيز القيم التي سنمررها للدالة
int[] array = {0, 4, 2, 3, 2, 4, 3, 5, 2, 0, 1, 4, 2};
// هنا قمنا بتجربة الدالة
countOccurrence(array);
}
}
سنحصل على النتيجة التالية عند التشغيل.
[0] is repeated 2 time(s) [4] is repeated 3 time(s) [2] is repeated 4 time(s) [3] is repeated 2 time(s) [5] is repeated 1 time(s) [1] is repeated 1 time(s)