2017-04-22 6 views
1

내 수업의 코딩 과제의 일환으로 10 가지 다른 작업을 제공하는 코드를 생성해야합니다.타겟에 대한 선형 검색

이 작업에서 필자의 목표는 배열의 특정 항목을 검색하고 발견 된 경우 해당 위치를 표시하는 선형 검색 알고리즘을 만드는 것입니다.

이 내 현재 코드입니다 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Linearsearch2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var array = new int[] { 1, 31, 10, 9, 420, -5, 77, 420, 300, 99 }; //Sets up the array 

      var targetvalue = 77; //Establishes what number the search will attempt to find. 
      var targetpos = -1; //Establishes the position in the array of the target. 
      var targetnumber = 0; //Establishes the counter for the number of times the target appears. 
      bool found = false; //Decides wether to change the number or use a counter method. 

      var foundpositions = new int[] { }; //Establishes an array which will hold the positions of located items 

      for (var i = 1; i < array.Length; i++) 
      { 
       if (found == true && array[i] == targetvalue) 
       { 
        targetnumber = targetnumber + 1; 
       } 

       if (found == false && array[i] == targetvalue) //If the target value has not been found yet 
       { 
        foundpositions.Add(i); //This is the line i need help with. I dont know how to add a value to an array properly. 
        found = true; 
       } 
      } 

      if (targetpos != -1){ //If the target number was found 
       Console.WriteLine("The number " + targetvalue + " appeared " + targetnumber + " times, at positions " + foundpositions + "."); // Prints the final outcome. 
      } 
      else //If the target number was not found 
      { 
       Console.WriteLine("The number " + targetvalue + " did not appear in this array."); // Prints the final outcome. 
      } 
     } 
    } 
} 

내가 foundpositions.Add (I)와, 라인 (31) 함께 도움이 필요한 문제;

배열에 값을 제대로 추가하는 줄을 모릅니다.이 문제가 원인 인 것 같습니다. (이 줄에서는 나중에 표시 할 배열에 검색의 현재 위치를 추가하려고합니다.)

감사합니다. 또한, 명백한 다른 눈에 띄는 오류가 있으면이를 지적 해 주시면 감사하겠습니다.

+0

대상이 발견되었는지 확인하는 이유를 설명 할 수 있습니까? 이것은 불필요한 것으로 보인다. – JohnG

답변

0

제가 도움이 필요한 문제는 과 31 행입니다. foundpositions.Add (i);

배열은 하지 동적하고는 add() 방법이 없습니다. 대신 List을 사용할 수 있습니다.

이 대체 :이와

var foundpositions = new int[] { }; 

: 또한

var foundpositions = new List<int>(); 

을, 당신이와 아무 짓도 한 것으로 변수를 선언하지 않는 것 :

var targetpos = -1; 

이 때문에 의지를 제어 결코 안으로 들어가는이 if 블록 : 이 작업에

if (targetpos != -1){ //If the target number was found 
     Console.WriteLine("The number " + targetvalue + " appeared " + targetnumber + " times, at positions " + foundpositions + "."); // Prints the final outcome. 
} 

, 내 목표는 배열에서 특정 항목을 검색하고 찾을 경우 그 위치 (들)을 표시하는 선형 검색 알고리즘을 만드는 것입니다.

코드가 현재 보이는 것처럼 몇 가지 오류가있는 것 같습니다.

public static int LinearSearch(int[] items, int target) 
{ 
     if (items == null) throw new ArgumentNullException("argument items has null reference"); 
     if (items.Length == 0) return -1; // return -1 if the item is not found 
     for (int i = 0; i < items.Length; i++) 
      if (items[i] == target) return i; 
     return -1; // return -1 if the item is not found 
} 

는 단순히 필요한 데이터의 main 방법 통과 내에 LinearSearch를 호출하고 당신은 갈 수 있어요 그러나, 아래의 예는이 시작하는 데 도움이됩니다.

변수에 LinearSearch의 반환 값을 할당하거나 단순히 콘솔에 출력하는 것을 잊지 마십시오.

0

잘 모르겠습니다 타겟 번호가 있는지 확인하는 이유는 무엇입니까?타겟 int와 동일한 모든 int의 배열의 인덱스를 취득하고 싶은 경우는, 배열을 루프 해, 일치를 int의 List에 넣고이리스트를 돌려 줄 수가 있습니다.

이 반환 된 목록의 개수는 일치하는 대상의 수와 목록에 일치하는 색인이 포함되어 있음을 알려줍니다. 배열을 반복하면서 대상을 찾았는지 확인해야 할 이유가없는 것으로 보입니다. 리턴 된 목록이 비어 있으면 대상을 찾을 수 없습니다. 아래 코드는이 방법을 사용했습니다. 나는 뭔가를 놓치지 않기를 바란다.

private static void FindTargets() { 
    var array = new int[] { 1, 31, 10, 9, 420, -5, 77, 420, 300, 99, 1, 31, 10, 9, 420, -5, 77, 420, 300, 99 }; //Sets up the array 
    int target = 77; 
    List<int> foundTargets = GetPositions(target, array); 
    StringBuilder sb = new StringBuilder(); 
    sb.Append("There are " + foundTargets.Count + " int(s) that match " + target + Environment.NewLine); 
    sb.Append("The array indexs for the target ints " + target + " are: "); 
    int count = 0; 
    foreach (int curInt in foundTargets) { 
    sb.Append(curInt); 
    if (count < foundTargets.Count - 1) 
     sb.Append(", "); 
    count++; 
    } 
    Console.WriteLine(sb.ToString()); 
} 

private static List<int> GetPositions(int target, int[] intArray) { 
    List<int> foundTargets = new List<int>(); 
    for (int i = 0; i < intArray.Length; i++) { 
    if (intArray[i] == target) { 
     foundTargets.Add(i); 
    } 
    } 
    return foundTargets; 
}