#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// -1 if invalid, else number
int to_num(char c) {
return ('0' < c && c < '9') ? c - '0' : -1;
}
// ugly:
struct stack {
// data
int d[200000];
// ptr
int p;
};
void stack_init(struct stack* s) {
memset(s, 0, sizeof(*s));
}
void stack_push(struct stack* s, int val) {
s->d[s->p++] = val;
}
int stack_pop(struct stack* s) {
s->p--;
return s->d[s->p];
}
int solution(char *S) {
struct stack mystack;
char *p = S;
stack_init(&mystack);
while (*p != '\0') {
int c = to_num(*p);
if (c > 0) {
stack_push(&mystack, c);
} else if (*p == '+') {
// 2 pops and add
int a, b;
a = stack_pop(&mystack);
b = stack_pop(&mystack);
if (a < 0 || b < 0)
return -1;
stack_push(&mystack, a + b);
} else if (*p == '*') {
// 2 pops and multiply
// check that both are ints
int a, b;
a = stack_pop(&mystack);
b = stack_pop(&mystack);
if (a < 0 || b < 0)
return -1;
stack_push(&mystack, a * b);
} else {
return -1;
}
p++;
}
if (mystack.p == 1)
return stack_pop(&mystack);
return -1;
}
int main(int argc, char *argv[])
{
char *s = "13+62*7+*";
//char *s = "11++";
printf("answer = %d\n", solution(s));
}
#include <stdio.h>
#include <stdlib.h>
int solution(int A[], int N) {
// write your code in C99
int result = 0;
int i, j;
// find largest distance between indexes containing same values
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
if (A[i] == A[j])
if (abs(i - j) > result) {
result = abs(i - j);
printf("Setting result = %d at (%d,%d)\n", result, i, j);
}
return result;
}
int solution2(int A[], int N) {
// write your code in C99
int result = 0;
int i, j;
// find largest distance between indexes containing same values
//for (i = 0, j = N - 1; i < N && j > 0; i++, j--)
for (i = 0; i < N/2; i++)
for (j = N - 1; j > i; j--) {
printf("comparing a[%d] = %d, [%d] = %d\n", i, A[i], j, A[j]);
if (A[i] == A[j] && abs(i - j) > result) {
result = abs(i - j);
printf("Setting result = %d at (%d,%d)\n", result, i, j);
break;
}
}
return result;
}
int main(int argc, char *argv[])
{
//int A[] = {4, 6, 20, 2, 4, 64, 34, 2, 6, 6, 1};
//int A[] = {4, 6, 2, 2, 6, 6, 1, 4, 5, 4};
//int A[] = {3, 6, 2, 2, 6, 6, 1};
//int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int A[] = {1, 2, 3, 4, 1, 5, 6, 7, 8, 9, 10, 11};
int x = solution(A, sizeof(A)/sizeof(A[0]));
printf("x = %d\n", x);
int x2 = solution2(A, sizeof(A)/sizeof(A[0]));
printf("x2 = %d\n", x2);
if (x == x2)
printf("matches!!\n");
}
#include <stdio.h>
void solution(int N) {
// write your code in C99
for (int i = 1; i <= N; i++) {
int print_num = 1;
if (i % 3 == 0) {
printf("Fizz");
print_num = 0;
}
if (i % 5 == 0) {
printf("Buzz");
print_num = 0;
}
if (i % 7 == 0) {
printf("Woof");
print_num = 0;
}
if (print_num)
printf("%d\n", i);
else
printf("\n");
}
}
int main(int argc, char *argv[])
{
solution(24);
}