تحديات برمجيةالتحدي الثالث - حل التمرين الثاني بلغة C#
المطلوب
قم بتعريف دالة إسمها CountOccurrence
, مهمتها البحث في مصفوفة أحادية ( تتألف من أعداد صحيحة ) و طباعة كم مرة تكررت كل قيمة موجودة فيها.
بعدها قم بتجربة هذه الدالة في البرنامج.
الحل بلغة C#
using System;
class Program
{
// هنا قمنا بتعريف الدالة
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)
{
Console.WriteLine("[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;
}
}
Console.WriteLine("[" + arr[i] + "] is repeated " + counter + " time(s)");
}
}
}
static void Main(string[] args)
{
// هنا قمنا بتجهيز القيم التي سنمررها للدالة
int[] array = { 0, 4, 2, 3, 2, 4, 3, 5, 2, 0, 1, 4, 2 };
// هنا قمنا بتجربة الدالة
CountOccurrence(array);
Console.ReadKey();
}
}
using System;
class Program
{
// هنا قمنا بتعريف الدالة
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)
{
Console.WriteLine("[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;
}
}
Console.WriteLine("[" + arr[i] + "] is repeated " + counter + " time(s)");
}
}
}
static void Main(string[] args)
{
// هنا قمنا بتجهيز القيم التي سنمررها للدالة
int[] array = { 0, 4, 2, 3, 2, 4, 3, 5, 2, 0, 1, 4, 2 };
// هنا قمنا بتجربة الدالة
CountOccurrence(array);
Console.ReadKey();
}
}
سنحصل على النتيجة التالية عند التشغيل.
[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)