Algorithm 17 - A Needle in the Haystack

Beast from the east·2021년 10월 6일
0

Algorithm

목록 보기
17/27

Q.

Description:
Can you find the needle in the haystack?

Write a function findNeedle() that takes an array full of junk but containing one "needle"

After your function finds the needle it should return a message (as a string) that says:

"found the needle at position " plus the index it found the needle, so:

find_needle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])
should return "found the needle at position 5"

A)

#include <stddef.h>
#include <stdlib.h>
#include <string.h>

char *find_needle(const char **haystack, size_t count)
{
  char *buf = calloc(100, sizeof(char));
  char *tmp = malloc(256);
  if (!buf || !tmp)
    return NULL;
  size_t i = 0;
  strcpy(buf, "found the needle at position ");
  while (i < count)
  {
    if (strcmp(haystack[i], "needle") == 0)
      break;
    i++;
  }
  sprintf(tmp, "%d", i);
  strcat(buf, tmp);
  return buf;
}

another solution
#include <stdio.h>

char *find_needle(const char **haystack, size_t count)
{
  for(int i=0; i<count;++i)
  {
    if(!strcmp(haystack[i], "needle")) // strcmp will return 0 if true, so we need '!' to it to work
    {
      char* buff;
      asprintf(&buff, "found the needle at position %d", i);
      return buff;
    }
  }
} -> asprintf() .. i의 숫자를 넣은 문자열(read only)을 buff에 저장.

another solution
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

char *find_needle(const char **haystack, size_t count)
{
  while (strcmp(haystack[--count], "needle"));
  char *buf = malloc(128);
  sprintf(buf, "found the needle at position %d", count);
  return buf;
} -> sprintf() .. 위와 비슷.
profile
Hello, Rabbit

0개의 댓글