id
int64 4
16.3M
| file_name
stringlengths 3
68
| file_path
stringlengths 14
181
| content
stringlengths 39
9.06M
| size
int64 39
9.06M
| language
stringclasses 1
value | extension
stringclasses 2
values | total_lines
int64 1
711k
| avg_line_length
float64 3.18
138
| max_line_length
int64 10
140
| alphanum_fraction
float64 0.02
0.93
| repo_name
stringlengths 7
69
| repo_stars
int64 2
61.6k
| repo_forks
int64 12
7.81k
| repo_open_issues
int64 0
1.13k
| repo_license
stringclasses 10
values | repo_extraction_date
stringclasses 657
values | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 1
class | exact_duplicates_redpajama
bool 1
class | exact_duplicates_githubcode
bool 2
classes | near_duplicates_stackv2
bool 1
class | near_duplicates_stackv1
bool 1
class | near_duplicates_redpajama
bool 1
class | near_duplicates_githubcode
bool 2
classes |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,465
|
util-checksum.c
|
robertdavidgraham_masscan/src/util-checksum.c
|
/*
Calculates Internet checksums for protocols like TCP/IP.
Author: Robert David Graham
Copyright: 2020
License: The MIT License (MIT)
Dependencies: none
*/
#include "util-checksum.h"
/**
* Calculates the checksum over a buffer.
* @param checksum
* The value of the pseudo-header checksum that this sum will be
* added to. This value must be calculated separately. This
* is the original value in 2s-complement. In other words,
* for TCP, which will be the integer value of the
* IP addresses, protocol number, and length field added together.
* @param buf
* The buffer that we are checksumming, such as all the
* payload after an IPv4 or IPv6 header.
*/
static unsigned
_checksum_calculate(const void *vbuf, size_t length)
{
unsigned sum = 0;
size_t i;
const unsigned char *buf = (const unsigned char *)vbuf;
int is_remainder;
/* If there is an odd number of bytes, then we handle the
* last byte in a custom manner. */
is_remainder = (length & 1);
length &= (~1);
/* Sum up all the 16-bit words in the packet */
for (i=0; i<length; i += 2) {
sum += buf[i]<<8 | buf[i+1];
}
/* If there is an odd number of bytes, then add the last
* byte to the sum, in big-endian format as if there was
* an additional trailing byte of zero. */
if (is_remainder)
sum += buf[length]<<8;
/* Return the raw checksum. Note that this hasn't been
* truncated to 16-bits yet or had the bits reversed. */
return sum;
}
/**
* After we sum up all the numbers involved, we must "fold" the upper
* 16-bits back into the lower 16-bits. Since something like 0x1FFFF
* will fold into 0x10000, we need to call a second fold operation
* (obtaining 0x0001 in this example). In other words, we need to
* keep folding until the result is 16-bits, but that never takes
* more than two folds. After this, we need to take the 1s-complement,
* which means reversing the bits so that 0 becomes 1 and 1 becomes 0.
*/
static unsigned
_checksum_finish(unsigned sum)
{
sum = (sum >> 16) + (sum & 0xFFFF);
sum = (sum >> 16) + (sum & 0xFFFF);
return (~sum) & 0xFFFF;
}
unsigned
checksum_ipv4(unsigned ip_src, unsigned ip_dst, unsigned ip_proto, size_t payload_length, const void *payload)
{
unsigned sum;
const unsigned char *buf = (const unsigned char *)payload;
/* Calculate the sum of the pseudo-header. Note that all these fields
* are assumed to be in host byte-order, not big-endian */
sum = (ip_src>>16) & 0xFFFF;
sum += (ip_src>> 0) & 0xFFFF;
sum += (ip_dst>>16) & 0xFFFF;
sum += (ip_dst>> 0) & 0xFFFF;
sum += ip_proto;
sum += (unsigned)payload_length;
sum += _checksum_calculate(buf, payload_length);
/* Remove the existing checksum field from the calculation. */
switch (ip_proto) {
case 0: /* IP header -- has no pseudo header */
sum = _checksum_calculate(buf, payload_length);
sum -= buf[10]<<8 | buf[11]; /* pretend the existing checksum field is zero */
break;
case 1:
sum -= buf[2]<<8 | buf[3];
break;
case 2: /* IGMP - group message - has no pseudo header */
sum = _checksum_calculate(payload, payload_length);
sum -= buf[2]<<8 | buf[3];
break;
case 6:
sum -= buf[16]<<8 | buf[17];
break;
case 17:
sum -= buf[6]<<8 | buf[7];
break;
default:
return 0xFFFFFFFF;
}
sum = _checksum_finish(sum);
return sum;
}
unsigned
checksum_ipv6(const unsigned char *ip_src, const unsigned char *ip_dst, unsigned ip_proto, size_t payload_length, const void *payload)
{
const unsigned char *buf = (const unsigned char *)payload;
unsigned sum;
/* Calculate the pseudo-header */
sum = _checksum_calculate(ip_src, 16);
sum += _checksum_calculate(ip_dst, 16);
sum += (unsigned)payload_length;
sum += ip_proto;
/* Calculate the remainder of the checksum */
sum += _checksum_calculate(payload, payload_length);
/* Remove the existing checksum field. */
switch (ip_proto) {
case 0:
return 0;
case 1:
case 58:
sum -= buf[2]<<8 | buf[3];
break;
case 6:
sum -= buf[16]<<8 | buf[17];
break;
case 17:
sum -= buf[6]<<8 | buf[7];
break;
default:
return 0xFFFFFFFF;
}
/* fold and invert */
sum = _checksum_finish(sum);
return sum;
}
/*
* Test cases for IPv4
*/
static struct {
unsigned checksum;
const char *buf;
unsigned ip_src;
unsigned ip_dst;
size_t length;
unsigned ip_proto;
} ipv4packets[] = {
{
0xee9b,
"\x11\x64\xee\x9b\x00\x00\x00\x00",
0x0a141e01, 0xe0000001, 8, 2 /* IGMP - Group Message protocol */
}, {
0x6042,
"\xdc\x13\x01\xbb\x00\x29\x60\x42"
"\x5b\xd6\x16\x3a\xb1\x78\x3d\x5d\xdd\x0e\x5a\x05\x35\x74\x92\x91"
"\x57\x4c\xaa\xc1\x85\x76\xc0\x0f\x8d\x9e\x19\xa5\xcc\xa2\x81\x65\xbe",
0x0a141ec9, 0xadc2900a, 41, 17 /* UDP */
}, {
0x84b2,
"\x7e\x70\x69\x95\x1f\xb9\x77\xc6\xee\x09\x7b\x72\x50\x18\x03\xfd"
"\x84\xb2\x00\x00"
"\x17\x03\x03\x00\x3a\x6c\x04\xe3\x0e\x25\x79\x8e\x1c\x98\xdd\x2c"
"\x8d\x41\x39\x53\xfb\xd0\xd5\x3e\x14\xf8\xdf\xb9\xb8\x47\xe0\x43"
"\xab\x09\x24\x58\x7c\x6a\xab\x91\xaf\x24\xc0\x5c\xc6\xaf\x56\x45"
"\xed\xa3\xde\x06\xa2\xd1\x79\x0a\x21\xfe\x9c\x2e\x6e\x81\x19",
0x0a141ec9, 0xa2fec14a, 83, 6 /* TCP */
}, {0}
};
/*
* Test cases for IPv6
*/
static struct {
unsigned checksum;
const char *buf;
const char *ip_src;
const char *ip_dst;
size_t length;
unsigned ip_proto;
} ipv6packets[] = {
{
0x09e3,
"\x02\x22\x02\x23\x00\x32\x09\xe3"
"\x0b\x15\x18\x54\x00\x06\x00\x0a\x00\x17\x00\x18\x00\x38\x00\x1f"
"\x00\x0e\x00\x01\x00\x0e\x00\x02\x00\x00\xab\x11\xfd\xb3\xae\xbb"
"\xe6\x57\x00\x5c\x00\x08\x00\x02\x00\x00",
"\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x07\x32\xff\xfe\x42\x5e\x35",
"\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02",
50, 17 /* UDP */
}, { 0xbf3c,
"\x8f\x00\xbf\x3c\x00\x00\x00\x04\x04\x00\x00\x00\xff\x02\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x01\xff\x03\x68\x4c\x04\x00\x00\x00"
"\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xff\xd4\xa6\x80"
"\x04\x00\x00\x00\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"
"\xff\x06\xab\x72\x04\x00\x00\x00\xff\x02\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x01\xff\x2f\x65\x52",
"\xfe\x80\x00\x00\x00\x00\x00\x00\x1c\x7b\x06\x42\x4e\x57\x19\xcc",
"\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16",
88, 58 /* ICMPv6 */
}, { 0x0d0e,
"\x8d\x59\x01\xbb\xed\xb8\x70\x8b\x91\x6c\x8d\x68\x50\x10\x04\x01"
"\x0d\x0e\x00\x00",
"\x20\x02\x18\x62\x5d\xeb\x00\x00\xac\xc3\x59\xad\x84\x6b\x97\x80",
"\x26\x02\xff\x52\x00\x00\x00\x6a\x00\x00\x00\x00\x1f\xd2\x94\x5a",
20, 6 /* TCP */
}, {0}
};
int checksum_selftest(void)
{
unsigned sum;
size_t i;
/* Run through some IPv6 examples of TCP, UDP, and ICMP */
for (i=0; ipv6packets[i].buf; i++) {
sum = checksum_ipv6(
(const unsigned char *)ipv6packets[i].ip_src,
(const unsigned char *)ipv6packets[i].ip_dst,
ipv6packets[i].ip_proto,
ipv6packets[i].length,
ipv6packets[i].buf);
if (sum != ipv6packets[i].checksum)
return 1; /* fail */
}
/* Run through some IPv4 examples of TCP, UDP, and ICMP */
for (i=0; ipv4packets[i].buf; i++) {
sum = checksum_ipv4(ipv4packets[i].ip_src,
ipv4packets[i].ip_dst,
ipv4packets[i].ip_proto,
ipv4packets[i].length,
ipv4packets[i].buf);
if (sum != ipv4packets[i].checksum)
return 1; /* fail */
}
return 0; /* success */
}
| 8,104
|
C
|
.c
| 229
| 29.515284
| 134
| 0.614022
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,467
|
main.c
|
robertdavidgraham_masscan/src/main.c
|
/*
main
This includes:
* main()
* transmit_thread() - transmits probe packets
* receive_thread() - receives response packets
You'll be wanting to study the transmit/receive threads, because that's
where all the action is.
This is the lynch-pin of the entire program, so it includes a heckuva lot
of headers, and the functions have a lot of local variables. I'm trying
to make this file relative "flat" this way so that everything is visible.
*/
#include "masscan.h"
#include "masscan-version.h"
#include "masscan-status.h" /* open or closed */
#include "massip-parse.h"
#include "massip-port.h"
#include "main-status.h" /* printf() regular status updates */
#include "main-throttle.h" /* rate limit */
#include "main-dedup.h" /* ignore duplicate responses */
#include "main-ptrace.h" /* for nmap --packet-trace feature */
#include "main-globals.h" /* all the global variables in the program */
#include "main-readrange.h"
#include "crypto-siphash24.h" /* hash function, for hash tables */
#include "crypto-blackrock.h" /* the BlackRock shuffling func */
#include "crypto-lcg.h" /* the LCG randomization func */
#include "crypto-base64.h" /* base64 encode/decode */
#include "templ-pkt.h" /* packet template, that we use to send */
#include "util-logger.h" /* adjust with -v command-line opt */
#include "stack-ndpv6.h" /* IPv6 Neighbor Discovery Protocol */
#include "stack-arpv4.h" /* Handle ARP resolution and requests */
#include "rawsock.h" /* API on top of Linux, Windows, Mac OS X*/
#include "rawsock-adapter.h" /* Get Ethernet adapter configuration */
#include "rawsock-pcapfile.h" /* for saving pcap files w/ raw packets */
#include "syn-cookie.h" /* for SYN-cookies on send */
#include "output.h" /* for outputting results */
#include "rte-ring.h" /* producer/consumer ring buffer */
#include "stub-pcap.h" /* dynamically load libpcap library */
#include "smack.h" /* Aho-corasick state-machine pattern-matcher */
#include "pixie-timer.h" /* portable time functions */
#include "pixie-threads.h" /* portable threads */
#include "pixie-backtrace.h" /* maybe print backtrace on crash */
#include "templ-payloads.h" /* UDP packet payloads */
#include "in-binary.h" /* convert binary output to XML/JSON */
#include "vulncheck.h" /* checking vulns like monlist, poodle, heartblee */
#include "scripting.h"
#include "read-service-probes.h"
#include "misc-rstfilter.h"
#include "proto-x509.h"
#include "proto-arp.h" /* for responding to ARP requests */
#include "proto-banner1.h" /* for snatching banners from systems */
#include "stack-tcp-core.h" /* for TCP/IP connection table */
#include "proto-preprocess.h" /* quick parse of packets */
#include "proto-icmp.h" /* handle ICMP responses */
#include "proto-udp.h" /* handle UDP responses */
#include "proto-snmp.h" /* parse SNMP responses */
#include "proto-ntp.h" /* parse NTP responses */
#include "proto-coap.h" /* CoAP selftest */
#include "proto-zeroaccess.h"
#include "proto-sctp.h"
#include "proto-oproto.h" /* Other protocols on top of IP */
#include "util-malloc.h"
#include "util-checksum.h"
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <signal.h>
#include <stdint.h>
#if defined(WIN32)
#include <WinSock.h>
#if defined(_MSC_VER)
#pragma comment(lib, "Ws2_32.lib")
#endif
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#endif
/*
* yea I know globals suck
*/
unsigned volatile is_tx_done = 0;
unsigned volatile is_rx_done = 0;
time_t global_now;
uint64_t usec_start;
/***************************************************************************
* We create a pair of transmit/receive threads for each network adapter.
* This structure contains the parameters we send to each pair.
***************************************************************************/
struct ThreadPair {
/** This points to the central configuration. Note that it's 'const',
* meaning that the thread cannot change the contents. That'd be
* unsafe */
const struct Masscan *masscan;
/** The adapter used by the thread-pair. Normally, thread-pairs have
* their own network adapter, especially when doing PF_RING
* clustering. */
struct Adapter *adapter;
struct stack_t *stack;
/**
* The index of the network adapter that we are using for this
* thread-pair. This is an index into the "masscan->nic[]"
* array.
*
* NOTE: this is also the "thread-id", because we create one
* transmit/receive thread pair per NIC.
*/
unsigned nic_index;
/**
* A copy of the master 'index' variable. This is just advisory for
* other threads, to tell them how far we've gotten.
*/
volatile uint64_t my_index;
/* This is used both by the transmit and receive thread for
* formatting packets */
struct TemplateSet tmplset[1];
/**
* The current IP address we are using for transmit/receive.
*/
struct stack_src_t _src_;
macaddress_t source_mac;
macaddress_t router_mac_ipv4;
macaddress_t router_mac_ipv6;
unsigned done_transmitting;
unsigned done_receiving;
double pt_start;
struct Throttler throttler[1];
uint64_t *total_synacks;
uint64_t *total_tcbs;
uint64_t *total_syns;
size_t thread_handle_xmit;
size_t thread_handle_recv;
};
struct source_t {
unsigned ipv4;
unsigned ipv4_mask;
unsigned port;
unsigned port_mask;
ipv6address ipv6;
ipv6address ipv6_mask;
};
/***************************************************************************
* We support a range of source IP/port. This function converts that
* range into useful variables we can use to pick things form that range.
***************************************************************************/
static void
adapter_get_source_addresses(const struct Masscan *masscan,
unsigned nic_index,
struct source_t *src)
{
const struct stack_src_t *ifsrc = &masscan->nic[nic_index].src;
static ipv6address mask = {~0ULL, ~0ULL};
src->ipv4 = ifsrc->ipv4.first;
src->ipv4_mask = ifsrc->ipv4.last - ifsrc->ipv4.first;
src->port = ifsrc->port.first;
src->port_mask = ifsrc->port.last - ifsrc->port.first;
src->ipv6 = ifsrc->ipv6.first;
/* TODO: currently supports only a single address. This needs to
* be fixed to support a list of addresses */
src->ipv6_mask = mask;
}
/***************************************************************************
* This thread spews packets as fast as it can
*
* THIS IS WHERE ALL THE EXCITEMENT HAPPENS!!!!
* 90% of CPU cycles are in the function.
*
***************************************************************************/
static void
transmit_thread(void *v) /*aka. scanning_thread() */
{
struct ThreadPair *parms = (struct ThreadPair *)v;
uint64_t i;
uint64_t start;
uint64_t end;
const struct Masscan *masscan = parms->masscan;
uint64_t retries = masscan->retries;
uint64_t rate = (uint64_t)masscan->max_rate;
unsigned r = (unsigned)retries + 1;
uint64_t range;
uint64_t range_ipv6;
struct BlackRock blackrock;
uint64_t count_ipv4 = rangelist_count(&masscan->targets.ipv4);
uint64_t count_ipv6 = range6list_count(&masscan->targets.ipv6).lo;
struct Throttler *throttler = parms->throttler;
struct TemplateSet pkt_template = templ_copy(parms->tmplset);
struct Adapter *adapter = parms->adapter;
uint64_t packets_sent = 0;
unsigned increment = masscan->shard.of * masscan->nic_count;
struct source_t src;
uint64_t seed = masscan->seed;
uint64_t repeats = 0; /* --infinite repeats */
uint64_t *status_syn_count;
uint64_t entropy = masscan->seed;
/* Wait to make sure receive_thread is ready */
pixie_usleep(1000000);
LOG(1, "[+] starting transmit thread #%u\n", parms->nic_index);
/* export a pointer to this variable outside this threads so
* that the 'status' system can print the rate of syns we are
* sending */
status_syn_count = MALLOC(sizeof(uint64_t));
*status_syn_count = 0;
parms->total_syns = status_syn_count;
/* Normally, we have just one source address. In special cases, though
* we can have multiple. */
adapter_get_source_addresses(masscan, parms->nic_index, &src);
/* "THROTTLER" rate-limits how fast we transmit, set with the
* --max-rate parameter */
throttler_start(throttler, masscan->max_rate/masscan->nic_count);
infinite:
/* Create the shuffler/randomizer. This creates the 'range' variable,
* which is simply the number of IP addresses times the number of
* ports.
* IPv6: low index will pick addresses from the IPv6 ranges, and high
* indexes will pick addresses from the IPv4 ranges. */
range = count_ipv4 * rangelist_count(&masscan->targets.ports)
+ count_ipv6 * rangelist_count(&masscan->targets.ports);
range_ipv6 = count_ipv6 * rangelist_count(&masscan->targets.ports);
blackrock_init(&blackrock, range, seed, masscan->blackrock_rounds);
/* Calculate the 'start' and 'end' of a scan. One reason to do this is
* to support --shard, so that multiple machines can co-operate on
* the same scan. Another reason to do this is so that we can bleed
* a little bit past the end when we have --retries. Yet another
* thing to do here is deal with multiple network adapters, which
* is essentially the same logic as shards. */
start = masscan->resume.index + (masscan->shard.one-1) * masscan->nic_count + parms->nic_index;
end = range;
if (masscan->resume.count && end > start + masscan->resume.count)
end = start + masscan->resume.count;
end += retries * range;
/* -----------------
* the main loop
* -----------------*/
LOG(3, "THREAD: xmit: starting main loop: [%llu..%llu]\n", start, end);
for (i=start; i<end; ) {
uint64_t batch_size;
/*
* Do a batch of many packets at a time. That because per-packet
* throttling is expensive at 10-million pps, so we reduce the
* per-packet cost by doing batches. At slower rates, the batch
* size will always be one. (--max-rate)
*/
batch_size = throttler_next_batch(throttler, packets_sent);
/*
* Transmit packets from other thread, when doing --banners. This
* takes priority over sending SYN packets. If there is so much
* activity grabbing banners that we cannot transmit more SYN packets,
* then "batch_size" will get decremented to zero, and we won't be
* able to transmit SYN packets.
*/
stack_flush_packets(parms->stack, adapter,
&packets_sent, &batch_size);
/*
* Transmit a bunch of packets. At any rate slower than 100,000
* packets/second, the 'batch_size' is likely to be 1. At higher
* rates, we can't afford to throttle on a per-packet basis and
* instead throttle on a per-batch basis. In other words, throttle
* based on 2-at-a-time, 3-at-time, and so on, with the batch
* size increasing as the packet rate increases. This gives us
* very precise packet-timing for low rates below 100,000 pps,
* while not incurring the overhead for high packet rates.
*/
while (batch_size && i < end) {
uint64_t xXx;
uint64_t cookie;
/*
* RANDOMIZE THE TARGET:
* This is kinda a tricky bit that picks a random IP and port
* number in order to scan. We monotonically increment the
* index 'i' from [0..range]. We then shuffle (randomly transmog)
* that index into some other, but unique/1-to-1, number in the
* same range. That way we visit all targets, but in a random
* order. Then, once we've shuffled the index, we "pick" the
* IP address and port that the index refers to.
*/
xXx = (i + (r--) * rate);
if (rate > range)
xXx %= range;
else
while (xXx >= range)
xXx -= range;
xXx = blackrock_shuffle(&blackrock, xXx);
if (xXx < range_ipv6) {
ipv6address ip_them;
unsigned port_them;
ipv6address ip_me;
unsigned port_me;
ip_them = range6list_pick(&masscan->targets.ipv6, xXx % count_ipv6);
port_them = rangelist_pick(&masscan->targets.ports, xXx / count_ipv6);
ip_me = src.ipv6;
port_me = src.port;
cookie = syn_cookie_ipv6(ip_them, port_them, ip_me, port_me, entropy);
rawsock_send_probe_ipv6(
adapter,
ip_them, port_them,
ip_me, port_me,
(unsigned)cookie,
!batch_size, /* flush queue on last packet in batch */
&pkt_template
);
/* Our index selects an IPv6 target */
} else {
/* Our index selects an IPv4 target. In other words, low numbers
* index into the IPv6 ranges, and high numbers index into the
* IPv4 ranges. */
ipv4address ip_them;
ipv4address port_them;
unsigned ip_me;
unsigned port_me;
xXx -= range_ipv6;
ip_them = rangelist_pick(&masscan->targets.ipv4, xXx % count_ipv4);
port_them = rangelist_pick(&masscan->targets.ports, xXx / count_ipv4);
/*
* SYN-COOKIE LOGIC
* Figure out the source IP/port, and the SYN cookie
*/
if (src.ipv4_mask > 1 || src.port_mask > 1) {
uint64_t ck = syn_cookie_ipv4((unsigned)(i+repeats),
(unsigned)((i+repeats)>>32),
(unsigned)xXx, (unsigned)(xXx>>32),
entropy);
port_me = src.port + (ck & src.port_mask);
ip_me = src.ipv4 + ((ck>>16) & src.ipv4_mask);
} else {
ip_me = src.ipv4;
port_me = src.port;
}
cookie = syn_cookie_ipv4(ip_them, port_them, ip_me, port_me, entropy);
/*
* SEND THE PROBE
* This is sorta the entire point of the program, but little
* exciting happens here. The thing to note that this may
* be a "raw" transmit that bypasses the kernel, meaning
* we can call this function millions of times a second.
*/
rawsock_send_probe_ipv4(
adapter,
ip_them, port_them,
ip_me, port_me,
(unsigned)cookie,
!batch_size, /* flush queue on last packet in batch */
&pkt_template
);
}
batch_size--;
packets_sent++;
(*status_syn_count)++;
/*
* SEQUENTIALLY INCREMENT THROUGH THE RANGE
* Yea, I know this is a puny 'i++' here, but it's a core feature
* of the system that is linearly increments through the range,
* but produces from that a shuffled sequence of targets (as
* described above). Because we are linearly incrementing this
* number, we can do lots of creative stuff, like doing clever
* retransmits and sharding.
*/
if (r == 0) {
i += increment; /* <------ increment by 1 normally, more with shards/nics */
r = (unsigned)retries + 1;
}
} /* end of batch */
/* save our current location for resuming, if the user pressed
* <ctrl-c> to exit early */
parms->my_index = i;
/* If the user pressed <ctrl-c>, then we need to exit. In case
* the user wants to --resume the scan later, we save the current
* state in a file */
if (is_tx_done) {
break;
}
}
/*
* --infinite
* For load testing, go around and do this again
*/
if (masscan->is_infinite && !is_tx_done) {
seed++;
repeats++;
goto infinite;
}
/*
* Flush any untransmitted packets. High-speed mechanisms like Windows
* "sendq" and Linux's "PF_RING" queue packets and transmit many together,
* so there may be some packets that we've queued but not yet transmitted.
* This call makes sure they are transmitted.
*/
rawsock_flush(adapter);
/*
* Wait until the receive thread realizes the scan is over
*/
LOG(1, "[+] transmit thread #%u complete\n", parms->nic_index);
/*
* We are done transmitting. However, response packets will take several
* seconds to arrive. Therefore, sit in short loop waiting for those
* packets to arrive. Pressing <ctrl-c> a second time will exit this
* prematurely.
*/
while (!is_rx_done) {
unsigned k;
uint64_t batch_size;
for (k=0; k<1000; k++) {
/*
* Only send a few packets at a time, throttled according to the max
* --max-rate set by the user
*/
batch_size = throttler_next_batch(throttler, packets_sent);
/* Transmit packets from the receive thread */
stack_flush_packets( parms->stack, adapter,
&packets_sent,
&batch_size);
/* Make sure they've actually been transmitted, not just queued up for
* transmit */
rawsock_flush(adapter);
pixie_usleep(100);
}
}
/* Thread is about to exit */
parms->done_transmitting = 1;
LOG(1, "[+] exiting transmit thread #%u \n", parms->nic_index);
}
/***************************************************************************
***************************************************************************/
static unsigned
is_nic_port(const struct Masscan *masscan, unsigned ip)
{
unsigned i;
for (i=0; i<masscan->nic_count; i++)
if (is_my_port(&masscan->nic[i].src, ip))
return 1;
return 0;
}
static unsigned
is_ipv6_multicast(ipaddress ip_me)
{
/* If this is an IPv6 multicast packet, one sent to the IPv6
* address with a prefix of FF02::/16 */
return ip_me.version == 6 && (ip_me.ipv6.hi>>48ULL) == 0xFF02;
}
/***************************************************************************
*
* Asynchronous receive thread
*
* The transmit and receive threads run independently of each other. There
* is no record what was transmitted. Instead, the transmit thread sets a
* "SYN-cookie" in transmitted packets, which the receive thread will then
* use to match up requests with responses.
***************************************************************************/
static void
receive_thread(void *v)
{
struct ThreadPair *parms = (struct ThreadPair *)v;
const struct Masscan *masscan = parms->masscan;
struct Adapter *adapter = parms->adapter;
int data_link = stack_if_datalink(adapter);
struct Output *out;
struct DedupTable *dedup;
struct PcapFile *pcapfile = NULL;
struct TCP_ConnectionTable *tcpcon = 0;
uint64_t *status_synack_count;
uint64_t *status_tcb_count;
uint64_t entropy = masscan->seed;
struct ResetFilter *rf;
struct stack_t *stack = parms->stack;
struct source_t src = {0};
/* For reducing RST responses, see rstfilter_is_filter() below */
rf = rstfilter_create(entropy, 16384);
/* some status variables */
status_synack_count = MALLOC(sizeof(uint64_t));
*status_synack_count = 0;
parms->total_synacks = status_synack_count;
status_tcb_count = MALLOC(sizeof(uint64_t));
*status_tcb_count = 0;
parms->total_tcbs = status_tcb_count;
LOG(1, "[+] starting receive thread #%u\n", parms->nic_index);
/* Lock this thread to a CPU. Transmit threads are on even CPUs,
* receive threads on odd CPUs */
if (pixie_cpu_get_count() > 1) {
unsigned cpu_count = pixie_cpu_get_count();
unsigned cpu = parms->nic_index * 2 + 1;
while (cpu >= cpu_count) {
cpu -= cpu_count;
cpu++;
}
//TODO:
//pixie_cpu_set_affinity(cpu);
}
/*
* If configured, open a --pcap file for saving raw packets. This is
* so that we can debug scans, but also so that we can look at the
* strange things people send us. Note that we don't record transmitted
* packets, just the packets we've received.
*/
if (masscan->pcap_filename[0]) {
pcapfile = pcapfile_openwrite(masscan->pcap_filename, 1);
}
/*
* Open output. This is where results are reported when saving
* the --output-format to the --output-filename
*/
out = output_create(masscan, parms->nic_index);
/*
* Create deduplication table. This is so when somebody sends us
* multiple responses, we only record the first one.
*/
dedup = dedup_create();
/*
* Create a TCP connection table (per thread pair) for interacting with live
* connections when doing --banners
*/
if (masscan->is_banners) {
struct TcpCfgPayloads *pay;
size_t i;
/*
* Create TCP connection table
*/
tcpcon = tcpcon_create_table(
(size_t)((masscan->max_rate/5) / masscan->nic_count),
parms->stack,
&parms->tmplset->pkts[Proto_TCP],
output_report_banner,
out,
masscan->tcb.timeout,
masscan->seed
);
/*
* Initialize TCP scripting
*/
scripting_init_tcp(tcpcon, masscan->scripting.L);
/*
* Get the possible source IP addresses and ports that masscan
* might be using to transmit from.
*/
adapter_get_source_addresses(masscan, parms->nic_index, &src);
/*
* Set some flags [kludge]
*/
tcpcon_set_banner_flags(tcpcon,
masscan->is_capture_cert,
masscan->is_capture_servername,
masscan->is_capture_html,
masscan->is_capture_heartbleed,
masscan->is_capture_ticketbleed);
if (masscan->is_hello_smbv1)
tcpcon_set_parameter(tcpcon, "hello", 1, "smbv1");
if (masscan->is_hello_http)
tcpcon_set_parameter(tcpcon, "hello", 1, "http");
if (masscan->is_hello_ssl)
tcpcon_set_parameter(tcpcon, "hello", 1, "ssl");
if (masscan->is_heartbleed)
tcpcon_set_parameter(tcpcon, "heartbleed", 1, "1");
if (masscan->is_ticketbleed)
tcpcon_set_parameter(tcpcon, "ticketbleed", 1, "1");
if (masscan->is_poodle_sslv3)
tcpcon_set_parameter(tcpcon, "sslv3", 1, "1");
if (masscan->http.payload)
tcpcon_set_parameter( tcpcon,
"http-payload",
masscan->http.payload_length,
masscan->http.payload);
if (masscan->http.user_agent)
tcpcon_set_parameter( tcpcon,
"http-user-agent",
masscan->http.user_agent_length,
masscan->http.user_agent);
if (masscan->http.host)
tcpcon_set_parameter( tcpcon,
"http-host",
masscan->http.host_length,
masscan->http.host);
if (masscan->http.method)
tcpcon_set_parameter( tcpcon,
"http-method",
masscan->http.method_length,
masscan->http.method);
if (masscan->http.url)
tcpcon_set_parameter( tcpcon,
"http-url",
masscan->http.url_length,
masscan->http.url);
if (masscan->http.version)
tcpcon_set_parameter( tcpcon,
"http-version",
masscan->http.version_length,
masscan->http.version);
if (masscan->tcp_connection_timeout) {
char foo[64];
snprintf(foo, sizeof(foo), "%u", masscan->tcp_connection_timeout);
tcpcon_set_parameter( tcpcon,
"timeout",
strlen(foo),
foo);
}
if (masscan->tcp_hello_timeout) {
char foo[64];
snprintf(foo, sizeof(foo), "%u", masscan->tcp_hello_timeout);
tcpcon_set_parameter( tcpcon,
"hello-timeout",
strlen(foo),
foo);
}
for (i=0; i<masscan->http.headers_count; i++) {
tcpcon_set_http_header(tcpcon,
masscan->http.headers[i].name,
masscan->http.headers[i].value_length,
masscan->http.headers[i].value,
http_field_replace);
}
for (i=0; i<masscan->http.cookies_count; i++) {
tcpcon_set_http_header(tcpcon,
"Cookie",
masscan->http.cookies[i].value_length,
masscan->http.cookies[i].value,
http_field_add);
}
for (i=0; i<masscan->http.remove_count; i++) {
tcpcon_set_http_header(tcpcon,
masscan->http.headers[i].name,
0,
0,
http_field_remove);
}
for (pay = masscan->payloads.tcp; pay; pay = pay->next) {
char name[64];
snprintf(name, sizeof(name), "hello-string[%u]", pay->port);
tcpcon_set_parameter( tcpcon,
name,
strlen(pay->payload_base64),
pay->payload_base64);
}
}
/*
* In "offline" mode, we don't have any receive threads, so simply
* wait until transmitter thread is done then go to the end
*/
if (masscan->is_offline) {
while (!is_rx_done)
pixie_usleep(10000);
parms->done_receiving = 1;
goto end;
}
/*
* Receive packets. This is where we catch any responses and print
* them to the terminal.
*/
LOG(2, "[+] THREAD: recv: starting main loop\n");
while (!is_rx_done) {
int status;
unsigned length;
unsigned secs;
unsigned usecs;
const unsigned char *px;
int err;
unsigned x;
struct PreprocessedInfo parsed;
ipaddress ip_me;
unsigned port_me;
ipaddress ip_them;
unsigned port_them;
unsigned seqno_me;
unsigned seqno_them;
unsigned cookie;
unsigned Q = 0;
/*
* RECEIVE
*
* This is the boring part of actually receiving a packet
*/
err = rawsock_recv_packet(
adapter,
&length,
&secs,
&usecs,
&px);
if (err != 0) {
if (tcpcon)
tcpcon_timeouts(tcpcon, (unsigned)time(0), 0);
continue;
}
/*
* Do any TCP event timeouts based on the current timestamp from
* the packet. For example, if the connection has been open for
* around 10 seconds, we'll close the connection. (--banners)
*/
if (tcpcon) {
tcpcon_timeouts(tcpcon, secs, usecs);
}
if (length > 1514)
continue;
/*
* "Preprocess" the response packet. This means to go through and
* figure out where the TCP/IP headers are and the locations of
* some fields, like IP address and port numbers.
*/
x = preprocess_frame(px, length, data_link, &parsed);
if (!x)
continue; /* corrupt packet */
ip_me = parsed.dst_ip;
ip_them = parsed.src_ip;
port_me = parsed.port_dst;
port_them = parsed.port_src;
seqno_them = TCP_SEQNO(px, parsed.transport_offset);
seqno_me = TCP_ACKNO(px, parsed.transport_offset);
assert(ip_me.version != 0);
assert(ip_them.version != 0);
switch (parsed.ip_protocol) {
case 132: /* SCTP */
cookie = syn_cookie(ip_them, port_them | (Proto_SCTP<<16), ip_me, port_me, entropy) & 0xFFFFFFFF;
break;
default:
cookie = syn_cookie(ip_them, port_them, ip_me, port_me, entropy) & 0xFFFFFFFF;
}
/* verify: my IP address */
if (!is_my_ip(stack->src, ip_me)) {
/* NDP Neighbor Solicitations don't come to our IP address, but to
* a multicast address */
if (is_ipv6_multicast(ip_me)) {
if (parsed.found == FOUND_NDPv6 && parsed.opcode == 135) {
stack_ndpv6_incoming_request(stack, &parsed, px, length);
}
}
continue;
}
/*
* Handle non-TCP protocols
*/
switch (parsed.found) {
case FOUND_NDPv6:
switch (parsed.opcode) {
case 133: /* Router Solicitation */
/* Ignore router solicitations, since we aren't a router */
continue;
case 134: /* Router advertisement */
/* TODO: We need to process router advertisements while scanning
* so that we can print warning messages if router information
* changes while scanning. */
continue;
case 135: /* Neighbor Solicitation */
/* When responses come back from our scans, the router will send us
* these packets. We need to respond to them, so that the router
* can then forward the packets to us. If we don't respond, we'll
* get no responses. */
stack_ndpv6_incoming_request(stack, &parsed, px, length);
continue;
case 136: /* Neighbor Advertisement */
/* TODO: If doing an --ndpscan, the scanner subsystem needs to deal
* with these */
continue;
case 137: /* Redirect */
/* We ignore these, since we really don't have the capability to send
* packets to one router for some destinations and to another router
* for other destinations */
continue;
default:
break;
}
continue;
case FOUND_ARP:
LOGip(2, ip_them, 0, "-> ARP [%u] \n", px[parsed.found_offset]);
switch (parsed.opcode) {
case 1: /* request */
/* This function will transmit a "reply" to somebody's ARP request
* for our IP address (as part of our user-mode TCP/IP).
* Since we completely bypass the TCP/IP stack, we have to handle ARPs
* ourself, or the router will lose track of us.*/
stack_arp_incoming_request(stack,
ip_me.ipv4,
parms->source_mac,
px, length);
break;
case 2: /* response */
/* This is for "arp scan" mode, where we are ARPing targets rather
* than port scanning them */
/* If we aren't doing an ARP scan, then ignore ARP responses */
if (!masscan->scan_type.arp)
break;
/* If this response isn't in our range, then ignore it */
if (!rangelist_is_contains(&masscan->targets.ipv4, ip_them.ipv4))
break;
/* Ignore duplicates */
if (dedup_is_duplicate(dedup, ip_them, 0, ip_me, 0))
continue;
/* ...everything good, so now report this response */
arp_recv_response(out, secs, px, length, &parsed);
break;
}
continue;
case FOUND_UDP:
case FOUND_DNS:
if (!is_nic_port(masscan, port_me))
continue;
if (parms->masscan->nmap.packet_trace)
packet_trace(stdout, parms->pt_start, px, length, 0);
handle_udp(out, secs, px, length, &parsed, entropy);
continue;
case FOUND_ICMP:
handle_icmp(out, secs, px, length, &parsed, entropy);
continue;
case FOUND_SCTP:
handle_sctp(out, secs, px, length, cookie, &parsed, entropy);
break;
case FOUND_OPROTO: /* other IP proto */
handle_oproto(out, secs, px, length, &parsed, entropy);
break;
case FOUND_TCP:
/* fall down to below */
break;
default:
continue;
}
/* verify: my port number */
if (!is_my_port(stack->src, port_me))
continue;
if (parms->masscan->nmap.packet_trace)
packet_trace(stdout, parms->pt_start, px, length, 0);
Q = 0;
/* Save raw packet in --pcap file */
if (pcapfile) {
pcapfile_writeframe(
pcapfile,
px,
length,
length,
secs,
usecs);
}
{
char buf[64];
LOGip(5, ip_them, port_them, "-> TCP ackno=0x%08x flags=0x%02x(%s)\n",
seqno_me,
TCP_FLAGS(px, parsed.transport_offset),
reason_string(TCP_FLAGS(px, parsed.transport_offset), buf, sizeof(buf)));
}
/* If recording --banners, create a new "TCP Control Block (TCB)" */
if (tcpcon) {
struct TCP_Control_Block *tcb;
/* does a TCB already exist for this connection? */
tcb = tcpcon_lookup_tcb(tcpcon,
ip_me, ip_them,
port_me, port_them);
if (TCP_IS_SYNACK(px, parsed.transport_offset)) {
if (cookie != seqno_me - 1) {
ipaddress_formatted_t fmt = ipaddress_fmt(ip_them);
LOG(0, "%s - bad cookie: ackno=0x%08x expected=0x%08x\n",
fmt.string, seqno_me-1, cookie);
continue;
}
if (tcb == NULL) {
tcb = tcpcon_create_tcb(tcpcon,
ip_me, ip_them,
port_me, port_them,
seqno_me, seqno_them+1,
parsed.ip_ttl, NULL,
secs, usecs);
(*status_tcb_count)++;
}
Q += stack_incoming_tcp(tcpcon, tcb, TCP_WHAT_SYNACK,
0, 0, secs, usecs, seqno_them+1, seqno_me);
} else if (tcb) {
/* If this is an ACK, then handle that first */
if (TCP_IS_ACK(px, parsed.transport_offset)) {
Q += stack_incoming_tcp(tcpcon, tcb, TCP_WHAT_ACK,
0, 0, secs, usecs, seqno_them, seqno_me);
}
/* If this contains payload, handle that second */
if (parsed.app_length) {
Q += stack_incoming_tcp(tcpcon, tcb, TCP_WHAT_DATA,
px + parsed.app_offset, parsed.app_length,
secs, usecs, seqno_them, seqno_me);
}
/* If this is a FIN, handle that. Note that ACK +
* payload + FIN can come together */
if (TCP_IS_FIN(px, parsed.transport_offset)
&& !TCP_IS_RST(px, parsed.transport_offset)) {
Q += stack_incoming_tcp(tcpcon, tcb, TCP_WHAT_FIN,
0, 0,
secs, usecs,
seqno_them + parsed.app_length, /* the FIN comes after any data in the packet */
seqno_me);
}
/* If this is a RST, then we'll be closing the connection */
if (TCP_IS_RST(px, parsed.transport_offset)) {
Q += stack_incoming_tcp(tcpcon, tcb, TCP_WHAT_RST,
0, 0, secs, usecs, seqno_them, seqno_me);
}
} else if (TCP_IS_FIN(px, parsed.transport_offset)) {
ipaddress_formatted_t fmt;
/*
* NO TCB!
* This happens when we've sent a FIN, deleted our connection,
* but the other side didn't get the packet.
*/
fmt = ipaddress_fmt(ip_them);
LOG(4, "%s: received FIN but no TCB\n", fmt.string);
if (TCP_IS_RST(px, parsed.transport_offset))
; /* ignore if it's own TCP flag is set */
else {
int is_suppress;
is_suppress = rstfilter_is_filter(rf, ip_me, port_me, ip_them, port_them);
if (!is_suppress)
tcpcon_send_RST(
tcpcon,
ip_me, ip_them,
port_me, port_them,
seqno_them, seqno_me);
}
}
}
if (Q == 0)
; //printf("\nerr\n");
if (TCP_IS_SYNACK(px, parsed.transport_offset)
|| TCP_IS_RST(px, parsed.transport_offset)) {
/* figure out the status */
status = PortStatus_Unknown;
if (TCP_IS_SYNACK(px, parsed.transport_offset))
status = PortStatus_Open;
if (TCP_IS_RST(px, parsed.transport_offset)) {
status = PortStatus_Closed;
}
/* verify: syn-cookies */
if (cookie != seqno_me - 1) {
ipaddress_formatted_t fmt = ipaddress_fmt(ip_them);
LOG(2, "%s - bad cookie: ackno=0x%08x expected=0x%08x\n",
fmt.string, seqno_me-1, cookie);
continue;
}
/* verify: ignore duplicates */
if (dedup_is_duplicate(dedup, ip_them, port_them, ip_me, port_me))
continue;
/* keep statistics on number received */
if (TCP_IS_SYNACK(px, parsed.transport_offset))
(*status_synack_count)++;
/*
* This is where we do the output
*/
output_report_status(
out,
global_now,
status,
ip_them,
6, /* ip proto = tcp */
port_them,
px[parsed.transport_offset + 13], /* tcp flags */
parsed.ip_ttl,
parsed.mac_src
);
/*
* Send RST so other side isn't left hanging (only doing this in
* complete stateless mode where we aren't tracking banners)
*/
if (tcpcon == NULL && !masscan->is_noreset)
tcp_send_RST(
&parms->tmplset->pkts[Proto_TCP],
parms->stack,
ip_them, ip_me,
port_them, port_me,
0, seqno_me);
}
}
LOG(1, "[+] exiting receive thread #%u \n", parms->nic_index);
/*
* cleanup
*/
end:
if (tcpcon)
tcpcon_destroy_table(tcpcon);
dedup_destroy(dedup);
output_destroy(out);
if (pcapfile)
pcapfile_close(pcapfile);
/*TODO: free stack packet buffers */
/* Thread is about to exit */
parms->done_receiving = 1;
}
/***************************************************************************
* We trap the <ctrl-c> so that instead of exiting immediately, we sit in
* a loop for a few seconds waiting for any late response. But, the user
* can press <ctrl-c> a second time to exit that waiting.
***************************************************************************/
static void control_c_handler(int x)
{
static unsigned control_c_pressed = 0;
static unsigned control_c_pressed_again = 0;
if (control_c_pressed == 0) {
fprintf(stderr,
"waiting several seconds to exit..."
" \n"
);
fflush(stderr);
control_c_pressed = 1+x;
is_tx_done = control_c_pressed;
} else {
if (is_rx_done) {
fprintf(stderr, "\nERROR: threads not exiting %d\n", is_rx_done);
if (is_rx_done++ > 1)
exit(1);
} else {
control_c_pressed_again = 1;
is_rx_done = control_c_pressed_again;
}
}
}
/***************************************************************************
* Called from main() to initiate the scan.
* Launches the 'transmit_thread()' and 'receive_thread()' and waits for
* them to exit.
***************************************************************************/
static int
main_scan(struct Masscan *masscan)
{
struct ThreadPair parms_array[8];
uint64_t count_ips;
uint64_t count_ports;
uint64_t range;
unsigned index;
time_t now = time(0);
struct Status status;
uint64_t min_index = UINT64_MAX;
struct MassVulnCheck *vulncheck = NULL;
struct stack_t *stack;
memset(parms_array, 0, sizeof(parms_array));
/*
* Vuln check initialization
*/
if (masscan->vuln_name) {
unsigned i;
unsigned is_error;
vulncheck = vulncheck_lookup(masscan->vuln_name);
/* If no ports specified on command-line, grab default ports */
is_error = 0;
if (rangelist_count(&masscan->targets.ports) == 0)
rangelist_parse_ports(&masscan->targets.ports, vulncheck->ports, &is_error, 0);
/* Kludge: change normal port range to vulncheck range */
for (i=0; i<masscan->targets.ports.count; i++) {
struct Range *r = &masscan->targets.ports.list[i];
r->begin = (r->begin&0xFFFF) | Templ_VulnCheck;
r->end = (r->end & 0xFFFF) | Templ_VulnCheck;
}
}
/*
* Initialize the task size
*/
count_ips = rangelist_count(&masscan->targets.ipv4) + range6list_count(&masscan->targets.ipv6).lo;
if (count_ips == 0) {
LOG(0, "FAIL: target IP address list empty\n");
LOG(0, " [hint] try something like \"--range 10.0.0.0/8\"\n");
LOG(0, " [hint] try something like \"--range 192.168.0.100-192.168.0.200\"\n");
return 1;
}
count_ports = rangelist_count(&masscan->targets.ports);
if (count_ports == 0) {
LOG(0, "FAIL: no ports were specified\n");
LOG(0, " [hint] try something like \"-p80,8000-9000\"\n");
LOG(0, " [hint] try something like \"--ports 0-65535\"\n");
return 1;
}
range = count_ips * count_ports;
range += (uint64_t)(masscan->retries * range);
/*
* If doing an ARP scan, then don't allow port scanning
*/
if (rangelist_is_contains(&masscan->targets.ports, Templ_ARP)) {
if (masscan->targets.ports.count != 1) {
LOG(0, "FAIL: cannot arpscan and portscan at the same time\n");
return 1;
}
}
/*
* If the IP address range is very big, then require that that the
* user apply an exclude range
*/
if (count_ips > 1000000000ULL && rangelist_count(&masscan->exclude.ipv4) == 0) {
LOG(0, "FAIL: range too big, need confirmation\n");
LOG(0, " [hint] to prevent accidents, at least one --exclude must be specified\n");
LOG(0, " [hint] use \"--exclude 255.255.255.255\" as a simple confirmation\n");
exit(1);
}
/*
* trim the nmap UDP payloads down to only those ports we are using. This
* makes lookups faster at high packet rates.
*/
payloads_udp_trim(masscan->payloads.udp, &masscan->targets);
payloads_oproto_trim(masscan->payloads.oproto, &masscan->targets);
#ifdef __AFL_HAVE_MANUAL_CONTROL
__AFL_INIT();
#endif
/*
* Start scanning threats for each adapter
*/
for (index=0; index<masscan->nic_count; index++) {
struct ThreadPair *parms = &parms_array[index];
int err;
parms->masscan = masscan;
parms->nic_index = index;
parms->my_index = masscan->resume.index;
parms->done_transmitting = 0;
parms->done_receiving = 0;
/* needed for --packet-trace option so that we know when we started
* the scan */
parms->pt_start = 1.0 * pixie_gettime() / 1000000.0;
/*
* Turn the adapter on, and get the running configuration
*/
err = masscan_initialize_adapter(
masscan,
index,
&parms->source_mac,
&parms->router_mac_ipv4,
&parms->router_mac_ipv6
);
if (err != 0)
exit(1);
parms->adapter = masscan->nic[index].adapter;
if (!masscan->nic[index].is_usable) {
LOG(0, "FAIL: failed to detect IP of interface\n");
LOG(0, " [hint] did you spell the name correctly?\n");
LOG(0, " [hint] if it has no IP address, "
"manually set with \"--adapter-ip 192.168.100.5\"\n");
exit(1);
}
/*
* Initialize the TCP packet template. The way this works is that
* we parse an existing TCP packet, and use that as the template for
* scanning. Then, we adjust the template with additional features,
* such as the IP address and so on.
*/
parms->tmplset->vulncheck = vulncheck;
template_packet_init(
parms->tmplset,
parms->source_mac,
parms->router_mac_ipv4,
parms->router_mac_ipv6,
masscan->payloads.udp,
masscan->payloads.oproto,
stack_if_datalink(masscan->nic[index].adapter),
masscan->seed,
masscan->templ_opts);
/*
* Set the "source port" of everything we transmit.
*/
if (masscan->nic[index].src.port.range == 0) {
unsigned port = 40000 + now % 20000;
masscan->nic[index].src.port.first = port;
masscan->nic[index].src.port.last = port + 16;
masscan->nic[index].src.port.range = 16;
}
stack = stack_create(parms->source_mac, &masscan->nic[index].src);
parms->stack = stack;
/*
* Set the "TTL" (IP time-to-live) of everything we send.
*/
if (masscan->nmap.ttl)
template_set_ttl(parms->tmplset, masscan->nmap.ttl);
if (masscan->nic[0].is_vlan)
template_set_vlan(parms->tmplset, masscan->nic[0].vlan_id);
/*
* trap <ctrl-c> to pause
*/
signal(SIGINT, control_c_handler);
}
/*
* Print helpful text
*/
{
char buffer[80];
struct tm x;
now = time(0);
safe_gmtime(&x, &now);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S GMT", &x);
LOG(0, "Starting masscan " MASSCAN_VERSION " (http://bit.ly/14GZzcT) at %s\n",
buffer);
if (count_ports == 1 && \
masscan->targets.ports.list->begin == Templ_ICMP_echo && \
masscan->targets.ports.list->end == Templ_ICMP_echo)
{ /* ICMP only */
//LOG(0, " -- forced options: -sn -n --randomize-hosts -v --send-eth\n");
LOG(0, "Initiating ICMP Echo Scan\n");
LOG(0, "Scanning %u hosts\n",(unsigned)count_ips);
}
else /* This could actually also be a UDP only or mixed UDP/TCP/ICMP scan */
{
//LOG(0, " -- forced options: -sS -Pn -n --randomize-hosts -v --send-eth\n");
LOG(0, "Initiating SYN Stealth Scan\n");
LOG(0, "Scanning %u hosts [%u port%s/host]\n",
(unsigned)count_ips, (unsigned)count_ports, (count_ports==1)?"":"s");
}
}
/*
* Start all the threads
*/
for (index=0; index<masscan->nic_count; index++) {
struct ThreadPair *parms = &parms_array[index];
/*
* Start the scanning thread.
* THIS IS WHERE THE PROGRAM STARTS SPEWING OUT PACKETS AT A HIGH
* RATE OF SPEED.
*/
parms->thread_handle_xmit = pixie_begin_thread(transmit_thread, 0, parms);
/*
* Start the MATCHING receive thread. Transmit and receive threads
* come in matching pairs.
*/
parms->thread_handle_recv = pixie_begin_thread(receive_thread, 0, parms);
}
/*
* Now wait for <ctrl-c> to be pressed OR for threads to exit
*/
pixie_usleep(1000 * 100);
LOG(1, "[+] waiting for threads to finish\n");
status_start(&status);
status.is_infinite = masscan->is_infinite;
while (!is_tx_done && masscan->output.is_status_updates) {
unsigned i;
double rate = 0;
uint64_t total_tcbs = 0;
uint64_t total_synacks = 0;
uint64_t total_syns = 0;
/* Find the minimum index of all the threads */
min_index = UINT64_MAX;
for (i=0; i<masscan->nic_count; i++) {
struct ThreadPair *parms = &parms_array[i];
if (min_index > parms->my_index)
min_index = parms->my_index;
rate += parms->throttler->current_rate;
if (parms->total_tcbs)
total_tcbs += *parms->total_tcbs;
if (parms->total_synacks)
total_synacks += *parms->total_synacks;
if (parms->total_syns)
total_syns += *parms->total_syns;
}
if (min_index >= range && !masscan->is_infinite) {
/* Note: This is how we can tell the scan has ended */
is_tx_done = 1;
}
/*
* update screen about once per second with statistics,
* namely packets/second.
*/
if (masscan->output.is_status_updates)
status_print(&status, min_index, range, rate,
total_tcbs, total_synacks, total_syns,
0, masscan->output.is_status_ndjson);
/* Sleep for almost a second */
pixie_mssleep(750);
}
/*
* If we haven't completed the scan, then save the resume
* information.
*/
if (min_index < count_ips * count_ports) {
masscan->resume.index = min_index;
/* Write current settings to "paused.conf" so that the scan can be restarted */
masscan_save_state(masscan);
}
/*
* Now wait for all threads to exit
*/
now = time(0);
for (;;) {
unsigned transmit_count = 0;
unsigned receive_count = 0;
unsigned i;
double rate = 0;
uint64_t total_tcbs = 0;
uint64_t total_synacks = 0;
uint64_t total_syns = 0;
/* Find the minimum index of all the threads */
min_index = UINT64_MAX;
for (i=0; i<masscan->nic_count; i++) {
struct ThreadPair *parms = &parms_array[i];
if (min_index > parms->my_index)
min_index = parms->my_index;
rate += parms->throttler->current_rate;
if (parms->total_tcbs)
total_tcbs += *parms->total_tcbs;
if (parms->total_synacks)
total_synacks += *parms->total_synacks;
if (parms->total_syns)
total_syns += *parms->total_syns;
}
if (time(0) - now >= masscan->wait) {
is_rx_done = 1;
}
if (time(0) - now - 10 > masscan->wait) {
LOG(0, "[-] Passed the wait window but still running, forcing exit...\n");
exit(0);
}
if (masscan->output.is_status_updates) {
status_print(&status, min_index, range, rate,
total_tcbs, total_synacks, total_syns,
masscan->wait - (time(0) - now),
masscan->output.is_status_ndjson);
for (i=0; i<masscan->nic_count; i++) {
struct ThreadPair *parms = &parms_array[i];
transmit_count += parms->done_transmitting;
receive_count += parms->done_receiving;
}
pixie_mssleep(250);
if (transmit_count < masscan->nic_count)
continue;
is_tx_done = 1;
is_rx_done = 1;
if (receive_count < masscan->nic_count)
continue;
} else {
/* [AFL-fuzz]
* Join the threads, which doesn't allow us to print out
* status messages, but allows us to exit cleanly without
* any waiting */
for (i=0; i<masscan->nic_count; i++) {
struct ThreadPair *parms = &parms_array[i];
pixie_thread_join(parms->thread_handle_xmit);
parms->thread_handle_xmit = 0;
pixie_thread_join(parms->thread_handle_recv);
parms->thread_handle_recv = 0;
}
is_tx_done = 1;
is_rx_done = 1;
}
break;
}
/*
* Now cleanup everything
*/
status_finish(&status);
if (!masscan->output.is_status_updates) {
uint64_t usec_now = pixie_gettime();
printf("%u milliseconds elapsed\n", (unsigned)((usec_now - usec_start)/1000));
}
LOG(1, "[+] all threads have exited \n");
return 0;
}
/***************************************************************************
***************************************************************************/
int main(int argc, char *argv[])
{
struct Masscan masscan[1];
unsigned i;
int has_target_addresses = 0;
int has_target_ports = 0;
usec_start = pixie_gettime();
#if defined(WIN32)
{WSADATA x; WSAStartup(0x101, &x);}
#endif
global_now = time(0);
/* Set system to report debug information on crash */
{
int is_backtrace = 1;
for (i=1; i<(unsigned)argc; i++) {
if (strcmp(argv[i], "--nobacktrace") == 0)
is_backtrace = 0;
}
if (is_backtrace)
pixie_backtrace_init(argv[0]);
}
/*
* Initialize those defaults that aren't zero
*/
memset(masscan, 0, sizeof(*masscan));
/* 14 rounds seem to give way better statistical distribution than 4 with a
very low impact on scan rate */
masscan->blackrock_rounds = 14;
masscan->output.is_show_open = 1; /* default: show syn-ack, not rst */
masscan->output.is_status_updates = 1; /* default: show status updates */
masscan->wait = 10; /* how long to wait for responses when done */
masscan->max_rate = 100.0; /* max rate = hundred packets-per-second */
masscan->nic_count = 1;
masscan->shard.one = 1;
masscan->shard.of = 1;
masscan->min_packet_size = 60;
masscan->redis.password = NULL;
masscan->payloads.udp = payloads_udp_create();
masscan->payloads.oproto = payloads_oproto_create();
safe_strcpy( masscan->output.rotate.directory,
sizeof(masscan->output.rotate.directory),
".");
masscan->is_capture_cert = 1;
/*
* Pre-parse the command-line
*/
if (masscan_conf_contains("--readscan", argc, argv)) {
masscan->is_readscan = 1;
}
/*
* On non-Windows systems, read the defaults from the file in
* the /etc directory. These defaults will contain things
* like the output directory, max packet rates, and so on. Most
* importantly, the master "--excludefile" might be placed here,
* so that blacklisted ranges won't be scanned, even if the user
* makes a mistake
*/
#if !defined(WIN32)
if (!masscan->is_readscan) {
if (access("/etc/masscan/masscan.conf", 0) == 0) {
masscan_read_config_file(masscan, "/etc/masscan/masscan.conf");
}
}
#endif
/*
* Read in the configuration from the command-line. We are looking for
* either options or a list of IPv4 address ranges.
*/
masscan_command_line(masscan, argc, argv);
if (masscan->seed == 0)
masscan->seed = get_entropy(); /* entropy for randomness */
/*
* Load database files like "nmap-payloads" and "nmap-service-probes"
*/
masscan_load_database_files(masscan);
/*
* Load the scripting engine if needed and run those that were
* specified.
*/
if (masscan->is_scripting)
scripting_init(masscan);
/* We need to do a separate "raw socket" initialization step. This is
* for Windows and PF_RING. */
if (pcap_init() != 0)
LOG(2, "libpcap: failed to load\n");
rawsock_init();
/* Init some protocol parser data structures */
snmp_init();
x509_init();
/*
* Apply excludes. People ask us not to scan them, so we maintain a list
* of their ranges, and when doing wide scans, add the exclude list to
* prevent them from being scanned.
*/
has_target_addresses = massip_has_ipv4_targets(&masscan->targets) || massip_has_ipv6_targets(&masscan->targets);
has_target_ports = massip_has_target_ports(&masscan->targets);
massip_apply_excludes(&masscan->targets, &masscan->exclude);
if (!has_target_ports && masscan->op == Operation_ListScan)
massip_add_port_string(&masscan->targets, "80", 0);
/* Optimize target selection so it's a quick binary search instead
* of walking large memory tables. When we scan the entire Internet
* our --excludefile will chop up our pristine 0.0.0.0/0 range into
* hundreds of subranges. This allows us to grab addresses faster. */
massip_optimize(&masscan->targets);
/* FIXME: we only support 63-bit scans at the current time.
* This is big enough for the IPv4 Internet, where scanning
* for all TCP ports on all IPv4 addresses results in a 48-bit
* scan, but this isn't big enough even for a single port on
* an IPv6 subnet (which are 64-bits in size, usually). However,
* even at millions of packets per second scanning rate, you still
* can't complete a 64-bit scan in a reasonable amount of time.
* Nor would you want to attempt the feat, as it would overload
* the target IPv6 subnet. Since implementing this would be
* difficult for 32-bit processors, for now, I'm going to stick
* to a simple 63-bit scan.
*/
if (massint128_bitcount(massip_range(&masscan->targets)) > 63) {
fprintf(stderr, "[-] FAIL: scan range too large, max is 63-bits, requested is %u bits\n",
massint128_bitcount(massip_range(&masscan->targets)));
fprintf(stderr, " Hint: scan range is number of IP addresses times number of ports\n");
fprintf(stderr, " Hint: IPv6 subnet must be at least /66 \n");
exit(1);
}
/*
* Once we've read in the configuration, do the operation that was
* specified
*/
switch (masscan->op) {
case Operation_Default:
/* Print usage info and exit */
masscan_usage();
break;
case Operation_Scan:
/*
* THIS IS THE NORMAL THING
*/
if (rangelist_count(&masscan->targets.ipv4) == 0 && massint128_is_zero(range6list_count(&masscan->targets.ipv6))) {
/* We check for an empty target list here first, before the excludes,
* so that we can differentiate error messages after excludes, in case
* the user specified addresses, but they were removed by excludes. */
LOG(0, "FAIL: target IP address list empty\n");
if (has_target_addresses) {
LOG(0, " [hint] all addresses were removed by exclusion ranges\n");
} else {
LOG(0, " [hint] try something like \"--range 10.0.0.0/8\"\n");
LOG(0, " [hint] try something like \"--range 192.168.0.100-192.168.0.200\"\n");
}
exit(1);
}
if (rangelist_count(&masscan->targets.ports) == 0) {
if (has_target_ports) {
LOG(0, " [hint] all ports were removed by exclusion ranges\n");
} else {
LOG(0, "FAIL: no ports were specified\n");
LOG(0, " [hint] try something like \"-p80,8000-9000\"\n");
LOG(0, " [hint] try something like \"--ports 0-65535\"\n");
}
return 1;
}
return main_scan(masscan);
case Operation_ListScan:
/* Create a randomized list of IP addresses */
main_listscan(masscan);
return 0;
case Operation_List_Adapters:
/* List the network adapters we might want to use for scanning */
rawsock_list_adapters();
break;
case Operation_DebugIF:
for (i=0; i<masscan->nic_count; i++)
rawsock_selftest_if(masscan->nic[i].ifname);
return 0;
case Operation_ReadRange:
main_readrange(masscan);
return 0;
case Operation_ReadScan:
{
unsigned start;
unsigned stop;
/* find first file */
for (start=1; start<(unsigned)argc; start++) {
if (memcmp(argv[start], "--readscan", 10) == 0) {
start++;
break;
}
}
/* find last file */
for (stop=start+1; stop<(unsigned)argc && argv[stop][0] != '-'; stop++)
;
/*
* read the binary files, and output them again depending upon
* the output parameters
*/
readscan_binary_scanfile(masscan, start, stop, argv);
}
break;
case Operation_Benchmark:
printf("=== benchmarking (%u-bits) ===\n\n", (unsigned)sizeof(void*)*8);
blackrock_benchmark(masscan->blackrock_rounds);
blackrock2_benchmark(masscan->blackrock_rounds);
smack_benchmark();
exit(1);
break;
case Operation_Echo:
masscan_echo(masscan, stdout, 0);
exit(0);
break;
case Operation_EchoAll:
masscan_echo(masscan, stdout, 0);
exit(0);
break;
case Operation_EchoCidr:
masscan_echo_cidr(masscan, stdout, 0);
exit(0);
break;
case Operation_Selftest:
/*
* Do a regression test of all the significant units
*/
{
int x = 0;
extern int proto_isakmp_selftest(void);
x += massip_selftest();
x += ranges6_selftest();
x += dedup_selftest();
x += checksum_selftest();
x += ipv6address_selftest();
x += proto_coap_selftest();
x += smack_selftest();
x += sctp_selftest();
x += base64_selftest();
x += banner1_selftest();
x += output_selftest();
x += siphash24_selftest();
x += ntp_selftest();
x += snmp_selftest();
x += proto_isakmp_selftest();
x += templ_payloads_selftest();
x += blackrock_selftest();
x += rawsock_selftest();
x += lcg_selftest();
x += template_selftest();
x += ranges_selftest();
x += massip_parse_selftest();
x += pixie_time_selftest();
x += rte_ring_selftest();
x += mainconf_selftest();
x += zeroaccess_selftest();
x += nmapserviceprobes_selftest();
x += rstfilter_selftest();
x += masscan_app_selftest();
if (x != 0) {
/* one of the selftests failed, so return error */
fprintf(stderr, "regression test: failed :( \n");
return 1;
} else {
fprintf(stderr, "regression test: success!\n");
return 0;
}
}
break;
}
return 0;
}
| 66,599
|
C
|
.c
| 1,600
| 30.49875
| 123
| 0.534658
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,487
|
massip.h
|
robertdavidgraham_masscan/src/massip.h
|
#ifndef MASSIP_H
#define MASSIP_H
#include <stddef.h>
#include "massip-rangesv4.h"
#include "massip-rangesv6.h"
struct MassIP {
struct RangeList ipv4;
struct Range6List ipv6;
/**
* The ports we are scanning for. The user can specify repeated ports
* and overlapping ranges, but we'll deduplicate them, scanning ports
* only once.
* NOTE: TCP ports are stored 0-64k, but UDP ports are stored in the
* range 64k-128k, thus, allowing us to scan both at the same time.
*/
struct RangeList ports;
/**
* Used internally to differentiate between indexes selecting an
* IPv4 address and higher ones selecting an IPv6 address.
*/
uint64_t ipv4_index_threshold;
uint64_t count_ports;
uint64_t count_ipv4s;
uint64_t count_ipv6s;
};
/**
* Count the total number of targets in a scan. This is calculated
* the (IPv6 addresses * IPv4 addresses * ports). This can produce
* a 128-bit number (larger, actually).
*/
massint128_t massip_range(struct MassIP *massip);
/**
* Remove everything in "targets" that's listed in the "exclude"
* list. The reason for this is that we'll have a single policy
* file of those address ranges which we are forbidden to scan.
* Then, each time we run a scan with different targets, we
* apply this policy file.
*/
void massip_apply_excludes(struct MassIP *targets, struct MassIP *exclude);
/**
* The last step after processing the configuration, setting up the
* state to be used for scanning. This sorts the address, removes
* duplicates, and creates an optimized 'picker' system to easily
* find an address given an index, or find an index given an address.
*/
void massip_optimize(struct MassIP *targets);
/**
* This selects an IP+port combination given an index whose value
* is [0..range], where 'range' is the value returned by the function
* `massip_range()`. Since the optimization step (`massip_optimized()`)
* sorted all addresses/ports, a monotonically increasing index will
* list everything in sorted order. The intent, however, is to use the
* "blackrock" algorithm to randomize the index before calling this function.
*
* It is this function, plus the 'blackrock' randomization algorithm, that
* is at the heart of Masscan.
*/
int massip_pick(const struct MassIP *massip, uint64_t index, ipaddress *addr, unsigned *port);
int massip_has_ip(const struct MassIP *massip, ipaddress ip);
int massip_has_port(const struct MassIP *massip, unsigned port);
int massip_add_target_string(struct MassIP *massip, const char *string);
/**
* Parse the string contain port specifier.
*/
int massip_add_port_string(struct MassIP *massip, const char *string, unsigned proto);
/**
* Indicates whether there are IPv4 targets. If so, we'll have to
* initialize the IPv4 portion of the stack.
* @return true if there are IPv4 targets to be scanned, false
* otherwise
*/
int massip_has_ipv4_targets(const struct MassIP *massip);
int massip_has_target_ports(const struct MassIP *massip);
/**
* Indicates whether there are IPv6 targets. If so, we'll have to
* initialize the IPv6 portion of the stack.
* @return true if there are IPv6 targets to be scanned, false
* otherwise
*/
int massip_has_ipv6_targets(const struct MassIP *massip);
int massip_selftest(void);
#endif
| 3,320
|
C
|
.h
| 82
| 37.768293
| 94
| 0.745263
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,506
|
proto-http.h
|
robertdavidgraham_masscan/src/proto-http.h
|
#ifndef PROTO_HTTP_H
#define PROTO_HTTP_H
#include "proto-banner1.h"
#include "util-bool.h"
extern struct ProtocolParserStream banner_http;
/**
* Called during configuration when processing a command-line option
* like "--http-field <name=value>" to add/change a field in the HTTP
* header.
*/
size_t
http_change_field(unsigned char **inout_header, size_t header_length,
const char *field_name,
const unsigned char *field_value, size_t field_value_len,
int what);
/**
* Called during configuration when processing a command-line option
* like "--http-url /foo.html". This replaces whatever the existing
* URL is into the new one.
* @param item
* 0=method, 1=url, 2=version
* @return
* the new length of the header (expanded or shrunk)
*/
size_t
http_change_requestline(unsigned char **inout_header, size_t header_length,
const void *url, size_t url_length, int item);
#endif
| 983
|
C
|
.h
| 28
| 30.5
| 77
| 0.687764
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,508
|
proto-oproto.h
|
robertdavidgraham_masscan/src/proto-oproto.h
|
/*
Other IP protocol (not TCP, UDP, TCP, ICMP
Specifically for scanning things like GRE.
*/
#ifndef PROTO_OPROTO_H
#define PROTO_OPROTO_H
#include <stdint.h>
#include <time.h>
struct Output;
struct PreprocessedInfo;
/**
* Parse an incoming response.
* @param entropy
* The random seed, used in calculating syn-cookies.
*/
void
handle_oproto(struct Output *out, time_t timestamp,
const unsigned char *px, unsigned length,
struct PreprocessedInfo *parsed,
uint64_t entropy);
#endif
| 529
|
C
|
.h
| 21
| 22.095238
| 57
| 0.720238
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,520
|
crypto-siphash24.h
|
robertdavidgraham_masscan/src/crypto-siphash24.h
|
#ifndef CRYPTO_SIPHASH24_H
#define CRYPTO_SIPHASH24_H
#include <stdint.h>
uint64_t
siphash24(const void *in, size_t inlen, const uint64_t key[2]);
/**
* Regression-test this module.
* @return
* 0 on success, a positive integer otherwise.
*/
int
siphash24_selftest(void);
#endif
| 291
|
C
|
.h
| 13
| 20.769231
| 63
| 0.748175
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,533
|
massip-addr.h
|
robertdavidgraham_masscan/src/massip-addr.h
|
/*
Simple module for handling addresses (IPv6, IPv4, MAC).
Also implements a 128-bit type for dealing with addresses.
This is the module that almost all the other code depends
upon, because everything else deals with the IP address
types defined here.
*/
#ifndef MASSIP_ADDR_H
#define MASSIP_ADDR_H
#include <stdint.h>
#include <stddef.h>
#if defined(_MSC_VER) && !defined(inline)
#define inline __inline
#endif
#if defined(_MSC_VER)
#pragma warning(disable: 4201)
#endif
/**
* An IPv6 address is represented as two 64-bit integers instead of a single
* 128-bit integer. This is because currently (year 2020) most compilers
* do not support the `uint128_t` type, but all relevant ones do support
* the `uint64_t` type.
*/
struct ipv6address {uint64_t hi; uint64_t lo;};
typedef struct ipv6address ipv6address;
typedef struct ipv6address ipv6address_t;
/**
* IPv4 addresses are represented simply with an integer.
*/
typedef unsigned ipv4address;
typedef ipv4address ipv4address_t;
/**
* MAC address (layer 2). Since we have canonical types for IPv4/IPv6
* addresses, we may as well have a canonical type for MAC addresses,
* too.
*/
struct macaddress_t {unsigned char addr[6];};
typedef struct macaddress_t macaddress_t;
/**
* In many cases we need to do arithmetic on IPv6 addresses, treating
* them as a large 128-bit integer. Thus, we declare our own 128-bit
* integer type (and some accompanying math functions). But it's
* still just the same as a 128-bit integer.
*/
typedef ipv6address massint128_t;
/**
* Most of the code in this project is agnostic to the version of IP
* addresses (IPv4 or IPv6). Therefore, we represent them as a union
* distinguished by a version number. The `version` is an integer
* with a value of either 4 or 6.
*/
struct ipaddress {
union {
unsigned ipv4;
ipv6address ipv6;
};
unsigned char version;
};
typedef struct ipaddress ipaddress;
/** @return true if the IPv6 address is zero [::] */
static inline int ipv6address_is_zero(ipv6address_t a) {
return a.hi == 0 && a.lo == 0;
}
#define massint128_is_zero ipv6address_is_zero
/** The IPv6 address [FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF]
* is invalid */
static inline int ipv6address_is_invalid(ipv6address_t a) {
return a.hi == ~0ULL && a.lo == ~0ULL;
}
/** Compare two IPv6 addresses */
static inline int ipv6address_is_equal(ipv6address_t a, ipv6address_t b) {
return a.hi == b.hi && a.lo == b.lo;
}
static inline int ipaddress_is_equal(ipaddress a, ipaddress b) {
if (a.version != b.version)
return 0;
if (a.version == 4) {
return a.ipv4 == b.ipv4;
} else if (a.version == 6) {
return ipv6address_is_equal(a.ipv6, b.ipv6);
} else
return 0;
}
/** Compare two IPv6 addresses, to see which one comes frist. This is used
* in sorting the addresses
* @return true if a < b, false otherwise */
static inline int ipv6address_is_lessthan(ipv6address_t a, ipv6address_t b) {
return (a.hi == b.hi)?(a.lo < b.lo):(a.hi < b.hi);
}
/**
* Mask the lower bits of each address and test if the upper bits are equal
*/
int ipv6address_is_equal_prefixed(ipv6address_t lhs, ipv6address_t rhs, unsigned prefix);
ipv6address_t ipv6address_add_uint64(ipv6address_t lhs, uint64_t rhs);
ipv6address_t ipv6address_subtract(ipv6address_t lhs, ipv6address_t rhs);
ipv6address_t ipv6address_add(ipv6address_t lhs, ipv6address_t rhs);
/**
* Given a typical EXTERNAL representation of an IPv6 address, which is
* an array of 16 bytes, convert to the canonical INTERNAL address.
*/
static inline ipv6address ipv6address_from_bytes(const unsigned char *buf) {
ipv6address addr;
addr.hi = (uint64_t)buf[ 0] << 56
| (uint64_t)buf[ 1] << 48
| (uint64_t)buf[ 2] << 40
| (uint64_t)buf[ 3] << 32
| (uint64_t)buf[ 4] << 24
| (uint64_t)buf[ 5] << 16
| (uint64_t)buf[ 6] << 8
| (uint64_t)buf[ 7] << 0;
addr.lo = (uint64_t)buf[ 8] << 56
| (uint64_t)buf[ 9] << 48
| (uint64_t)buf[10] << 40
| (uint64_t)buf[11] << 32
| (uint64_t)buf[12] << 24
| (uint64_t)buf[13] << 16
| (uint64_t)buf[14] << 8
| (uint64_t)buf[15] << 0;
return addr;
}
/**
* Given a typical EXTERNAL representation of an Ethernet MAC address,
* which is an array of 6 bytes, convert to the canonical INTERNAL address.
*/
static inline macaddress_t macaddress_from_bytes(const void *vbuf)
{
const unsigned char *buf = (const unsigned char *)vbuf;
macaddress_t result;
result.addr[0] = buf[0];
result.addr[1] = buf[1];
result.addr[2] = buf[2];
result.addr[3] = buf[3];
result.addr[4] = buf[4];
result.addr[5] = buf[5];
return result;
}
/** Test if the Ethernet MAC address is all zeroes */
static inline int macaddress_is_zero(macaddress_t mac)
{
return mac.addr[0] == 0
&& mac.addr[1] == 0
&& mac.addr[2] == 0
&& mac.addr[3] == 0
&& mac.addr[4] == 0
&& mac.addr[5] == 0;
}
/** Compare two Ethernet MAC addresses to see if they are equal */
static inline int macaddress_is_equal(macaddress_t lhs, macaddress_t rhs)
{
return lhs.addr[0] == rhs.addr[0]
&& lhs.addr[1] == rhs.addr[1]
&& lhs.addr[2] == rhs.addr[2]
&& lhs.addr[3] == rhs.addr[3]
&& lhs.addr[4] == rhs.addr[4]
&& lhs.addr[5] == rhs.addr[5];
}
/**
* Return a buffer with the formatted address
*/
typedef struct ipaddress_formatted {
char string[48];
} ipaddress_formatted_t;
struct ipaddress_formatted ipv6address_fmt(ipv6address a);
struct ipaddress_formatted ipv4address_fmt(ipv4address a);
struct ipaddress_formatted ipaddress_fmt(ipaddress a);
struct ipaddress_formatted macaddress_fmt(macaddress_t a);
unsigned massint128_bitcount(massint128_t num);
/**
* @return 0 on success, 1 on failure
*/
int ipv6address_selftest(void);
#endif
| 5,965
|
C
|
.h
| 172
| 31.05814
| 89
| 0.679799
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,543
|
util-bool.h
|
robertdavidgraham_masscan/src/util-bool.h
|
#ifndef UTIL_BOOL_H
#define UTIL_BOOL_H
#if _MSC_VER && _MSC_VER < 1800
typedef enum {false=0, true=1} bool;
#else
#include <stdbool.h>
#endif
#endif
| 152
|
C
|
.h
| 8
| 17.75
| 36
| 0.725352
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,548
|
templ-nmap-payloads.h
|
robertdavidgraham_masscan/src/templ-nmap-payloads.h
|
/*
Parses the "nmap-payloads" file.
*/
#ifndef TEMPL_NMAP_PAYLOADS_H
#define TEMPL_NMAP_PAYLOADS_H
#include <stdio.h>
struct PayloadsUDP;
struct RangeList;
typedef unsigned
(*payloads_datagram_add_cb)(struct PayloadsUDP *payloads,
const unsigned char *buf, size_t length,
struct RangeList *ports, unsigned source_port
);
void
read_nmap_payloads(FILE *fp, const char *filename,
struct PayloadsUDP *payloads,
payloads_datagram_add_cb add_payload
);
int
templ_nmap_selftest(void);
#endif
| 624
|
C
|
.h
| 21
| 22.095238
| 67
| 0.627713
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,553
|
massip-parse.h
|
robertdavidgraham_masscan/src/massip-parse.h
|
/*
massip-parse
This module parses IPv4 and IPv6 addresses.
It's not a typical parser. It's optimized around parsing large
files containing millions of addresses and ranges using a
"state-machine parser".
*/
#ifndef MASSIP_PARSE_H
#define MASSIP_PARSE_H
#include "massip-addr.h"
struct MassIP;
struct Range;
struct Range6;
/**
* Parse a file, extracting all the IPv4 and IPv6 addresses and ranges.
* This is optimized for speed, handling millions of entries in under
* a second. This is especially tuned for IPv6 addresses, as while IPv4
* scanning is mostly done with target rnages, IPv6 scanning is mostly
* done with huge lists of target addresses.
* @param filename
* The name of the file that we'll open, parse, and close.
* @param targets_ipv4
* The list of IPv4 targets that we append any IPv4 addresses to.
* @param targets_ipv6
* The list of IPv6 targets that we append any IPv6 addresses/ranges to.
* @return
0 on success, any other number on failure.
*/
int
massip_parse_file(struct MassIP *massip, const char *filename);
enum RangeParseResult {
Bad_Address,
Ipv4_Address=4,
Ipv6_Address=6,
};
/**
* Parse the next IPv4/IPv6 range from a string. This is called
* when parsing strings from the command-line.
*/
enum RangeParseResult
massip_parse_range(const char *line, size_t *inout_offset, size_t max, struct Range *ipv4, struct Range6 *ipv6);
/**
* Parse a single IPv6 address. This is called when working with
* the operating system stack, when querying addresses from
* the local network adapters.
*/
ipv6address_t
massip_parse_ipv6(const char *buf);
ipv4address_t
massip_parse_ipv4(const char *buf);
/**
* Do a simplistic unit test of the parser.
* @return 0 on success, 1 on failure
*/
int
massip_parse_selftest(void);
#endif
| 1,838
|
C
|
.h
| 57
| 29.842105
| 112
| 0.748584
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,554
|
templ-opts.h
|
robertdavidgraham_masscan/src/templ-opts.h
|
#ifndef TEMPL_OPTS_H
#define TEMPL_OPTS_H
#include "massip-addr.h"
#ifdef _MSC_VER
#pragma warning(disable:4214)
#endif
/**
* This tells us whether we should add, remove, or leave default
* a field in the packet headers.
* FIXME: not all of these are supported
*/
typedef enum {Default, Add, Remove} addremove_t;
struct TemplateOptions {
struct {
addremove_t is_badsum:4; /* intentionally bad checksum */
addremove_t is_tsecho:4; /* enable timestamp echo */
addremove_t is_tsreply:4; /* enable timestamp echo */
addremove_t is_flags:4;
addremove_t is_ackno:4;
addremove_t is_seqno:4;
addremove_t is_win:4;
addremove_t is_mss:4;
addremove_t is_sackok:4;
addremove_t is_wscale:4;
unsigned flags;
unsigned ackno;
unsigned seqno;
unsigned win;
unsigned mss;
unsigned sackok;
unsigned wscale;
unsigned tsecho;
unsigned tsreply;
} tcp;
struct {
addremove_t is_badsum:4; /* intentionally bad checksum */
} udp;
struct {
addremove_t is_sender_mac:4;
addremove_t is_sender_ip:4;
addremove_t is_target_mac:4;
addremove_t is_target_ip:4;
macaddress_t sender_mac;
ipaddress sender_ip;
macaddress_t target_mac;
ipaddress target_ip;
} arp;
struct {
addremove_t is_badsum:4; /* intentionally bad checksum */
addremove_t is_tos:4;
addremove_t is_ipid:4;
addremove_t is_df:4;
addremove_t is_mf:4;
addremove_t is_ttl:4;
unsigned tos;
unsigned ipid;
unsigned ttl;
} ipv4;
};
#endif
| 1,709
|
C
|
.h
| 60
| 21.716667
| 65
| 0.620183
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,563
|
util-errormsg.h
|
robertdavidgraham_masscan/src/util-errormsg.h
|
#ifndef UTIL_ERRORMSG_H
#define UTIL_ERRORMSG_H
#include "massip-addr.h"
void errmsg_init(unsigned long long entropy);
/**
* Prints an error message only once
*/
void
ERRMSG(const char *fmt, ...);
void
ERRMSGip(ipaddress ip, unsigned port, const char *fmt, ...);
#endif
| 277
|
C
|
.h
| 12
| 21.5
| 60
| 0.75
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,569
|
massip-rangesv6.h
|
robertdavidgraham_masscan/src/massip-rangesv6.h
|
/*
List of IPv6 ranges.
Sames as the "ranges.h" module, but for IPv6 instead of IPv4.
*/
#ifndef RANGES6_H
#define RANGES6_H
#include "massip-addr.h"
#include <stdio.h>
#include <stdint.h>
struct Range;
/**
* A range of IPv6 ranges.
* Inclusive, so [n..m] includes both 'n' and 'm'.
*/
struct Range6
{
ipv6address begin;
ipv6address end;
};
/**
* An array of ranges in sorted order
*/
struct Range6List
{
struct Range6 *list;
size_t count;
size_t max;
size_t *picker;
unsigned is_sorted:1;
};
/**
* Adds the given range to the targets list. The given range can be a duplicate
* or overlap with an existing range, which will get combined with existing
* ranges.
* @param targets
* A list of IPv6 ranges.
* @param begin
* The first address of the range that'll be added.
* @param end
* The last address (inclusive) of the range that'll be added.
*/
void
range6list_add_range(struct Range6List *targets, ipv6address begin, ipv6address end);
/**
* Removes the given range from the target list. The input range doesn't
* have to exist, or can partial overlap with existing ranges.
* @param targets
* A list of IPv6 ranges.
* @param begin
* The first address of the range that'll be removed.
* @param end
* The last address of the range that'll be removed (inclusive).
*/
void
range6list_remove_range(struct Range6List *targets, const ipv6address begin, const ipv6address end);
/**
* Same as 'rangelist_remove_range()', except the input is a range
* structure instead of a start/stop numbers.
*/
void
range6list_remove_range2(struct Range6List *targets, struct Range6 range);
/**
* Returns 'true' if the indicated IPv6 address is in one of the target
* ranges.
* @param targets
* A list of IPv6 ranges
* @param ip
* An IPv6 address that might in be in the list of ranges
* @return
* 'true' if the ranges contain the item, or 'false' otherwise
*/
int
range6list_is_contains(const struct Range6List *targets, const ipv6address ip);
/**
* Tests if the range is bad/invalid.
* @return 1 is invalid, 0 if good.
*/
int range6_is_bad_address(const struct Range6 *range);
/**
* Remove things from the target list. The primary use of this is the
* "exclude-file" containing a list of IP addresses that we should
* not scan
* @param targets
* Our array of target IP address (or port) ranges that we'll be
* scanning.
* @param excludes
* A list, probably read in from --excludefile, of things that we
* should not be scanning, that will override anything we otherwise
* try to scan.
* @return
* the total number of IP addresses or ports removed.
*/
ipv6address
range6list_exclude( struct Range6List *targets,
const struct Range6List *excludes);
/**
* Counts the total number of IPv6 addresses in the target list. This
* iterates over all the ranges in the table, summing up the count within
* each range.
* @param targets
* A list of IP address or port ranges.
* @return
* The total number of address or ports.
*/
massint128_t
range6list_count(const struct Range6List *targets);
/**
* Given an index in a continuous range of [0...count], pick a corresponding
* number (IP address or port) from a list of non-continuous ranges (not
* necessarily starting from 0). In other words, given the two ranges
* 10-19 50-69
* we'll have a total of 30 possible numbers. Thus, the index goes from
* [0..29], with the values 0..9 picking the corresponding values from the
* first range, and the values 10..29 picking the corresponding values
* from the second range.
*
* NOTE: This is a fundamental part of this program's design, that the user
* can specify non-contiguous IP and port ranges, but yet we iterate over
* them using a monotonically increasing index variable.
*
* @param targets
* A list of IP address ranges, or a list of port ranges (one or the
* other, but not both).
* @param index
* An integer starting at 0 up to (but not including) the value returned
* by 'rangelist_count()' for this target list.
* @return
* an IP address or port corresponding to this index.
*/
ipv6address
range6list_pick(const struct Range6List *targets, uint64_t index);
/**
* Remove all the ranges in the range list.
*/
void
range6list_remove_all(struct Range6List *list);
/**
* Merge two range lists
*/
void
range6list_merge(struct Range6List *list1, const struct Range6List *list2);
/**
* Optimizes the target list, so that when we call "rangelist_pick()"
* from an index, it runs faster. It currently configures this for
* a binary-search, though in the future some more efficient
* algorithm may be chosen.
*/
void
range6list_optimize(struct Range6List *targets);
/**
* Sorts the list of target. We maintain the list of targets in sorted
* order internally even though we scan the targets in random order
* externally.
*/
void
range6list_sort(struct Range6List *targets);
/**
* Does a regression test of this module
* @return
* 0 if the regression test succeeds, or a positive value on failure
*/
int
ranges6_selftest(void);
#endif
| 5,200
|
C
|
.h
| 164
| 29.591463
| 100
| 0.723863
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,581
|
massip-port.h
|
robertdavidgraham_masscan/src/massip-port.h
|
#ifndef MASSIP_PORT_H
#define MASSIP_PORT_H
/*
* Ports are 16-bit numbers ([0..65535], but different
* transports (TCP, UDP, SCTP) are distinct port ranges. Thus, we
* instead of three 64k ranges we could instead treat this internally
* as a 192k port range. We can expand this range to include other
* things we scan for, such as ICMP pings or ARP requests.
*/
enum {
Templ_TCP = 0,
Templ_TCP_last = 65535,
Templ_UDP = 65536,
Templ_UDP_last = 65536 + 65535,
Templ_SCTP = 65536*2,
Templ_SCTP_last = 65536*2 + 65535,
Templ_ICMP_echo = 65536*3+0,
Templ_ICMP_timestamp = 65536*3+1,
Templ_ARP = 65536*3+2,
Templ_Oproto_first = 65536*3 + 256,
Templ_Oproto_last = 65536*3 + 256 + 255,
Templ_VulnCheck = 65536*4,
};
#endif
| 777
|
C
|
.h
| 24
| 28.833333
| 69
| 0.682306
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,584
|
proto-arp.h
|
robertdavidgraham_masscan/src/proto-arp.h
|
#ifndef PROTO_ARP_H
#define PROTO_ARP_H
#include <time.h>
struct Output;
struct PreprocessedInfo;
void
arp_recv_response(struct Output *out, time_t timestamp, const unsigned char *px, unsigned length, struct PreprocessedInfo *parsed);
#endif
| 245
|
C
|
.h
| 8
| 29.25
| 131
| 0.811966
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,590
|
util-logger.h
|
robertdavidgraham_masscan/src/util-logger.h
|
#ifndef UTIL_LOGGER_H
#define UTIL_LOGGER_H
#include "massip-addr.h"
void LOG(int level, const char *fmt, ...);
void LOGip(int level, ipaddress ip, unsigned port, const char *fmt, ...);
void LOGnet(unsigned port_me, ipaddress ip_them, const char *fmt, ...);
void LOG_add_level(int level);
#endif
| 300
|
C
|
.h
| 8
| 36
| 73
| 0.729167
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,592
|
main-dedup.h
|
robertdavidgraham_masscan/src/main-dedup.h
|
#ifndef MAIN_DEDUP_H
#define MAIN_DEDUP_H
#include "massip-addr.h"
struct DedupTable *
dedup_create(void);
void
dedup_destroy(struct DedupTable *table);
unsigned
dedup_is_duplicate( struct DedupTable *dedup,
ipaddress ip_them, unsigned port_them,
ipaddress ip_me, unsigned port_me);
/**
* Simple unit test
* @return 0 on success, 1 on failure.
*/
int dedup_selftest(void);
#endif
| 453
|
C
|
.h
| 17
| 21.823529
| 66
| 0.665116
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,595
|
in-filter.h
|
robertdavidgraham_masscan/src/in-filter.h
|
/*
This is for filtering input in the "--readscan" feature
*/
#ifndef IN_FILTER_H
#define IN_FILTER_H
#include "massip-addr.h"
struct RangeList;
struct Range6List;
struct MassIP;
/**
* Filters readscan record by IP address, port number,
* or banner-type.
*/
int
readscan_filter_pass(ipaddress ip, unsigned port, unsigned type,
const struct MassIP *massip,
const struct RangeList *btypes);
#endif
| 435
|
C
|
.h
| 18
| 21
| 64
| 0.72155
|
robertdavidgraham/masscan
| 23,250
| 3,042
| 399
|
AGPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,619
|
hangman.c
|
TheAlgorithms_C/games/hangman.c
|
/**
* @file
* @brief C implementation of [Hangman Game](https://en.wikipedia.org/wiki/Hangman_(game))
* @details
* Simple, readable version of hangman.
* Changed graphic to duck instead of traditional stick figure (same number of guesses).
* @author [AtlantaEmrys2002](https://github.com/AtlantaEmrys2002)
*/
#include <ctype.h> /// for main() - tolower()
#include <stdio.h> /// for main(), new_word(), new_guess(), won() - I/O operations
#include <stdlib.h> /// for all functions - exit(), rand() and file functions
#include <string.h> /// for main() - for string operations strlen, strchr, strcpy
#include <time.h> /// for new_game() - used with srand() for declaring new game instance
/*
* @brief game_instance structure that holds current state of game
*/
struct game_instance{
char current_word[30]; ///< word to be guessed by player
char hidden[30]; ///< hidden version of word that is displayed to player
int size; ///< size of word
int incorrect; ///< number of incorrect guesses
char guesses[25]; ///< previous guesses
int guesses_size; ///< size of guesses array
};
// function prototypes
struct game_instance new_game(void); // creates a new game
int new_guess(char, const char guesses[], int size); // checks if player has already played letter
int in_word(char, const char word[], unsigned int size); // checks if letter is in word
void picture(int score); // outputs image of duck (instead of hang man)
void won(const char word[], int score); // checks if player has won or lost
/**
* @brief Main Function
* @returns 0 on exit
*/
int main() {
struct game_instance game = new_game(); // new game created
char guess; // current letter guessed by player
// main loop - asks player for guesses
while ((strchr(game.hidden, '_') != NULL) && game.incorrect <= 12) {
do {
printf("\n****************************\n");
printf("Your word: ");
for (int i = 0; i < game.size; i++) {
printf("%c ", game.hidden[i]);
}
if (game.guesses_size > 0) {
printf("\nSo far, you have guessed: ");
for (int i = 0; i < game.guesses_size; i++) {
printf("%c ", game.guesses[i]);
}
}
printf("\nYou have %d guesses left.", (12 - game.incorrect));
printf("\nPlease enter a letter: ");
scanf(" %c", &guess);
guess = tolower(guess);
} while (new_guess(guess, game.guesses, game.guesses_size) != -1);
game.guesses[game.guesses_size] = guess; // adds new letter to guesses array
game.guesses_size++; // updates size of guesses array
if (in_word(guess, game.current_word, game.size) == 1) {
printf("That letter is in the word!");
for (int i = 0; i < game.size; i++) {
if ((game.current_word[i]) == guess) {
game.hidden[i] = guess;
}
}
} else {
printf("That letter is not in the word.\n");
(game.incorrect)++;
}
picture(game.incorrect);
}
won(game.current_word, game.incorrect);
return 0;
}
/**
* @brief checks if letter has been guessed before
* @param new_guess letter that has been guessed by player
* @param guesses array of player's previous guesses
* @param size size of guesses[] array
* @returns 1 if letter has been guessed before
* @returns -1 if letter has not been guessed before
*/
int new_guess(char new_guess, const char guesses[], int size) {
for (int j = 0; j < size; j++) {
if (guesses[j] == new_guess) {
printf("\nYou have already guessed that letter.");
return 1;
}
}
return -1;
}
/**
* @brief checks if letter is in current word
* @param letter letter guessed by player
* @param word current word
* @param size length of word
* @returns 1 if letter is in word
* @returns -1 if letter is not in word
*/
int in_word(char letter, const char word[], unsigned int size) {
for (int i = 0; i < size; i++) {
if ((word[i]) == letter) {
return 1;
}
}
return -1;
}
/**
* @brief creates a new game - generates a random word and stores in global variable current_word
* @returns current_game - a new game instance containing randomly selected word, its length and hidden version of word
*/
struct game_instance new_game() {
char word[30]; // used throughout function
FILE *fptr;
fptr = fopen("games/words.txt", "r");
if (fptr == NULL){
fprintf(stderr, "File not found.\n");
exit(EXIT_FAILURE);
}
// counts number of words in file - assumes each word on new line
int line_number = 0;
while (fgets(word, 30, fptr) != NULL) {
line_number++;
}
rewind(fptr);
// generates random number
int random_num;
srand(time(NULL));
random_num = rand() % line_number;
// selects randomly generated word
int s = 0;
while (s <= random_num){
fgets(word, 30, fptr);
s++;
}
// formats string correctly
if (strchr(word, '\n') != NULL){
word[strlen(word) - 1] = '\0';
}
fclose(fptr);
// creates new game instance
struct game_instance current_game;
strcpy(current_game.current_word, word);
current_game.size = strlen(word);
for (int i = 0; i < (strlen(word)); i++) {
current_game.hidden[i] = '_';
}
current_game.incorrect = 0;
current_game.guesses_size = 0;
return current_game;
}
/**
* @brief checks if player has won or lost
* @param word the word player has attempted to guess
* @param score how many incorrect guesses player has made
* @returns void
*/
void won(const char word[], int score) {
if (score > 12) {
printf("\nYou lost! The word was: %s.\n", word);
}
else {
printf("\nYou won! You had %d guesses left.\n", (12 - score));
}
}
/*
* @brief gradually draws duck as player gets letters incorrect
* @param score how many incorrect guesses player has made
* @returns void
*/
void picture(int score) {
switch(score) {
case 12:
printf("\n _\n"
" __( ' )> \n"
" \\_ < _ ) ");
break;
case 11:
printf("\n _\n"
" __( ' )\n"
" \\_ < _ ) ");
break;
case 10:
printf("\n _\n"
" __( )\n"
" \\_ < _ ) ");
break;
case 9:
printf("\n \n"
" __( )\n"
" \\_ < _ ) ");
break;
case 8:
printf("\n \n"
" __( \n"
" \\_ < _ ) ");
break;
case 7:
printf("\n \n"
" __ \n"
" \\_ < _ ) ");
break;
case 6:
printf("\n \n"
" _ \n"
" \\_ < _ ) ");
break;
case 5:
printf("\n \n"
" _ \n"
" _ < _ ) ");
break;
case 4:
printf("\n \n"
" \n"
" _ < _ ) ");
break;
case 3:
printf("\n \n"
" \n"
" < _ ) ");
break;
case 2:
printf("\n \n"
" \n"
" _ ) ");
break;
case 1:
printf("\n \n"
" \n"
" ) ");
break;
case 0:
break;
default:
printf("\n _\n"
" __( ' )> QUACK!\n"
" \\_ < _ ) ");
break;
}
}
| 8,044
|
C
|
.c
| 241
| 25.070539
| 119
| 0.50703
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,622
|
rot13.c
|
TheAlgorithms_C/cipher/rot13.c
|
/**
* @file
* @brief [ROT13](https://en.wikipedia.org/wiki/ROT13) is a simple letter
* substitution cipher that replaces a letter with the 13th letter after it in
* the alphabet.
* @details ROT13 transforms a piece of text by examining its alphabetic
* characters and replacing each one with the letter 13 places further along in
* the alphabet, wrapping back to the beginning if necessary. A becomes N, B
* becomes O, and so on up to M, which becomes Z, then the sequence continues at
* the beginning of the alphabet: N becomes A, O becomes B, and so on to Z,
* which becomes M.
* @author [Jeremias Moreira Gomes](https://github.com/j3r3mias)
*/
#include <stdio.h> /// for IO operations
#include <string.h> /// for string operations
#include <assert.h> /// for assert
/**
* @brief Apply the ROT13 cipher
* @param s contains the string to be processed
*/
void rot13(char *s) {
for (int i = 0; s[i]; i++) {
if (s[i] >= 'A' && s[i] <= 'Z') {
s[i] = 'A' + ((s[i] - 'A' + 13) % 26);
} else if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = 'a' + ((s[i] - 'a' + 13) % 26);
}
}
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
char test_01[] = "The more I C, the less I see.";
rot13(test_01);
assert(strcmp(test_01, "Gur zber V P, gur yrff V frr.") == 0);
char test_02[] = "Which witch switched the Swiss wristwatches?";
rot13(test_02);
assert(strcmp(test_02, "Juvpu jvgpu fjvgpurq gur Fjvff jevfgjngpurf?") == 0);
char test_03[] = "Juvpu jvgpu fjvgpurq gur Fjvff jevfgjngpurf?";
rot13(test_03);
assert(strcmp(test_03, "Which witch switched the Swiss wristwatches?") == 0);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
| 1,905
|
C
|
.c
| 53
| 32.396226
| 81
| 0.634146
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,623
|
affine.c
|
TheAlgorithms_C/cipher/affine.c
|
/**
* @file
* @brief An [affine cipher](https://en.wikipedia.org/wiki/Affine_cipher) is a
* letter substitution cipher that uses a linear transformation to substitute
* letters in a message.
* @details Given an alphabet of length M with characters with numeric values
* 0-(M-1), an arbitrary character x can be transformed with the expression (ax
* + b) % M into our ciphertext character. The only caveat is that a must be
* relatively prime with M in order for this transformation to be invertible,
* i.e., gcd(a, M) = 1.
* @author [Daniel Murrow](https://github.com/dsmurrow)
*/
#include <assert.h> /// for assertions
#include <stdio.h> /// for IO
#include <stdlib.h> /// for div function and div_t struct as well as malloc and free
#include <string.h> /// for strlen, strcpy, and strcmp
/**
* @brief number of characters in our alphabet (printable ASCII characters)
*/
#define ALPHABET_SIZE 95
/**
* @brief used to convert a printable byte (32 to 126) to an element of the
* group Z_95 (0 to 94)
*/
#define Z95_CONVERSION_CONSTANT 32
/**
* @brief a structure representing an affine cipher key
*/
typedef struct
{
int a; ///< what the character is being multiplied by
int b; ///< what is being added after the multiplication with `a`
} affine_key_t;
/**
* @brief finds the value x such that (a * x) % m = 1
*
* @param a number we are finding the inverse for
* @param m the modulus the inversion is based on
*
* @returns the modular multiplicative inverse of `a` mod `m`
*/
int modular_multiplicative_inverse(unsigned int a, unsigned int m)
{
int x[2] = {1, 0};
div_t div_result;
if (m == 0) {
return 0;
}
a %= m;
if (a == 0) {
return 0;
}
div_result.rem = a;
while (div_result.rem > 0)
{
div_result = div(m, a);
m = a;
a = div_result.rem;
// Calculate value of x for this iteration
int next = x[1] - (x[0] * div_result.quot);
x[1] = x[0];
x[0] = next;
}
return x[1];
}
/**
* @brief Given a valid affine cipher key, this function will produce the
* inverse key.
*
* @param key They key to be inverted
*
* @returns inverse of key
*/
affine_key_t inverse_key(affine_key_t key)
{
affine_key_t inverse;
inverse.a = modular_multiplicative_inverse(key.a, ALPHABET_SIZE);
// Turn negative results positive
inverse.a += ALPHABET_SIZE;
inverse.a %= ALPHABET_SIZE;
inverse.b = -(key.b % ALPHABET_SIZE) + ALPHABET_SIZE;
return inverse;
}
/**
* @brief Encrypts character string `s` with key
*
* @param s string to be encrypted
* @param key affine key used for encryption
*
* @returns void
*/
void affine_encrypt(char *s, affine_key_t key)
{
for (int i = 0; s[i] != '\0'; i++)
{
int c = (int)s[i] - Z95_CONVERSION_CONSTANT;
c *= key.a;
c += key.b;
c %= ALPHABET_SIZE;
s[i] = (char)(c + Z95_CONVERSION_CONSTANT);
}
}
/**
* @brief Decrypts an affine ciphertext
*
* @param s string to be decrypted
* @param key Key used when s was encrypted
*
* @returns void
*/
void affine_decrypt(char *s, affine_key_t key)
{
affine_key_t inverse = inverse_key(key);
for (int i = 0; s[i] != '\0'; i++)
{
int c = (int)s[i] - Z95_CONVERSION_CONSTANT;
c += inverse.b;
c *= inverse.a;
c %= ALPHABET_SIZE;
s[i] = (char)(c + Z95_CONVERSION_CONSTANT);
}
}
/**
* @brief Tests a given string
*
* @param s string to be tested
* @param a value of key.a
* @param b value of key.b
*
* @returns void
*/
void test_string(const char *s, const char *ciphertext, int a, int b)
{
char *copy = malloc((strlen(s) + 1) * sizeof(char));
strcpy(copy, s);
affine_key_t key = {a, b};
affine_encrypt(copy, key);
assert(strcmp(copy, ciphertext) == 0); // assert that the encryption worked
affine_decrypt(copy, key);
assert(strcmp(copy, s) ==
0); // assert that we got the same string we started with
free(copy);
}
/**
* @brief Test multiple strings
*
* @returns void
*/
static void tests()
{
test_string("Hello!", "&3ddy2", 7, 11);
test_string("TheAlgorithms/C", "DNC}=jHS2zN!7;E", 67, 67);
test_string("0123456789", "840,($ {ws", 91, 88);
test_string("7W@;cdeRT9uL", "JDfa*we?z&bL", 77, 76);
test_string("~Qr%^-+++$leM", "r'qC0$sss;Ahf", 8, 90);
test_string("The quick brown fox jumps over the lazy dog",
"K7: .*6<4 =-0(1 90' 5*2/, 0):- +7: 3>%& ;08", 94, 0);
test_string(
"One-1, Two-2, Three-3, Four-4, Five-5, Six-6, Seven-7, Eight-8, "
"Nine-9, Ten-10",
"H&60>\\2*uY0q\\2*p4660E\\2XYn40x\\2XDB60L\\2VDI0 "
"\\2V6B6&0S\\2%D=p;0'\\2tD&60Z\\2*6&0>j",
51, 18);
printf("All tests have successfully passed!\n");
}
/**
* @brief main function
*
* @returns 0 upon successful program exit
*/
int main()
{
tests();
return 0;
}
| 4,969
|
C
|
.c
| 175
| 24.554286
| 85
| 0.623268
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,633
|
secant_method.c
|
TheAlgorithms_C/numerical_methods/secant_method.c
|
/**
* @file
* @brief [Secant Method](https://en.wikipedia.org/wiki/Secant_method) implementation. Find a
* continuous function's root by using a succession of roots of secant lines to
* approximate it, starting from the given points' secant line.
* @author [Samuel Pires](https://github.com/disnoca)
*/
#include <assert.h> /// for assert
#include <math.h> /// for fabs
#include <stdio.h> /// for io operations
#define TOLERANCE 0.0001 // root approximation result tolerance
#define NMAX 100 // maximum number of iterations
/**
* @brief Continuous function for which we want to find the root
* @param x Real input variable
* @returns The evaluation result of the function using the input value
*/
double func(double x)
{
return x * x - 3.; // x^2 = 3 - solution is sqrt(3)
}
/**
* @brief Root-finding method for a continuous function given two points
* @param x0 One of the starting secant points
* @param x1 One of the starting secant points
* @param tolerance Determines how accurate the returned value is. The returned
* value will be within `tolerance` of the actual root
* @returns `root of the function` if secant method succeed within the
* maximum number of iterations
* @returns `-1` if secant method fails
*/
double secant_method(double x0, double x1, double tolerance)
{
int n = 1; // step counter
while (n++ < NMAX)
{
// calculate secant line root
double x2 = x1 - func(x1) * (x1 - x0) / (func(x1) - func(x0));
// update values
x0 = x1;
x1 = x2;
// return value if it meets tolerance
if (fabs(x1 - x0) < tolerance)
return x2;
}
return -1; // method failed (maximum number of steps exceeded)
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
// compares root values found by the secant method within the tolerance
assert(secant_method(0.2, 0.5, TOLERANCE) - sqrt(3) < TOLERANCE);
assert(fabs(secant_method(-2, -5, TOLERANCE)) - sqrt(3) < TOLERANCE);
assert(secant_method(-3, 2, TOLERANCE) - sqrt(3) < TOLERANCE);
assert(fabs(secant_method(1, -1.5, TOLERANCE)) - sqrt(3) < TOLERANCE);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 2,373
|
C
|
.c
| 69
| 31.072464
| 93
| 0.679023
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,641
|
bisection_method.c
|
TheAlgorithms_C/numerical_methods/bisection_method.c
|
/**
* @file
* @brief In mathematics, the [Bisection
* Method](https://en.wikipedia.org/wiki/Bisection_method) is a root-finding
* method that applies to any continuous function for which one knows two values
* with opposite signs.
* @details
* The method consists of repeatedly bisecting the interval
* defined by the two values and then selecting the subinterval in which the
* function changes sign, and therefore must contain a root. It is a very
* simple and robust method, but it is also relatively slow. Because of this,
* it is often used to obtain a rough approximation to a solution which is
* then used as a starting point for more rapidly converging methods.
* @author [Aybars Nazlica](https://github.com/aybarsnazlica)
*/
#include <assert.h> /// for assert
#include <math.h> /// for fabs
#include <stdio.h> /// for IO operations
#define EPSILON 0.0001 // a small positive infinitesimal quantity
#define NMAX 50 // maximum number of iterations
/**
* @brief Function to check if two input values have the same sign (the property
* of being positive or negative)
* @param a Input value
* @param b Input value
* @returns 1.0 if the input values have the same sign,
* @returns -1.0 if the input values have different signs
*/
double sign(double a, double b)
{
return (a > 0 && b > 0) + (a < 0 && b < 0) - (a > 0 && b < 0) -
(a < 0 && b > 0);
}
/**
* @brief Continuous function for which we want to find the root
* @param x Real input variable
* @returns The evaluation result of the function using the input value
*/
double func(double x)
{
return x * x * x + 2.0 * x - 10.0; // f(x) = x**3 + 2x - 10
}
/**
* @brief Root-finding method for a continuous function given two values with
* opposite signs
* @param x_left Lower endpoint value of the interval
* @param x_right Upper endpoint value of the interval
* @param tolerance Error threshold
* @returns `root of the function` if bisection method succeed within the
* maximum number of iterations
* @returns `-1` if bisection method fails
*/
double bisection(double x_left, double x_right, double tolerance)
{
int n = 1; // step counter
double middle; // midpoint
while (n <= NMAX)
{
middle = (x_left + x_right) / 2; // bisect the interval
double error = middle - x_left;
if (fabs(func(middle)) < EPSILON || error < tolerance)
{
return middle;
}
if (sign(func(middle), func(x_left)) > 0.0)
{
x_left = middle; // new lower endpoint
}
else
{
x_right = middle; // new upper endpoint
}
n++; // increase step counter
}
return -1; // method failed (maximum number of steps exceeded)
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
/* Compares root value that is found by the bisection method within a given
* floating point error*/
assert(fabs(bisection(1.0, 2.0, 0.0001) - 1.847473) <
EPSILON); // the algorithm works as expected
assert(fabs(bisection(100.0, 250.0, 0.0001) - 249.999928) <
EPSILON); // the algorithm works as expected
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 3,396
|
C
|
.c
| 99
| 30.494949
| 80
| 0.665449
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,684
|
trie.c
|
TheAlgorithms_C/data_structures/trie/trie.c
|
/*------------------Trie Data Structure----------------------------------*/
/*-------------Implimented for search a word in dictionary---------------*/
/*-----character - 97 used for get the character from the ASCII value-----*/
// needed for strnlen
#define _POSIX_C_SOURCE 200809L
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHABET_SIZE 26
/*--Node in the Trie--*/
struct trie {
struct trie *children[ALPHABET_SIZE];
bool end_of_word;
};
/*--Create new trie node--*/
int trie_new (
struct trie ** trie
)
{
*trie = calloc(1, sizeof(struct trie));
if (NULL == *trie) {
// memory allocation failed
return -1;
}
return 0;
}
/*--Insert new word to Trie--*/
int trie_insert (
struct trie * trie,
char *word,
unsigned word_len
)
{
int ret = 0;
// this is the end of this word; add an end-of-word marker here and we're
// done.
if (0 == word_len) {
trie->end_of_word = true;
return 0;
}
// if you have some more complex mapping, you could introduce one here. In
// this easy example, we just subtract 'a' (97) from it, meaning that 'a' is 0,
// 'b' is 1, and so on.
const unsigned int index = word[0] - 'a';
// this index is outside the alphabet size; indexing this would mean an
// out-of-bound memory access (bad!). If you introduce a separate map
// function for indexing, then you could move the out-of-bounds index in
// there.
if (ALPHABET_SIZE <= index) {
return -1;
}
// The index does not exist yet, allocate it.
if (NULL == trie->children[index]) {
ret = trie_new(&trie->children[index]);
if (-1 == ret) {
// creating new trie node failed
return -1;
}
}
// recurse into the child node
return trie_insert(
/* trie = */ trie->children[index],
/* word = */ word + 1,
/* word_len = */ word_len - 1
);
}
/*--Search a word in the Trie--*/
int trie_search(
struct trie * trie,
char *word,
unsigned word_len,
struct trie ** result
)
{
// we found a match
if (0 == word_len) {
*result = trie;
return 0;
}
// same here as in trie_insert, if you have a separate index mapping, add
// it here. In this example, we just subtract 'a'.
const unsigned int index = word[0] - 'a';
// This word contains letters outside the alphabet length; it's invalid.
// Remember to do this to prevent buffer overflows.
if (ALPHABET_SIZE <= index) {
return -1;
}
// No match
if (NULL == trie->children[index]) {
return -1;
}
// traverse the trie
return trie_search(
/* trie = */ trie->children[index],
/* word = */ word + 1,
/* word_len = */ word_len - 1,
/* result = */ result
);
}
/*---Return all the related words------*/
void trie_print (
struct trie * trie,
char prefix[],
unsigned prefix_len
)
{
// An end-of-word marker means that this is a complete word, print it.
if (true == trie->end_of_word) {
printf("%.*s\n", prefix_len, prefix);
}
// However, there can be longer words with the same prefix; traverse into
// those as well.
for (int i = 0; i < ALPHABET_SIZE; i++) {
// No words on this character
if (NULL == trie->children[i]) {
continue;
}
// If you have a separate index mapping, then you'd need the inverse of
// the map here. Since we subtracted 'a' for the index, we can just add
// 'a' to get the inverse map function.
prefix[prefix_len] = i + 'a';
// traverse the print into the child
trie_print(trie->children[i], prefix, prefix_len + 1);
}
}
/*------Demonstrate purposes uses text file called dictionary -------*/
int main() {
int ret = 0;
struct trie * root = NULL;
struct trie * trie = NULL;
char word[100] = {0};
// Create a root trie
ret = trie_new(&root);
if (-1 == ret) {
fprintf(stderr, "Could not create trie\n");
exit(1);
}
// open the dictionary file
FILE *fp = fopen("dictionary.txt", "r");
if (NULL == fp) {
fprintf(stderr, "Error while opening dictionary file");
exit(1);
}
// insert all the words from the dictionary
while (1 == fscanf(fp, "%100s\n", word)) {
ret = trie_insert(root, word, strnlen(word, 100));
if (-1 == ret) {
fprintf(stderr, "Could not insert word into trie\n");
exit(1);
}
}
while (1) {
printf("Enter keyword: ");
if (1 != scanf("%100s", word)) {
break;
}
printf(
"\n==========================================================\n");
printf("\n********************* Possible Words ********************\n");
ret = trie_search(root, word, strnlen(word, 100), &trie);
if (-1 == ret) {
printf("No results\n");
continue;
}
trie_print(trie, word, strnlen(word, 100));
printf("\n==========================================================\n");
}
}
| 5,241
|
C
|
.c
| 169
| 25.106509
| 83
| 0.544623
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,685
|
dynamic_stack.c
|
TheAlgorithms_C/data_structures/stack/dynamic_stack.c
|
/**
* @file
*
* @brief
* Dynamic [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)),
* just like Dynamic Array, is a stack data structure whose the length or
* capacity (maximum number of elements that can be stored) increases or
* decreases in real time based on the operations (like insertion or deletion)
* performed on it.
*
* In this implementation, functions such as PUSH, POP, PEEK, show_capacity,
* isempty, and stack_size are coded to implement dynamic stack.
*
* @author [SahilK-027](https://github.com/SahilK-027)
*
*/
#include <assert.h> /// to verify assumptions made by the program and print a diagnostic message if this assumption is false.
#include <inttypes.h> /// to provide a set of integer types with universally consistent definitions that are operating system-independent
#include <stdio.h> /// for IO operations
#include <stdlib.h> /// for including functions involving memory allocation such as `malloc`
/**
* @brief DArrayStack Structure of stack.
*/
typedef struct DArrayStack
{
int capacity, top; ///< to store capacity and top of the stack
int *arrPtr; ///< array pointer
} DArrayStack;
/**
* @brief Create a Stack object
*
* @param cap Capacity of stack
* @return DArrayStack* Newly created stack object pointer
*/
DArrayStack *create_stack(int cap)
{
DArrayStack *ptr;
ptr = (DArrayStack *)malloc(sizeof(DArrayStack));
ptr->capacity = cap;
ptr->top = -1;
ptr->arrPtr = (int *)malloc(sizeof(int) * cap);
printf("\nStack of capacity %d is successfully created.\n", ptr->capacity);
return (ptr);
}
/**
* @brief As this is stack implementation using dynamic array this function will
* expand the size of the stack by twice as soon as the stack is full.
*
* @param ptr Stack pointer
* @param cap Capacity of stack
* @return DArrayStack*: Modified stack
*/
DArrayStack *double_array(DArrayStack *ptr, int cap)
{
int newCap = 2 * cap;
int *temp;
temp = (int *)malloc(sizeof(int) * newCap);
for (int i = 0; i < (ptr->top) + 1; i++)
{
temp[i] = ptr->arrPtr[i];
}
free(ptr->arrPtr);
ptr->arrPtr = temp;
ptr->capacity = newCap;
return ptr;
}
/**
* @brief As this is stack implementation using dynamic array this function will
* shrink the size of stack by twice as soon as the stack's capacity and size
* has significant difference.
*
* @param ptr Stack pointer
* @param cap Capacity of stack
* @return DArrayStack*: Modified stack
*/
DArrayStack *shrink_array(DArrayStack *ptr, int cap)
{
int newCap = cap / 2;
int *temp;
temp = (int *)malloc(sizeof(int) * newCap);
for (int i = 0; i < (ptr->top) + 1; i++)
{
temp[i] = ptr->arrPtr[i];
}
free(ptr->arrPtr);
ptr->arrPtr = temp;
ptr->capacity = newCap;
return ptr;
}
/**
* @brief The push function pushes the element onto the stack.
*
* @param ptr Stack pointer
* @param data Value to be pushed onto stack
* @return int Position of top pointer
*/
int push(DArrayStack *ptr, int data)
{
if (ptr->top == (ptr->capacity) - 1)
{
ptr = double_array(ptr, ptr->capacity);
ptr->top++;
ptr->arrPtr[ptr->top] = data;
}
else
{
ptr->top++;
ptr->arrPtr[ptr->top] = data;
}
printf("Successfully pushed : %d\n", data);
return ptr->top;
}
/**
* @brief The pop function to pop an element from the stack.
*
* @param ptr Stack pointer
* @return int Popped value
*/
int pop(DArrayStack *ptr)
{
if (ptr->top == -1)
{
printf("Stack is empty UNDERFLOW \n");
return -1;
}
int ele = ptr->arrPtr[ptr->top];
ptr->arrPtr[ptr->top] = 0;
ptr->top = (ptr->top - 1);
if ((ptr->capacity) % 2 == 0)
{
if (ptr->top <= (ptr->capacity / 2) - 1)
{
ptr = shrink_array(ptr, ptr->capacity);
}
}
printf("Successfully popped: %d\n", ele);
return ele;
}
/**
* @brief To retrieve or fetch the first element of the Stack or the element
* present at the top of the Stack.
*
* @param ptr Stack pointer
* @return int Top of the stack
*/
int peek(DArrayStack *ptr)
{
if (ptr->top == -1)
{
printf("Stack is empty UNDERFLOW \n");
return -1;
}
return ptr->arrPtr[ptr->top];
}
/**
* @brief To display the current capacity of the stack.
*
* @param ptr Stack pointer
* @return int Current capacity of the stack
*/
int show_capacity(DArrayStack *ptr) { return ptr->capacity; }
/**
* @brief The function is used to check whether the stack is empty or not and
* return true or false accordingly.
*
* @param ptr Stack pointer
* @return int returns 1 -> true OR returns 0 -> false
*/
int isempty(DArrayStack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
return 0;
}
/**
* @brief Used to get the size of the Stack or the number of elements present in
* the Stack.
*
* @param ptr Stack pointer
* @return int size of stack
*/
int stack_size(DArrayStack *ptr) { return ptr->top + 1; }
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
DArrayStack *NewStack;
int capacity = 1;
NewStack = create_stack(capacity);
uint64_t arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
printf("\nTesting Empty stack: ");
assert(stack_size(NewStack) == 0);
assert(isempty(NewStack) == 1);
printf("Size of an empty stack is %d\n", stack_size(NewStack));
printf("\nTesting PUSH operation:\n");
for (int i = 0; i < 12; ++i)
{
int topVal = push(NewStack, arr[i]);
printf("Size: %d, Capacity: %d\n\n", stack_size(NewStack),
show_capacity(NewStack));
assert(topVal == i);
assert(peek(NewStack) == arr[i]);
assert(stack_size(NewStack) == i + 1);
assert(isempty(NewStack) == 0);
}
printf("\nTesting POP operation:\n");
for (int i = 11; i > -1; --i)
{
peek(NewStack);
assert(peek(NewStack) == arr[i]);
int ele = pop(NewStack);
assert(ele == arr[i]);
assert(stack_size(NewStack) == i);
}
printf("\nTesting Empty stack size: ");
assert(stack_size(NewStack) == 0);
assert(isempty(NewStack) == 1);
printf("Size of an empty stack is %d\n", stack_size(NewStack));
printf("\nTesting POP operation on empty stack: ");
assert(pop(NewStack) == -1);
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 6,537
|
C
|
.c
| 234
| 24.166667
| 138
| 0.639256
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,703
|
circular_doubly_linked_list.c
|
TheAlgorithms_C/data_structures/linked_list/circular_doubly_linked_list.c
|
/**
* @file
*
* @details
* Circular [Doubly Linked
* List](https://en.wikipedia.org/wiki/Doubly_linked_list) combines the
* properties of a doubly linked list and a circular linked list in which two
* consecutive elements are linked or connected by the previous. Next, the
* pointer and the last node point to the first node via the next pointer, and
* the first node points to the last node via the previous pointer.
*
* In this implementation, functions to insert at the head, insert at the last
* index, delete the first node, delete the last node, display list, and get
* list size functions are coded.
*
* @author [Sahil Kandhare](https://github.com/SahilK-027)
*
*/
#include <assert.h> /// to verify assumptions made by the program and print a diagnostic message if this assumption is false.
#include <inttypes.h> /// to provide a set of integer types with universally consistent definitions that are operating system-independent
#include <stdio.h> /// for IO operations
#include <stdlib.h> /// for including functions involving memory allocation such as `malloc`
/**
* @brief Circular Doubly linked list struct
*/
typedef struct node
{
struct node *prev, *next; ///< List pointers
uint64_t value; ///< Data stored on each node
} ListNode;
/**
* @brief Create a list node
* @param data the data that the node initialises with
* @return ListNode* pointer to the newly created list node
*/
ListNode *create_node(uint64_t data)
{
ListNode *new_list = (ListNode *)malloc(sizeof(ListNode));
new_list->value = data;
new_list->next = new_list;
new_list->prev = new_list;
return new_list;
}
/**
* @brief Insert a node at start of list
* @param head start pointer of list
* @param data the data that the node initialises with
* @return ListNode* pointer to the newly created list node
* inserted at the head
*/
ListNode *insert_at_head(ListNode *head, uint64_t data)
{
if (head == NULL)
{
head = create_node(data);
return head;
}
else
{
ListNode *temp;
ListNode *new_node = create_node(data);
temp = head->prev;
new_node->next = head;
head->prev = new_node;
new_node->prev = temp;
temp->next = new_node;
head = new_node;
return head;
}
}
/**
* @brief Insert a node at end of list
*
* @param head start pointer of list
* @param data the data that the node initialises with
* @return ListNode* pointer to the newly added list node that was
* inserted at the head of list.
*/
ListNode *insert_at_tail(ListNode *head, uint64_t data)
{
if (head == NULL)
{
head = create_node(data);
return head;
}
else
{
ListNode *temp1, *temp2;
ListNode *new_node = create_node(data);
temp1 = head;
temp2 = head->prev;
new_node->prev = temp2;
new_node->next = temp1;
temp1->prev = new_node;
temp2->next = new_node;
return head;
}
}
/**
* @brief Function for deletion of the first node in list
*
* @param head start pointer of list
* @return ListNode* pointer to the list node after deleting first node
*/
ListNode *delete_from_head(ListNode *head)
{
if (head == NULL)
{
printf("The list is empty\n");
return head;
}
ListNode *temp1, *temp2;
temp1 = head;
temp2 = temp1->prev;
if (temp1 == temp2)
{
free(temp2);
head = NULL;
return head;
}
temp2->next = temp1->next;
(temp1->next)->prev = temp2;
head = temp1->next;
free(temp1);
return head;
}
/**
* @brief Function for deletion of the last node in list
*
* @param head start pointer of list
* @return ListNode* pointer to the list node after deleting first node
*/
ListNode *delete_from_tail(ListNode *head)
{
if (head == NULL)
{
printf("The list is empty\n");
return head;
}
ListNode *temp1, *temp2;
temp1 = head;
temp2 = temp1->prev;
if (temp1 == temp2)
{
free(temp2);
head = NULL;
return head;
}
(temp2->prev)->next = temp1;
temp1->prev = temp2->prev;
free(temp2);
return head;
}
/**
* @brief The function that will return current size of list
*
* @param head start pointer of list
* @return int size of list
*/
int getsize(ListNode *head)
{
if (!head)
{
return 0;
}
int size = 1;
ListNode *temp = head->next;
while (temp != head)
{
temp = temp->next;
size++;
}
return size;
}
/**
* @brief Display list function
* @param head start pointer of list
* @returns void
*/
void display_list(ListNode *head)
{
printf("\nContents of your linked list: ");
ListNode *temp;
temp = head;
if (head != NULL)
{
while (temp->next != head)
{
printf("%" PRIu64 " <-> ", temp->value);
temp = temp->next;
}
if (temp->next == head)
{
printf("%" PRIu64, temp->value);
}
}
else
{
printf("The list is empty");
}
printf("\n");
}
/**
* @brief access the list by index
* @param list pointer to the target list
* @param index access location
* @returns the value at the specified index,
* wrapping around if the index is larger than the size of the target
* list
*/
uint64_t get(ListNode *list, const int index)
{
if (list == NULL || index < 0)
{
exit(EXIT_FAILURE);
}
ListNode *temp = list;
for (int i = 0; i < index; ++i)
{
temp = temp->next;
}
return temp->value;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
ListNode *testList = NULL;
unsigned int array[] = {2, 3, 4, 5, 6};
assert(getsize(testList) == 0);
printf("Testing inserting elements:\n");
for (int i = 0; i < 5; ++i)
{
display_list(testList);
testList = insert_at_head(testList, array[i]);
assert(testList->value == array[i]);
assert(getsize(testList) == i + 1);
}
printf("\nTesting removing elements:\n");
for (int i = 4; i > -1; --i)
{
display_list(testList);
assert(testList->value == array[i]);
testList = delete_from_head(testList);
assert(getsize(testList) == i);
}
printf("\nTesting inserting at tail:\n");
for (int i = 0; i < 5; ++i)
{
display_list(testList);
testList = insert_at_tail(testList, array[i]);
assert(get(testList, i) == array[i]);
assert(getsize(testList) == i + 1);
}
printf("\nTesting removing from tail:\n");
for (int i = 4; i > -1; --i)
{
display_list(testList);
testList = delete_from_tail(testList);
assert(getsize(testList) == i);
// If list is not empty, assert that accessing the just removed element
// will wrap around to the list head
if (testList != NULL)
{
assert(get(testList, i) == testList->value);
}
else
{
// If the list is empty, assert that the elements were removed after
// the correct number of iterations
assert(i == 0);
}
}
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 7,579
|
C
|
.c
| 285
| 21.792982
| 138
| 0.597663
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,705
|
singly_link_list_deletion.c
|
TheAlgorithms_C/data_structures/linked_list/singly_link_list_deletion.c
|
/*Includes structure for a node which can be use to make new nodes of the Linked
List. It is assumed that the data in nodes will be an integer, though function
can be modified according to the data type, easily. deleteNode deletes a node
when passed with a key of the node.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct node
{
int info;
struct node *link;
};
struct node *start = NULL;
//////////////////////////////////////////////////////////////////
struct node *createnode() // function to create node
{
struct node *t;
t = (struct node *)malloc(sizeof(struct node));
return (t);
}
//////////////////////////////////////////////////////////////////
int insert(int pos, int d)
{
struct node *new;
new = createnode();
new->info = d;
if (pos == 1)
{
new->link = NULL;
if (start == NULL)
{
start = new;
}
else
{
new->link = start;
start = new;
}
}
else
{
struct node *pre = start;
for (int i = 2; i < pos; i++)
{
if (pre == NULL)
{
break;
}
pre = pre->link;
}
if(pre==NULL)
{
printf("Position not found!");
return 0;
}
new->link = pre->link;
pre->link = new;
}
return 0;
}
///////////////////////////////////////////////////////////////////
int deletion(int pos) // function to delete from any position
{
struct node *t;
if (start == NULL)
{
printf("\nlist is empty");
}
else
{
if (pos == 1)
{
struct node *p;
p = start;
start = start->link;
free(p);
}
else
{
struct node *prev = start;
for (int i = 2; i < pos; i++)
{
if (prev == NULL)
{
printf("Position not found!");
return 0;
}
prev = prev->link;
}
struct node *n = prev->link; // n points to required node to be deleted
prev->link = n->link;
free(n);
}
}
return 0;
}
///////////////////////////////////////////////////////////////////
void viewlist() // function to display values
{
struct node *p;
if (start == NULL)
{
printf("\nlist is empty");
}
else
{
p = start;
while (p != NULL)
{
printf("%d ", p->info);
p = p->link;
}
}
}
//////////////////////////////////////////////////////////////////
static void test()
{
insert(1, 39);
assert(start->info == 39);
insert(2, 10);
insert(3, 11);
deletion(1);
assert(start->info != 39);
printf("Self-tests successfully passed!\n");
}
//////////////////////////////////////////////////////////////////
int main()
{
int n = 0, pos = 0, p = 0, num = 0, c = 0;
printf("\n1.self test mode");
printf("\n2.interactive mode");
printf("\nenter your choice:");
scanf("%d", &c);
if (c == 1)
{
test();
}
else if (c == 2)
{
while (1)
{
printf("\n1.add value at the given location");
printf("\n2.delete value at the given location");
printf("\n3.view list");
printf("\nenter your choice :");
scanf("%d", &n);
switch (n)
{
case 1:
printf("enter the position where the element is to be added :");
scanf("%d", &p);
printf("enter the element is to be added :");
scanf("%d", &num);
insert(p, num);
break;
case 2:
printf("enter the position where the element is to be deleted :");
scanf("%d", &pos);
deletion(pos);
break;
case 3:
viewlist();
break;
default:
printf("\ninvalid choice");
}
}
}
else
{
printf("Invalid choice");
}
return 0;
}
| 4,265
|
C
|
.c
| 175
| 16.371429
| 83
| 0.41047
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,728
|
hash_blake2b.c
|
TheAlgorithms_C/hash/hash_blake2b.c
|
/**
* @addtogroup hash Hash algorithms
* @{
* @file
* @author [Daniel Murrow](https://github.com/dsmurrow)
* @brief [Blake2b cryptographic hash
* function](https://www.rfc-editor.org/rfc/rfc7693)
*
* The Blake2b cryptographic hash function provides
* hashes for data that are secure enough to be used in
* cryptographic applications. It is designed to perform
* optimally on 64-bit platforms. The algorithm can output
* digests between 1 and 64 bytes long, for messages up to
* 128 bits in length. Keyed hashing is also supported for
* keys up to 64 bytes in length.
*/
#include <assert.h> /// for asserts
#include <inttypes.h> /// for fixed-width integer types e.g. uint64_t and uint8_t
#include <stdio.h> /// for IO
#include <stdlib.h> /// for malloc, calloc, and free. As well as size_t
/* Warning suppressed is in blake2b() function, more
* details are over there */
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wshift-count-overflow"
#elif _MSC_VER
#pragma warning(disable : 4293)
#endif
/**
* @brief the size of a data block in bytes
*/
#define bb 128
/**
* @brief max key length for BLAKE2b
*/
#define KK_MAX 64
/**
* @brief max length of BLAKE2b digest in bytes
*/
#define NN_MAX 64
/**
* @brief ceiling division macro without floats
*
* @param a dividend
* @param b divisor
*/
#define CEIL(a, b) (((a) / (b)) + ((a) % (b) != 0))
/**
* @brief returns minimum value
*/
#define MIN(a, b) ((a) < (b) ? (a) : (b))
/**
* @brief returns maximum value
*/
#define MAX(a, b) ((a) > (b) ? (a) : (b))
/**
* @brief macro to rotate 64-bit ints to the right
* Ripped from RFC 7693
*/
#define ROTR64(n, offset) (((n) >> (offset)) ^ ((n) << (64 - (offset))))
/**
* @brief zero-value initializer for u128 type
*/
#define U128_ZERO \
{ \
0, 0 \
}
/** 128-bit number represented as two uint64's */
typedef uint64_t u128[2];
/** Padded input block containing bb bytes */
typedef uint64_t block_t[bb / sizeof(uint64_t)];
static const uint8_t R1 = 32; ///< Rotation constant 1 for mixing function G
static const uint8_t R2 = 24; ///< Rotation constant 2 for mixing function G
static const uint8_t R3 = 16; ///< Rotation constant 3 for mixing function G
static const uint8_t R4 = 63; ///< Rotation constant 4 for mixing function G
static const uint64_t blake2b_iv[8] = {
0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B,
0xA54FF53A5F1D36F1, 0x510E527FADE682D1, 0x9B05688C2B3E6C1F,
0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179}; ///< BLAKE2b Initialization vector
///< blake2b_iv[i] = floor(2**64 *
///< frac(sqrt(prime(i+1)))),
///< where prime(i) is the i:th
///< prime number
static const uint8_t blake2b_sigma[12][16] = {
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3},
{11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4},
{7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8},
{9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13},
{2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9},
{12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11},
{13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10},
{6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5},
{10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
{14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5,
3}}; ///< word schedule permutations for each round of the algorithm
/**
* @brief put value of n into dest
*
* @param dest 128-bit number to get copied from n
* @param n value put into dest
*
* @returns void
*/
static inline void u128_fill(u128 dest, size_t n)
{
dest[0] = n & UINT64_MAX;
if (sizeof(n) > 8)
{
/* The C standard does not specify a maximum length for size_t,
* although most machines implement it to be the same length as
* uint64_t. On machines where size_t is 8 bytes long this will issue a
* compiler warning, which is why it is suppressed. But on a machine
* where size_t is greater than 8 bytes, this will work as normal. */
dest[1] = n >> 64;
}
else
{
dest[1] = 0;
}
}
/**
* @brief increment an 128-bit number by a given amount
*
* @param dest the value being incremented
* @param n what dest is being increased by
*
* @returns void
*/
static inline void u128_increment(u128 dest, uint64_t n)
{
/* Check for overflow */
if (UINT64_MAX - dest[0] <= n)
{
dest[1]++;
}
dest[0] += n;
}
/**
* @brief blake2b mixing function G
*
* Shuffles values in block v depending on
* provided indeces a, b, c, and d. x and y
* are also mixed into the block.
*
* @param v array of words to be mixed
* @param a first index
* @param b second index
* @param c third index
* @param d fourth index
* @param x first word being mixed into v
* @param y second word being mixed into y
*
* @returns void
*/
static void G(block_t v, uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint64_t x,
uint64_t y)
{
v[a] += v[b] + x;
v[d] = ROTR64(v[d] ^ v[a], R1);
v[c] += v[d];
v[b] = ROTR64(v[b] ^ v[c], R2);
v[a] += v[b] + y;
v[d] = ROTR64(v[d] ^ v[a], R3);
v[c] += v[d];
v[b] = ROTR64(v[b] ^ v[c], R4);
}
/**
* @brief compression function F
*
* Securely mixes the values in block m into
* the state vector h. Value at v[14] is also
* inverted if this is the final block to be
* compressed.
*
* @param h the state vector
* @param m message vector to be compressed into h
* @param t 128-bit offset counter
* @param f flag to indicate whether this is the final block
*
* @returns void
*/
static void F(uint64_t h[8], block_t m, u128 t, int f)
{
int i;
block_t v;
/* v[0..7] := h[0..7] */
for (i = 0; i < 8; i++)
{
v[i] = h[i];
}
/* v[8..15] := IV[0..7] */
for (; i < 16; i++)
{
v[i] = blake2b_iv[i - 8];
}
v[12] ^= t[0]; /* v[12] ^ (t mod 2**w) */
v[13] ^= t[1]; /* v[13] ^ (t >> w) */
if (f)
{
v[14] = ~v[14];
}
for (i = 0; i < 12; i++)
{
const uint8_t *s = blake2b_sigma[i];
G(v, 0, 4, 8, 12, m[s[0]], m[s[1]]);
G(v, 1, 5, 9, 13, m[s[2]], m[s[3]]);
G(v, 2, 6, 10, 14, m[s[4]], m[s[5]]);
G(v, 3, 7, 11, 15, m[s[6]], m[s[7]]);
G(v, 0, 5, 10, 15, m[s[8]], m[s[9]]);
G(v, 1, 6, 11, 12, m[s[10]], m[s[11]]);
G(v, 2, 7, 8, 13, m[s[12]], m[s[13]]);
G(v, 3, 4, 9, 14, m[s[14]], m[s[15]]);
}
for (i = 0; i < 8; i++)
{
h[i] ^= v[i] ^ v[i + 8];
}
}
/**
* @brief driver function to perform the hashing as described in specification
*
* pseudocode: (credit to authors of RFC 7693 listed above)
* FUNCTION BLAKE2( d[0..dd-1], ll, kk, nn )
* |
* | h[0..7] := IV[0..7] // Initialization Vector.
* |
* | // Parameter block p[0]
* | h[0] := h[0] ^ 0x01010000 ^ (kk << 8) ^ nn
* |
* | // Process padded key and data blocks
* | IF dd > 1 THEN
* | | FOR i = 0 TO dd - 2 DO
* | | | h := F( h, d[i], (i + 1) * bb, FALSE )
* | | END FOR.
* | END IF.
* |
* | // Final block.
* | IF kk = 0 THEN
* | | h := F( h, d[dd - 1], ll, TRUE )
* | ELSE
* | | h := F( h, d[dd - 1], ll + bb, TRUE )
* | END IF.
* |
* | RETURN first "nn" bytes from little-endian word array h[].
* |
* END FUNCTION.
*
* @param dest destination of hashing digest
* @param d message blocks
* @param dd length of d
* @param ll 128-bit length of message
* @param kk length of secret key
* @param nn length of hash digest
*
* @returns 0 upon successful hash
*/
static int BLAKE2B(uint8_t *dest, block_t *d, size_t dd, u128 ll, uint8_t kk,
uint8_t nn)
{
uint8_t bytes[8];
uint64_t i, j;
uint64_t h[8];
u128 t = U128_ZERO;
/* h[0..7] = IV[0..7] */
for (i = 0; i < 8; i++)
{
h[i] = blake2b_iv[i];
}
h[0] ^= 0x01010000 ^ (kk << 8) ^ nn;
if (dd > 1)
{
for (i = 0; i < dd - 1; i++)
{
u128_increment(t, bb);
F(h, d[i], t, 0);
}
}
if (kk != 0)
{
u128_increment(ll, bb);
}
F(h, d[dd - 1], ll, 1);
/* copy bytes from h to destination buffer */
for (i = 0; i < nn; i++)
{
if (i % sizeof(uint64_t) == 0)
{
/* copy values from uint64 to 8 u8's */
for (j = 0; j < sizeof(uint64_t); j++)
{
uint16_t offset = 8 * j;
uint64_t mask = 0xFF;
mask <<= offset;
bytes[j] = (h[i / 8] & (mask)) >> offset;
}
}
dest[i] = bytes[i % 8];
}
return 0;
}
/**
* @brief blake2b hash function
*
* This is the front-end function that sets up the argument for BLAKE2B().
*
* @param message the message to be hashed
* @param len length of message (0 <= len < 2**128) (depends on sizeof(size_t)
* for this implementation)
* @param key optional secret key
* @param kk length of optional secret key (0 <= kk <= 64)
* @param nn length of output digest (1 <= nn < 64)
*
* @returns NULL if heap memory couldn't be allocated. Otherwise heap allocated
* memory nn bytes large
*/
uint8_t *blake2b(const uint8_t *message, size_t len, const uint8_t *key,
uint8_t kk, uint8_t nn)
{
uint8_t *dest = NULL;
uint64_t long_hold;
size_t dd, has_key, i;
size_t block_index, word_in_block;
u128 ll;
block_t *blocks;
if (message == NULL)
{
len = 0;
}
if (key == NULL)
{
kk = 0;
}
kk = MIN(kk, KK_MAX);
nn = MIN(nn, NN_MAX);
dd = MAX(CEIL(kk, bb) + CEIL(len, bb), 1);
blocks = calloc(dd, sizeof(block_t));
if (blocks == NULL)
{
return NULL;
}
dest = malloc(nn * sizeof(uint8_t));
if (dest == NULL)
{
free(blocks);
return NULL;
}
/* If there is a secret key it occupies the first block */
for (i = 0; i < kk; i++)
{
long_hold = key[i];
long_hold <<= 8 * (i % 8);
word_in_block = (i % bb) / 8;
/* block_index will always be 0 because kk <= 64 and bb = 128*/
blocks[0][word_in_block] |= long_hold;
}
has_key = kk > 0 ? 1 : 0;
for (i = 0; i < len; i++)
{
/* long_hold exists because the bit-shifting will overflow if we don't
* store the value */
long_hold = message[i];
long_hold <<= 8 * (i % 8);
block_index = has_key + (i / bb);
word_in_block = (i % bb) / 8;
blocks[block_index][word_in_block] |= long_hold;
}
u128_fill(ll, len);
BLAKE2B(dest, blocks, dd, ll, kk, nn);
free(blocks);
return dest;
}
/** @} */
/**
* @brief Self-test implementations
* @returns void
*/
static void assert_bytes(const uint8_t *expected, const uint8_t *actual,
uint8_t len)
{
uint8_t i;
assert(expected != NULL);
assert(actual != NULL);
assert(len > 0);
for (i = 0; i < len; i++)
{
assert(expected[i] == actual[i]);
}
}
/**
* @brief testing function
*
* @returns void
*/
static void test()
{
uint8_t *digest = NULL;
/* "abc" example straight out of RFC-7693 */
uint8_t abc[3] = {'a', 'b', 'c'};
uint8_t abc_answer[64] = {
0xBA, 0x80, 0xA5, 0x3F, 0x98, 0x1C, 0x4D, 0x0D, 0x6A, 0x27, 0x97,
0xB6, 0x9F, 0x12, 0xF6, 0xE9, 0x4C, 0x21, 0x2F, 0x14, 0x68, 0x5A,
0xC4, 0xB7, 0x4B, 0x12, 0xBB, 0x6F, 0xDB, 0xFF, 0xA2, 0xD1, 0x7D,
0x87, 0xC5, 0x39, 0x2A, 0xAB, 0x79, 0x2D, 0xC2, 0x52, 0xD5, 0xDE,
0x45, 0x33, 0xCC, 0x95, 0x18, 0xD3, 0x8A, 0xA8, 0xDB, 0xF1, 0x92,
0x5A, 0xB9, 0x23, 0x86, 0xED, 0xD4, 0x00, 0x99, 0x23};
digest = blake2b(abc, 3, NULL, 0, 64);
assert_bytes(abc_answer, digest, 64);
free(digest);
uint8_t key[64] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f};
uint8_t key_answer[64] = {
0x10, 0xeb, 0xb6, 0x77, 0x00, 0xb1, 0x86, 0x8e, 0xfb, 0x44, 0x17,
0x98, 0x7a, 0xcf, 0x46, 0x90, 0xae, 0x9d, 0x97, 0x2f, 0xb7, 0xa5,
0x90, 0xc2, 0xf0, 0x28, 0x71, 0x79, 0x9a, 0xaa, 0x47, 0x86, 0xb5,
0xe9, 0x96, 0xe8, 0xf0, 0xf4, 0xeb, 0x98, 0x1f, 0xc2, 0x14, 0xb0,
0x05, 0xf4, 0x2d, 0x2f, 0xf4, 0x23, 0x34, 0x99, 0x39, 0x16, 0x53,
0xdf, 0x7a, 0xef, 0xcb, 0xc1, 0x3f, 0xc5, 0x15, 0x68};
digest = blake2b(NULL, 0, key, 64, 64);
assert_bytes(key_answer, digest, 64);
free(digest);
uint8_t zero[1] = {0};
uint8_t zero_key[64] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f};
uint8_t zero_answer[64] = {
0x96, 0x1f, 0x6d, 0xd1, 0xe4, 0xdd, 0x30, 0xf6, 0x39, 0x01, 0x69,
0x0c, 0x51, 0x2e, 0x78, 0xe4, 0xb4, 0x5e, 0x47, 0x42, 0xed, 0x19,
0x7c, 0x3c, 0x5e, 0x45, 0xc5, 0x49, 0xfd, 0x25, 0xf2, 0xe4, 0x18,
0x7b, 0x0b, 0xc9, 0xfe, 0x30, 0x49, 0x2b, 0x16, 0xb0, 0xd0, 0xbc,
0x4e, 0xf9, 0xb0, 0xf3, 0x4c, 0x70, 0x03, 0xfa, 0xc0, 0x9a, 0x5e,
0xf1, 0x53, 0x2e, 0x69, 0x43, 0x02, 0x34, 0xce, 0xbd};
digest = blake2b(zero, 1, zero_key, 64, 64);
assert_bytes(zero_answer, digest, 64);
free(digest);
uint8_t filled[64] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f};
uint8_t filled_key[64] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f};
uint8_t filled_answer[64] = {
0x65, 0x67, 0x6d, 0x80, 0x06, 0x17, 0x97, 0x2f, 0xbd, 0x87, 0xe4,
0xb9, 0x51, 0x4e, 0x1c, 0x67, 0x40, 0x2b, 0x7a, 0x33, 0x10, 0x96,
0xd3, 0xbf, 0xac, 0x22, 0xf1, 0xab, 0xb9, 0x53, 0x74, 0xab, 0xc9,
0x42, 0xf1, 0x6e, 0x9a, 0xb0, 0xea, 0xd3, 0x3b, 0x87, 0xc9, 0x19,
0x68, 0xa6, 0xe5, 0x09, 0xe1, 0x19, 0xff, 0x07, 0x78, 0x7b, 0x3e,
0xf4, 0x83, 0xe1, 0xdc, 0xdc, 0xcf, 0x6e, 0x30, 0x22};
digest = blake2b(filled, 64, filled_key, 64, 64);
assert_bytes(filled_answer, digest, 64);
free(digest);
printf("All tests have successfully passed!\n");
}
/**
* @brief main function
*
* @returns 0 on successful program exit
*/
int main()
{
test();
return 0;
}
| 16,001
|
C
|
.c
| 480
| 28.197917
| 82
| 0.558252
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,742
|
hamming_distance.c
|
TheAlgorithms_C/misc/hamming_distance.c
|
/**
* @file
* @brief [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance)
* algorithm implementation.
* @details
* In information theory, the Hamming distance between two strings of
* equal length is the number of positions at which the corresponding symbols
* are different.
* @author [Aybars Nazlica](https://github.com/aybarsnazlica)
*/
#include <assert.h> /// for assert
#include <stdio.h> /// for IO operations
/**
* @brief Function to calculate the Hamming distance between two strings
* @param param1 string 1
* @param param2 string 2
* @returns Hamming distance
*/
int hamming_distance(char* str1, char* str2)
{
int i = 0, distance = 0;
while (str1[i] != '\0')
{
if (str1[i] != str2[i])
{
distance++;
}
i++;
}
return distance;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
char str1[] = "karolin";
char str2[] = "kathrin";
assert(hamming_distance(str1, str2) == 3);
char str3[] = "00000";
char str4[] = "11111";
assert(hamming_distance(str3, str4) == 5);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 1,312
|
C
|
.c
| 54
| 20.925926
| 77
| 0.6496
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,746
|
run_length_encoding.c
|
TheAlgorithms_C/misc/run_length_encoding.c
|
/**
* @file
* @author [serturx](https://github.com/serturx/)
* @brief Encode a null terminated string using [Run-length encoding](https://en.wikipedia.org/wiki/Run-length_encoding)
* @details
* Run-length encoding is a lossless compression algorithm.
* It works by counting the consecutive occurences symbols
* and encodes that series of consecutive symbols into the
* counted symbol and a number denoting the number of
* consecutive occorences.
*
* For example the string "AAAABBCCD" gets encoded into "4A2B2C1D"
*
*/
#include <stdio.h> /// for IO operations
#include <string.h> /// for string functions
#include <stdlib.h> /// for malloc/free
#include <assert.h> /// for assert
/**
* @brief Encodes a null-terminated string using run-length encoding
* @param str String to encode
* @return char* Encoded string
*/
char* run_length_encode(char* str) {
int str_length = strlen(str);
int encoded_index = 0;
//allocate space for worst-case scenario
char* encoded = malloc(2 * strlen(str));
//temp space for int to str conversion
char int_str[20];
for(int i = 0; i < str_length; ++i) {
int count = 0;
char current = str[i];
//count occurences
while(current == str[i + count]) count++;
i += count - 1;
//convert occurrence amount to string and write to encoded string
sprintf(int_str, "%d", count);
int int_str_length = strlen(int_str);
strncpy(&encoded[encoded_index], int_str, strlen(int_str));
//write current char to encoded string
encoded_index += strlen(int_str);
encoded[encoded_index] = current;
++encoded_index;
}
//null terminate string and move encoded string to compacted memory space
encoded[encoded_index] = '\0';
char* compacted_string = malloc(strlen(encoded) + 1);
strcpy(compacted_string, encoded);
free(encoded);
return compacted_string;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
char* test;
test = run_length_encode("aaaaaaabbbaaccccdefaadr");
assert(!strcmp(test, "7a3b2a4c1d1e1f2a1d1r"));
free(test);
test = run_length_encode("lidjhvipdurevbeirbgipeahapoeuhwaipefupwieofb");
assert(!strcmp(test, "1l1i1d1j1h1v1i1p1d1u1r1e1v1b1e1i1r1b1g1i1p1e1a1h1a1p1o1e1u1h1w1a1i1p1e1f1u1p1w1i1e1o1f1bq"));
free(test);
test = run_length_encode("htuuuurwuquququuuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahghghrw");
assert(!strcmp(test, "1h1t4u1r1w1u1q1u1q1u1q3u76a1h1g1h1g1h1r1w"));
free(test);
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
printf("All tests have passed!\n");
return 0;
}
| 2,788
|
C
|
.c
| 77
| 31.818182
| 133
| 0.701637
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,748
|
mcnaughton_yamada_thompson.c
|
TheAlgorithms_C/misc/mcnaughton_yamada_thompson.c
|
/**
* @file
* @brief [McNaughton–Yamada–Thompson algorithm](https://en.wikipedia.org/wiki/Thompson%27s_construction)
* @details
* From Wikipedia:
* In computer science, Thompson's construction algorithm,
* also called the McNaughton–Yamada–Thompson algorithm,
* is a method of transforming a regular expression into
* an equivalent nondeterministic finite automaton (NFA).
* This implementation implements the all three operations
* (implicit concatenation, '|' for union, '*' for Kleene star)
* required by the formal definition of regular expressions.
* @author [Sharon Cassidy](https://github.com/CascadingCascade)
*/
#include <assert.h> /// for assert()
#include <stdio.h> /// for IO operations
#include <string.h> /// for string operations
#include <stdlib.h> /// for memory management
/* Begin declarations, I opted to place various helper / utility functions
* close to their usages and didn't split their declaration / definition */
/**
* @brief Definition for a binary abstract syntax tree (AST) node
*/
struct ASTNode {
char content; ///< the content of this node
struct ASTNode* left; ///< left child
struct ASTNode* right; ///< right child
};
struct ASTNode* createNode(char content);
void destroyNode(struct ASTNode* node);
char* preProcessing(const char* input);
struct ASTNode* buildAST(const char* input);
/**
* @brief Definition for a NFA state transition rule
*/
struct transRule {
struct NFAState* target; ///< pointer to the state to transit to
char cond; ///< the input required to activate this transition
};
struct transRule* createRule(struct NFAState* state, char c);
void destroyRule(struct transRule* rule);
/**
* @brief Definition for a NFA state. Each NFAState object is initialized
* to have a capacity of three rules, since there will only be at most two
* outgoing rules and one empty character circular rule in this algorithm
*/
struct NFAState {
int ruleCount; ///< number of transition rules this state have
struct transRule** rules; ///< the transition rules
};
struct NFAState* createState(void);
void destroyState(struct NFAState* state);
/**
* @brief Definition for the NFA itself.
* statePool[0] is defined to be its starting state,
* and statePool[1] is defined to be its accepting state.
* for simplicity's sake all NFAs are initialized to have
* a small fixed capacity, although due to the recursive nature
* of this algorithm this capacity is believed to be sufficient
*/
struct NFA {
int stateCount; ///< the total number of states this NFA have
struct NFAState** statePool; ///< the pool of all available states
int ruleCount; ///< the total number of transition rules in this NFA
struct transRule** rulePool; ///< the pool of all transition rules
int CSCount; ///< the number of currently active states
struct NFAState** currentStates; ///< the pool of all active states
int subCount; ///< the number of sub NFAs
struct NFA** subs; ///< the pool of all sub NFAs
int wrapperFlag; ///< whether this NFA is a concatenation wrapper
};
struct NFA* createNFA(void);
void destroyNFA(struct NFA* nfa);
void addState(struct NFA* nfa, struct NFAState* state);
void addRule(struct NFA* nfa, struct transRule* rule, int loc);
void postProcessing(struct NFA* nfa);
void transit(struct NFA* nfa, char input);
int isAccepting(const struct NFA* nfa);
/* End definitions, begin abstract syntax tree construction */
/**
* @brief helper function to determine whether a character should be
* considered a character literal
* @param ch the character to be tested
* @returns `1` if it is a character literal
* @returns `0` otherwise
*/
int isLiteral(const char ch) {
return !(ch == '(' || ch == ')' || ch == '*' || ch == '\n' || ch == '|');
}
/**
* @brief performs preprocessing on a regex string,
* making all implicit concatenations explicit
* @param input target regex string
* @returns pointer to the processing result
*/
char* preProcessing(const char* input) {
const size_t len = strlen(input);
if(len == 0) {
char* str = malloc(1);
str[0] = '\0';
return str;
}
char* str = malloc(len * 2);
size_t op = 0;
for (size_t i = 0; i < len - 1; ++i) {
char c = input[i];
str[op++] = c;
// one character lookahead
char c1 = input[i + 1];
if( (isLiteral(c) && isLiteral(c1)) ||
(isLiteral(c) && c1 == '(') ||
(c == ')' && c1 == '(') ||
(c == ')' && isLiteral(c1)) ||
(c == '*' && isLiteral(c1)) ||
(c == '*' && c1 == '(')
) {
// '\n' is used to represent concatenation
// in this implementation
str[op++] = '\n';
}
}
str[op++] = input[len - 1];
str[op] = '\0';
return str;
}
/**
* @brief utility function to locate the first occurrence
* of a character in a string while respecting parentheses
* @param str target string
* @param key the character to be located
* @returns the index of its first occurrence, `0` if it could not be found
*/
size_t indexOf(const char* str, char key) {
int depth = 0;
for (size_t i = 0; i < strlen(str); ++i) {
const char c = str[i];
if(depth == 0 && c == key) {
return i;
}
if(c == '(') depth++;
if(c == ')') depth--;
}
// Due to the way this function is intended to be used,
// it's safe to assume the character will not appear as
// the string's first character
// thus `0` is used as the `not found` value
return 0;
}
/**
* @brief utility function to create a subString
* @param str target string
* @param begin starting index, inclusive
* @param end ending index, inclusive
* @returns pointer to the newly created subString
*/
char* subString(const char* str, size_t begin, size_t end) {
char* res = malloc(end - begin + 2);
strncpy(res, str + begin, end - begin + 1);
res[end - begin + 1] = '\0';
return res;
}
/**
* @brief recursively constructs a AST from a preprocessed regex string
* @param input regex
* @returns pointer to the resulting tree
*/
struct ASTNode* buildAST(const char* input) {
struct ASTNode* node = createNode('\0');
node->left = NULL;
node->right = NULL;
const size_t len = strlen(input);
size_t index;
// Empty input
if(len == 0) return node;
// Character literals
if(len == 1) {
node->content = input[0];
return node;
}
// Discard parentheses
if(input[0] == '(' && input[len - 1] == ')') {
char* temp = subString(input, 1, len - 2);
destroyNode(node);
node = buildAST(temp);
free(temp);
return node;
}
// Union
index = indexOf(input, '|');
if(index) {
node->content = '|';
char* temp1 = subString(input, 0, index - 1);
char* temp2 = subString(input, index + 1, len - 1);
node->left = buildAST(temp1);
node->right = buildAST(temp2);
free(temp2);
free(temp1);
return node;
}
// Concatenation
index = indexOf(input, '\n');
if(index) {
node->content = '\n';
char* temp1 = subString(input, 0, index - 1);
char* temp2 = subString(input, index + 1, len - 1);
node->left = buildAST(temp1);
node->right = buildAST(temp2);
free(temp2);
free(temp1);
return node;
}
// Kleene star
// Testing with indexOf() is unnecessary here,
// Since all other possibilities have been exhausted
node->content = '*';
char* temp = subString(input, 0, len - 2);
node->left = buildAST(temp);
node->right = NULL;
free(temp);
return node;
}
/* End AST construction, begins the actual algorithm itself */
/**
* @brief helper function to recursively redirect transition rule targets
* @param nfa target NFA
* @param src the state to redirect away from
* @param dest the state to redirect to
* @returns void
*/
void redirect(struct NFA* nfa, struct NFAState* src, struct NFAState* dest) {
for (int i = 0; i < nfa->subCount; ++i) {
redirect(nfa->subs[i], src, dest);
}
for (int i = 0; i < nfa->ruleCount; ++i) {
struct transRule* rule = nfa->rulePool[i];
if (rule->target == src) {
rule->target = dest;
}
}
}
struct NFA* compileFromAST(struct ASTNode* root) {
struct NFA* nfa = createNFA();
// Empty input
if (root->content == '\0') {
addRule(nfa, createRule(nfa->statePool[1], '\0'), 0);
return nfa;
}
// Character literals
if (isLiteral(root->content)) {
addRule(nfa, createRule(nfa->statePool[1], root->content), 0);
return nfa;
}
switch (root->content) {
case '\n': {
struct NFA* ln = compileFromAST(root->left);
struct NFA* rn = compileFromAST(root->right);
// Redirects all rules targeting ln's accepting state to
// target rn's starting state
redirect(ln, ln->statePool[1], rn->statePool[0]);
// Manually creates and initializes a special
// "wrapper" NFA
destroyNFA(nfa);
struct NFA* wrapper = malloc(sizeof(struct NFA));
wrapper->stateCount = 2;
wrapper->statePool = malloc(sizeof(struct NFAState*) * 2);
wrapper->subCount = 0;
wrapper->subs = malloc(sizeof(struct NFA*) * 2);
wrapper->ruleCount = 0;
wrapper->rulePool = malloc(sizeof(struct transRule*) * 3);
wrapper->CSCount = 0;
wrapper->currentStates = malloc(sizeof(struct NFAState*) * 2);
wrapper->wrapperFlag = 1;
wrapper->subs[wrapper->subCount++] = ln;
wrapper->subs[wrapper->subCount++] = rn;
// Maps the wrapper NFA's starting and ending states
// to its sub NFAs
wrapper->statePool[0] = ln->statePool[0];
wrapper->statePool[1] = rn->statePool[1];
return wrapper;
}
case '|': {
struct NFA* ln = compileFromAST(root->left);
struct NFA* rn = compileFromAST(root->right);
nfa->subs[nfa->subCount++] = ln;
nfa->subs[nfa->subCount++] = rn;
// Adds empty character transition rules
addRule(nfa, createRule(ln->statePool[0], '\0'), 0);
addRule(ln, createRule(nfa->statePool[1], '\0'), 1);
addRule(nfa, createRule(rn->statePool[0], '\0'), 0);
addRule(rn, createRule(nfa->statePool[1], '\0'), 1);
return nfa;
}
case '*': {
struct NFA* ln = compileFromAST(root->left);
nfa->subs[nfa->subCount++] = ln;
addRule(ln, createRule(ln->statePool[0], '\0'), 1);
addRule(nfa, createRule(ln->statePool[0], '\0'), 0);
addRule(ln, createRule(nfa->statePool[1], '\0'), 1);
addRule(nfa, createRule(nfa->statePool[1], '\0'), 0);
return nfa;
}
}
// Fallback, shouldn't happen in normal operation
destroyNFA(nfa);
return NULL;
}
/* Ends the algorithm, begins NFA utility functions*/
/**
* @brief adds a state to a NFA
* @param nfa target NFA
* @param state the NFA state to be added
* @returns void
*/
void addState(struct NFA* nfa, struct NFAState* state) {
nfa->statePool[nfa->stateCount++] = state;
}
/**
* @brief adds a transition rule to a NFA
* @param nfa target NFA
* @param rule the rule to be added
* @param loc which state this rule should be added to
* @returns void
*/
void addRule(struct NFA* nfa, struct transRule* rule, int loc) {
nfa->rulePool[nfa->ruleCount++] = rule;
struct NFAState* state = nfa->statePool[loc];
state->rules[state->ruleCount++] = rule;
}
/**
* @brief performs postprocessing on a compiled NFA,
* add circular empty character transition rules where
* it's needed for the NFA to function correctly
* @param nfa target NFA
* @returns void
*/
void postProcessing(struct NFA* nfa) {
// Since the sub NFA's states and rules are managed
// through their own pools, recursion is necessary
for (int i = 0; i < nfa->subCount; ++i) {
postProcessing(nfa->subs[i]);
}
// If a state does not have any empty character accepting rule,
// we add a rule that circles back to itself
// So this state will be preserved when
// empty characters are inputted
for (int i = 0; i < nfa->stateCount; ++i) {
struct NFAState* pState = nfa->statePool[i];
int f = 0;
for (int j = 0; j < pState->ruleCount; ++j) {
if(pState->rules[j]->cond == '\0') {
f = 1;
break;
}
}
if (!f) {
addRule(nfa, createRule(pState, '\0'), i);
}
}
}
/**
* @brief helper function to determine an element's presence in an array
* @param states target array
* @param len length of the target array
* @param state the element to search for
* @returns `1` if the element is present, `0` otherwise
*/
int contains(struct NFAState** states, int len, struct NFAState* state) {
int f = 0;
for (int i = 0; i < len; ++i) {
if(states[i] == state) {
f = 1;
break;
}
}
return f;
}
/**
* @brief helper function to manage empty character transitions
* @param target target NFA
* @param states pointer to results storage location
* @param sc pointer to results count storage location
* @returns void
*/
void findEmpty(struct NFAState* target, struct NFAState** states, int *sc) {
for (int i = 0; i < target->ruleCount; ++i) {
const struct transRule *pRule = target->rules[i];
if (pRule->cond == '\0' && !contains(states, *sc, pRule->target)) {
states[(*sc)++] = pRule->target;
// the use of `states` and `sc` is necessary
// to sync data across recursion levels
findEmpty(pRule->target, states, sc);
}
}
}
/**
* @brief moves a NFA forward
* @param nfa target NFA
* @param input the character to be fed into the NFA
* @returns void
*/
void transit(struct NFA* nfa, char input) {
struct NFAState** newStates = malloc(sizeof(struct NFAState*) * 10);
int NSCount = 0;
if (input == '\0') {
// In case of empty character input, it's possible for
// a state to transit to another state that's more than
// one rule away, we need to take that into account
for (int i = nfa->CSCount - 1; i > -1; --i) {
struct NFAState *pState = nfa->currentStates[i];
nfa->CSCount--;
struct NFAState** states = malloc(sizeof(struct NFAState*) * 10);
int sc = 0;
findEmpty(pState, states, &sc);
for (int j = 0; j < sc; ++j) {
if(!contains(newStates,NSCount, states[j])) {
newStates[NSCount++] = states[j];
}
}
free(states);
}
} else {
// Iterates through all current states
for (int i = nfa->CSCount - 1; i > -1; --i) {
struct NFAState *pState = nfa->currentStates[i];
// Gradually empties the current states pool, so
// it can be refilled
nfa->CSCount--;
// Iterates through rules of this state
for (int j = 0; j < pState->ruleCount; ++j) {
const struct transRule *pRule = pState->rules[j];
if(pRule->cond == input) {
if(!contains(newStates, NSCount, pRule->target)) {
newStates[NSCount++] = pRule->target;
}
}
}
}
}
nfa->CSCount = NSCount;
for (int i = 0; i < NSCount; ++i) {
nfa->currentStates[i] = newStates[i];
}
free(newStates);
}
/**
* @brief determines whether the NFA is currently in its accepting state
* @param nfa target NFA
* @returns `1` if the NFA is in its accepting state
* @returns `0` otherwise
*/
int isAccepting(const struct NFA* nfa) {
for (int i = 0; i < nfa->CSCount; ++i) {
if(nfa->currentStates[i] == nfa->statePool[1]) {
return 1;
}
}
return 0;
}
/* Ends NFA utilities, begins testing function*/
/**
* @brief Testing helper function
* @param regex the regular expression to be used
* @param string the string to match against
* @param expected expected results
* @returns void
*/
void testHelper(const char* regex, const char* string, const int expected) {
char* temp = preProcessing(regex);
struct ASTNode* node = buildAST(temp);
struct NFA* nfa = compileFromAST(node);
postProcessing(nfa);
// reallocates the outermost NFA's current states pool
// because it will actually be used to store all the states
nfa->currentStates = realloc(nfa->currentStates, sizeof(struct NFAState*) * 100);
// Starts the NFA by adding its starting state to the pool
nfa->currentStates[nfa->CSCount++] = nfa->statePool[0];
// feeds empty characters into the NFA before and after
// every normal character
for (size_t i = 0; i < strlen(string); ++i) {
transit(nfa, '\0');
transit(nfa, string[i]);
}
transit(nfa, '\0');
assert(isAccepting(nfa) == expected);
destroyNFA(nfa);
destroyNode(node);
free(temp);
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test(void) {
testHelper("(c|a*b)", "c", 1);
testHelper("(c|a*b)", "aab", 1);
testHelper("(c|a*b)", "ca", 0);
testHelper("(c|a*b)*", "caaab", 1);
testHelper("(c|a*b)*", "caba", 0);
testHelper("", "", 1);
testHelper("", "1", 0);
testHelper("(0|(1(01*(00)*0)*1)*)*","11",1);
testHelper("(0|(1(01*(00)*0)*1)*)*","110",1);
testHelper("(0|(1(01*(00)*0)*1)*)*","1100",1);
testHelper("(0|(1(01*(00)*0)*1)*)*","10000",0);
testHelper("(0|(1(01*(00)*0)*1)*)*","00000",1);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main(void) {
test(); // run self-test implementations
return 0;
}
/* I opted to place these more-or-less boilerplate code and their docs
* at the end of file for better readability */
/**
* @brief creates and initializes a AST node
* @param content data to initializes the node with
* @returns pointer to the newly created node
*/
struct ASTNode* createNode(const char content) {
struct ASTNode* node = malloc(sizeof(struct ASTNode));
node->content = content;
node->left = NULL;
node->right = NULL;
return node;
}
/**
* @brief recursively destroys a AST
* @param node the root node of the tree to be deleted
* @returns void
*/
void destroyNode(struct ASTNode* node) {
if(node->left != NULL) {
destroyNode(node->left);
}
if(node->right != NULL) {
destroyNode(node->right);
}
free(node);
}
/**
* @brief creates and initializes a transition rule
* @param state transition target
* @param c transition condition
* @returns pointer to the newly created rule
*/
struct transRule* createRule(struct NFAState* state, char c) {
struct transRule* rule = malloc(sizeof(struct transRule));
rule->target = state;
rule->cond = c;
return rule;
}
/**
* @brief destroys a transition rule object
* @param rule pointer to the object to be deleted
* @returns void
*/
void destroyRule(struct transRule* rule) {
free(rule);
}
/**
* @brief creates and initializes a NFA state
* @returns pointer to the newly created NFA state
*/
struct NFAState* createState(void) {
struct NFAState* state = malloc(sizeof(struct NFAState));
state->ruleCount = 0;
state->rules = malloc(sizeof(struct transRule*) * 3);
return state;
}
/**
* @brief destroys a NFA state
* @param state pointer to the object to be deleted
* @returns void
*/
void destroyState(struct NFAState* state) {
free(state->rules);
free(state);
}
/**
* @brief creates and initializes a NFA
* @returns pointer to the newly created NFA
*/
struct NFA* createNFA(void) {
struct NFA* nfa = malloc(sizeof(struct NFA));
nfa->stateCount = 0;
nfa->statePool = malloc(sizeof(struct NFAState*) * 5);
nfa->ruleCount = 0;
nfa->rulePool = malloc(sizeof(struct transRule*) * 10);
nfa->CSCount = 0;
nfa->currentStates = malloc(sizeof(struct NFAState*) * 5);
nfa->subCount = 0;
nfa->subs = malloc(sizeof(struct NFA*) * 5);
nfa->wrapperFlag = 0;
addState(nfa, createState());
addState(nfa, createState());
return nfa;
}
/**
* @brief recursively destroys a NFA
* @param nfa pointer to the object to be deleted
* @returns void
*/
void destroyNFA(struct NFA* nfa) {
for (int i = 0; i < nfa->subCount; ++i) {
destroyNFA(nfa->subs[i]);
}
// In case of a wrapper NFA, do not free its states
// because it doesn't really have any states of its own
if (!nfa->wrapperFlag) {
for (int i = 0; i < nfa->stateCount; ++i) {
destroyState(nfa->statePool[i]);
}
}
for (int i = 0; i < nfa->ruleCount; ++i) {
destroyRule(nfa->rulePool[i]);
}
free(nfa->statePool);
free(nfa->currentStates);
free(nfa->rulePool);
free(nfa->subs);
free(nfa);
}
| 21,687
|
C
|
.c
| 626
| 29.107029
| 105
| 0.612797
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,761
|
non_preemptive_priority_scheduling.c
|
TheAlgorithms_C/process_scheduling_algorithms/non_preemptive_priority_scheduling.c
|
/**
* @file
* @brief
* [Non-Preemptive Priority
* Scheduling](https://en.wikipedia.org/wiki/Scheduling_(computing))
* is a scheduling algorithm that selects the tasks to execute based on
* priority.
*
* @details
* In this algorithm, processes are executed according to their
* priority. The process with the highest priority is to be executed first and
* so on. In this algorithm, a variable is maintained known as the time quantum.
* The length of the time quantum is decided by the user. The process which is
* being executed is interrupted after the expiration of the time quantum and
* the next process with the highest priority is executed. This cycle of
* interrupting the process after every time quantum and resuming the next
* process with the highest priority continues until all the processes have
* been executed.
* @author [Aryan Raj](https://github.com/aryaraj132)
*/
#include <assert.h> /// for assert
#include <stdbool.h> /// for boolean data type
#include <stdio.h> /// for IO operations (`printf`)
#include <stdlib.h> /// for memory allocation eg: `malloc`, `realloc`, `free`, `exit`
/**
* @brief Structure to represent a process
*/
typedef struct node {
int ID; ///< ID of the process node
int AT; ///< Arrival Time of the process node
int BT; ///< Burst Time of the process node
int priority; ///< Priority of the process node
int CT; ///< Completion Time of the process node
int WT; ///< Waiting Time of the process node
int TAT; ///< Turn Around Time of the process node
struct node *next; ///< pointer to the node
} node;
/**
* @brief To insert a new process in the queue
* @param root pointer to the head of the queue
* @param id process ID
* @param at arrival time
* @param bt burst time
* @param prior priority of the process
* @returns void
*/
void insert(node **root, int id, int at, int bt, int prior)
{
// create a new node and initialize it
node *new = (node *)malloc(sizeof(node));
node *ptr = *root;
new->ID = id;
new->AT = at;
new->BT = bt;
new->priority = prior;
new->next = NULL;
new->CT = 0;
new->WT = 0;
new->TAT = 0;
// if the root is null, make the new node the root
if (*root == NULL)
{
*root = new;
return;
}
// else traverse to the end of the queue and insert the new node there
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = new;
return;
}
/*
* @brief To delete a process from the queue
* @param root pointer to the head of the queue
* @param id process ID
* @returns void
*/
void delete(node **root, int id)
{
node *ptr = *root, *prev;
// if the root is null, return
if (ptr == NULL)
{
return;
}
// if the root is the process to be deleted, make the next node the root
if (ptr->ID == id)
{
*root = ptr->next;
free(ptr);
return;
}
// else traverse the queue and delete the process
while (ptr != NULL && ptr->ID != id)
{
prev = ptr;
ptr = ptr->next;
}
if (ptr == NULL)
{
return;
}
prev->next = ptr->next;
free(ptr);
}
/**
* @brief To show the process queue
* @param head pointer to the head of the queue
* @returns void
*/
void show_list(node *head)
{
printf("Process Priority AT BT CT TAT WT \n");
while (head != NULL)
{
printf("P%d. %d %d %d %d %d %d \n", head->ID, head->priority, head->AT,
head->BT, head->CT, head->TAT, head->WT);
head = head->next;
}
}
/**
* @brief To length process queue
* @param root pointer to the head of the queue
* @returns int total length of the queue
*/
int l_length(node **root)
{
int count = 0;
node *ptr = *root;
while (ptr != NULL)
{
count++;
ptr = ptr->next;
}
return count;
}
/**
* @brief To update the completion time, turn around time and waiting time of
* the processes
* @param root pointer to the head of the queue
* @param id process ID
* @param ct current time
* @param wt waiting time
* @param tat turn around time
* @returns void
*/
void update(node **root, int id, int ct, int wt, int tat)
{
node *ptr = *root;
// If process to be updated is head node
if (ptr != NULL && ptr->ID == id)
{
if (ct != 0)
{
ptr->CT = ct;
}
if (wt != 0)
{
ptr->WT = wt;
}
if (tat != 0)
{
ptr->TAT = tat;
}
return;
}
// else traverse the queue and update the values
while (ptr != NULL && ptr->ID != id)
{
ptr = ptr->next;
}
if (ct != 0)
{
ptr->CT = ct;
}
if (wt != 0)
{
ptr->WT = wt;
}
if (tat != 0)
{
ptr->TAT = tat;
}
return;
}
/**
* @brief To compare the priority of two processes based on their arrival time
* and priority
* @param a pointer to the first process
* @param b pointer to the second process
* @returns true if the priority of the first process is greater than the
* the second process
* @returns false if the priority of the first process is NOT greater than the
* second process
*/
bool compare(node *a, node *b)
{
if (a->AT == b->AT)
{
return a->priority < b->priority;
}
else
{
return a->AT < b->AT;
}
}
/**
* @brief To calculate the average completion time of all the processes
* @param root pointer to the head of the queue
* @returns float average completion time
*/
float calculate_ct(node **root)
{
// calculate the total completion time of all the processes
node *ptr = *root, *prior, *rpt;
int ct = 0, i, time = 0;
int n = l_length(root);
float avg, sum = 0;
node *duproot = NULL;
// create a duplicate queue
while (ptr != NULL)
{
insert(&duproot, ptr->ID, ptr->AT, ptr->BT, ptr->priority);
ptr = ptr->next;
}
ptr = duproot;
rpt = ptr->next;
// sort the queue based on the arrival time and priority
while (rpt != NULL)
{
if (!compare(ptr, rpt))
{
ptr = rpt;
}
rpt = rpt->next;
}
// ptr is the process to be executed first.
ct = ptr->AT + ptr->BT;
time = ct;
sum += ct;
// update the completion time, turn around time and waiting time of the
// process
update(root, ptr->ID, ct, 0, 0);
delete (&duproot, ptr->ID);
// repeat the process until all the processes are executed
for (i = 0; i < n - 1; i++)
{
ptr = duproot;
while (ptr != NULL && ptr->AT > time)
{
ptr = ptr->next;
}
rpt = ptr->next;
while (rpt != NULL)
{
if (rpt->AT <= time)
{
if (rpt->priority < ptr->priority)
{
ptr = rpt;
}
}
rpt = rpt->next;
}
ct += ptr->BT;
time += ptr->BT;
sum += ct;
update(root, ptr->ID, ct, 0, 0);
delete (&duproot, ptr->ID);
}
avg = sum / n;
return avg;
}
/**
* @brief To calculate the average turn around time of all the processes
* @param root pointer to the head of the queue
* @returns float average turn around time
*/
float calculate_tat(node **root)
{
float avg, sum = 0;
int n = l_length(root);
node *ptr = *root;
// calculate the completion time if not already calculated
if (ptr->CT == 0)
{
calculate_ct(root);
}
// calculate the total turn around time of all the processes
while (ptr != NULL)
{
ptr->TAT = ptr->CT - ptr->AT;
sum += ptr->TAT;
ptr = ptr->next;
}
avg = sum / n;
return avg;
}
/**
* @brief To calculate the average waiting time of all the processes
* @param root pointer to the head of the queue
* @returns float average waiting time
*/
float calculate_wt(node **root)
{
float avg, sum = 0;
int n = l_length(root);
node *ptr = *root;
// calculate the completion if not already calculated
if (ptr->CT == 0)
{
calculate_ct(root);
}
// calculate the total waiting time of all the processes
while (ptr != NULL)
{
ptr->WT = (ptr->TAT - ptr->BT);
sum += ptr->WT;
ptr = ptr->next;
}
avg = sum / n;
return avg;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
// Entered processes
// printf("ID Priority Arrival Time Burst Time \n");
// printf("1 0 5 1 \n");
// printf("2 1 4 2 \n");
// printf("3 2 3 3 \n");
// printf("4 3 2 4 \n");
// printf("5 4 1 5 \n");
node *root = NULL;
insert(&root, 1, 0, 5, 1);
insert(&root, 2, 1, 4, 2);
insert(&root, 3, 2, 3, 3);
insert(&root, 4, 3, 2, 4);
insert(&root, 5, 4, 1, 5);
float avgCT = calculate_ct(&root);
float avgTAT = calculate_tat(&root);
float avgWT = calculate_wt(&root);
assert(avgCT == 11);
assert(avgTAT == 9);
assert(avgWT == 6);
printf("[+] All tests have successfully passed!\n");
// printf("Average Completion Time is : %f \n", calculate_ct(&root));
// printf("Average Turn Around Time is : %f \n", calculate_tat(&root));
// printf("Average Waiting Time is : %f \n", calculate_wt(&root));
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 9,585
|
C
|
.c
| 364
| 21.508242
| 86
| 0.581272
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,766
|
remote_command_exec_udp_server.c
|
TheAlgorithms_C/client_server/remote_command_exec_udp_server.c
|
/**
* @file
* @author [NVombat](https://github.com/NVombat)
* @brief Server-side implementation of [Remote Command
* Execution Using
* UDP](https://www.imperva.com/learn/ddos/udp-user-datagram-protocol/)
* @see remote_command_exec_udp_server.c
*
* @details
* The algorithm is based on the simple UDP client and server model. It
* runs an infinite loop which takes user input and sends it to the server
* for execution. The server receives the commands and executes them
* until the user exits the loop. In this way, Remote Command Execution
* using UDP is shown using the server-client model & socket programming
*/
#ifdef _WIN32
#define bzero(b, len) \
(memset((b), '\0', (len)), (void)0) /**< BSD name not in windows */
#define close _close
#include <Ws2tcpip.h>
#include <io.h>
#include <winsock2.h> /// For the type in_addr_t and in_port_t
#else
#include <arpa/inet.h> /// For the type in_addr_t and in_port_t
#include <netdb.h> /// For structures returned by the network database library - formatted internet addresses and port numbers
#include <netinet/in.h> /// For in_addr and sockaddr_in structures
#include <sys/socket.h> /// For macro definitions related to the creation of sockets
#include <sys/types.h> /// For definitions to allow for the porting of BSD programs
#include <unistd.h>
#endif
#include <errno.h> /// To indicate what went wrong if an error occurs
#include <stdint.h> /// For specific bit size values of variables
#include <stdio.h> /// Variable types, several macros, and various functions for performing input and output
#include <stdlib.h> /// Variable types, several macros, and various functions for performing general functions
#include <string.h> /// Various functions for manipulating arrays of characters
#define PORT 10000 /// Define port over which communication will take place
/**
* @brief Utility function used to print an error message to `stderr`.
* It prints `str` and an implementation-defined error
* message corresponding to the global variable `errno`.
* @returns void
*/
void error()
{
perror("Socket Creation Failed");
exit(EXIT_FAILURE);
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main()
{
/** Variable Declarations */
uint32_t
sockfd; ///< socket descriptors - Like file handles but for sockets
char recv_msg[1024],
success_message[] =
"Command Executed Successfully!\n"; ///< character arrays to read
/// and store string data
/// for communication & Success
/// message
struct sockaddr_in server_addr,
client_addr; ///< basic structures for all syscalls and functions that
/// deal with internet addresses. Structures for handling
/// internet addresses
socklen_t clientLength = sizeof(client_addr); /// size of address
/**
* The UDP socket is created using the socket function.
*
* AF_INET (Family) - it is an address family that is used to designate the
* type of addresses that your socket can communicate with
*
* SOCK_DGRAM (Type) - Indicates UDP Connection - UDP does not require the
* source and destination to establish a three-way handshake before
* transmission takes place. Additionally, there is no need for an
* end-to-end connection
*
* 0 (Protocol) - Specifies a particular protocol to be used with the
* socket. Specifying a protocol of 0 causes socket() to use an unspecified
* default protocol appropriate for the requested socket type.
*/
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
error();
}
/**
* Server Address Information
*
* The bzero() function erases the data in the n bytes of the memory
* starting at the location pointed to, by writing zeros (bytes
* containing '\0') to that area.
*
* We bind the server_addr to the internet address and port number thus
* giving our socket an identity with an address and port where it can
* listen for connections
*
* htons - The htons() function translates a short integer from host byte
* order to network byte order
*
* htonl - The htonl() function translates a long integer from host byte
* order to network byte order
*
* These functions are necessary so that the binding of address and port
* takes place with data in the correct format
*/
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
/**
* This binds the socket descriptor to the server thus enabling the server
* to listen for connections and communicate with other clients
*/
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
error(); /// If binding is unsuccessful
}
printf("Server is Connected Successfully...\n");
/**
* Communication between client and server
*
* The bzero() function erases the data in the n bytes of the memory
* starting at the location pointed to, by writing zeros (bytes
* containing '\0') to that area. The variables are emptied and then
* ready for use
*
* The server receives data from the client which is a command. It then
* executes the command.
*
* The client then receives a response from the server when the
* command has been executed
*
* The server and client can communicate indefinitely till one of them
* exits the connection
*
* The client sends the server a command which it executes thus showing
* remote command execution using UDP
*/
while (1)
{
bzero(recv_msg, sizeof(recv_msg));
recvfrom(sockfd, recv_msg, sizeof(recv_msg), 0,
(struct sockaddr *)&client_addr, &clientLength);
printf("Command Output: \n");
system(recv_msg);
printf("Command Executed\n");
sendto(sockfd, success_message, sizeof(success_message), 0,
(struct sockaddr *)&client_addr, clientLength);
}
/// Close socket
close(sockfd);
printf("Server is offline...\n");
return 0;
}
| 6,402
|
C
|
.c
| 155
| 35.458065
| 127
| 0.66966
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,778
|
1695.c
|
TheAlgorithms_C/leetcode/src/1695.c
|
// Window sliding. Runtime: O(n), Space: O(n)
int maximumUniqueSubarray(int* nums, int numsSize){
short* numsSet = (short*)calloc(10001, sizeof(short));
numsSet[nums[0]] = 1;
int maxSum = nums[0];
int windowSumm = maxSum;
int leftIndex = 0;
int num = 0;
for(int i = 1; i < numsSize; i++){
num = nums[i];
while (numsSet[num] != 0){
numsSet[nums[leftIndex]] = 0;
windowSumm -= nums[leftIndex];
leftIndex++;
}
numsSet[num] = 1;
windowSumm += num;
if (maxSum < windowSumm){
maxSum = windowSumm;
}
}
return maxSum;
}
| 715
|
C
|
.c
| 23
| 21.26087
| 59
| 0.523006
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,780
|
119.c
|
TheAlgorithms_C/leetcode/src/119.c
|
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getRow(int rowIndex, int* returnSize){
int colIndex = rowIndex + 1;
int* ans = (int*) malloc(sizeof(int) * colIndex);
for (int i = 0; i < colIndex; i++)
{
ans[i] = 1;
}
*returnSize = colIndex;
for (int r = 2; r <= rowIndex; r++)
{
for (int c = r - 1; c > 0; c--)
{
ans[c] = ans[c] + ans[c-1];
}
}
return ans;
}
| 492
|
C
|
.c
| 20
| 18.8
| 73
| 0.504329
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,782
|
2130.c
|
TheAlgorithms_C/leetcode/src/2130.c
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int pairSum(struct ListNode* head)
{
struct ListNode* dup = head;
int count = 0, i = 0, max = 0;
while (head != NULL)
{
count++;
head = head->next;
}
int* arr = malloc(count * sizeof(int));
while (dup != NULL)
{
arr[i++] = dup->val;
dup = dup->next;
}
for (i = 0; i < count / 2; ++i)
{
if (arr[i] + arr[count - i - 1] > max)
max = arr[i] + arr[count - i - 1];
}
return max;
}
| 600
|
C
|
.c
| 29
| 15.862069
| 46
| 0.485965
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,785
|
98.c
|
TheAlgorithms_C/leetcode/src/98.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Depth first search approach.
// Runtime: O(n)
// Space: O(1)
bool checkIsBst(struct TreeNode* node, bool leftBoundInf, int leftBound, bool rightBoundInf, int rightBound){
return
(node == NULL)
|| (leftBoundInf || node->val > leftBound)
&& (rightBoundInf || node->val < rightBound)
&& checkIsBst(node->left, leftBoundInf, leftBound, false, node->val)
&& checkIsBst(node->right, false, node->val, rightBoundInf, rightBound);
}
bool isValidBST(struct TreeNode* root){
return checkIsBst(root, true, INT_MIN, true, INT_MAX);
}
| 750
|
C
|
.c
| 22
| 29.363636
| 110
| 0.640884
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,787
|
69.c
|
TheAlgorithms_C/leetcode/src/69.c
|
//using the binary search method is one of the efficient ones for this problem statement.
int mySqrt(int x){
int start=0;
int end=x;
long long int ans=0;
while(start <= end){
long long int mid=(start+end)/2;
long long int val=mid*mid;
if( val == x){
return mid;
}
//if mid is less than the square root of the number(x) store the value of mid in ans.
if( val < x){
ans = mid;
start = mid+1;
}
//if mid is greater than the square root of the number(x) then ssign the value mid-1 to end.
if( val > x){
end = mid-1;
}
}
return ans;
}
| 789
|
C
|
.c
| 23
| 22.043478
| 107
| 0.472585
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,788
|
2270.c
|
TheAlgorithms_C/leetcode/src/2270.c
|
// Prefix sum.
// Collect sum fromleft part and compare it with left sum.
// Runtime: O(n)
// Space: O(1)
int waysToSplitArray(int* nums, int numsSize){
long sumNums = 0;
for (int i = 0; i < numsSize; i++){
sumNums += nums[i];
}
long prefixSum = 0;
int result = 0;
for (int i = 0; i < numsSize - 1; i++){
prefixSum += nums[i];
if (prefixSum >= sumNums - prefixSum){
result += 1;
}
}
return result;
}
| 503
|
C
|
.c
| 19
| 20.052632
| 59
| 0.529412
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,789
|
1524.c
|
TheAlgorithms_C/leetcode/src/1524.c
|
// Counting whole summ. evens sums number and odd summs number.
// Runtime: O(n),
// Space: O(1)
int numOfSubarrays(int* arr, int arrSize){
int result = 0;
int curSumm = 0;
int currOddSumms = 0;
int currEvenSumm = 0;
int modulo = 1000000000 + 7;
for(int i = 0; i < arrSize; i++){
curSumm += arr[i];
if (curSumm % 2 == 0){
currEvenSumm++;
result = (result + currOddSumms) % modulo;
}
else {
currOddSumms++;
result = (result + 1 + currEvenSumm) % modulo;
}
}
return result % modulo;
}
| 629
|
C
|
.c
| 22
| 20.954545
| 64
| 0.525705
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,790
|
17.c
|
TheAlgorithms_C/leetcode/src/17.c
|
/**
* Letter Combinations of a Phone Number problem
* The algorithm determines the final size of the return array (combs) and allocates
* corresponding letter for each element, assuming that the return array is alphabetically sorted.
* It does so by running two loops for each letter:
* - the first loop determines the starting positions of the sequence of subsequent letter positions
* - the second loop determines the length of each subsequent sequence for each letter
* The size and space complexity are both O("size of final array"), as even though there are 4 loops,
* each element in the final array is accessed only once.
*/
#include <stdlib.h> // for the malloc() function
#include <string.h> // for the strlen() function
char *get_letters(char digit) {
switch (digit) {
case '2':
return "abc";
case '3':
return "def";
case '4':
return "ghi";
case '5':
return "jkl";
case '6':
return "mno";
case '7':
return "pqrs";
case '8':
return "tuv";
case '9':
return "wxyz";
default:
return "";
}
}
char **letterCombinations(char *digits, int *return_size) {
char *cp;
int i, j, k, l, ind, k_tot, l_tot, digits_size = 0;
if (*digits == '\0') {
*return_size = 0;
return NULL;
}
*return_size = 1;
cp = digits;
while (*cp != '\0') {
*return_size *= strlen(get_letters(*cp));
digits_size++;
cp++;
}
char **combs = malloc(sizeof(char*) * (*return_size));
for (i = 0; i < *return_size; i++) {
combs[i] = malloc(sizeof(char) * (digits_size + 1));
combs[i][digits_size] = '\0';
}
k_tot = 1;
l_tot = (*return_size);
for (i = 0; i < digits_size; i++) { // loop accross digits
cp = get_letters(digits[i]);
l_tot /= strlen(cp);
for (j = 0; j < strlen(cp); j++) { // loop accross letters of the digit
for (k = 0; k < k_tot; k++) { // loop across the subset starting positions for each letter
for (l = 0; l < l_tot; l++) { // loop accross each subset positions for each letter
ind = k * l_tot * strlen(cp) + l + l_tot * j;
combs[ind][i] = cp[j];
}
}
}
k_tot *= strlen(cp);
}
return combs;
}
| 2,440
|
C
|
.c
| 70
| 27.271429
| 102
| 0.550804
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,797
|
50.c
|
TheAlgorithms_C/leetcode/src/50.c
|
double powPositive(double x, int n){
if (n == 1){
return x;
}
double val = powPositive(x, n / 2);
double result = val * val;
// if n is odd
if (n & 1 > 0){
result *= x;
}
return result;
}
// Divide and conquer.
// Runtime: O(log(n))
// Space: O(1)
double myPow(double x, int n){
if (n == 0){
return 1;
}
const int LOWER_BOUND = -2147483648;
// n is the minimum int, couldn't be converted in -n because maximum is 2147483647.
// this case we use (1 / pow(x, -(n + 1))) * n
if (n == LOWER_BOUND){
return 1 / (powPositive(x, -(n + 1)) * x);
}
// 1 / pow(x, -(n + 1))
if (n < 0){
return 1 / powPositive(x, -n);
}
return powPositive(x, n);
}
| 804
|
C
|
.c
| 31
| 19.548387
| 88
| 0.500664
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,801
|
1147.c
|
TheAlgorithms_C/leetcode/src/1147.c
|
#define max(a,b) (((a)>(b))?(a):(b))
bool equalSubstrings(char* text, int firstIndex, int secondIndex, int length){
for (int i = 0; i < length; i++){
if (text[firstIndex + i] != text[secondIndex + i]){
return false;
}
}
return true;
}
int longestDecompositionDpCached(char* text, int textLen, int index, int* dp){
if (2 * index >= textLen){
return 0;
}
if (dp[index] == 0){
dp[index] = longestDecompositionDp(text, textLen, index, dp);
}
return dp[index];
}
int longestDecompositionDp(char* text, int textLen, int index, int* dp){
char ch = text[index];
int result = 1;
for (int i = 0; i < (textLen - 2 * index) / 2; i++){
if (ch == text[textLen - 1 - index - i]
&& equalSubstrings(text, index, textLen - 1 - index - i, i + 1)){
return max(result, 2 + longestDecompositionDpCached(text, textLen, index + i + 1, dp));
}
}
return result;
}
// Dynamic programming. Up -> down approach.
// Runtime: O(n*n)
// Space: O(n)
int longestDecomposition(char * text){
int textLen = strlen(text);
int* dp = calloc(textLen, sizeof(int));
int result = longestDecompositionDpCached(text, textLen, 0, dp);
free(dp);
return result;
}
| 1,340
|
C
|
.c
| 39
| 27.615385
| 104
| 0.580266
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,802
|
2256.c
|
TheAlgorithms_C/leetcode/src/2256.c
|
// Prefix sum.
// - Calculate whole nums sum.
// - Calculate currIndex sum.
// - Compare averages
// Runtime: O(n)
// Space: O(1)
int minimumAverageDifference(int* nums, int numsSize){
long numsSum = 0;
for (int i = 0; i < numsSize; i++){
numsSum += nums[i];
}
long currSum = 0;
long minAverage = 9223372036854775807; // Long max
int minIndex = 0;
for (int i = 0; i < numsSize; i++){
currSum += nums[i];
int leftItemsNumber = (numsSize - i - 1);
long leftItemsNumberAverage = 0;
if (leftItemsNumber != 0){
leftItemsNumberAverage = (numsSum - currSum) / leftItemsNumber;
}
long currItemsNumberAverage = currSum / (i + 1);
long averageDiff = abs(currItemsNumberAverage - leftItemsNumberAverage);
if (averageDiff < minAverage){
minAverage = averageDiff;
minIndex = i;
}
}
return minIndex;
}
| 993
|
C
|
.c
| 30
| 25.3
| 81
| 0.585547
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,805
|
953.c
|
TheAlgorithms_C/leetcode/src/953.c
|
#define min(x, y) (((x) < (y)) ? (x) : (y))
bool isWordLess(char* word1, char* word2, int* charOrder){
int word1Length = strlen(word1);
int word2Length = strlen(word2);
for(int i = 0; i < min(word1Length, word2Length); i++) {
int charWordsDiff = (charOrder[word1[i] - 'a'] - charOrder[word2[i] - 'a']);
if (charWordsDiff < 0){
return true;
}
if (charWordsDiff > 0){
return false;
}
}
return word1Length <= word2Length;
}
// Keep array-hashtable of order letters.
// Runtime: O(n)
// Space: O(1)
bool isAlienSorted(char ** words, int wordsSize, char * order){
const int lowerCaseLettersNumber = 26;
int charorder[lowerCaseLettersNumber];
for(int i = 0; i < lowerCaseLettersNumber; i++) {
charorder[order[i] - 'a'] = i;
}
for(int i = 0; i < wordsSize - 1; i++) {
if (!isWordLess(words[i], words[i + 1], charorder)){
return false;
}
}
return true;
}
| 1,052
|
C
|
.c
| 31
| 26.322581
| 85
| 0.560804
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,809
|
997.c
|
TheAlgorithms_C/leetcode/src/997.c
|
// Using hashtable.
// Runtime: O(n + len(trust))
// Space: O(n)
int findJudge(int n, int** trust, int trustSize, int* trustColSize){
int* personsToTrust = calloc(n + 1, sizeof(int));
int* personsFromTrust = calloc(n + 1, sizeof(int));
for(int i = 0; i < trustSize; i++){
int* currentTrust = trust[i];
personsToTrust[currentTrust[1]] += 1;
personsFromTrust[currentTrust[0]] += 1;
}
int potentialJudjeNumber = -1;
for(int i = 1; i < n + 1; i++){
if (personsToTrust[i] == n - 1 && personsFromTrust[i] == 0){
if (potentialJudjeNumber > -1){
return -1;
}
potentialJudjeNumber = i;
}
}
free(personsToTrust);
free(personsFromTrust);
return potentialJudjeNumber;
}
| 824
|
C
|
.c
| 24
| 26.416667
| 69
| 0.563291
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,814
|
2279.c
|
TheAlgorithms_C/leetcode/src/2279.c
|
int compare(const int* i, const int* j)
{
return *i - *j;
}
// Sorting.
// Runtime: O(n*log(n))
// Space: O(n)
int maximumBags(int* capacity, int capacitySize, int* rocks, int rocksSize, int additionalRocks) {
int* capacityLeft = malloc(capacitySize * sizeof(int));
for (int i = 0; i < capacitySize; i++) {
capacityLeft[i] = capacity[i] - rocks[i];
}
qsort(capacityLeft, capacitySize, sizeof (int), (int(*) (const void*, const void*)) compare);
int bags = 0;
for (int i = 0; i < capacitySize; i++) {
if (additionalRocks < capacityLeft[i]){
break;
}
additionalRocks -= capacityLeft[i];
bags++;
}
free(capacityLeft);
return bags;
}
| 760
|
C
|
.c
| 24
| 25.25
| 99
| 0.584488
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,815
|
1752.c
|
TheAlgorithms_C/leetcode/src/1752.c
|
bool check(int* nums, int numsSize){
if (numsSize == 1) {
return true;
}
bool wasShift = false;
for(int i = 1; i < numsSize; i++) {
if (nums[i - 1] > nums[i]) {
if (wasShift) {
return false;
}
wasShift = true;
}
}
return !wasShift || nums[0] >= nums[numsSize-1];
}
| 406
|
C
|
.c
| 15
| 16.666667
| 53
| 0.441096
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,817
|
1008.c
|
TheAlgorithms_C/leetcode/src/1008.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* bstFromPreorder(int* preorder, int preorderSize)
{
struct TreeNode* new;
int left_ptr;
new = malloc(sizeof(struct TreeNode));
new->val = preorder[0];
if (preorderSize == 1)
{
new->right = NULL;
new->left = NULL;
return new;
}
left_ptr = 1;
while ((left_ptr < preorderSize) && (preorder[left_ptr] < preorder[0]))
left_ptr++;
if (left_ptr == 1)
new->left = NULL;
else
new->left = bstFromPreorder(preorder + 1, left_ptr - 1);
if (left_ptr < preorderSize)
new->right =
bstFromPreorder(preorder + left_ptr, preorderSize - left_ptr);
else
new->right = NULL;
return new;
}
| 870
|
C
|
.c
| 34
| 20.352941
| 75
| 0.587244
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,818
|
1009.c
|
TheAlgorithms_C/leetcode/src/1009.c
|
// Bit manipulation.
// - Find the bit length of n using log2
// - Create bit mask of bit length of n
// - Retun ~n and bit of ones mask
// Runtime: O(log2(n))
// Space: O(1)
int bitwiseComplement(int n){
if (n == 0){
return 1;
}
int binary_number_length = ceil(log2(n));
return (~n) & ((1 << binary_number_length) - 1);
}
| 364
|
C
|
.c
| 13
| 23.846154
| 53
| 0.587896
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,824
|
5.c
|
TheAlgorithms_C/leetcode/src/5.c
|
/**
* Find longest palindrome by traversing the string and checking how
* long palindrome can be constructed from each element by going left and right.
* Checking palindromes of types '..aa..' and '..bab..'
*/
#include <stdlib.h> /// for allocating new string via malloc()
#include <string.h> /// for copying the contents of the string via strncpy()
char * longestPalindrome(char * s) {
int si_max = 0, ei_max = 0, sz_max = 0, sz, i, delta_i;
char ch, *s_longest;
if (s[1] == '\0') return s;
for (ch = s[1], i = 1; ch != '\0'; ch = s[++i]) {
if (s[i - 1] == ch) {
sz = 2;
delta_i = 1;
while (i - 1 - delta_i >= 0 && s[i + delta_i] != '\0' && s[i - 1 - delta_i] == s[i + delta_i]) {
sz += 2;
delta_i += 1;
}
if (sz > sz_max) {
sz_max = sz;
si_max = i - 1 - delta_i + 1;
ei_max = i + delta_i - 1;
}
}
}
for (ch = s[0], i = 1; ch != '\0'; ch = s[++i]) {
sz = 1;
delta_i = 1;
while (i - delta_i >= 0 && s[i + delta_i] != '\0' && s[i - delta_i] == s[i + delta_i]) {
sz += 2;
delta_i += 1;
}
if (sz > sz_max) {
sz_max = sz;
si_max = i - delta_i + 1;
ei_max = i + delta_i - 1;
}
}
if ((s_longest = (char *) malloc(sizeof(s))) == NULL) {
return NULL;
}
strncpy(s_longest, s + si_max, sz_max);
s_longest[sz_max] = '\0';
return s_longest;
}
| 1,573
|
C
|
.c
| 46
| 25.76087
| 108
| 0.44313
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,825
|
236.c
|
TheAlgorithms_C/leetcode/src/236.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// The list for TreeNodes.
struct ListItem {
struct TreeNode* node; // TreeNode pointer
struct ListItem* next; // Pointer to the next ListItem
};
bool findTargetPath(struct TreeNode* node, struct TreeNode* target, struct ListItem* path){
if (node == NULL){
return false;
}
struct ListItem* pathItem = malloc(sizeof(struct ListItem));
pathItem->node = node;
pathItem->next = NULL;
path->next = pathItem;
if (node->val == target->val){
return true;
}
if (findTargetPath(node->left, target, pathItem)){
return true;
}
if (findTargetPath(node->right, target, pathItem)){
return true;
}
path->next = NULL;
free(pathItem);
return false;
}
void freeList(struct ListItem* target){
if (target->next != NULL){
freeList(target->next);
}
free(target);
}
// Find full path for p and q.
// Find the longest common path in paths.
// Runtime: O(n)
// Space: O(n)
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
struct ListItem* pPath = malloc(sizeof(struct ListItem));
struct ListItem* qPath = malloc(sizeof(struct ListItem));
findTargetPath(root, p, pPath);
findTargetPath(root, q, qPath);
struct TreeNode* lowestTreeNode = NULL;
struct ListItem* pPathCursor = pPath->next;
struct ListItem* qPathCursor = qPath->next;
while(pPathCursor != NULL && qPathCursor != NULL) {
if (pPathCursor->node->val == qPathCursor->node->val){
lowestTreeNode = pPathCursor->node;
pPathCursor = pPathCursor->next;
qPathCursor = qPathCursor->next;
continue;
}
break;
}
freeList(pPath);
freeList(qPath);
return lowestTreeNode;
}
| 2,072
|
C
|
.c
| 65
| 25
| 103
| 0.62984
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,826
|
14.c
|
TheAlgorithms_C/leetcode/src/14.c
|
int findMaxConsecutiveOnes(int* nums, int numsSize){
int i=0;
int maxCount=0;
int count = 0;
while(i<numsSize){
while(i<numsSize && nums[i]!=0){
count++;
i++;
}
if(maxCount<=count){
maxCount = count;
}
count = 0;
while(i<numsSize && nums[i]==0){
i++;
}
}
return maxCount;
}
| 448
|
C
|
.c
| 19
| 13.421053
| 52
| 0.464752
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,833
|
985.c
|
TheAlgorithms_C/leetcode/src/985.c
|
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// collecting sum Runtime: O(len(queries)), Space: O(1)
int* sumEvenAfterQueries(int* nums, int numsSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize){
int summ = 0;
int* result = malloc(queriesSize * sizeof(int));
*returnSize = queriesSize;
for(int i = 0; i < numsSize; i++){
if (nums[i] % 2 == 0) {
summ += nums[i];
}
}
for(int i = 0; i < queriesSize; i++){
int* query = queries[i];
int val = query[0];
int index = query[1];
// sub index value from summ if it's even
if (nums[index] % 2 == 0) {
summ -= nums[index];
}
// modify the nums[index] value
nums[index] += val;
// add index value from summ if it's even
if (nums[index] % 2 == 0) {
summ += nums[index];
}
result[i] = summ;
}
return result;
}
| 1,064
|
C
|
.c
| 31
| 25.032258
| 121
| 0.525784
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,837
|
931.c
|
TheAlgorithms_C/leetcode/src/931.c
|
#define min(a,b) (((a)<(b))?(a):(b))
// Dynamic programming.
// Runtime O(n*n)
// Space O(n)
int minFallingPathSum(int** matrix, int matrixSize, int* matrixColSize){
int* dp = calloc(matrixSize, sizeof(int));
for (int i = 0; i < matrixSize; i++){
int* nextDp = calloc(matrixSize, sizeof(int));
for (int j = 0; j < matrixSize; j++){
nextDp[j] = dp[j] + matrix[i][j];
// If not the first column - try to find minimum in prev column
if(j > 0){
nextDp[j] = min(nextDp[j], dp[j - 1] + matrix[i][j]);
}
// If not the last column - try to find minimum in next column
if (j < matrixSize - 1){
nextDp[j] = min(nextDp[j], dp[j + 1] + matrix[i][j]);
}
}
free(dp);
dp = nextDp;
}
int result = dp[0];
for (int j = 1; j < matrixSize; j++){
result = min(result, dp[j]);
}
free(dp);
return result;
}
| 1,025
|
C
|
.c
| 29
| 26.034483
| 76
| 0.490816
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,841
|
32.c
|
TheAlgorithms_C/leetcode/src/32.c
|
#define max(x,y)(((x)>(y))?(x):(y))
const int notCalculated = -2;
const int notValid = -1;
int getEndValidIndexFromDp(int* dp, char* s, int index, int lenS){
if (index >= lenS){
return notValid;
}
if (dp[index] == notCalculated){
dp[index] = getEndValidIndex(dp, s, index, lenS);
}
return dp[index];
}
int getEndValidIndex(int* dp, char* s, int index, int lenS){
if (s[index] == '('){
if (index + 1 >= lenS){
return notValid;
}
if (s[index + 1] == ')'){
return max(index + 1, getEndValidIndexFromDp(dp, s, index + 2, lenS));
}
int nextEndValidIndex = getEndValidIndexFromDp(dp, s, index + 1, lenS);
if (nextEndValidIndex == notValid || nextEndValidIndex + 1 >= lenS || s[nextEndValidIndex + 1] != ')') {
return notValid;
}
return max(nextEndValidIndex + 1, getEndValidIndexFromDp(dp, s, nextEndValidIndex + 2, lenS));
}
return notValid;
}
// Dynamic Programming. UP -> down approach.
// Runtime: O(n)
// Space: O(n)
int longestValidParentheses(char * s){
int lenS = strlen(s);
if (lenS == 0){
return 0;
}
int* dp = malloc(lenS * sizeof(int));
for(int i = 0; i < lenS; i++){
dp[i] = notCalculated;
}
int result = 0;
for(int i = 0; i < lenS; i++){
result = max(result, getEndValidIndexFromDp(dp, s, i, lenS) - i + 1);
}
free(dp);
return result;
}
| 1,558
|
C
|
.c
| 47
| 25.489362
| 113
| 0.555099
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,843
|
901.c
|
TheAlgorithms_C/leetcode/src/901.c
|
// Use monotonic stack.
// Keep the stack of monotonically increasing price and index.
// Runtime: O(n)
// Space: O(n)
typedef struct stack{
int price;
int index;
struct stack* previous;
} Stack;
typedef struct {
int index;
Stack* stackPointer;
Stack* sentry;
} StockSpanner;
StockSpanner* stockSpannerCreate() {
Stack* sentry = (Stack *)malloc(sizeof(Stack));
StockSpanner* result = (StockSpanner *)malloc(sizeof(StockSpanner));
result->index = 0;
result->sentry = sentry;
result->stackPointer = sentry;
return result;
}
int stockSpannerNext(StockSpanner* obj, int price) {
while(obj->stackPointer != obj->sentry && obj->stackPointer->price <= price){
Stack* currStackPointer = obj->stackPointer;
obj->stackPointer = obj->stackPointer->previous;
free(currStackPointer);
}
obj->index += 1;
int result = obj->index;
if (obj->stackPointer != obj->sentry){
result -= obj->stackPointer->index;
}
Stack* newStackItem = (Stack *)malloc(sizeof(Stack));
newStackItem->index = obj->index;
newStackItem->price = price;
newStackItem->previous = obj->stackPointer;
obj->stackPointer = newStackItem;
return result;
}
void stockSpannerFree(StockSpanner* obj) {
while(obj->stackPointer != obj->sentry){
Stack* currStackPointer = obj->stackPointer;
obj->stackPointer = obj->stackPointer->previous;
free(currStackPointer);
}
free(obj->sentry);
free(obj);
}
/**
* Your StockSpanner struct will be instantiated and called as such:
* StockSpanner* obj = stockSpannerCreate();
* int param_1 = stockSpannerNext(obj, price);
* stockSpannerFree(obj);
*/
| 1,797
|
C
|
.c
| 55
| 26.818182
| 82
| 0.664122
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,845
|
1838.c
|
TheAlgorithms_C/leetcode/src/1838.c
|
#define max(a,b) (((a)>(b))?(a):(b))
int compare(const int* i, const int* j)
{
return *i - *j;
}
// Sort + prefix sum + windows sliding
// Runtime: O(n*log(n))
// Space: O(n)
int maxFrequency(int* nums, int numsSize, int k){
qsort(nums, numsSize, sizeof (int), (int(*) (const void*, const void*)) compare);
long* prefixSum = malloc(numsSize * sizeof(long));
prefixSum[0] = nums[0];
for(int i = 0; i < numsSize - 1; i++){
prefixSum[i + 1] = prefixSum[i] + nums[i];
}
int leftWindowPosition = 0;
int result = 0;
for(int rightWindowPosition = 0; rightWindowPosition < numsSize; rightWindowPosition++){
long rightSum = prefixSum[rightWindowPosition];
long leftSum = prefixSum[leftWindowPosition];
while ((long)nums[rightWindowPosition] * (rightWindowPosition - leftWindowPosition) - (rightSum - leftSum) > k){
leftWindowPosition += 1;
}
result = max(result, rightWindowPosition - leftWindowPosition + 1);
}
free(prefixSum);
return result;
}
| 1,097
|
C
|
.c
| 28
| 32.464286
| 121
| 0.62201
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,846
|
19.c
|
TheAlgorithms_C/leetcode/src/19.c
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
struct ListNode entry, *p_free, *p = head;
int i, sz = 0;
entry.next = head;
while (p != NULL) {
p = p->next;
sz++;
}
for (i = 0, p = &entry; i < sz - n; i++, p = p -> next)
;
p_free = p->next;
if (n != 1) {
p->next = p->next->next;
} else {
p->next = NULL;
}
free(p_free);
return entry.next;
}
| 565
|
C
|
.c
| 26
| 17.230769
| 65
| 0.507435
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,848
|
230.c
|
TheAlgorithms_C/leetcode/src/230.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* findKthSmallest(struct TreeNode* node, int* k){
if (node == NULL){
return NULL;
}
struct TreeNode* resultNode = findKthSmallest(node->left, k);
if (resultNode != NULL){
return resultNode;
}
*k -= 1;
if (*k == 0){
return node;
}
return findKthSmallest(node->right, k);
}
// Depth-First Search
// Runtime: O(n)
// Space: O(1)
int kthSmallest(struct TreeNode* root, int k){
return findKthSmallest(root, &k)->val;
}
| 701
|
C
|
.c
| 28
| 19.428571
| 66
| 0.59098
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,850
|
2095.c
|
TheAlgorithms_C/leetcode/src/2095.c
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteMiddle(struct ListNode* head)
{
if (head == NULL || head->next == NULL)
return NULL;
struct ListNode *fast, *slow, *prev;
int n = 0;
fast = head;
slow = head;
while (fast != NULL)
{
n = n + 1;
fast = fast->next;
}
fast = head;
while (fast->next != NULL && fast->next->next != NULL) // finds mid node
{
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
if (n % 2 == 0)
{
prev = slow;
slow = slow->next;
prev->next = slow->next;
}
else
prev->next = slow->next;
return head;
}
| 775
|
C
|
.c
| 37
| 15.756757
| 77
| 0.51289
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,852
|
669.c
|
TheAlgorithms_C/leetcode/src/669.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Depth-First Search
// Runtime: O(n)
// Space: O(1)
struct TreeNode* trimBST(struct TreeNode* root, int low, int high){
if (root == NULL){
return NULL;
}
if (root->val > high){
return trimBST(root->left, low, high);
}
if (root->val < low){
return trimBST(root->right, low, high);
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
| 644
|
C
|
.c
| 25
| 20.36
| 68
| 0.570715
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,854
|
75.c
|
TheAlgorithms_C/leetcode/src/75.c
|
void swap(int *x, int *y){
if (x==y)
return;
*x = *x + *y;
*y= *x - *y;
*x= *x - *y;
}
void sortColors(int* arr, int n){
int start=0, mid=0, end=n-1;
while(mid<=end){
if(arr[mid]==1)
mid++;
else if(arr[mid]==0){
swap(&arr[mid],&arr[start]);
mid++;
start++;
}
else{
swap(&arr[mid],&arr[end]);
end--;
}
}
}
| 453
|
C
|
.c
| 23
| 12.26087
| 40
| 0.377622
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,859
|
45.c
|
TheAlgorithms_C/leetcode/src/45.c
|
// Breadth-first search, imitation.
// Runtime: O(n)
// Space: O(n)
int jump(int* nums, int numsSize) {
if (numsSize == 1) {
return 0;
}
int step = 1;
int* visitedCells = calloc(numsSize, sizeof(int));
int* queue = malloc(numsSize * sizeof(int));
queue[0] = 0;
int queueLength = 1;
while (queueLength > 0){
int* nextQueue = malloc(numsSize * sizeof(int));
int nextQueueLength = 0;
for (int i = 0; i < queueLength; i++) {
int cell = queue[i];
int jump = nums[cell];
if (cell + jump >= numsSize - 1) {
free(visitedCells);
free(queue);
free(nextQueue);
return step;
}
// populate next queue wave for searching
for (int nextCell = cell; nextCell <= cell + jump; nextCell++) {
if (visitedCells[nextCell] == 0){
nextQueue[nextQueueLength++] = nextCell;
visitedCells[nextCell] = 1;
}
}
}
step++;
free(queue);
queue = nextQueue;
queueLength = nextQueueLength;
}
free(visitedCells);
free(queue);
return -1;
}
| 1,299
|
C
|
.c
| 41
| 20.95122
| 77
| 0.490323
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,860
|
807.c
|
TheAlgorithms_C/leetcode/src/807.c
|
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
// Collect maxes on each row and each column.
// Runtime: O(n * n)
// Space: O(n)
int maxIncreaseKeepingSkyline(int** grid, int gridSize, int* gridColSize){
int* rowsMaxs = calloc(gridSize, sizeof(int));
int* colsMaxs = calloc(gridSize, sizeof(int));
// Find max of each row and column
for(int i = 0; i < gridSize; i++){
for (int j = 0; j < gridSize; j++){
rowsMaxs[i] = max(rowsMaxs[i], grid[i][j]);
colsMaxs[j] = max(colsMaxs[j], grid[i][j]);
}
}
int result = 0;
for(int i = 0; i < gridSize; i++){
for (int j = 0; j < gridSize; j++){
int rowMax = rowsMaxs[i];
int colMax = colsMaxs[j];
result += min(rowMax - grid[i][j], colMax - grid[i][j]);
}
}
free(rowsMaxs);
free(colsMaxs);
return result;
}
| 945
|
C
|
.c
| 27
| 27.592593
| 75
| 0.523128
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,863
|
79.c
|
TheAlgorithms_C/leetcode/src/79.c
|
int getPointKey(int i, int j, int boardSize, int boardColSize){
return boardSize * boardColSize * i + j;
}
const int directionsSize = 4;
const int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool exitsWord(int i, int j, char** board, int boardSize, int* boardColSize, int wordIndex, char* word, int* vistedPointSet){
if (board[i][j] != word[wordIndex]){
return false;
}
if (wordIndex == strlen(word) - 1){
return true;
}
for (int k = 0; k < directionsSize; k++){
int nextI = i + directions[k][0];
int nextJ = j + directions[k][1];
if (nextI < 0 || nextI >= boardSize || nextJ < 0 || nextJ >= boardColSize[i]){
continue;
}
int key = getPointKey(nextI, nextJ, boardSize, boardColSize[i]);
if (vistedPointSet[key] == 1){
continue;
}
vistedPointSet[key] = 1;
if (exitsWord(nextI, nextJ, board, boardSize, boardColSize, wordIndex + 1, word, vistedPointSet)){
return true;
}
vistedPointSet[key] = 0;
}
return false;
}
// Use backtracking.
// Runtime: Runtime: O(n*m*4^len(word))
bool exist(char** board, int boardSize, int* boardColSize, char* word){
int* vistedPointSet = (int*) calloc(getPointKey(boardSize, boardColSize[0], boardSize, boardColSize[0]), sizeof(int));
for (int i = 0; i < boardSize; i++){
for (int j = 0; j < boardColSize[i]; j++){
int key = getPointKey(i, j, boardSize, boardColSize[i]);
vistedPointSet[key] = 1;
if (exitsWord(i, j, board, boardSize, boardColSize, 0, word, vistedPointSet)){
return true;
};
vistedPointSet[key] = 0;
}
}
return false;
}
| 1,883
|
C
|
.c
| 46
| 31.108696
| 126
| 0.568014
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,864
|
2482.c
|
TheAlgorithms_C/leetcode/src/2482.c
|
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
// Calculating ones on each row and column.
// Runtime: O(n * m)
// Space: O(n + m)
int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes){
int n = gridSize;
int m = gridColSize[0];
int** result = malloc(gridSize * sizeof(int*));
for (int i = 0; i < n; i++){
result[i] = malloc(m * sizeof(int));
}
int* onesRows = calloc(n, sizeof(int));
int* onesCols = calloc(m, sizeof(int));
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (grid[i][j] == 1){
onesRows[i] += 1;
onesCols[j] += 1;
}
}
}
for (int i = 0; i < gridSize; i++){
for (int j = 0; j < gridColSize[i]; j++){
result[i][j] = onesRows[i] + onesCols[j] - (m - onesRows[i]) - (n - onesCols[j]);
}
}
free(onesRows);
free(onesCols);
*returnSize = gridSize;
*returnColumnSizes = gridColSize;
return result;
}
| 1,268
|
C
|
.c
| 36
| 28
| 108
| 0.545902
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,867
|
979.c
|
TheAlgorithms_C/leetcode/src/979.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct NodeDistributeInfo {
int distributeMoves;
int distributeExcess;
};
struct NodeDistributeInfo* getDisturb(struct TreeNode* node) {
struct NodeDistributeInfo* result = malloc(sizeof(struct NodeDistributeInfo));
if (node == NULL) {
result->distributeMoves = 0;
result->distributeExcess = 1;
return result;
}
struct NodeDistributeInfo* leftDistribute = getDisturb(node->left);
struct NodeDistributeInfo* rightDistribute = getDisturb(node->right);
int coinsToLeft = 1 - leftDistribute->distributeExcess;
int coinsToRight = 1 - rightDistribute->distributeExcess;
// Calculate moves as excess and depth between left and right subtrees.
result->distributeMoves = leftDistribute->distributeMoves + rightDistribute->distributeMoves + abs(coinsToLeft) + abs(coinsToRight);
result->distributeExcess = node->val - coinsToLeft - coinsToRight;
free(leftDistribute);
free(rightDistribute);
return result;
}
// Depth-first search .
// On each node-step we try to recombinate coins between left and right subtree.
// We know that coins are the same number that nodes, and we can get coins by depth
// Runtime: O(n)
// Space: O(1)
int distributeCoins(struct TreeNode* root) {
return getDisturb(root)->distributeMoves;
}
| 1,503
|
C
|
.c
| 38
| 34.552632
| 137
| 0.713891
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,868
|
684.c
|
TheAlgorithms_C/leetcode/src/684.c
|
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int find(int* sets, int index){
while (sets[index] != index){
index = sets[index];
}
return index;
}
void unionSet(int* sets, int i1, int i2){
int i1Parent = find(sets, i1);
int i2Parent = find(sets, i2);
sets[i1Parent] = i2Parent;
}
// Union find
// Runtime: O(n)
// Space: O(n)
int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){
int setsSize = edgesSize + 1;
int* sets = malloc(setsSize * sizeof(int));
for (int i = 0; i < setsSize; i++){
sets[i] = i;
}
int* result = malloc(2 * sizeof(int));
*returnSize = 2;
for (int i = 0; i < edgesSize; i++){
int* edge = edges[i];
int i0Parent = find(sets, edge[0]);
int i1Parent = find(sets, edge[1]);
if (i0Parent == i1Parent){
result[0] = edge[0];
result[1] = edge[1];
continue;
}
unionSet(sets, i0Parent, i1Parent);
}
free(sets);
return result;
}
| 1,143
|
C
|
.c
| 39
| 22.435897
| 94
| 0.555556
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,871
|
1019.c
|
TheAlgorithms_C/leetcode/src/1019.c
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int* nextLargerNodes(struct ListNode* head, int* returnSize)
{
int *output, count = 0;
struct ListNode *tmp = head, *tmp2;
for (; tmp != NULL; tmp = tmp->next, count++)
;
output = (int*)calloc(count, sizeof(int));
*returnSize = count;
for (tmp = head, count = 0; tmp->next != NULL; tmp = tmp->next, count++)
{
for (tmp2 = tmp->next; tmp2 != NULL; tmp2 = tmp2->next)
{
if (tmp2->val > tmp->val)
{
output[count] = tmp2->val;
break;
}
}
}
return output;
}
| 709
|
C
|
.c
| 28
| 19.214286
| 76
| 0.516176
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,872
|
62.c
|
TheAlgorithms_C/leetcode/src/62.c
|
// Dynamic programming can be applied here, because every solved sub-problem has
// an optimal sub-solution
// Searching backwards from end to start, we can incrementally calculate number
// of paths to destination. i.e. start from bottom-right, and calculate
// leftwards (lowest row should all be 1). then go to second-last-row, rightmost
// column, and calculate leftwards the last cell to be calculated is the start
// location (0, 0). The iteration ordering is intentional: the inner loop
// iterates the contents of each vector, the outer loop iterates each vector.
// This is more cache-friendly.
// Example below, calculated from right-to-left, bottom-to-top.
// 7 by 3 grid
// 28 21 15 10 6 3 1
// 7 6 5 4 3 2 1
// 1 1 1 1 1 1 1
int uniquePaths(int m, int n)
{
int dp[m][n];
for (int column = 0; column < n; column++)
{
dp[0][column] = 1;
}
for (int row = 1; row < m; row++)
{
dp[row][0] = 1;
}
for (int row = 1; row < m; row++)
{
for (int column = 1; column < n; column++)
{
dp[row][column] = dp[row - 1][column] + dp[row][column - 1];
}
}
return dp[m - 1][n - 1];
}
| 1,195
|
C
|
.c
| 34
| 31.176471
| 80
| 0.627163
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,873
|
1653.c
|
TheAlgorithms_C/leetcode/src/1653.c
|
#define min(X, Y) ((X) < (Y) ? (X) : (Y))
// Dynamic programming approach. Down -> Up.
// Runtime: O(n)
// Space: O(1)
int minimumDeletions(char * s){
int len = strlen(s);
int aStateValue = s[0] == 'b';
int bStateValue = 0;
int newAStateValue;
int newBStateValue;
for(int i = 1; i < len; i++){
newAStateValue = aStateValue + (s[i] == 'b');
newBStateValue = min(
aStateValue,
bStateValue + (s[i] == 'a')
);
aStateValue = newAStateValue;
bStateValue = newBStateValue;
}
return min(aStateValue, bStateValue);
}
| 725
|
C
|
.c
| 21
| 23.238095
| 59
| 0.496988
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,874
|
1704.c
|
TheAlgorithms_C/leetcode/src/1704.c
|
bool isVowel(char chr){
switch(chr){
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
}
return false;
}
// Counting
// Runtime: O(n)
// Space: O(1)
bool halvesAreAlike(char * s){
int lenS = strlen(s);
int halfVowels = 0;
int currVowels = 0;
for (int i = 0; i < lenS; i++){
if (isVowel(s[i])){
currVowels++;
}
if (2 * (i + 1) == lenS){
halfVowels = currVowels;
}
}
return 2 * halfVowels == currVowels;
}
| 714
|
C
|
.c
| 33
| 13.151515
| 41
| 0.427035
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,875
|
485.c
|
TheAlgorithms_C/leetcode/src/485.c
|
int max(a,b){
if(a>b)
return a;
else
return b;
}
int findMaxConsecutiveOnes(int* nums, int numsSize){
int count = 0;
int result = 0;
for (int i = 0; i < numsSize; i++)
{
if (nums[i] == 0)
count = 0;
else
{
count++;
result = max(result, count);
}
}
return result;
}
| 329
|
C
|
.c
| 21
| 11.619048
| 52
| 0.546358
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,876
|
1833.c
|
TheAlgorithms_C/leetcode/src/1833.c
|
int compare(const void* i, const void* j)
{
return *((int*)i) - *((int*)j);
}
// Greedy + sorting
// Runtime: O(n*log(n))
// Space: O(1)
int maxIceCream(int* costs, int costsSize, int coins){
qsort(costs, costsSize, sizeof(int), compare);
int result = 0;
int leftCoins = coins;
for (int i = 0; i < costsSize; i++){
if (costs[i] > leftCoins){
break;
}
leftCoins -= costs[i];
result++;
}
return result;
}
| 503
|
C
|
.c
| 20
| 19.15
| 55
| 0.536842
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,878
|
2222.c
|
TheAlgorithms_C/leetcode/src/2222.c
|
long numberOfWaysForChar(char * s, char c){
long firstBuildingAppearNumber = 0;
long secondBuildingAppearNumber = 0;
long result = 0;
int sLength = strlen(s);
for (int i = 0; i < sLength; i++){
if (s[i] == c){
result += secondBuildingAppearNumber;
firstBuildingAppearNumber += 1;
continue;
}
secondBuildingAppearNumber += firstBuildingAppearNumber;
}
return result;
}
// numberOfWays returns the sum of number ways of selecting first building
// and the number of ways of selecting second building which gives us the
// number of ways of selecting three building such that no
// consecutive buildings are in the same category.
// Runtime: O(n)
// Space: O(n)
long long numberOfWays(char * s){
return numberOfWaysForChar(s, '0') + numberOfWaysForChar(s, '1');
}
| 875
|
C
|
.c
| 24
| 30.708333
| 74
| 0.683957
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,884
|
2304.c
|
TheAlgorithms_C/leetcode/src/2304.c
|
#define min(x,y)(((x)<(y))?(x):(y))
// DP up -> down. We are going down from gridline to gridline
// and collect the minumum cost path.
// Runtime : O(gridSize*gridColSize*gridColSize)
// Space: O(gridColSize)
int minPathCost(int** grid, int gridSize, int* gridColSize, int** moveCost, int moveCostSize, int* moveCostColSize){
int* dp = (int*)calloc(gridColSize[0], sizeof(int));
int* newDp = (int*)calloc(gridColSize[0], sizeof(int));
for(int i = 0; i < gridSize - 1; i++){
int currGridColSize = gridColSize[i];
for(int j = 0; j < currGridColSize; j++){
newDp[j] = -1;
}
for(int j = 0; j < currGridColSize; j++){
int currGridItem = grid[i][j];
for(int z = 0; z < currGridColSize; z++){
int currMoveCost = dp[j] + moveCost[currGridItem][z] + currGridItem;
newDp[z] = (newDp[z] == -1) ? currMoveCost : min(newDp[z], currMoveCost);
}
}
for(int j = 0; j < currGridColSize; j++){
dp[j] = newDp[j];
}
}
// Find minimum value.
int minValue = dp[0] + grid[gridSize - 1][0];
for(int j = 1; j < gridColSize[0]; j++){
minValue = min(minValue, dp[j] + grid[gridSize - 1][j]);
}
// free resources
free(dp);
free(newDp);
return minValue;
}
| 1,429
|
C
|
.c
| 34
| 32.147059
| 117
| 0.549962
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,885
|
1137.c
|
TheAlgorithms_C/leetcode/src/1137.c
|
// Dynamic Programming
// Runtime: O(n)
// Space: O(1)
int tribonacci(int n){
int t0 = 0;
int t1 = 1;
int t2 = 1;
if (n == 0) {
return t0;
}
if (n == 1){
return t1;
}
if (n == 2){
return t2;
}
for (int i = 0; i < n - 2; i++){
int nextT = t0 + t1 + t2;
t0 = t1;
t1 = t2;
t2 = nextT;
}
return t2;
}
| 435
|
C
|
.c
| 24
| 11.375
| 37
| 0.38404
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,888
|
567.c
|
TheAlgorithms_C/leetcode/src/567.c
|
const int EnglishLettersNumber = 26;
void countCharsForStringSlice(int* charsCounter, char* s, int length, int sign) {
for (int i = 0; i < length; i++) {
charsCounter[s[i] - 'a'] += sign;
}
}
// Sliding window
// Calculate number of chars in the current slide.
// Runtime: O(n)
// Space: O(1) - only number of english lowercase letters.
bool checkInclusion(char* s1, char* s2) {
int lengthS1 = strlen(s1);
int lengthS2 = strlen(s2);
if (lengthS1 > lengthS2) {
return false;
}
int* charsCounter = calloc(EnglishLettersNumber, sizeof(int));
// We keep counters of s1 with '-' sign. It has to be offset by s2 chars
countCharsForStringSlice(charsCounter, s1, lengthS1, -1);
countCharsForStringSlice(charsCounter, s2, lengthS1, 1);
int diffChars = 0;
for (int i = 0; i < EnglishLettersNumber; i++) {
if (charsCounter[i] != 0) {
diffChars++;
}
}
if (diffChars == 0) {
return true;
}
for (int i = 0; i < lengthS2 - lengthS1; i++) {
int charNumberLeft = s2[i] - 'a';
int charNumberRight = s2[i + lengthS1] - 'a';
charsCounter[charNumberLeft] -= 1;
if (charsCounter[charNumberLeft] == 0) {
diffChars -= 1;
}
else if (charsCounter[charNumberLeft] == -1) {
diffChars += 1;
}
charsCounter[charNumberRight] += 1;
if (charsCounter[charNumberRight] == 0) {
diffChars -= 1;
}
else if (charsCounter[charNumberRight] == 1) {
diffChars += 1;
}
if (diffChars == 0) {
return true;
}
}
free(charsCounter);
return false;
}
| 1,783
|
C
|
.c
| 53
| 25.415094
| 82
| 0.564042
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,889
|
63.c
|
TheAlgorithms_C/leetcode/src/63.c
|
/*
I walk through the grids and record the path numbers at the
same time.
By using a 2D array called paths, it will add up possible so
urce path and save the number.
Noted that:
if the destination has obstacle, we can't reach it
the first grid (paths[0][0]) always set as 1 our previous
path source is either from top or left border of grid has
different condition
*/
int uniquePathsWithObstacles(int** obstacleGrid, int obstacleGridSize,
int* obstacleGridColSize)
{
if (obstacleGrid[obstacleGridSize - 1][*obstacleGridColSize - 1] == 1)
{
return 0;
}
int paths[obstacleGridSize][*obstacleGridColSize];
for (int i = 0; i < obstacleGridSize; i++)
{
for (int j = 0; j < *obstacleGridColSize; j++)
{
if (obstacleGrid[i][j])
{
paths[i][j] = 0;
}
else
{
paths[i][j] = (i == 0 && j == 0)
? 1
: ((i == 0 ? 0 : paths[i - 1][j]) +
(j == 0 ? 0 : paths[i][j - 1]));
}
}
}
return paths[obstacleGridSize - 1][*obstacleGridColSize - 1];
}
| 1,255
|
C
|
.c
| 38
| 24.052632
| 74
| 0.519737
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,890
|
223.c
|
TheAlgorithms_C/leetcode/src/223.c
|
#define min(X, Y) ((X) < (Y) ? (X) : (Y))
int intersectionSize(int p11, int p12, int p21, int p22){
if (p11 >= p22 || p12 <= p21){
return 0;
}
if (p11 < p21){
return min(p12 - p21, p22 - p21);
}
return min(p22 - p11, p12 - p11);
}
// Calculation area of the A, then area of the B then minus intersection of A and B
// Runtime: O(1)
// Space: O(1)
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2){
int areaA = (ay2 - ay1) * (ax2 - ax1);
int areaB = (by2 - by1) * (bx2 - bx1);
int areaInteresection = intersectionSize(ax1, ax2, bx1, bx2) * intersectionSize(ay1, ay2, by1, by2);
return areaA + areaB - areaInteresection;
}
| 721
|
C
|
.c
| 19
| 33.684211
| 104
| 0.604618
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,894
|
1283.c
|
TheAlgorithms_C/leetcode/src/1283.c
|
#define max(a,b) (((a)>(b))?(a):(b))
long getSum(int* nums, int numsSize, int divizor){
long result = 0;
for (int i = 0; i < numsSize; i++){
int value = nums[i] / divizor;
if (value * divizor != nums[i]){
value++;
}
result += value;
}
return result;
}
// Divide and conquer
// Runtime: O(n*log(n))
// Space: O(1)
int smallestDivisor(int* nums, int numsSize, int threshold){
int maxNum = 0;
for (int i = 0; i < numsSize; i++){
maxNum = max(maxNum, nums[i]);
}
int left = 1;
int right = maxNum;
while (left <= right){
int middle = (left + right) / 2;
long middleSum = getSum(nums, numsSize, middle);
if (middleSum <= threshold && (middle == 1 || getSum(nums, numsSize, middle - 1) > threshold)){
return middle;
}
if (middleSum > threshold){
left = middle + 1;
}
else{
right = middle - 1;
}
}
return -1;
}
| 1,054
|
C
|
.c
| 37
| 20.702703
| 104
| 0.498504
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,895
|
10.c
|
TheAlgorithms_C/leetcode/src/10.c
|
/*
Prompt:
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
- '.' Matches any single character.
- '*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Constraints:
1 <= s.length <= 20
1 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.
*/
bool isMatch(char* s, char* p);
bool matchStar(char ch, char* s, char* p);
/*
Uses Rob pikes Regexp matcher - https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html
Implementation:
// match: search for regexp anywhere in text
int match(char *regexp, char *text)
{
if (regexp[0] == '^')
return matchhere(regexp+1, text);
do {
if (matchhere(regexp, text))
return 1;
} while (*text++ != '\0');
return 0;
}
*/
bool matchStar(char ch, char* s, char* p) {
do {
if (isMatch(s, p))
return true;
} while (*s != '\0' && (*s++ == ch || ch == '.'));
return false;
}
bool isMatch(char* s, char* p) {
if (*p == '\0')
return *s == '\0';
if (p[1] == '*')
return matchStar(p[0], s, p + 2);
if (*s != '\0' && (p[0] == '.' || *p == *s)) {
return isMatch(s + 1, p + 1);
}
return false;
}
| 1,473
|
C
|
.c
| 47
| 27.340426
| 114
| 0.607496
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,898
|
2125.c
|
TheAlgorithms_C/leetcode/src/2125.c
|
int coundDevices(char* bankRow){
int result = 0;
int bankRowSize = strlen(bankRow);
for(int i = 0; i < bankRowSize; i++){
if (bankRow[i] == '1'){
result++;
}
}
return result;
}
// Counting devices in each row
// Runtime: O(n*m), n-number of bank rows, m - max size of row.
// Space: O(1)
int numberOfBeams(char ** bank, int bankSize){
int prevRowDevices = 0;
int result = 0;
for(int i = 0; i < bankSize; i++){
int devices = coundDevices(bank[i]);
if (devices == 0){
continue;
}
result += devices * prevRowDevices;
prevRowDevices = devices;
}
return result;
}
| 713
|
C
|
.c
| 26
| 20.5
| 64
| 0.544919
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,904
|
2501.c
|
TheAlgorithms_C/leetcode/src/2501.c
|
#define max(a,b) (((a)>(b))?(a):(b))
int longestSquareStreakDp(int* numsSet, int numsSetSize, int* dp, long num){
if (dp[num] != 0){
return dp[num];
}
long numSquare = num * num;
dp[num] = 1;
if (numSquare <= numsSetSize && numsSet[numSquare] == 1){
dp[num] += longestSquareStreakDp(numsSet, numsSetSize, dp, numSquare);
}
return dp[num];
}
// Dynamic approach. Up -> down.
// Runtime: O(numsSize)
// Space: O(max(nums))
int longestSquareStreak(int* nums, int numsSize){
// Find nums maximum
int numMax = 0;
for(int i = 0; i < numsSize; i++){
numMax = max(numMax, nums[i]);
}
int* numsSet = calloc(numMax + 1, sizeof(int));
int* dp = calloc(numMax + 1, sizeof(int));
// Init set of nums
for(int i = 0; i < numsSize; i++){
numsSet[nums[i]] = 1;
}
// Find result
int result = -1;
for(int i = 0; i < numsSize; i++){
long num = nums[i];
long numSquare = num * num;
if (numSquare > numMax || numsSet[numSquare] == 0){
continue;
}
result = max(result, 1 + longestSquareStreakDp(numsSet, numMax, dp, numSquare));
}
free(dp);
free(numsSet);
return result;
}
| 1,293
|
C
|
.c
| 41
| 24.609756
| 89
| 0.555465
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,906
|
841.c
|
TheAlgorithms_C/leetcode/src/841.c
|
void visitRooms(int key, int** rooms, int roomsSize, int* roomsColSize, int* visitedRooms){
if (visitedRooms[key] == 1){
return;
}
visitedRooms[key] = 1;
for (int i = 0; i < roomsColSize[key]; i++){
visitRooms(rooms[key][i], rooms, roomsSize, roomsColSize, visitedRooms);
}
}
// Depth-first search
// Runtime: O(n)
// Space: O(n)
bool canVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize){
int* visitedRooms = calloc(roomsSize, sizeof(int));
visitRooms(0, rooms, roomsSize, roomsColSize, visitedRooms);
int visitedRoomsNumber = 0;
for (int i = 0; i < roomsSize; i++){
if (visitedRooms[i] == 1){
visitedRoomsNumber++;
}
}
return visitedRoomsNumber == roomsSize;
}
| 792
|
C
|
.c
| 23
| 28.26087
| 92
| 0.624179
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,908
|
42.c
|
TheAlgorithms_C/leetcode/src/42.c
|
#define max(x,y)(((x)>(y))?(x):(y))
#define min(x,y)(((x)<(y))?(x):(y))
// Max stack. Runtime: O(n), Space: O(n)
// Algorithm description:
// - Calculate the stack of maximums from right board.
// - For each index find left maximum and right maximum of height
// - The each index if heights could place nor greater than minimum of left and right max minus curr height
// - Sum all index in result
int trap(int* height, int heightSize){
int* rightMaxStack = malloc(heightSize * sizeof(int));
rightMaxStack[heightSize - 1] = height[heightSize - 1];
for (int i = heightSize - 2; i >= 0; i--){
rightMaxStack[i] = max(rightMaxStack[i + 1], height[i]);
}
int leftMax = 0;
int result = 0;
for (int i = 0; i < heightSize; i++){
leftMax = max(leftMax, height[i]);
result += max(0, min(leftMax, rightMaxStack[i]) - height[i]);
}
free(rightMaxStack);
return result;
}
| 957
|
C
|
.c
| 23
| 36.26087
| 108
| 0.62256
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,909
|
16.c
|
TheAlgorithms_C/leetcode/src/16.c
|
#include <stdlib.h> // for qsort()
int cmp(const void* a, const void* b) {
const int *A = a, *B = b;
return (*A > *B) - (*A < *B);
}
int threeSumClosest(int* nums, int nums_size, int target) {
int i, j, k, result, sum3;
qsort(nums, nums_size, sizeof(int), cmp);
result = nums[0] + nums[1] + nums[2];
for (i = 0; i < nums_size - 2; i++) {
j = i + 1;
k = nums_size - 1;
while (j < k) {
sum3 = nums[i] + nums[j] + nums[k];
if (abs(target - sum3) < abs(target - result)) {
result = sum3;
}
if (sum3 < target) {
j++;
} else if (sum3 > target) {
k--;
} else {
return sum3;
}
}
}
return result;
}
| 804
|
C
|
.c
| 28
| 20.071429
| 60
| 0.428941
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,911
|
274.c
|
TheAlgorithms_C/leetcode/src/274.c
|
int diff(const int* i, const int* j)
{
return *i - *j;
}
// Sorting.
// Runtime: O(n*log(n))
// Space: O(1)
int hIndex(int* citations, int citationsSize){
qsort(citations, citationsSize, sizeof(int), (int(*) (const void*, const void*)) diff);
for(int i = 0; i < citationsSize; i++){
if (citations[citationsSize - 1 - i] <= i){
return i;
}
}
return citationsSize;
}
| 439
|
C
|
.c
| 16
| 21.8125
| 92
| 0.566586
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,915
|
2024.c
|
TheAlgorithms_C/leetcode/src/2024.c
|
#define max(X, Y) ((X) > (Y) ? (X) : (Y))
int maximizeTarget(char * answerKey, char targetChar, int k){
int leftIndex = -1;
int result = 0;
int currTargetChars = 0;
int lenAnswerKey = strlen(answerKey);
for (int rightIndex = 0; rightIndex < lenAnswerKey; rightIndex++){
char ch = answerKey[rightIndex];
if (ch == targetChar){
currTargetChars++;
}
while (rightIndex - leftIndex > currTargetChars + k) {
leftIndex++;
if (answerKey[leftIndex] == targetChar){
currTargetChars--;
}
}
result = max(result, rightIndex - leftIndex);
}
return result;
}
// Use sliding window approach + two pointers.
// Runtime: O(n)
// Space: O(1)
int maxConsecutiveAnswers(char * answerKey, int k){
return max(maximizeTarget(answerKey, 'T', k), maximizeTarget(answerKey, 'F', k));
}
| 962
|
C
|
.c
| 27
| 27.111111
| 86
| 0.585825
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,917
|
1769.c
|
TheAlgorithms_C/leetcode/src/1769.c
|
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// Count one's from right. Each step from right side decrease for one for each 1's and increase from left:
// 1001*0101 -> left: 4 + 1, right: 2 + 4
// 10010*101 -> left: (4+1) + (1+1), right: (2-1) + (4-1)
// Runtime: O(n)
// Space: O(1)
int* minOperations(char* boxes, int* returnSize){
int leftOnes = 0;
int leftCommonDistance = 0;
int rightOnes = 0;
int rightCommonDistance = 0;
int boxesLength = strlen(boxes);
*returnSize = boxesLength;
int* result = malloc(boxesLength * sizeof(int));
for (int i = 0; i < boxesLength; i++){
if (boxes[i] == '1'){
rightOnes += 1;
rightCommonDistance += i;
}
}
for (int i = 0; i < boxesLength; i++){
if (boxes[i] == '1'){
rightOnes -= 1;
leftOnes += 1;
}
result[i] = rightCommonDistance + leftCommonDistance;
rightCommonDistance -= rightOnes;
leftCommonDistance += leftOnes;
}
return result;
}
| 1,141
|
C
|
.c
| 33
| 26.69697
| 107
| 0.567416
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,919
|
1026.c
|
TheAlgorithms_C/leetcode/src/1026.c
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define max(a,b) (((a)>(b))?(a):(b))
#define min(a,b) (((a)<(b))?(a):(b))
void recursiveSolve(struct TreeNode* node, int* result, int minVal, int maxVal){
if (node == NULL){
return;
}
*result = max(*result, abs(minVal - node->val));
*result = max(*result, abs(maxVal - node->val));
minVal = min(minVal, node->val);
maxVal = max(maxVal, node->val);
recursiveSolve(node->left, result, minVal, maxVal);
recursiveSolve(node->right, result, minVal, maxVal);
}
// Depth First Search
// If The maximum diff is exists it should be the difference of the MAX or MIN value in the tree path to the LEAF
// Runtime: O(n)
// Space: O(1)
int maxAncestorDiff(struct TreeNode* root){
int result = 0;
int maxVal = root->val;
int minVal = root->val;
recursiveSolve(root, &result, minVal, maxVal);
return result;
}
| 1,049
|
C
|
.c
| 32
| 28.3125
| 114
| 0.622886
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,920
|
231.c
|
TheAlgorithms_C/leetcode/src/231.c
|
// Without loops/recursion.
// Runtime: O(1)
// Space: O(1)
bool isPowerOfTwo(int n){
return (n > 0) && ((n & (n - 1)) == 0);
}
| 138
|
C
|
.c
| 6
| 20.333333
| 44
| 0.522727
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,921
|
540.c
|
TheAlgorithms_C/leetcode/src/540.c
|
/**
* Time complexity: O(log n).
* Space complexity: O(1).
* @details The array has a pattern that consists in of the existing sub-array to
* the left of the non-repeating number will satisfy the condition that
* each pair of repeated elements have their first occurrence at the even index
* and their second occurrence at the odd index, and that the sub-array to
* the right of the non-repeating number will satisfy the condition that
* each pair of repeated elements have their first occurrence at the odd index
* and their second occurrence at the even index. With this pattern in mind,
* we can solve the problem using binary search.
*/
int singleNonDuplicate(int* nums, int numsSize) {
int left = 0, right = numsSize - 1;
while (left < right) {
int mid = (right + left) / 2;
if (mid % 2 == 0) {
if (nums[mid] == nums[mid + 1])
left = mid + 2;
else
right = mid;
}
else {
if (nums[mid] == nums[mid - 1])
left = mid + 1;
else
right = mid - 1;
}
}
return nums[left];
}
| 1,218
|
C
|
.c
| 31
| 32.322581
| 88
| 0.577572
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| true
|
5,930
|
euclidean_algorithm_extended.c
|
TheAlgorithms_C/math/euclidean_algorithm_extended.c
|
/**
* @{
* @file
* @brief Program to perform the [extended Euclidean
* algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)
*
* @details The extended Euclidean algorithm, on top of finding the GCD (greatest common
* divisor) of two integers a and b, also finds the values x and y such that
* ax+by = gcd(a, b)
*/
#include <assert.h> /// for tests
#include <stdio.h> /// for IO
#include <stdlib.h> /// for div function and corresponding div_t struct
/**
* @brief a structure holding the values resulting from the extended Euclidean
* algorithm
*/
typedef struct euclidean_result
{
int gcd; ///< the greatest common divisor calculated with the Euclidean
///< algorithm
int x, y; ///< the values x and y such that ax + by = gcd(a, b)
} euclidean_result_t;
/**
* @brief gives queue-like behavior to an array of two ints, pushing an element
* onto the end and pushing one off the front
*
* @param arr an array of ints acting as a queue
* @param newval the value being pushed into arr
*
* @returns void
*/
static inline void xy_push(int arr[2], int newval)
{
arr[1] = arr[0];
arr[0] = newval;
}
/**
* @brief calculates the value of x or y and push those into the small 'queues'
*
* @details Both x and y are found by taking their value from 2 iterations ago minus the
* product of their value from 1 iteration ago and the most recent quotient.
*
* @param quotient the quotient from the latest iteration of the Euclidean
* algorithm
* @param prev the 'queue' holding the values of the two previous iterations
*
* @returns void
*/
static inline void calculate_next_xy(int quotient, int prev[2])
{
int next = prev[1] - (prev[0] * quotient);
xy_push(prev, next);
}
/**
* @brief performs the extended Euclidean algorithm on integer inputs a and b
*
* @param a first integer input
* @param b second integer input
*
* @returns euclidean_result_t containing the gcd, and values x and y such that
* ax + by = gcd
*/
euclidean_result_t extended_euclidean_algorithm(int a, int b)
{
int previous_remainder = 1;
int previous_x_values[2] = {0, 1};
int previous_y_values[2] = {1, 0};
div_t div_result;
euclidean_result_t result;
/* swap values of a and b */
if (abs(a) < abs(b))
{
a ^= b;
b ^= a;
a ^= b;
}
div_result.rem = b;
while (div_result.rem > 0)
{
div_result = div(a, b);
previous_remainder = b;
a = b;
b = div_result.rem;
calculate_next_xy(div_result.quot, previous_x_values);
calculate_next_xy(div_result.quot, previous_y_values);
}
result.gcd = previous_remainder;
result.x = previous_x_values[1];
result.y = previous_y_values[1];
return result;
}
/** @} */
/**
* @brief perform one single check on the result of the algorithm with provided
* parameters and expected output
*
* @param a first paramater for Euclidean algorithm
* @param b second parameter for Euclidean algorithm
* @param gcd expected value of result.gcd
* @param x expected value of result.x
* @param y expected value of result.y
*
* @returns void
*/
static inline void single_test(int a, int b, int gcd, int x, int y)
{
euclidean_result_t result;
result = extended_euclidean_algorithm(a, b);
assert(result.gcd == gcd);
assert(result.x == x);
assert(result.y == y);
}
/**
* @brief Perform tests on known results
* @returns void
*/
static void test()
{
single_test(40, 27, 1, -2, 3);
single_test(71, 41, 1, -15, 26);
single_test(48, 18, 6, -1, 3);
single_test(99, 303, 3, -16, 49);
single_test(14005, 3507, 1, -305, 1218);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main Function
* @returns 0 upon successful program exit
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 3,900
|
C
|
.c
| 135
| 25.622222
| 88
| 0.671116
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,939
|
fibonacci.c
|
TheAlgorithms_C/math/fibonacci.c
|
/**
* @file
* @brief Program to print the nth term of the Fibonacci series.
* @details
* Fibonacci series generally starts from 0 and 1. Every next term in
* the series is equal to the sum of the two preceding terms.
* For further info: https://en.wikipedia.org/wiki/Fibonacci_sequence
*
* @author [Luiz Carlos Aguiar C](https://github.com/IKuuhakuI)
* @author [Niranjan](https://github.com/niranjank2022)
*/
#include <assert.h> /// for assert()
#include <errno.h> /// for errno - to determine whether there is an error while using strtol()
#include <stdio.h> /// for input, output
#include <stdlib.h> /// for exit() - to exit the program
#include <time.h> /// to calculate time taken by fib()
/**
* @brief Determines the nth Fibonacci term
* @param number - n in "nth term" and it can't be negative as well as zero
* @return nth term in unsigned type
* @warning
* Only till 47th and 48th fibonacci element can be stored in `int` and
* `unsigned int` respectively (takes more than 20 seconds to print)
*/
unsigned int fib(int number)
{
// Check for negative integers
if (number <= 0)
{
fprintf(stderr, "Illegal Argument Is Passed!\n");
exit(EXIT_FAILURE);
}
// Base conditions
if (number == 1)
return 0;
if (number == 2)
return 1;
// Recursive call to the function
return fib(number - 1) + fib(number - 2);
}
/**
* @brief Get the input from the user
* @return valid argument to the fibonacci function
*/
int getInput(void)
{
int num, excess_len;
char buffer[3], *endPtr;
while (1)
{ // Repeat until a valid number is entered
printf("Please enter a valid number:");
fgets(buffer, 3, stdin); // Inputs the value from user
excess_len = 0;
if (!(buffer[0] == '\n' ||
buffer[1] == '\n' ||
buffer[2] == '\n')) {
while (getchar() != '\n') excess_len++;
}
num = strtol(buffer, &endPtr,
10); // Attempts to convert the string to integer
// Checking the input
if ( // The number is too large
(excess_len > 0 || num > 48) ||
// Characters other than digits are included in the input
(*endPtr != '\0' && *endPtr != '\n') ||
// No characters are entered
endPtr == buffer)
{
continue;
}
break;
}
printf("\nEntered digit: %d (it might take sometime)\n", num);
return num;
}
/**
* @brief self-test implementation
* @return void
*/
static void test()
{
assert(fib(5) == 3);
assert(fib(2) == 1);
assert(fib(9) == 21);
}
/**
* @brief Main function
* @return 0 on exit
*/
int main()
{
// Performing the test
test();
printf("Tests passed...\n");
// Getting n
printf(
"Enter n to find nth fibonacci element...\n"
"Note: You would be asked to enter input until valid number ( less "
"than or equal to 48 ) is entered.\n");
int number = getInput();
clock_t start, end;
start = clock();
printf("Fibonacci element %d is %u ", number, fib(number));
end = clock();
printf("in %.3f seconds.\n", ((double)(end - start)) / CLOCKS_PER_SEC );
return 0;
}
| 3,274
|
C
|
.c
| 107
| 25.476636
| 95
| 0.60254
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,946
|
lcs.c
|
TheAlgorithms_C/dynamic_programming/lcs.c
|
/**
* @file
* @brief [Longest Common
* Subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem)
* algorithm
* @details
* From Wikipedia: The longest common subsequence (LCS) problem is the problem
* of finding the longest subsequence common to all sequences in a set of
* sequences (often just two sequences).
* @author [Kurtz](https://github.com/itskurtz)
*/
#include <stdio.h> /* for io operations */
#include <stdlib.h> /* for memory management & exit */
#include <string.h> /* for string manipulation & ooperations */
#include <assert.h> /* for asserts */
enum {LEFT, UP, DIAG};
/**
* @brief Computes LCS between s1 and s2 using a dynamic-programming approach
* @param s1 first null-terminated string
* @param s2 second null-terminated string
* @param l1 length of s1
* @param l2 length of s2
* @param L matrix of size l1 x l2
* @param B matrix of size l1 x l2
* @returns void
*/
void lcslen(const char *s1, const char *s2, int l1, int l2, int **L, int **B) {
/* B is the directions matrix
L is the LCS matrix */
int i, j;
/* loop over the simbols in my sequences
save the directions according to the LCS */
for (i = 1; i <= l1; ++i) {
for (j = 1; j <= l2; ++j) {
if (s1[i-1] == s2[j-1]) {
L[i][j] = 1 + L[i-1][j-1];
B[i][j] = DIAG;
}
else if (L[i-1][j] < L[i][j-1]) {
L[i][j] = L[i][j-1];
B[i][j] = LEFT;
}
else {
L[i][j] = L[i-1][j];
B[i][j] = UP;
}
}
}
}
/**
* @brief Builds the LCS according to B using a traceback approach
* @param s1 first null-terminated string
* @param l1 length of s1
* @param l2 length of s2
* @param L matrix of size l1 x l2
* @param B matrix of size l1 x l2
* @returns lcs longest common subsequence
*/
char *lcsbuild(const char *s1, int l1, int l2, int **L, int **B) {
int i, j, lcsl;
char *lcs;
lcsl = L[l1][l2];
/* my lcs is at least the empty symbol */
lcs = (char *)calloc(lcsl+1, sizeof(char)); /* null-terminated \0 */
if (!lcs) {
perror("calloc: ");
return NULL;
}
i = l1, j = l2;
while (i > 0 && j > 0) {
/* walk the matrix backwards */
if (B[i][j] == DIAG) {
lcs[--lcsl] = s1[i-1];
i = i - 1;
j = j - 1;
}
else if (B[i][j] == LEFT)
{
j = j - 1;
}
else
{
i = i - 1;
}
}
return lcs;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
/* https://en.wikipedia.org/wiki/Subsequence#Applications */
int **L, **B, j, l1, l2;
char *s1 = "ACGGTGTCGTGCTATGCTGATGCTGACTTATATGCTA";
char *s2 = "CGTTCGGCTATCGTACGTTCTATTCTATGATTTCTAA";
char *lcs;
l1 = strlen(s1);
l2 = strlen(s2);
L = (int **)calloc(l1+1, sizeof(int *));
B = (int **)calloc(l1+1, sizeof(int *));
if (!L) {
perror("calloc: ");
exit(1);
}
if (!B) {
perror("calloc: ");
exit(1);
}
for (j = 0; j <= l1; j++) {
L[j] = (int *)calloc(l2+1, sizeof(int));
if (!L[j]) {
perror("calloc: ");
exit(1);
}
B[j] = (int *)calloc(l2+1, sizeof(int));
if (!L[j]) {
perror("calloc: ");
exit(1);
}
}
lcslen(s1, s2, l1, l2, L, B);
lcs = lcsbuild(s1, l1, l2, L, B);
assert(L[l1][l2] == 27);
assert(strcmp(lcs, "CGTTCGGCTATGCTTCTACTTATTCTA") == 0);
printf("S1: %s\tS2: %s\n", s1, s2);
printf("LCS len:%3d\n", L[l1][l2]);
printf("LCS: %s\n", lcs);
free(lcs);
for (j = 0; j <= l1; j++)
{
free(L[j]), free(B[j]);
}
free(L);
free(B);
printf("All tests have successfully passed!\n");
}
/**
* @brief Main function
* @param argc commandline argument count (ignored)
* @param argv commandline array of arguments (ignored)
* @returns 0 on exit
*/
int main(int argc, char *argv[]) {
test(); // run self-test implementations
return 0;
}
| 3,757
|
C
|
.c
| 147
| 22.503401
| 81
| 0.599609
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,947
|
matrix_chain_order.c
|
TheAlgorithms_C/dynamic_programming/matrix_chain_order.c
|
/**
* @file
* @brief [Matrix Chain
* Order](https://en.wikipedia.org/wiki/Matrix_chain_multiplication)
* @details
* From Wikipedia: Matrix chain multiplication (or the matrix chain ordering
* problem) is an optimization problem concerning the most efficient way to
* multiply a given sequence of matrices. The problem is not actually to perform
* the multiplications, but merely to decide the sequence of the matrix
* multiplications involved.
* @author [CascadingCascade](https://github.com/CascadingCascade)
*/
#include <assert.h> /// for assert
#include <limits.h> /// for INT_MAX macro
#include <stdio.h> /// for IO operations
#include <stdlib.h> /// for malloc() and free()
/**
* @brief Finds the optimal sequence using the classic O(n^3) algorithm.
* @param l length of cost array
* @param p costs of each matrix
* @param s location to store results
* @returns number of operations
*/
int matrixChainOrder(int l, const int *p, int *s)
{
// mat stores the cost for a chain that starts at i and ends on j (inclusive
// on both ends)
int **mat = malloc(l * sizeof(int *));
for (int i = 0; i < l; ++i)
{
mat[i] = malloc(l * sizeof(int));
}
for (int i = 0; i < l; ++i)
{
mat[i][i] = 0;
}
// cl denotes the difference between start / end indices, cl + 1 would be
// chain length.
for (int cl = 1; cl < l; ++cl)
{
for (int i = 0; i < l - cl; ++i)
{
int j = i + cl;
mat[i][j] = INT_MAX;
for (int div = i; div < j; ++div)
{
int q = mat[i][div] + mat[div + 1][j] + p[i] * p[div] * p[j];
if (q < mat[i][j])
{
mat[i][j] = q;
s[i * l + j] = div;
}
}
}
}
int result = mat[0][l - 1];
// Free dynamically allocated memory
for (int i = 0; i < l; ++i)
{
free(mat[i]);
}
free(mat);
return result;
}
/**
* @brief Recursively prints the solution
* @param l dimension of the solutions array
* @param s solutions
* @param i starting index
* @param j ending index
* @returns void
*/
void printSolution(int l, int *s, int i, int j)
{
if (i == j)
{
printf("A%d", i);
return;
}
putchar('(');
printSolution(l, s, i, s[i * l + j]);
printSolution(l, s, s[i * l + j] + 1, j);
putchar(')');
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test()
{
int sizes[] = {35, 15, 5, 10, 20, 25};
int len = 6;
int *sol = malloc(len * len * sizeof(int));
int r = matrixChainOrder(len, sizes, sol);
assert(r == 18625);
printf("Result : %d\n", r);
printf("Optimal ordering : ");
printSolution(len, sol, 0, 5);
free(sol);
printf("\n");
}
/**
* @brief Main function
* @returns 0
*/
int main()
{
test(); // run self-test implementations
return 0;
}
| 2,964
|
C
|
.c
| 110
| 22.063636
| 80
| 0.568717
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,964
|
merge_sort.c
|
TheAlgorithms_C/sorting/merge_sort.c
|
/**
* @file
* @brief Implementation of [merge
* sort](https://en.wikipedia.org/wiki/Merge_sort) algorithm
*/
#include <stdio.h>
#include <stdlib.h>
/**
* @addtogroup sorting Sorting algorithms
* @{
*/
/** Swap two integer variables
* @param [in,out] a pointer to first variable
* @param [in,out] b pointer to second variable
*/
void swap(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
}
/**
* @brief Perform merge of segments.
*
* @param a array to sort
* @param l left index for merge
* @param r right index for merge
* @param n total number of elements in the array
*/
void merge(int *a, int l, int r, int n)
{
int *b = (int *)malloc(n * sizeof(int)); /* dynamic memory must be freed */
if (b == NULL)
{
printf("Can't Malloc! Please try again.");
exit(EXIT_FAILURE);
}
int c = l;
int p1, p2;
p1 = l;
p2 = ((l + r) / 2) + 1;
while ((p1 < ((l + r) / 2) + 1) && (p2 < r + 1))
{
if (a[p1] <= a[p2])
{
b[c++] = a[p1];
p1++;
}
else
{
b[c++] = a[p2];
p2++;
}
}
if (p2 == r + 1)
{
while ((p1 < ((l + r) / 2) + 1))
{
b[c++] = a[p1];
p1++;
}
}
else
{
while ((p2 < r + 1))
{
b[c++] = a[p2];
p2++;
}
}
for (c = l; c < r + 1; c++) a[c] = b[c];
free(b);
}
/** Merge sort algorithm implementation
* @param a array to sort
* @param n number of elements in the array
* @param l index to sort from
* @param r index to sort till
*/
void merge_sort(int *a, int n, int l, int r)
{
if (r - l == 1)
{
if (a[l] > a[r])
swap(&a[l], &a[r]);
}
else if (l != r)
{
merge_sort(a, n, l, (l + r) / 2);
merge_sort(a, n, ((l + r) / 2) + 1, r);
merge(a, l, r, n);
}
/* no change if l == r */
}
/** @} */
/** Main function */
int main(void)
{
int *a, n, i;
printf("Enter Array size: ");
scanf("%d", &n);
if (n <= 0) /* exit program if arraysize is not greater than 0 */
{
printf("Array size must be Greater than 0!\n");
return 1;
}
a = (int *)malloc(n * sizeof(int));
if (a == NULL) /* exit program if can't malloc memory */
{
printf("Can't Malloc! Please try again.");
return 1;
}
for (i = 0; i < n; i++)
{
printf("Enter number[%d]: ", i);
scanf("%d", &a[i]);
}
merge_sort(a, n, 0, n - 1);
printf("Sorted Array: ");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
free(a);
return 0;
}
| 2,715
|
C
|
.c
| 128
| 15.953125
| 79
| 0.463509
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
6,021
|
celsius_to_fahrenheit.c
|
TheAlgorithms_C/conversions/celsius_to_fahrenheit.c
|
/**
* @file
* @brief Conversion of temperature in degrees from [Celsius](https://en.wikipedia.org/wiki/Celsius)
* to [Fahrenheit](https://en.wikipedia.org/wiki/Fahrenheit).
*
* @author [Focusucof](https://github.com/Focusucof)
*/
#include <assert.h> /// for assert
#include <stdio.h> /// for IO operations
/**
* @brief Convert celsius to Fahrenheit
* @param celsius Temperature in degrees celsius double
* @returns Double of temperature in degrees Fahrenheit
*/
double celcius_to_fahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32.0;
}
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
// 1st test
double input = 0.0;
double expected = 32.0;
double output = celcius_to_fahrenheit(input);
// 1st test
printf("TEST 1\n");
printf("Input: %f\n", input);
printf("Expected Output: %f\n", expected);
printf("Output: %f\n", output);
assert(output == expected);
printf("== TEST PASSED ==\n\n");
// 2nd test
input = 100.0;
expected = 212.0;
output = celcius_to_fahrenheit(input);
printf("TEST 2\n");
printf("Input: %f\n", input);
printf("Expected Output: %f\n", expected);
printf("Output: %f\n", output);
assert(output == expected);
printf("== TEST PASSED ==\n\n");
// 3rd test
input = 22.5;
expected = 72.5;
output = celcius_to_fahrenheit(input);
printf("TEST 3\n");
printf("Input: %f\n", input);
printf("Expected Output: %f\n", expected);
printf("Output: %f\n", output);
assert(output == expected);
printf("== TEST PASSED ==\n\n");
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
| 1,753
|
C
|
.c
| 62
| 24.580645
| 100
| 0.63788
|
TheAlgorithms/C
| 18,806
| 4,291
| 23
|
GPL-3.0
|
9/7/2024, 9:40:14 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.