C Kata - Find the smallest integer in the array

By Lochard | As a newbie programmer | 23 Sep 2022


Learning from YayoDrayber, I am sharing my CodeWars Kata.

 

DESCRIPTION:

Given an array of integers your solution should find the smallest integer.

 

For example:

Given `[34, 15, 88, 2]` your solution will return `2`

Given `[34, -345, -1, 100]` your solution will return `-345`

You can assume, for the purpose of this kata, that the supplied array will not be empty.

 

Starting Code

#include <stddef.h>

int find_smallest_int(int *vec, size_t len)
{
    return *vec;
}

My attempt

#include <stddef.h>

int find_smallest_int(int *vec, size_t len) {
  int smallest = vec[0];

  for (int i = 1; i < len; i++)
    smallest = smallest > vec[i] ? vec[i] : smallest;

  return smallest;
}

Best Practice

#include <stddef.h>

int find_smallest_int(const int vec[], size_t len) {
  int res = vec[0];

  for (size_t i = 1; i < len; i++)
    if (vec[i] < res)
      res = vec[i];

  return res;
}

Clever

#include <stddef.h>

int find_smallest_int(int *vec, size_t len)
{
    int min = vec[0];

    while(len--)
      if (min > vec[len])
          min = vec[len];

    return min;
}

My Pick

#inclue <stddef.h>

extern int find_smallest_int(int *vec, size_t len);

inline int find_smallest_int(int *vec, size_t len)
{
  int min = *vec++ ;

  for( --len ; len ; --len , ++vec )
    *vec < min ? min = *vec : 0 ;

  return min;
}

My post-Kata snippet

int min(int *arr, int len) {
  int min = *arr;

  while (--len)
    min = *++arr < min ? *arr : min;

  return min;
}

My code snippets on GitHub

How do you rate this article?

1


Lochard
Lochard

20240228 Arrived in the UK for about 2 week. All my fears persist. Some are even getting worse. https://github.com/locharp/asylum_diary/


As a newbie programmer
As a newbie programmer

Sharing entry level codes. My snippets on GitHub https://github.com/locharp/code-snippets

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.