• Advertisement
Sign in to follow this  

***Converting C code to Java***

This topic is 4574 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If any of you have the time could you possibly help me convert some C code to its equivalent in Java plz, i really dont know much about c at all but have to try and implement a java version of some c code. below i have listed the c code and also what i have done so far, think its ok apart from the init_arguments method. thanks hope this doesnt seem like too much code, but thanks to all of you who take the time to help, greatly appreciated, even if you can just help with a single method that will be great! (as i know there is quite a few lines here) =) C Code first:
/* Program to produce suffix array. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>

typedef unsigned int boolean;

#define FALSE 0                 /* For boolean expressions */
#define TRUE 1                  /* For boolean expressions */

#define DUMP_STRING_SIZE 40     /* Used for dumping long strings
				   (for debug purposes */

unsigned int Order = 0;         /* Order used for comparison */

void
usage (void)
{
    fprintf (stderr,
	     "Usage: ident_language [options]\n"
	     "\n"
	     "options:\n"
	     "  -o n\tOrder=n\n"
	     );
    exit (2);
}

void
init_arguments (int argc, char *argv[])
{
    extern char *optarg;
    extern int optind;
    int opt;
    boolean order_found;

    /* set defaults */
    order_found = FALSE;

    /* get the argument options */

    while ((opt = getopt (argc, argv, "o:")) != -1)
	switch (opt)
	{
	case 'o':
	    order_found = TRUE;
	    sscanf (optarg, "%u", &Order);
	    assert (Order > 0);
	    fprintf (stderr, "Order = %d\n", Order);
	    break;
	default:
	    usage ();
	    break;
	}

    if (!order_found)
        usage ();
    for (; optind < argc; optind++)
	usage ();
}

void
SA_init_sarray (unsigned int *sarray, unsigned int size)
/* Initializes the suffix array's index. */
{
    unsigned int p;

    for (p = 0; p < size; p++)
      sarray 

= p; } void SA_check_sarray (char *string, unsigned int string_size, unsigned int *sarray) /* Checks that the suffix array is sorted */ { unsigned int p, i, prev_i; char cc; prev_i = sarray [0]; for (p = 1; p < string_size; p++) { i = sarray

; if (strcmp (string + prev_i, string + i) > 0) { fprintf (stderr, "Error in suffix array at index %d :\n", p); cc = string [prev_i + 40]; string [prev_i + 40] = '\0'; fprintf (stderr, "position %6d, string = %s\n", prev_i, string + prev_i); string [prev_i + 40] = cc; cc = string [i + 40]; string [i + 40] = '\0'; fprintf (stderr, "position %6d, string = %s\n", i, string + i); string [i + 40] = cc; } prev_i = i; } } static char *SA_String; int SA_qsort_compare (const void *index1, const void *index2) /* Comparison function used by qsort. */ { int p1, p2, cmp; /*fprintf (stderr, "Comparing %p with %p\n", index1, index2);*/ p1 = *((unsigned int *) index1); p2 = *((unsigned int *) index2); /*fprintf (stderr, "Value %d with %d\n", p1, p2);*/ cmp = strcmp (SA_String + p1, SA_String + p2); if (!cmp) { if (p1 > p2) return (1); if (p1 < p2) return (-1); return 0; } return cmp; } unsigned int * SA_make_sarray (char *string, unsigned int string_size) /* Builds the suffix array in memory. */ { unsigned int *sarray; SA_String = string; sarray = (unsigned int *) malloc (string_size * sizeof (unsigned int)); SA_init_sarray (sarray, string_size); qsort (sarray, string_size, sizeof (unsigned int), SA_qsort_compare); SA_check_sarray (string, string_size, sarray); return (sarray); } void SA_dump_string ( FILE *fp, char *string, unsigned int p, boolean full_dump) /* Dumps the string to FP. */ { int cc, len; len = strlen (string + p); if (full_dump) fprintf (fp, "position = %d, string = ", p); if (len < DUMP_STRING_SIZE) fprintf (fp, "%s\n", string + p); else { cc = string [p + DUMP_STRING_SIZE]; string [p + DUMP_STRING_SIZE] = '\0'; fprintf (stderr, "%s\n", string + p); string [p + DUMP_STRING_SIZE] = cc; } } void SA_dump_sarray (FILE *fp, char *string, unsigned int string_size, unsigned int *sarray) /* Dumps out the suffix array to file FP (fro debug purposes). */ { unsigned int p, i; for (p = 0; p < string_size; p++) { i = sarray

; fprintf (fp, "%6d : %6d ", p, i); SA_dump_string (fp, string, i, TRUE); } } unsigned int SA_compute_measure (char *string1, unsigned int string_size1, unsigned int *sarray1, char *string2, unsigned int string_size2, unsigned int *sarray2, unsigned int order) /* Computes a measure of similarity between the two strings using their respective suffix arrays. */ { unsigned int p1, p2, i1, i2, measure; int result; p2 = 0; measure = 0; for (p1 = 0; p1 < string_size1;) { /* We are now at the start of a "new" group of prefixes as determined by the Order length */ i2 = sarray2 [p2]; if (strlen (string1 + i1) < order) continue; while ((result = strncmp (string2 + i2, string1 + i1, order)) < 0) { /* fprintf (stderr, "Skipping suffix array at index %d,%d :\n", p1, p2); SA_dump_string (stderr, string1, i1, TRUE); SA_dump_string (stderr, string2, i2, TRUE); */ p2++; if (p2 >= string_size2) break; i2 = sarray2 [p2]; } if (!result) /* Prefixes up to length order are equal */ { measure++; fprintf (stderr, "Prefixes match at index %d,%d :\n", p1, p2); SA_dump_string (stderr, string1, i1, TRUE); SA_dump_string (stderr, string2, i2, TRUE); } /* Skip through suffix array 1 until we reach the start of a new group of prefixes */ old_p1 = p1; old_i1 = i1; for (;;) { p1++; if (p1 > string_size1) break; i1 = sarray [p1]; if ($$$result = strncmp (string1 + old_i1, string1 + i1, order)) < 0) } while ( { } /* fprintf (stderr, "Position %d,%d :\n", p1, p2); SA_dump_string (stderr, string1, i1, TRUE); SA_dump_string (stderr, string2, i2, TRUE); */ } return (measure); } int main (int argc, char *argv[]) { char string1 [128], string2 [128]; unsigned int *sarray1, *sarray2, string_size1, string_size2, measure; init_arguments (argc, argv); /* string = (char *) malloc (array_size * sizeof (char)); sarray = (unsigned int *) malloc (array_size * sizeof (unsigned int)); */ /* Read in the input file */ /*string_size = fread (string, sizeof (char), array_size+1, stdin);*/ fprintf (stdout, "Enter string1: "); fscanf (stdin, "%s", string1); string_size1 = strlen (string1) + 1; fprintf (stdout, "Enter string2: "); fscanf (stdin, "%s", string2); string_size2 = strlen (string2) + 1; sarray1 = SA_make_sarray (string1, string_size1); sarray2 = SA_make_sarray (string2, string_size2); /*dump_sarray (string, string_size, sarray);*/ measure = SA_compute_measure (string1, string_size1, sarray1, string2, string_size2, sarray2, Order); fprintf (stderr, "Measure = %d\n", measure); exit (1); }

================================================ My Java Code So Far:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class SArray
{
	
	
	// Builds the suffix array in memory
	public static int[] SA_make_sarray(String string, int stringSize)
	{
		String SA_string;
		int[] sarray;
		
		//SA_string = aString;
		sarray = new int[stringSize];
		
		SA_init_sarray(sarray, stringSize);
		SA_check_sarray(string, stringSize, sarray);
		
		return sarray;
	}
	
	//Initializes the suffix array's index. 
	public static void SA_init_sarray(int[] sarray, int size)
	{
		for(int p = 0; p < size; p++)
		{
			sarray

= p; } } public static void SA_check_sarray(String string, int stringSize, int[] sarray) { int p; int i = 0; int prev_i = 0; char cc; char[] charArray = string.toCharArray(); prev_i = sarray[0]; for(p = 1; p < stringSize; p++) { i = sarray

; if ((string + prev_i).compareTo((string + i)) > 0) { System.out.println ("Error in suffix array at index : " + p); } cc = charArray [prev_i + 40]; charArray [prev_i + 40] = '\0'; System.out.println ("position " + prev_i + ", string = " + (string + prev_i)); charArray [prev_i + 40] = cc; cc = charArray [i + 40]; charArray [i + 40] = '\0'; System.out.println ("position " + i + ", string = " + (string + i)); charArray [i + 40] = cc; } prev_i = i; } public static void init_arguments (String args[]) { char optarg = '?'; int optind; int opt = 0; boolean order_found; /* set defaults */ order_found = false; /* get the argument options */ while (opt != -1) { opt = args.toString().indexOf("o:" + 1); } switch (opt) { case 'o': order_found = true; //sscanf (optarg, "%u", &Order); get integer out of optarg and place in Order int Order = optarg; if (Order > 0) { System.out.println("Error, order greater than 0...Exiting"); System.exit(0); } System.out.println("Order = " + Order); break; default: usage (); break; } if (!order_found) usage (); //for (; optind < args; optind++) //usage (); } public static void usage() { System.out.println("Usage: ident_language [options]\n"); System.out.println("options:\n"); System.out.println("-o n\tOrder=n\n"); System.exit(0); } public static void main (String args[]) throws IOException { String string1; String string2; int[] sarray1, sarray2; int string_size1, string_size2, measure; init_arguments (args); /* string = (char *) malloc (array_size * sizeof (char)); sarray = (unsigned int *) malloc (array_size * sizeof (unsigned int)); */ /* Read in the input file */ /*string_size = fread (string, sizeof (char), array_size+1, stdin);*/ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter string1: "); string1 = br.readLine(); string_size1 = string1.length() + 1; System.out.println("Enter string2: "); string2 = br.readLine(); string_size2 = string2.length() + 1; sarray1 = SA_make_sarray (string1, string_size1); sarray2 = SA_make_sarray (string2, string_size2); } }

[Edited by - ug02070 on October 10, 2005 10:17:26 AM]

Share this post


Link to post
Share on other sites
Advertisement
Before I even try figuring any of that out, might I recommend reformatting your post to use the neat-o source code formatting? For C code, use [source lang="c"](code here)[/source]; for Java code, use [source lang="java"](code here)[/source].

Thanks,
Twilight Dragon

Share this post


Link to post
Share on other sites
Hokay...I got started on it for the heck of it (you're lucky in that respect; I normally don't help people with actual code much), and then realized I didn't know what exactly it was supposed to do. I pasted what I had so far below, in case you're interested.

In any case, there are two things I noted:

First, the plus symbol denotes two separate things in the C version and the Java version of the SA_check_sarray function; specifically, the line "if (strcmp (string + prev_i, string + i) > 0)". In the C version, it increments the memory pointer "string" by the amounts prev_i and i respectively, which in effect makes strcmp see a substring of the string rather than the whole thing. What you have in Java doesn't do that; rather, it concatenates the number onto the end of the string. Not what you want, I'd assume; rather, you need to use the String.substring() function.

Second, the qsort() function is a part of the C Standard Library, and you'll have to find some sort of equivalent in Java or make your own. Collections.sort(), possibly?

Here's what I had so far (please excuse any mistakes, as it's been a few months since I programmed Java):

public class SuffixArray
{
static int static_order = 1;

int order;

public SuffixArray(int input_order)
{
order = (input_order > 0) ? input_order : 1; //the check is unnecessary as the program currently stands,
//but good practice for if you ever change it
}

public static void main(String[] args) throws IOException
{
try
{
HandleArgs(args);
}
catch (ParseException e)
{
PrintUsage();
return;
}

//TODO
}

public static void HandleArgs(String[] args) throws ParseException
{
for (int arg_at = 0; arg_at < args.length; arg_at++)
{
if (args[arg_at].equals("-o"))
{
if (arg_at + 1 >= args.length)
throw new ParseException("-o must be followed by an order.");
arg_at++;
try
{
static_order = Integer.parseInt(args[arg_at]);
}
catch (NumberFormatException e)
{
throw new ParseException(args[arg_at] + "is not a valid order input.");
}
if (static_order <= 0)
throw new ParseException("The order must be greater than 0.");
}
else
throw new ParseException(args[arg_at] + "is not a valid argument.");
}
}
}

Share this post


Link to post
Share on other sites
nice one, thanks for your help, i'm glad you decided to help someone with code because i dont know c at all.
i shall try working through the rest now,
does anyone know if the qsort method can be done in java, my lecturer reckons that it traverses and compares two trees simultaneously (effectively) and said that he's not sure if this is possible in java, one person tried and failed, he is pretty hard on java so doesnt think it can be done? can anyone prove him wrong?
thanks

Share this post


Link to post
Share on other sites
Quote:
Original post by ug02070
nice one, thanks for your help, i'm glad you decided to help someone with code because i dont know c at all.
i shall try working through the rest now,
does anyone know if the qsort method can be done in java, my lecturer reckons that it traverses and compares two trees simultaneously (effectively) and said that he's not sure if this is possible in java, one person tried and failed, he is pretty hard on java so doesnt think it can be done? can anyone prove him wrong?
thanks


qsort is just the quicksort algorithm if I'm not mistaken, the java container classes most likely have a sorting algorithm, it would surprise me if they hadn't.

And quicksort does not work by comparing 2 trees.

Share this post


Link to post
Share on other sites
I'm pretty sure qsort is a fairly dumb function - just a standard quicksort which will use the comparison function to compare elements and memcpy with a buffer to swap them.

Anyway, what you'll probably be wanting is one of Java's containers instead of an array, although this won't be very efficient for such a simple case. Alternatively you could just write your own quicksort, it's pretty easy and will almost certainly CREAM the C qsort routine for speed.

Share this post


Link to post
Share on other sites
Quote:
Original post by ug02070
does anyone know if the qsort method can be done in java, my lecturer reckons that it traverses and compares two trees simultaneously (effectively) and said that he's not sure if this is possible in java, one person tried and failed, he is pretty hard on java so doesnt think it can be done? can anyone prove him wrong?

Either your instructor is talking BS or he's being misquoted.

Quicksort is extraordinarily easy to implement in Java for a single basic type. We did it in Data Structures last semester. But I'd suspect you don't even need to implement your own sorting algorithm for this instance; the Java class library has everything you could need and more. See the methods in the Collections class that I mentioned earlier for starters.

Cheers,
Twilight Dragon

Share this post


Link to post
Share on other sites
Instead of inserting items into an array and then sorting that array, you can insert into the Java TreeSet collection, which will guarantee that when you create an iterator for the collection, the elements are sorted. Or, you can use the toArray method after inserting everything into the TreeSet, if you must have the data in an array.

If you have taken any sort of algorithm analysis, the TreeSet uses a heap as its underlying data structure, so each insert is O(logN). When you remove elements from a heap, they are guaranteed to be in order by the properties associated with the heap, and each remove-smallest operation is O(logN) as well. Therefore, the entire insert-into-array-and-sort operation is O(NlogN), which is the same complexity as quick sort. Which method is actually faster on average depends on a bunch of different factors, and it is usually easiest to just do an empirical comparison on real data. The advantage to using a heap sort here is ease of coding - the whole thing is just a few lines of code in Java.

Java TreeSet API

Share this post


Link to post
Share on other sites
Or you could just use Arrays.Sort which probably uses quicksort, will be faster than a tree set, and won't take up extra memory.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement