Computing Strongly connected components using c programming language [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
confused in this semgent of code
so these are two functions which i suppose to be buggy
void dfsloop1(int **g)
{
int i;
int temp=0;
for(i=0;i<875714;i++)
{
temp = f[i];
x[temp-1] = i;
}
for(i=875714;i>0;i--)
{
if(!explored[x[i-1]])
{
s = i-1;
dfs1(g,x[i-1]);
}
}
}
void dfs1(int **g,int i)
{
explored[i] = 1;
leader[i] = s;
int j;
for(j=0;j<a[i];j++)
{
if(!explored[(g[i][j]-1)])
{
dfs1(g,g[i][j]);
}
}
}
here explored array is keeping account of node/vertex is checked or not if it is checked then say ith vertex is checked then explored[i-1] = 1 else explored[i-1] = 0,a[i] stores to how many vertex i+1 th vertex is connected
for example the vertex no.1 is connected with 2,4,5 then a[0] will be 3, graph is passed in adjacency list and i have already run dfs on reverse graph and stored that magical numbering in f[i]
using kosaraju's algorithm,now i am trying to run dfs on my original graph g
in x[i]
i am storing f[i] in increasing order for example lets say on 9 vertex graph f[0] = 7,f[1] = 3,f[2] = 1,f[4] = 2,f[5] = 5,f[6] = 9,f[7]=4,f[8] = 6 then x[0] = 2(which is the index of smallest f[i]),x[1] = 4,x[2] = 1 and so on.
if i left something or something is unclear please let me know.
Thanks
total number of vertices are 875714
i am new on stackoverflow so if i did anything wrong let me know
Thanks

I viewed your code. I am assuming that you are new into this as your main function is jumbled with codes which is not actually convenient.
Two things:
1. You are dealing with pointers and also pointer of pointers.
2. You are consuming more than 10^5 integer memory for local variable/pointer.
I don't have much knowledge about pointers. However, as a contestant I used to have "Runtime Error" while declaring huge sized array locally. So, I think your problem lies in these two sections. Try to declare that pointers of pointer globally. See if it helps.
I am giving you a link of the SCC algorithm.
e-maxx: https://e-maxx-eng.appspot.com/graph/strongly-connected-components.html
and my implementation of scc:
https://bitbucket.org/techboy_zero/programming-and-software-development/src/035560584ce7ab7e0a3f6ab5ae1406095bd39b62/Programming%20Contest%20Algorithms/Graph%20Theory/Strongly_Connected_Component.cpp
Though, mine is in c++. Just see the dfs and kosaraju functions. If you have any problem understanding keywords, search in cplusplus.com. If don't understand the mechanism then feel free to ask me.

Related

Custom Sorting algorithm (C) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Our teacher asked us today to make a custom sorting algorithm, and he gave us some instructions, however I wasn't able to solve it:
First you get the smallest number from a randomly generated array and assign it to a separate array. Then you get the second smallest number the array and assign it to the next position in the separate array.
I was able to build this, but it doesn't fully work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ANZAHL 5
int main() {
srand(time(0));
int zfeld[ANZAHL], zfeld1[ANZAHL] = {}, zfeld2[ANZAHL] = {}, i, d, ug, og, kl = ANZAHL + 1;
printf("Gib die untere und obere grenze an");
scanf("%d%d", &ug, &og);
for (i = 0; i < ANZAHL; i++) {
zfeld[i] = rand() % ((og - ug) - 1) + ug + 1;
}
for (d = 0; d < ANZAHL; d++) {
for (i = 0; i < ANZAHL; i++) {
if (zfeld[i] < kl && zfeld[i] != zfeld2[d - 1]) {
kl = zfeld[i];
}
}
zfeld2[d] = kl;
}
return 0;
}
Several issues:
kl=ANZAHL+1: the length of the original array has nothing to do with values. It would make more sense to do kl = og. But still, the place where you do this assignment is wrong. Once you have found the first minimum value, kl will be too small to detect the next smallest value: you need to reset it each time you iterate in the outer loop.
The inner loop should not iterate over all elements when you have already identified a few small values. You try to avoid to pick the same one twice, but just comparing with the previously identified value (zfeld[i] != zfeld2[d-1]) is not going to work. First, because when d is zero, this is an invalid reference, and second: there are in general more values in zfeld2 which you also don't want to select again. Instead consider that the first array should become "shorter". You can do this by moving the last value of the array into the slot where you found the smallest value. Then you can consider that the array became one unit smaller without losing any information. To make that work, you need to know the index where you find the smallest value.
So here is the corrected code for the loops:
for(d=0; d<ANZAHL; d++)
{
// Reset the index, and just consider the first value to the the smallest so far
int indexOfSmallest = 0;
// Each time you move one value, we look at one value less in this loop:
for(i=1; i<ANZAHL - d; i++)
{
if(zfeld[i] < zfeld[indexOfSmallest])
{
indexOfSmallest = i;
}
}
zfeld2[d] = zfeld[indexOfSmallest];
// Move last value in the slot that opens up:
zfeld[indexOfSmallest] = zfeld[ANZAHL - d - 1];
}
NB: this is a variant to selection sort. Selection sort does not use a second array, as it reuses the space that is liberated in the first array to store the sorted values.
I would also suggest to use better variable names. Names like kl, ug, og are maybe clear to you, but it is better practice to just use full names: kleinste, untereGrenze, ...etc.

No double picks in image Array Processing 3.0

i've been trying to make a program that takes (for example) 3 cards at random.
But i don't want my program to grab the same card twice, so that means it can't have duplicates, but i don't know how to do this with a image Array.
String[] card = {
"Aclubs.png",
"2clubs.png",
"3clubs.png",
};
PImage[] cards = new PImage [card.length];
void setup() {
size(1000,1000);
randomCards();
drawCards();
}
int randomCards() {
int i = (round(random(0,2)));
cards[i] = loadImage(card[i]);
return i;
}
void drawCards() {
for (int g = 0; g < 12000; g = g+round((displayWidth * 0.9))/12) {
image(cards[randomCards()], 25+g, 50);
}
}
Instead of using an array, use an ArrayList. Then remove the cards you use. Here's a small example:
ArrayList<String> things = new ArrayList<String>();
things.add("cat");
things.add("dog");
things.add("lizard");
while (!things.isEmpty()) {
int index = int(random(things.size()));
String thing = things.remove(index);
println(thing);
}
Of course, this isn't the only way to do it. You could use a Java Set, or you could use a data structure that holds what you've already picked, or you could store all of the options in a data structure, then shuffle it, then just chose from an index that you increment. Or you could use one of the array functions in the reference to do it.
It's hard to answer general "how do I do this" type questions. Stack Overflow is designed for more specific "I tried X, expected Y, but got Z instead" type questions. So you really should get into the habit of trying things out first. Ask yourself how you would do this in real life, then look at the reference to see if there are any classes or functions that would help with that. Break your problem down into smaller pieces. Write down how you would do this in real life, in English. Pretend you're handing those instructions to a friend. Could they follow your instructions to accomplish the goal? When you have those instructions written out, that's an algorithm that you can start thinking about implementing in code. Staring at code you've already written won't get you very far. Then when you do get stuck, you can ask a more specific question, and it'll be a lot easier to help you.

Text adventure game--randomly connecting rooms together - C

I'm trying to create a text adventure game that 7 rooms, with the information saved in files. This question IS similar to Connect Rooms Randomly in Adventure Game however the answer didn't exactly help me. I've gone about my program in a different way than that OP so I'm not sure how to use that answer to help me.
The idea is you have 7 rooms, named say A, B, C, D, E, F, and G. After the rooms are created, I need to randomly connect them to each other. Each room needs between 3 and 6 random connections. If room A is connected to B, C, and D, each of those rooms should be connected to A. This information is then saved to a file which is read later.
The code I have for this section so far is:
char *connections[7];
int j = 0;
int randomRoom;
for (j = 0; j <= randConnections; j++) {
randomRoom = rand() % 10;
if (randomRoom == randName) {
randomRoom = rand() % 10;
} else {
connections[j] = names[randomRoom];
}
randConnections is a random int between 3 and 6, defined earlier in the code. names is a string array that holds the names of the rooms, also defined earlier in my program.
I am pretty new to C (I'm mostly experienced with Java) so I can't figure it out. I should mention, this is all in one function defined as:
void createRooms(FILE *fp)
I know there are probably more efficient ways to do this, but at this point I'm just trying to get the code working and deal with efficiency later.
I've done a ton of googling and am honestly beating my head against the wall right now. Any help would be greatly appreciated. If there's any more code I should post or any other information let me know.
C-style strings can get a bit confusing. A "string" in pure C is a char array. Arrays in C are strongly related to pointers. In fact, instead of defining
char myCString[6] = "hello";
You could define
char * myCString = "hello";
In fact, in the first case, myCString used alone will just return a pointer to the first element. The [] operator is just a convenient dereference and increment operator. So &(myCString+1) becomes myCString[1]
So long story short, your "string" array in C is really an array of char* - pointers to the first element of an array of characters
You're trying to assign this to a single character, which doesn't make logical sense. If you mean for the connections to truly be strings, do like kcraigie says.
Here's some backup I found, I'm afraid there are more nuances and I'm not an expert, but that's the gist - https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays#Pointers_and_Arrays
This may seem absurd coming from java - that's C for ya. C++'s standard library includes a string construct like what you'd be familiar with. It's a class that wraps a "raw" C array and controls access to it and manages it like Java and C# strings. Modern C++ best practices try to stay away from the raw arrays. You'll also notice that nothing stops you from calling MyCString[4000], which is just going to grab a piece of memory from the middle of nowhere and do heaven knows what. There is no bounds checking on raw arrays in C. Be careful!

Can't delete snake's tail according to his head's movement

EDIT #1.
Now i see that my functions doesnt work with this game so please forget them.
Still haven't found a solution, saw some documentation about Queue's as fjf2002 mentioned but it's way too complex to me at this momment. Tried to make a snake[20] array to store coordinates by 2 {1, 1, 1, 2} would be: Head (1,1) Tail (1,2) on the map. Still can't figure how to move it around the map and make the tail follow the head. My mind is blank after trying everything and getting frustrated by my lack of experience. Im not allowed to use anything beyond two-dimensional arrays. Meaning that no structs, no queues, no stacks... This is supposed to be done without using those and profesor says that is more easier than i think. (Dont post that i should ask him for the solution as he keeps saying the same without answering my questions). Any idea would help me greatly...------------------------------------------------------------------------------------------------------------------------------------
im using VisualStudio 2013 and programming in C language.
Was looking for a solution in the past 2 days and found nothing over internet to help me. Saw dozens of different snake games in english and spanish but i can't understand them due to zero explaining of their programs or due to my lack of experience.
Tried everything of my knowledge without success and i can't really come up with a solution by my own.
I have:
-Function to generate the map.
-Function to move the snake:
COORD cxy;
#define posicion(x,y) {(cxy.X)= (x);(cxy.Y)= (y); SetConsoleCursorPosition((GetStdHandle(STD_OUTPUT_HANDLE)), (cxy) );}
int tablero[20][20], posx = 0, posy = 0;
void movimientoSnake(){
int m = 1, k = 0, tail = 3;
char dir = 'd';
do{
if (kbhit()){
dir = getch();
if (dir == 'w'){
m = 0;
k = -1;
}
if(dir == 's'){
m = 0;
k = 1;
}
if (dir == 'a'){
m = -1;
k = 0;
}
if (dir == 'd'){
m = 1;
k = 0;
}
}
else{
Sleep(500);
posicion(posx += m, posy += k);
printf("%d", 1);
posicion(posx - tail, posy);
printf("%d", 0);
}
} while (2 > 1);
*The snake moves OK according to wasd keys, and it leaves a trail with 1's (map is full of 0's).
*It moves based on position: position(x,y) of the map (moves there) printf("%d", 1); (prints an 1). for example
The main problem is when i want to delete the trail when i move down, delete the last position while at the same time im printing the new one ahead.
If possible i would like a solution without too much complex (using too many libraries) as by now i only know:
#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
I tried to store coordinates on arrays as i saw in almost 90% of snake games out there but i dont understand the concept so i ended up with a bunch of tries without success.
Any ideas?
Thank you very much in advance.
So let us summarize:
Knowing only the coordinates of the head of the snake, how to determine the coordinates of the tail?
Since the snake may have several turns, there is no straight forward way.
I tried to store coordinates on arrays as i saw in almost 90% of snake games out there
Seems to be the only solution.
but i dont understand the concept
You should store the positions occupied by the snake in an array. You have to keep track which array elements are currently occupied, where the head and where the tail is stored.
Or you use the above as an already implemented product: a data structure that allows easy access to first and last element. Read
about http://en.wikipedia.org/wiki/FIFO , http://www.cplusplus.com/reference/queue/queue/ .

Algorithm for 3D dice generation

I am making a simple test application in C that is supposed to generate three dimensional dice. I am going to use OpenGL to do the actual drawing, but I cannot figure out how to actually generate the vertices. Of course, the whole point of this test was to see if my algorithm worked, but I found a major logic error that I cannot fix. Can somebody please point me to an article, website, or something that explains the concept? If not, although I would prefer to do the actual implementation myself, the C code is acceptable.
Basically, this is what I did before I forgot what I was doing for the algorithm:
void calculateVertices(int sides) {
BOOL isDone = FALSE;
int vectorsPerSide = 3;
VDVector3f *vertices = malloc((sizeof(VDVector3f) * (sides + 1)));
VDVector3f *normals = malloc((sizeof(VDVector3f) * (sides + 1)));
while (!isDone) {
// Start by positioning the first vertex.
vertices[0] = VDVector3fMake(0.0, 0.0, 1.0);
for (int index = 1; index <= sides; index ++) {
}
// Not a match, increase the number of vectors
vectorsPerSide ++;
}
}
Basically, it loops until a match is found. This sounds inefficient to me, but I had no other idea as to how to do this. The first vertex will actually be removed from the array at the end; I was going to use it to create the first side, which would have been used to properly position the others.
My main goal here is to be able to pass number (like 30) to it, and have it set the vertices automatically. I will not have protections against making one sided and two sided dice, because I have something special in mind. I will have those vertices entered elsewhere.
Thanks in advance for the help!
By the way, I have an algorithm that can normalize the completed vertex array. You don't have to bother helping with that.
I don't think this is possible to generalize this. How, for example would you make a fair 5 or 9 sided die? I don't think I have ever seen such a thing. A quick search on wikipedia suggests platonic solids may be what you are after. http://en.wikipedia.org/wiki/Platonic_solid

Resources