[英]Searching Algorithm C#
我有問題要使用布爾函數創建搜索算法,這是我的代碼
private bool IsEqual(int data1, int[] arr2){
bool find=false;
foreach(int data2 in arr2){
if(data1==data2){
find=true;
break;
}
}
return find;
}
這是我所謂的功能
int data1=2;
int[] arr={1,2,3,4,5};
if(IsEqual(data1, arr)){
console.writeline("Find in index");
}
如果找到數字,如何獲取數組的索引?
注意:
我必須使用布爾功能
我無法在布爾函數中添加參數
我無法在ref int data1之類的參數中添加關鍵字
僅更改布爾功能
我無法添加其他功能
您可以返回index
。 如果未找到,則返回-1(而不是false)
您必須自己計算,或切換到使用for(int i=...
循環:
int i = 0;
foreach(int data2 in arr2) {
if( data2 == data1 ) return i;
i++;
}
return -1;
C#具有引用參數的概念: https : //msdn.microsoft.com/zh-cn/library/14akc2c7.aspx 。
private bool IsEqual(ref int data1, int[] arr2) {
bool find=false;
for(int i = 0; i < arr2.Length; i++) {
if(data1==arr2[i]) {
find=true;
data1 = i;
break;
}
}
if(!find) {
data1 = -1;
}
return find;
}
可以這樣稱呼
int data1=2;
int[] arr={5,4,3,2,1};
if(IsEqual(ref data1, arr)){
console.writeline("Find in index");
}
int index = data1;
將out
參數與for
循環結合使用。 在這里玩。 使用out
參數可以保持返回bool
,並且構建了for
循環來跟蹤數組索引。
using System;
public class Program
{
// this is your method
// using an out parameter and a for loop
// ignore the static keyword - it isn't important for the example
private static bool IsEqual(int data1, int[] arr2, out int index)
{
index = -1;
bool find = false;
for(int i = 0; i < arr2.Length; i++)
{
if (data1 == arr2[i])
{
find = true;
index = i;
break;
}
}
// you don't need to return the index
// the out parameter covers that for you
return find;
}
public static void Main()
{
// and this is i call the function
int data1 = 2;
int[] arr = { 1, 2, 3, 4, 5 };
int index;
if (IsEqual(data1, arr, out index))
{
Console.WriteLine("Find in index {0}", index);
}
}
}
好的,給定您奇怪的約束,下面是一些使用“ IsEqual
函數查找int索引的代碼:
int data1=2;
int[] arr={1,2,3,4,5};
for (int ix = 0; ix < arr.Length; ix++) {
if(IsEqual(data1, new int[] { arr[ix] })) {
Console.WriteLine("Find in index {0}", ix);
break;
}
}
這是非常糟糕的代碼,但是它可以滿足您的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.