value searching in an ascending arrays in two different ways - c

I am doing a project for my C class. We are going to find the value in an ascending array with 10 distinctive numbers, then search the value users wanna and return the index of the searching number. The first method is called Linear Search which compare each element in the array to the value user wanted. The second method is called Binary, which you take the middle index compare with the searching value. If List[middle] = target element then return the variable middle which is the index of the element. In the case that target element is greater than List[Middle], then continue the process on the right half of the array. If it is lesser, then continue the same process on the left half of the array. The process of halving is done only until the ‘Left’ index variable is less than or equal to the ‘Right’ index variable. In case the target element is not found , -1 is returned.
#include<stdio.h>
int main()
{
int array[10];
int i = 0,value;
printf("Please enter 10 distinctive postive numbers with ascending order.");
for(i;i<10;i++)
{
scanf("%d",&array[i]);
}
printf("What value are you seaching for?");
scanf("%d",value);
printf("searchLinear(value,*array[10],10)");
return 0;
}
int searchLinear(int s,int *list[10],int n){
list[n];
int i = 0;
for(i;i<n;i++)
{
if(s == *list[i])
return *list[i];
}
if(i = n)
return -1;
}
int searchBinary(int s, int *list[10],int n) {
list[n];
int i,left,right,middle;
left = 0;
right = n-1;
for(i = 0;i<n/2;i++)
{
middle = (left + right)/2;
if(*list[middle] > s)
right = middle;
else if(*list[middle] < s)
left = middle;
else if(*list[middle] = s)
return *list[middle];
if(left == right)
return -1;
}
}
This is my code, looks like it runs into an infinite loop. How can I fix it?

The corrected code is
#include<stdio.h>
int searchLinear(int s,int list[],int n);
int searchBinary(int s, int list[],int n); //you need to give forward declaration of funcs
int main()
{
int array[10];
int i = 0,value;
printf("Please enter 10 distinctive postive numbers with ascending order.");
for(i;i<10;i++)
{
scanf("%d",&array[i]);
}
printf("What value are you seaching for?");
scanf("%d",&value); //you missed & here
printf("%d",searchBinary(value,array,10));
return 0;
}
int searchLinear(int s,int list[],int n){ // you can use this format of arguments
//list[n]; //what did you wanted to do with this line
int i = 0;
for(i;i<n;i++)
{
if(s == list[i])
return i; //return index not value
}
if(i = n)
return -1;
}
int searchBinary(int s, int list[],int n){
//list[n];
int i,left,right,middle;
left = 0;
right = n-1;
for(i = 0;i<n/2;i++)
{
middle = (left + right)/2;
if(left > right) //you have to check left>right, instead of left==right
return -1;
if(list[middle] > s)
right = middle-1;
else if(list[middle] < s)
left = middle+1;
else if(list[middle] == s) //== is used for comparision
return middle;
}
}
Observe the corrections in comments

Related

How to solve the stock spans problem using a stack?

I am looking at this stock span problem:
The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of stock’s price for all n days.
The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
In this description an algorithm is explained:
Computing Spans with a Stack
We keep in a stack the indices of the last element that is taller when "looking back"
We scan the array from left to right
Let 𝑖 be the current index
We pop indices from the stack until we find index 𝑗 such that 𝑋[𝑖] < 𝑋[𝑗]
We set 𝑆[𝑖] <= 𝑖 − 𝑗
We push 𝑖 onto the stack
The output for the example is supposed to be {1,1,2,1,2,3,6,1}, but my code outputs {1,1,2,2,2,3,6,7}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
typedef int element;
typedef struct StackType {
element elem[SIZE];
int top;
} StackType;
void init(StackType *A) {
A->top = -1;
}
int isEmpty(StackType *A) {
return A->top == -1;
}
int isFull(StackType *A) {
return A->top == SIZE - 1;
}
void push(StackType *A, element i) {
if (isFull(A)) {
printf("FULL\n");
return;
}
A->top++;
A->elem[A->top] = i;
}
element pop(StackType *A) {
if (isEmpty(A)) {
printf("Empty\n");
return 0;
}
element temp = A->elem[A->top];
A->top--;
return temp;
}
void spans(StackType *A, int X[], int S[]) {
for (int i = 0; i < SIZE; i++) {
while (!isEmpty(A) && (X[A->top] <= X[i]))
pop(A);
if (isEmpty(A))
S[i] = i + 1;
else
S[i] = i - (A->top);
push(A, i);
}
while (!isEmpty(A))
pop(A);
return;
}
int main() {
StackType A;
init(&A);
int X[SIZE] = { 60, 30, 40, 10, 20, 30, 50, 40 };
int S[SIZE];
spans(&A, X, S);
for (int i = 0; i < SIZE; i++)
printf("[%d] ", S[i]);
printf("\n");
return 0;
}
I debugged the function void spans, and I saw A->top doesn't change in the right way. For example, when i = 2, A->top should be 2, but in reality, A->top is 1. There seems something wrong with function pop and push, but I couldn't find the problem.
The problem in your implementation is that A->top is an index, not the value stored at the top of the stack.
So I would suggest defining a function to retrieve the top value from the stack:
element peek(StackType *A) {
if (isEmpty(A)) {
printf("Empty\n");
return 0;
}
return A->elem[A->top];
}
And then in the function spans replace all occurrences of A->top with peek(A). I have also changed the if...else construct to a ternary operator:
void spans(StackType *A, int X[], int S[]) {
for (int i = 0; i < SIZE; i++) {
while (!isEmpty(A) && (X[peek(A)] <= X[i]))
pop(A);
S[i] = i + (isEmpty(A) ? 1 : -peek(A));
push(A, i);
}
while (!isEmpty(A))
pop(A);
return;
}
Last remark: I would not define the stack in main, but in spans.

No Output - The program doesn't give any output

I am learning data structures. I tried to write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.
By rotate I mean shifting the elements in an array.
The program doesn't give any error, rather it hangs a bit but it doesn't run.
Here's the code: -
#include <stdio.h>
int rotate(int arr[], int d, int n, int dir)
{
int temp, i;
while (d)
{
if (dir)
{
// for left shift
// First element will always get replaced in a rotation.
temp = arr[0];
for (i = 0; i < n - 1; i++)
// for left shifting the second element next to its original position.
arr[i] = arr[i + 1];
// Putting the temp value in the last position.
arr[n - 1] = temp;
}
else
{
// for right shift
// Last element will always get replaced in a rotation.
temp = arr[n - 1];
for (i = n - 1; i > 0; i--)
// for right shifting the second last element to the last position.
arr[i] = arr[i - 1];
// Putting the temp value in the first position
arr[0] = temp;
}
d--;
}
// Print the shifted array
for (i = 0; i < n; i++)
{
printf("%d, ", arr[i]);
}
}
The program only runs when I don't take inputs from the user.
int main()
{
int n;
int arr[n];
int dir;
int d;
printf("Enter the size of the array: \n");
scanf("%d", &n);
printf("Enter the elements of the array: \n");
for (int i = 1; i <= n; i++)
{
printf("Enter element %d", i);
scanf("%d", &arr[i]);
}
printf("Enter the position: \n");
scanf("%d", &d);
printf("Enter the direction: \n");
// 0: Right Direction and 1: Left Direction
scanf("%d", &dir);
// Before shifting the array
for (int i = 1; i <= n; i++)
{
printf("%d, ", arr[i]);
}
// After shifting the array
rotate(arr, d, n, dir);
return 0;
}
You might want to do int arr[n] after scanf("%d", &n); because n is not initialized when you do int arr[n]. Also array indexing in C starts from 0 so for (int i = 1; i <= n; i++) will be for (int i = 0; i < n; i++).
This is not a proper answer, so do not accept it as the correct answer. It is just a possible implementation for educational purposes.
Here is a way to rotate the array so that each element is moved only once (except that the first element of a "group" is moved via a temporary variable).
The rotation amount is specified as an integer with positive values rotating right and negative values rotating left. It converts this amount into a number in the range 0 to n-1 which is the index of the element that will be copied to element 0. It then divides the array into one or more interleaved groups of the same size such that successive elements in each group are separated by the rotation amount in a circular fashion, and rotates the elements within each group. (The number of groups is the greatest common divisor of n and the rotation amount, and the number of elements in each group is the total number of elements divided by the number of groups.)
#include <limits.h>
#include <stddef.h>
static size_t rotate_modulus(int d, size_t n);
static size_t gcd_size(size_t a, size_t b);
/* Rotate arr[] of length n right by d, or left by -d. */
void rotate(int arr[], int d, size_t n)
{
size_t md = rotate_modulus(d, n); /* Get offset in range 0 to n-1. */
if (md)
{
/* Rotation needed. */
/* Divide into interleaved groups and rotate each group. */
size_t num_groups = gcd_size(n, md);
size_t group_size = n / num_groups;
size_t group;
for (group = 0; group < num_groups; group++)
{
size_t a = group; /* Index of first element in group. */
size_t i;
/* Rotate elements in group. */
int temp = arr[a]; /* Get first element. */
for (i = 0; i < group_size - 1; i++)
{
/* Get index of next element in group. */
size_t b = (a + md);
if (a >= n - md)
{
b -= n; /* Index wraps around. */
}
arr[a] = arr[b]; /* Move an element. */
a = b; /* Advance to next index. */
}
arr[a] = temp; /* Move first element to last element. */
}
}
}
/*
* Get modulus for rotation of n elements.
*
* d is the amount to rotate right; negative d rotates left by -d.
*
* For zero n, the return value is 0.
*
* For non-zero n, the return value is n - s, where s is d plus an
* integer multiple of n such that s is in the range 1 to n, and the
* return value is in the range 0 to n - 1.
*/
static size_t rotate_modulus(int d, size_t n)
{
size_t md;
if (n < 2)
{
/* No rotation needed if n < 2. */
md = 0;
}
else if (d >= 0)
{
/* Non-negative d will rotate right. */
md = d % n;
if (md)
{
md = n - md;
}
}
else
{
/* Negative d will rotate left. */
/* -d would overflow if d == INT_MIN && INT_MIN == -INT_MAX - 1. */
int fix_overflow = (d < -INT_MAX);
md = -(d + fix_overflow) % n;
if (fix_overflow)
{
if (++md == n)
{
md = 0;
}
}
}
return md;
}
/*
* If both a and b are non-zero, return the greatest common divisor of a and b.
* Otherwise, return 0.
*/
static size_t gcd_size(size_t a, size_t b)
{
if (b == 0)
{
a = 0;
}
else
{
do
{
size_t t = b;
b = a % b;
a = t;
}
while (b);
}
return a;
}

Passing by Reference fails [C Programming]

I'm trying to use the function targetSum to find out if there are two values in the array that match the target value entered by the user. It takes in the array, the target, the 2 indices, and the size of the array. When I try to output the result in the main function, the value of indices does not change (even though I'm passing as reference). Help appreciated! [code below]
int targetSum(int arr[], int size, int target, int index1, int index2)
{
int max, min, sum;
index1 = 0;
index2 = size - 1;
min = arr[index1];
max = arr[index2];
while (index1 != index2) {
sum = max + min;
if (sum == target) {
return 1;
}
else if (sum < target) {
index1++;
min = arr[index1];
}
else if (sum > target) {
index2--;
max = arr[index2];
}
}
return -1;
}
int index1, index2 = 0;
int target;
if(target == -999){ // the program exits if the user enters target as -999
printf("Good Bye");
break;
}
if (targetSum(toArr, size, target, &index1, &index2) == 1) {
printf("Output: Success! Elements at indices ");
printf("%d", index1);
printf(" and ");
printf("%d", index2);
printf(" add up to ");
printf("%d", target);
printf("\n");
}
else {
printf("Output: Target sum failed!\n");
}
What you're passing to the function doesn't match what it's expecting.
The last two parameters to targetSum are of type int but you're passing in values of type int *. Your compiler should have warned you about this.
Change the function parameters to pointers:
int targetSum(int arr[], int size, int target, int *index1, int *index2)
Then dereference them as necessary in the body of the function.
In function definition, add pointer operator (*) everywhere before variables index1 and index2

Binary search implemention ( mostly code structure problems, aka newbie problems)

I have just learned my very first steps in C (I used to code in python) and as a such I'm facing great difficulty with the syntax, and as well as with binary search implementation. (I'm new to programming.)
So here's my code:
#include <stdlib.h>
#include <stdio.h>
#define size 1000
int binary_search(int array[size], int givenNumber) {
do {
int start = 0;
int end = size;
int middle = start + end / 2;
int left = size - 1;
int right = size + 1;
if (array[middle] == givenNumber) {
printf("location: %d, number: %i", middle, givenNumber);
return middle;
} else if (array[left] < givenNumber) {
int start = 0;
int end = array[left];
int middle = start + end / 2;
return middle;
} else if (array[right] > middle) {
int start = array[right];
int end = size;
int middle = start + end / 2;
return middle;
} else {
return -1;
break;
}
}
} while (int middle != givenNumber)
int main() {
int sorted_array[size];
for (int i = 0; i < size; i++) {
sorted_array[i] = i;
}
return binary_search(sorted_array, 349);
}
My problems are:
1 - when compiling, the error is something along the lines of "in while block "middle" isn't defined"
I have no clue on why the value isn't passing from the do block to the while block. Note that I added "return middle" to each if / else-if block, as I I thought it may help.
2- I'm not even quite sure if my own implementation of this binary search is correct. I have looked up how to implement it but I found it next to impossible to read the syntax, this is just to give a heads up.
UPDATE:
I have reconstructed the whole code according to the notes users have given in the answers below, and well, my algorithm is working and now it could find any number in any given array, however I'm unable to figure out a way to tell if the array doesn't have that givenNumber as it would get eventually stuck.
Here's an input/output:
int array[size] = {1,2,3,4,5,6,8,9,10,11,14,24,53,100};
function: binary_search(array, 24);
output: Location: 11, Number: 24
Which is pretty good, however if I enter a number which doesn't exist in the array, the loop continues to search endlessly (gets stuck in recursion)
here's the updated code:
#include <stdio.h>
#include <stdlib.h>
#define size 14
int start = 0;
int end = size -1;
int middle;
int left;
int right;
int binary_search(int array[size], int givenValue)
{
middle = (start + end) / 2;
printf("\nstart: %d \nend: %d \nmiddle: %d \n\n",start, end, middle);
do
{
if (start > end)
{
printf("item isn't found");
break;
return -1;
}
middle = (start+end)/2;
left = middle -1;
right = middle +1;
if (array[middle] == givenValue)
{
printf("Location: %d, Number: %d", middle, givenValue);
return middle;
break;
}
if(array[middle] > givenValue)
{
end = right;
return binary_search(array, givenValue);
}
if(array[middle] < givenValue)
{
start = left;
return binary_search(array, givenValue);
}
}
while (start <= end);
}
int main(void)
{
int array[size] = {1,2,3,4,5,6,8,9,10,11,14,24,53,100};
return binary_search(array, 24);
}
My condition is that if start is greater than end then the item doesn't exist, and it doesn't work at all because left/right keeps getting stuck at the same values (Run the code to know what I mean)
How do I fix this issue?
There are a number of issues:
The loop does not iterate. All parts of if/else have a return
massive amount of "shadowing" of variables
size is invariant so left/right are always set to the same thing
left and right should be started at 0 and size - 1 respectively
variables are used inconsistently (e.g. start is both an array index and an array value)
The function is more complex than it needs to be and has some extraneous variables
Your binary search algorithm is suspect
First and foremost, I'd recommend removing all "sub-scoped" variable declarations that shadow outer scoped ones (i.e. put all variables at the outermost scope).
Do this until you're more comfortable with these declarations. Learn more about the difference between:
variable declaration: int x;
variable declaration with initializer: int x = 5;
variable assignment: x = 5;
I've annotated your original function, created a test/diagnostic function and created a refactored function that passes the diagnostic test:
#include <stdio.h>
#define size 1000
int
binary_fixed(int *array, int givenNumber)
{
int left;
int right;
int middle;
int curval;
int retindex = -1;
left = 0;
right = size - 1;
while (left <= right) {
middle = (left + right) / 2;
curval = array[middle];
if (curval == givenNumber) {
retindex = middle;
break;
}
if (curval > givenNumber)
right = middle - 1;
else
left = middle + 1;
}
return retindex;
}
int
binary_search(int *array, int givenNumber)
{
int middle;
// NOTE/BUG: this does _not_ iterate
// NOTE/BUG: _massive_ amount of "shadowing" of variables
// NOTE/BUG: size is _invariant_ so left/right are _always_ set to the
// same thing
// NOTE/BUG: left and right should start at 0 and size - 1 respectively
// NOTE/BUG: variables are used _inconsistently_ (e.g. start is both
// an array index and an array _value_)
do {
int start = 0;
int end = size;
int middle = start + end / 2;
int left = size - 1;
int right = size + 1;
if (array[middle] == givenNumber) {
printf("location: %d, number: %i\n", middle, givenNumber);
return middle;
}
else if (array[left] < givenNumber) {
int start = 0;
int end = array[left];
int middle = start + end / 2;
return middle;
}
else if (array[right] > middle) {
int start = array[right];
int end = size;
int middle = start + end / 2;
return middle;
}
else {
return -1;
}
} while (middle != givenNumber);
printf("BADRETURN givenNumber=%d\n", givenNumber);
}
int sorted_array[size];
void
test(const char *who,int (*fnc)(int *,int))
{
int i;
int r;
for (i = 0; i < size; i++) {
r = fnc(sorted_array, i);
if (r != i) {
printf("ERROR -- EXPECTED: %d ACTUAL: %d (from %s)\n", i, r, who);
// break;
}
}
}
int
main()
{
for (int i = 0; i < size; i++) {
sorted_array[i] = i;
}
//test("ORIGINAL",binary_search);
test("FIXED",binary_fixed);
return 0;
}
UPDATE:
Since you're coming from python, here are a few points that may help with your understanding.
Arrays are passed to functions as pointers, so in the function argument list, int *array is equivalent. Doing int array[size] is an advanced technique. Avoid it for now. In C, you can't do array.count as you can in python. So, for now, pass the count as an additional argument.
Pointers are something that python doesn't have, so you'll have to learn about how to use them. Once you get the hang of them, they are quite powerful and can make code run quite fast.
In C [and most languages except python [and php]], the default scope is global. It's the reverse of python. In python, unless you specify global x, then x is private to the function. In other languages, to have x be local to the function, you have to declare it at function scope.
In C, all variables must be declared somewhere: global scope, function scope [or a block scope within a function], or as an argument. And, each declaration must specify an explicit type. There is no equivalent of javascript's declaration of var x. After that, x could be either a string or a value depending upon what you set it to: (e.g. x = 23 or x = "abc")
In C, x must be given a type such as: int x; or double x; or int *x; or char *x.
Here is your revised code with annotations:
#include <stdio.h>
#include <stdlib.h>
// NOTE: this is hardwired
#define size 14
// NOTE: this is _global_ scope -- while not absolutely wrong, using function
// scope below is faster/better and provides better isolation -- this doesn't
// scale as well
int start = 0;
int end = size - 1;
int middle;
int left;
int right;
// NOTE: in C, using "int *array" is equivalent [and in many cases preferred]
// NOTE: the array count should be passed in as a separate argument
int
binary_search(int array[size], int givenValue)
{
// NOTE: this is _function_ scope
// NOTE: this calc of middle is extraneous because it is recalculated
// below
middle = (start + end) / 2;
printf("\nstart: %d \nend: %d \nmiddle: %d \n\n", start, end, middle);
// NOTE/BUG: this function combines _both_ a loop implementation and a
// recursive implementation -- we have to pick one or the other as trying
// to do both messes things us -- the recursion is broken [see below]
// NOTE: this loop checks start vs end _twice_ in the loop -- it only
// needs to check in one place -- convert this to "while (start <= end) {"
// instead of a "do {...} while (whatever);" loop [which is usually not
// as good]
do {
if (start > end) {
printf("item isn't found");
break;
// NOTE/BUG: this return will _never_ be executed because we
// break out of the loop and what is worse we'll return an
// unknown/undefined value because
return -1;
}
middle = (start + end) / 2;
// NOTE/BUG: these are reversed
left = middle - 1;
right = middle + 1;
if (array[middle] == givenValue) {
printf("Location: %d, Number: %d", middle, givenValue);
return middle;
break;
}
// NOTE/BUG: these recursive calls do nothing because they do _not_
// further limit the scope and cause infinite recursion -- to make
// a recursive version work, start/end would need to be arguments:
// return binary_search(array,givenValue,start,end)
// and we shouldn't loop -- the recursive calls just aren't needed
// NOTE/BUG: the tests here are broken -- they are the reverse of
// the correct ones
if (array[middle] > givenValue) {
end = right;
return binary_search(array, givenValue);
}
if (array[middle] < givenValue) {
start = left;
return binary_search(array, givenValue);
}
// NOTE/BUG: this extra test is extraneous and would be done too late
// if the array size was zero -- a case that isn't handled here
} while (start <= end);
// NOTE/BUG: when we break out of the loop, we need to return _some_ value
// here -- this would be flagged by the compiler using the -Wall option
}
int
main(void)
{
int array[size] = { 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 14, 24, 53, 100 };
// NOTE/BUG: the return value from main can only handle numbers 0-255
// better to print the return value
return binary_search(array, 24);
}
Here is a working version of your revised code.
The loop is now a simple while. The function takes a separate count argument. It loops instead of recurses. The reversed if logic has been fixed. Again, a diagnostic test has been added.
#include <stdio.h>
#include <stdlib.h>
int
binary_search(int *array, int size, int givenValue)
{
// NOTE: this is _function_ scope
int start = 0;
int end = size - 1;
int middle;
int left;
int right;
int match_index;
// assume failure
match_index = -1;
// NOTE: this calc of middle is extraneous because it is recalculated
// below
middle = (start + end) / 2;
printf("\nstart: %d \nend: %d \nmiddle: %d \n\n", start, end, middle);
while (start <= end) {
middle = (start + end) / 2;
left = middle - 1;
right = middle + 1;
if (array[middle] == givenValue) {
printf("Location: %d, Number: %d\n", middle, givenValue);
match_index = middle;
break;
}
if (array[middle] > givenValue) {
end = left;
}
if (array[middle] < givenValue) {
start = right;
}
}
if (match_index < 0)
printf("match not found -- givenValue=%d\n",givenValue);
return match_index;
}
int
main(void)
{
int array[] = { 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 14, 24, 53, 100 };
int count = sizeof(array) / sizeof(array[0]);
int curidx;
int valwant;
int match;
printf("%d\n",binary_search(array, count, 24));
// run diagnostic on all values
for (curidx = 0; curidx < count; ++curidx) {
// get value to search for
valwant = array[curidx];
match = binary_search(array,count,valwant);
if (match != curidx) {
printf("fault: curidx=%d valwant=%d match=%d\n",
curidx,valwant,match);
}
}
// test lower range failure
valwant = array[0] - 1;
match = binary_search(array,count,valwant);
if (match >= 0)
printf("fault: valwant=%d match=%d\n",valwant,match);
// test upper range failure
valwant = array[count - 1] + 1;
match = binary_search(array,count,valwant);
if (match >= 0)
printf("fault: valwant=%d match=%d\n",valwant,match);
return 0;
}
A typical binary search implementation would either loop or recurse until the number is found. The naive recursive code is something like this:
#include <stdio.h>
#define size 1000
int binary_search(int array[size], int givenNumber, int start, int end) {
int middle;
middle = (start + end) / 2;
if (start > end)
return -1;
if (array[middle] == givenNumber) {
printf("location: %d, number: %i", middle, givenNumber);
return middle;
} else if (array[middle] < givenNumber) {
return binary_search(array, givenNumber, middle + 1, end);
} else { // if (array[middle] > givenNumber)
return binary_search(array, givenNumber, start, middle - 1);
}
}
int main() {
int sorted_array[size];
for (int i = 0; i < size; i++) {
sorted_array[i] = i * 2;
}
if (binary_search(sorted_array, 349, 0, size - 1) < 0) {
printf("value not found\n");
}
if (binary_search(sorted_array, 34, 0, size - 1) < 0) {
printf("value not found\n");
}
}
Notice in the recursion we call binary_search each time with a new start and end range based on the sorted array and the provided input in givenNumber.
You can't declare a variable inside a while statement. Move it to the top of your function.
You have a misplaced curly brace in your code.
Try this:
#include <stdlib.h>
#include <stdio.h>
#define size 1000
int binary_search(int array[size], int givenNumber) {
int middle;
do {
int start = 0;
int end = size;
int middle = start + end / 2;
int left = size - 1;
int right = size + 1;
if (array[middle] == givenNumber) {
printf("location: %d, number: %i", middle, givenNumber);
return middle;
} else if (array[left] < givenNumber) {
int start = 0;
int end = array[left];
int middle = start + end / 2;
return middle;
} else if (array[right] > middle) {
int start = array[right];
int end = size;
int middle = start + end / 2;
return middle;
} else {
return -1;
}
} while (middle != givenNumber);
}
int main() {
int sorted_array[size];
for (int i = 0; i < size; i++) {
sorted_array[i] = i;
}
return binary_search(sorted_array, 349);
}

UVA problems 12503 gives TLE

I am trying to solve 12503 problem on UVA online judge. I think I have figured out the solution, but it gives me TLE. Here is the problem :
You have a robot standing on the origin of x axis. The robot will be given some instructions.
Your task is to predict its position after executing all the instructions.
• LEFT: move one unit left (decrease p by 1, where p is the position of the robot before moving)
• RIGHT: move one unit right (increase p by 1)
• SAME AS i: perform the same action as in the i-th instruction. It is guaranteed that i is a positive
Input
integer not greater than the number of instructions before this.
The first line contains the number of test cases T (T <= 100). Each test case begins with an integer n (1 <= n <= 100), the number of instructions. Each of the following n lines contains an instruction.
Output
For each test case, print the final position of the robot. Note that after processing each test case, the
robot should be reset to the origin.
Sample Input
2
3
LEFT
RIGHT
SAME AS 2
5
LEFT
SAME AS 1
SAME AS 2
SAME AS 1
SAME AS 4
Sample Output
1
-5
Here is my code in C:
#include <stdio.h>
char com[102][20];
int command(char comd[], int pos);
int main() {
int t;
int pos;
int i, n;
char tmp[20];
scanf("%d", &t);
for(i = 0; i < t; i++) {
scanf("%d", &n);
int j;
pos = 0;
for (j = 0; j < n; j++) {
gets(com[j]);
if (strcmp(com[j], "LEFT") == 0)
pos--;
else if(strcmp(com[j], "RIGHT") == 0)
pos++;
else {
pos = command(com[j], pos);
}
}
printf("%d\n", pos);
}
return 0;
}
int command(char comd[], int pos) {
if (strcmp(comd, "LEFT") == 0) {
pos--;
return pos;
}
else if (strcmp(comd, "RIGHT") == 0) {
pos++;
return pos;
}
else{
int a = atoi(&comd[8]);
return command(com[a-1], pos);
}
}
Is there any suggestion why this code gives TLE ?
In the int command(char comd[], int pos) function, you are using recursive call at the last line. This may lead to TLE.
To solve this problem you can use another array to store the number of steps taken by the robot at a command. You just have to access the index of the array later to get step at a previous command.
Here is how I would do it-
#include <stdio.h>
#include <string.h>
int move[110];
int getMove(char inp[], int);
int main()
{
int t, n;
char inp[50];
scanf(" %d ",&t);
while(t--)
{
scanf(" %d ",&n);
int i, pos = 0;
for(i = 0; i < n; i++)
{
gets(inp);
pos += getMove(inp, i);
}
printf("%d\n",pos);
}
return 0;
}
int getMove(char inp[], int i)
{
if(inp[0]=='S')
{
int j;
sscanf(strrchr(inp,' ')," %d",&j);
move[i] = move[j - 1];
}
else
{
move[i] = (inp[0] == 'L') ? -1 : 1;
}
return move[i];
}

Resources