Hi I'm new to competitive programming and this is my first problem. (Here's the link this problem - : POJ 1007 -- DNA Sorting). The problem is basically simple string manipulation and here's the solution that I've come up with.
// POJ id=1007 - DNA
#include<stdio.h>
int a[50][100];
void insert(char temp[], int i)
{
int j=0;
while(temp[j]!='\0')
{
switch(temp[j])
{
case 'A':
a[i][j]=0;
break;
case 'C':
a[i][j]=1;
break;
case 'G':
a[i][j]=2;
break;
case 'T':
a[i][j]=3;
break;
}
j++;
}
}
int main()
{
int i,j,unso[100],k,m,n,large,largeindex=0;
scanf("%d%d", &n, &m); // n -length 50max|| m - number of strings 100max
char temp[50];
char dna[50][100];
for(i=0;i<m;i++)
{
gets(dna[i]);
gets(temp);
insert(temp,i);
} // Inserted the string as an equivalent integer array
// HERE: Calculate measure of ``unsortedness'' for ith string and put it in unso[i] for all 0<=i<n
for(j=0;j<n;j++)
for(i=0;i<m;i++)
for(k=i+1;k<m-1;k++)
if(a[j][i]<a[j][k])
unso[j]++;
// HERE: Find the largest element in anso, note the corresponding 'i', print dna[i][100];
i=0;
do{
large=unso[0];
for(j=1;j<m;j++)
{
if(unso[j]>large){
large=unso[j];
largeindex=j;}
}
printf ("%s" , dna[j]);
unso[j]=0;
largeindex=0;
i++;
}while(i<m);
return 0;
}
Please help to find what's wrong with my implementation.
Related
So my program is basically built to get game scores, and track w/l/t, etc. What I am needed to do is to arrange the scores in ascending order based off of the opponent's scores.
So to do that I decided to bubble sort, but when I do that and print it, the first pair [0][0], and [0][1] come out with big negative numbers, which is what I'm guessing is their reference then after that the rest print correctly. I've googled around and couldn't find anything about this so I was wanting to copy the original array into a copy and try sorting with that one.
#include <stdio.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS //doesn't work
#define FLUSH myFlush()
#define GAMES 50
void titleDisplay(int);
void menuOptions();
void gameResults(int *counter, int team[][2], int); // records games from user input
void showRecord(int counter, int team[][2]); // shows current record
void displayResultFromGamesWon(int counter, int team[][2]);
void displayAllResults(int counter, int team[][2]); // shows all results ordered by opp score.
char getChoice();
void myFlush();
int main() {
//const int GAMES = 50; - program doesn't read this as a const when used to create arr.
const int MAX_GAMES = 50;
int userTeam[GAMES][2]; // array column 0 is user score, column 1 is opp score
int gameCounter = 0;
char userChoice;
do {
system("clear");
titleDisplay(1);
menuOptions();
userChoice = getChoice();
switch (userChoice) {
case 'a': case 'A':
gameResults(&gameCounter, userTeam, MAX_GAMES);
break;
case 'b': case 'B':
showRecord(gameCounter, userTeam);
break;
case 'c': case 'C':
displayResultFromGamesWon(gameCounter, userTeam);
break;
case 'd': case 'D':
displayAllResults(gameCounter, userTeam);
break;
case 'e': case 'E':
printf("Bye bye.\n");
system("pause");
break;
default:
printf("Invalid selection, choose again!\n");
system("pause");
break;
}//end switch
} while (userChoice != 'e' && userChoice != 'E');
return 0;
}
Here's where I sort and print:
//function definition
void displayAllResults(int counter, int team[][2]) {
int i;
int temp, temp2 = 0;
system("clear");
if (counter == 0) {
printf("\n\n\tYou haven't played any games yet.\n\n\n");
}
else {
titleDisplay(4);
printf("\t (Arranged by Opponent score low to high)\n\n");
printf("\tUser Score\t\t\tOpponent Score\n");
printf("\t----------\t\t\t--------------\n");
//begin bubble sorting
for (int x = 0; x < counter; x++) {
for (int y = x + 1; y < counter; y++) {
if (team[x][0] > team[y][0]) {
temp = team[x][1];
temp2 = team[x][0];
team[x][0] = team[y][0];
team[x][1] = team[y][1];
team[y][0] = temp2;
team[y][1] = temp;
}//end if
}
}//end bubble sort
for (i = 0; i < counter; i++) {
printf("\t%-8i\t\t\t%-11i\n", team[i][0], team[i][1]);
}//end for
}//end else
system("pause");
}//end function
I've tried declaring a variable of 'int sortedArray = team[counter][2];' in the displayAllResults function but that gave memory problems, and failed when I tried to access that variable. I tried memcpy, but either I didn't implement correctly or that doesn't work either.
Is it even possible to copy a 2D array like this to another one?
There are two ways to copy an array to another:
1-Using sizeof(array) and dividing it to size of one element of the array, in this case it is a pointer.
2- The best way is, to have a variable which will show you the length of the array.
I think you made an implementational mistake. I couldn't understand what you are doing. What is 5 for?
In any case, do have a variable for the length of the array.
I'm getting crazy with C. I'm writing code for my battleship DOS app. I'm using a int matrix (10x10) to build the field, but a weird thing happens. When I assign a value to an other variable, some points in the field change their value.
I don't know how it's possible.
I use to fill the matrix with '1' (int value), so I print a char to simulate a "sea point" on the battleship field. Here's the problem: some unwanted ints appear on the field.
I removed all the functions from the game, leaving only "printfield". It still happens. Please help!
(i'm italian, i tried to translate the variables names to make things easier. i'm sorry if i did some english errors. I also added a lot of printfield functions to see how the field changes during the app execution)
Here the code: (note: changing, for example, the "pos_x" assignment, the unwanted values change)
#include <stdio.h>
int printfield(int camp[][9]);
int fill(int campo[][9]);
int main()
{
int continua;
int field1a[9][9];
fill(field1a);
printfield(field1a);
continua=0; //what do this assignment do?????
while(continua==0)
{
printfield(field1a);
system("pause");
int pos_x=7; //what do this assignment do?????
printfield(field1a);
int pos_y=3; //what do this assignment do?????
printfield(field1a);
system("pause");
}
printfield(field1a);
system("pause");
system("cls");
printfield(field1a);
system("pause");
}
int printfield(int camp[][9])
{
printf("\n\n\n");
printf(" ");
int word;
for(word=97;word<=106;word++)
{
printf("%c ", (char)word);
}
int q, r;
for(q=0;q<=9;q++)
{
for(r=0;r<=9;r++)
{
if(r==0)
{
printf("\n");
if(q!=9) //to print '10' (the row number) correctly spaced -see the different number of spaces I put into the next printf
{
printf("%d ", q+1); //printf with 2 space for numbers 1-9
}
else
{
printf("%d ", q+1); //printf with 1 space for number 10
}
}
switch(camp[r][q])
{
case 1:
printf("~ ");
break;
case 2:
printf("0 ");
break;
case 3:
printf("S ");
break;
case 4:
printf("- ");
break;
case 5:
printf("X ");
break;
case 6:
printf("S ");
break;
case 7:
printf("- ");
break;
case 8:
printf("X ");
break;
default:
printf("E ");
break;
}
}
}
}
int fill(int campo[][9])
{
int f, h;
for(h=0;h<=9;h++)
{
for(f=0;f<=9;f++)
{
campo[f][h]=1;
}
}
}
You are trying to assign in a matrix[9][9] a number in a position [10].Remember a int [10] represents an array who starts at 0 until 9.
So, an array [9] starts at 0 to 8.
So you should or correct the matrix to be an matrix[10][10] or correct the for statement like that:
`for(q=0;q<9;q++)` (LESS **not** LESS EQUAL)
I hope I've helped you. I am not a native and my english is not good also.
Background: I have an exercise which asks me to create a function which compares 2 int arrays using the backtracking technique. The function should return 0 if the arrays are different and 1 if they are the same. The size of the arrays, the method of filling them and the output of the program are not specified in the question so I took the liberty of working them out my own way.
By using a for I made a simple fill function which fills out the two arrays in a simple way so if the user inputs s the result should be
A[0]=B[0]=0
A[1]=B[1]=1
...
A[50]=B[50]=50
and if he inputs d it should be the same but
B[i]=A[i]+1
The problem:
Instead of A[0]=0 it ends up being A[0]=50 (and A[0]=51 in the d case) which makes the whole function return 0 in every case. I have tried numerous things, but I can't get it to work properly
Here's the code:
#include <stdio.h>
#include <stdlib.h>
void fill(int a, int A[],int B[])
{
int i,j;
if (a)
{
for(i=0;i<=50;i++)
{
A[i]=i;
B[i]=A[i];
}
}
else
{
for(i=0;i<=50;i++)
{
A[i]=i;
B[i]=i+1;
}
}
A[0]=0;
for (j=0;j<=50;j++)
printf("\nka %d %d %d",j, A[j],B[j]); //the purpose of this is to check the state of the two arrays after filling them, it's how I spotted the problem, it will be deleted in the final form
}
int compare(int i, int A[],int B[])
{
int a,b;
a=A[i];
b=B[i];
printf("j %d %d\n", a,b);
if (B[i+1]!='\0')
{
if (A[i]==B[i])
{
compare (i+1,A,B);
}
else
{
return 0;
}
}
else
return 1;
}
int main()
{
int A[50], B[50], i=0;
char s;
printf("Do you want the arrays to be the same or different?\n");
printf("Input 's' or 'd': ");
scanf("%c", &s);
switch(s)
{
case 's':
case 'S':
fill(1,A,B);
break;
case 'd':
case 'D':
fill(0,A,B);
break;
default:
printf("Sorry incorrect input, please input 's' or 'd'");
return 0;
break;
}
if (compare(i,A,B))
printf("They are the same");
else
printf("They are different");
return 0;
}
You need to correct your both the functions fill and compare. In function fill you are accessing arrays out of bounds which will invoke undefined behavior. Loop should be iterated from 0 to 50 (excluding 50)
for(i=0;i<50;i++) { ... }
The function compare should be like
// Pass the size of array to the function.
int compare(int i, int A[],int B[], int n)
{
if (i != n)
{
if (A[i]==B[i])
{
return compare (i+1, A, B, n);
}
else
{
return 0;
}
}
else
return 1;
}
The issue is in the for loop. It is looping for 51 elements.
for (i=0;i<=50;i++)
It should loop for 50 elements
for (i=0;i<50;i++)
Similarly for the loop for j, in the fill function.
There is also an issue in the compare function. The exit check is
if (B[i+1]!='\0')
This means that the input array must have the last element as '\0'. Which is not happening in your input array.
You have to either pass strings to this function, or modify this function to take care of the general array case.
Hi due to my lack of knowledge in C (second year in college). Compiler ate my code and built the app. But after accepting first value - numOfIntegers it stops working and debugging tells that the segmentation has been failed. SIGSEGV.
How to fix that?
There is the code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* -----------------------------------------
Program: Question 1
Author: Maggot #9
Email: maggot99999#gmail.com
ID: B00076450
Date: 16 September 2015
Purpose: Who knows?
------------------------------------------ */
void wait(int);
void controlMenu(int, int[]);
int sumOfIntegers(int, int[]);
int avgOfIntegers(int, int[]);
int prodOfIntegers(int, int[]);
int minInteger(int, int[]);
int maxInteger(int, int[]);
const char * getName (int value)
{
static char * arrayName[] = {"first","second","third", "fourth",
"fifth","sixth", "seventh", "eighth", "ninth", "tenth"};
static char badValue[] = "unknown";
if (value<10 && value>=0)
return arrayName[value];
else
return badValue;
}
int getValue(int numOfInteger)
{
int value;
wait(100);
printf("Please enter %s the value:", getName(numOfInteger));
scanf("%d",&value);
return value;
}
void prepare(int * numOfIntegers)
{
wait(300);
printf("Hey again that C stupid lang\n\n");
wait(200);
printf("Please enter how many values you want to put: ");
scanf("%d",numOfIntegers);
return;
}
void initialize(int numOfIntegers,int* arrayNum[])
{
int i;
for(i=0; i<(numOfIntegers); i++)
arrayNum[i] = getValue(i);
wait(500);
printf("\nPlease enter press any button to continue");
wait(100);
getch();
wait(600);
system("cls");
wait(200);
return;
}
int main()
{
int numOfIntegers;
prepare(&numOfIntegers);
int arrayNum[numOfIntegers];
initialize(numOfIntegers, &arrayNum[numOfIntegers]);
controlMenu(numOfIntegers, &arrayNum[numOfIntegers]);
return 0;
}
void controlMenu(int numOfIntegers, int arrayNum[])
{
int i;
char chooseNum;
printf("Please choose any of the following:\n\n1. The integers accepted\n2. The sum of the integers\n3. The average of the integers\n4. The product of the integers\n5. The smallest integer\n6. The largest integer\n0. Exit menu\n");
while(1)
{
chooseNum = getch();
switch(chooseNum)
{
case '0':
return;
case '1':
printf("\n>>> The integers are:");
for(i=0; i<(numOfIntegers); i++)
{
printf("\n>>> The %s is %d", getName((i+1)), arrayNum[i]);
}
break;
case '2':
printf("\n>>> The sum of integers is: %d", sumOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '3':
printf("\n>>> The average of integers is: %d", avgOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '4':
printf("\n>>> The product of integers is: %d", prodOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '5':
printf("\n>>> The smallest integer is: %d", minInteger(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '6':
printf("\n>>> The largest integer is: %d", maxInteger(numOfIntegers, &arrayNum[numOfIntegers]));
break;
default:
break;
}
printf("\n\n");
}
}
int sumOfIntegers(int numOfIntegers,int arrayNum[])
{
int sum=0;
for(int i=0; i<(numOfIntegers); i++)
sum += arrayNum[i];
return sum;
}
int avgOfIntegers(int numOfIntegers, int arrayNum[])
{
int average=0;
average = sumOfIntegers(numOfIntegers, arrayNum[numOfIntegers])/numOfIntegers;
return average;
}
int prodOfIntegers(int numOfIntegers, int arrayNum[])
{
int i,product=0;
for(i=0; i<(numOfIntegers); i++)
product *= arrayNum[i];
return product;
}
int minInteger(int numOfIntegers, int arrayNum[])
{
int i,smallest=0;
smallest = arrayNum[0];
for(i=1; i<(numOfIntegers); i++)
{
if(smallest>arrayNum[i])
smallest=arrayNum[i];
else
continue;
}
return smallest;
}
int maxInteger(int numOfIntegers, int arrayNum[])
{
int i,largest=0;
largest = arrayNum[0];
for(i=1; i<(numOfIntegers); i++)
{
if(largest<arrayNum[i])
largest=arrayNum[i];
else
continue;
}
return largest;
}
void wait(int ms)
{
Sleep(ms);
return;
}
I can see this fault in getName() which will access memory beyond the array bounds
if (value>10 || value<1)
return arrayName[value];
I believe you are using the wrong test, try
if (value <= 10 && value > 0)
return arrayName[value-1];
assuming value is in the range 1..10 as the textual array implies.
2) a fault in GetValue where you input into numOfInteger but return value, which is uninitialised.
3) in prepare the statement
scanf("%d",&numOfIntegers);
will not pass the input value back to the caller. You should have either passed a pointer to the variable, or returned the value input.
But there might be a lot else wrong. Build your program step by step, checking and trying to break it as you go (with absurd input). Pay attention to compiler warnings - the second fault I listed will generate one.
EDIT okay... let's examine function prepare which after removing noise is
void prepare(int numOfIntegers)
{
scanf("%d",&numOfIntegers);
return;
}
This inputs a value to the function parameter that was passed. This is legal, since you can use a function argument in the same way you can a local variable (perhaps subject to const qualification).
Although it's not a coding error, it does not achieve anything. 1) you usually pass an argument like this to be used by the function in some way, perhaps in its limits and/or in its prompt. 2) Altering the argument like this will not find its way back to the caller.
Here are two ways to deal with this.
A) the function returns the input value
int prepare(void)
{
int value;
scanf("%d", &value); // the address of value
return value;
}
...
int input = prepare();
printf("%d\n", input);
B) the function takes a pointer argument
void prepare(int *value)
{
scanf("%d", value); // value is already a pointer
}
...
int input;
prepare(&input);
printf("%d\n", input);
Im writing a program to give the user options whether they want to:
Add random numbers to an array
Print array
Search for an element in an array
Left shift array
These have to be in separate functions and it needs to b recursive and until the user wants to finish it keeps running my code is:
int main()
{
int array[M][N];
int ans;
puts("Please enter what you would like to do:\n
1: Create an array with random values\n
2: Print Array\n
3: Search for a number in an array\n
4: Shift each value to the left");
scanf("%d",&ans);
switch(ans) {
case 1:
PopulateRandom2D(array);
break;
case 2:
PrintArray(array);
break;
case 3:
LinearSearch2D(array);
break;
case 4:
LeftShift(array);
break;
default:
puts("Goodybye");
return 0;
}
main();
return 0;
}
void PopulateRandom2D(int array[][N])
{
int r,c;
srand(time(NULL));
for(r = 0; r < M; r++) {
for(c = 0; c < N; c++) {
array[r][c] = 1 + (rand() % (M * N));
}
}
}
After i call the function i need the user to enter another command and call a different function from the user input. Ive been experimenting by first hitting 1 so it fills the array with numbers and then hitting 2 so it will hopefully print out that array but all i get are huge numbers in the array. I don't think the function is editing the array in main correctly so main doesn't get the array with random values but how do i fix this?
The code below works:
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
const int M = 10;
const int N = 20;
void PrintArray(int array[][N]) {}
void LinearSearch2D(int array[][N]) {}
void LeftShift(int array[][N]) {}
void PopulateRandom2D(int array[][N])
{
int r, c;
srand(time(NULL));
for (r = 0; r < M; r++) {
for (c = 0; c < N; c++) {
array[r][c] = 1 + (rand() % (M * N));
}
}
}
int main()
{
int array[M][N];
int ans;
while (true)
{
puts("Please enter what you would like to do:"
"\n1: Create an array with random values"
"\n2: Print Array"
"\n3: Search for a number in an array"
"\n4: Shift each value to the left"
"\n5: Quit");
scanf("%d", &ans);
switch (ans) {
case 1:
PopulateRandom2D(array);
break;
case 2:
PrintArray(array);
break;
case 3:
LinearSearch2D(array);
break;
case 4:
LeftShift(array);
break;
default:
puts("Goodybye");
return 0;
}
}
return 0;
}
I leave it to you to fill in the other functions.
You're currently recursively calling main(). In each iteration of calling main(), you'll create a new array on the stack.
This isn't what you want.
Instead, wrap your code in a while(true) { ... } loop. It would look something like this:
#include <stdbool.h>
int main()
{
int array[M][N];
int ans;
while (true) {
puts("Please enter what you would like to do:\n
1: Create an array with random values\n
2: Print Array\n
3: Search for a number in an array\n
4: Shift each value to the left");
scanf("%d",&ans);
switch(ans) {
case 1:
PopulateRandom2D(array);
break;
case 2:
PrintArray(array);
break;
case 3:
LinearSearch2D(array);
break;
case 4:
LeftShift(array);
break;
default:
puts("Goodybye");
return 0;
}
}
return 0;
}